ia64/xen-unstable

changeset 1458:1d69c0528a2e

bitkeeper revision 1.946.1.3 (40c9c475sJLMEuc6TqUt-bX6hVFOpQ)

Add source tree for the management utils.
author mjw@wray-m-3.hpl.hp.com
date Fri Jun 11 14:40:53 2004 +0000 (2004-06-11)
parents 744f3757de91
children 138c55619f27 1c03ec9209f0
files .rootkeys BitKeeper/etc/ignore tools/Makefile tools/examples/xm_dom_control.py tools/examples/xm_dom_create.py tools/examples/xm_vd_tool.py tools/xenctl/lib/ip.py tools/xenctl/lib/vdisk.py tools/xenctl/setup.py tools/xend/lib/utils.c tools/xenmgr/Makefile tools/xenmgr/lib/Args.py tools/xenmgr/lib/EventServer.py tools/xenmgr/lib/EventTypes.py tools/xenmgr/lib/PrettyPrint.py tools/xenmgr/lib/XendClient.py tools/xenmgr/lib/XendConsole.py tools/xenmgr/lib/XendDB.py tools/xenmgr/lib/XendDomain.py tools/xenmgr/lib/XendDomainConfig.py tools/xenmgr/lib/XendDomainInfo.py tools/xenmgr/lib/XendMigrate.py tools/xenmgr/lib/XendNode.py tools/xenmgr/lib/XendRoot.py tools/xenmgr/lib/XendVdisk.py tools/xenmgr/lib/XendVnet.py tools/xenmgr/lib/__init__.py tools/xenmgr/lib/encode.py tools/xenmgr/lib/server/SrvBase.py tools/xenmgr/lib/server/SrvConsole.py tools/xenmgr/lib/server/SrvConsoleDir.py tools/xenmgr/lib/server/SrvConsoleServer.py tools/xenmgr/lib/server/SrvDeviceDir.py tools/xenmgr/lib/server/SrvDir.py tools/xenmgr/lib/server/SrvDomain.py tools/xenmgr/lib/server/SrvDomainDir.py tools/xenmgr/lib/server/SrvEventDir.py tools/xenmgr/lib/server/SrvNode.py tools/xenmgr/lib/server/SrvRoot.py tools/xenmgr/lib/server/SrvServer.py tools/xenmgr/lib/server/SrvVdisk.py tools/xenmgr/lib/server/SrvVdiskDir.py tools/xenmgr/lib/server/SrvVnetDir.py tools/xenmgr/lib/server/__init__.py tools/xenmgr/lib/server/blkif.py tools/xenmgr/lib/server/channel.py tools/xenmgr/lib/server/console.py tools/xenmgr/lib/server/controller.py tools/xenmgr/lib/server/cstruct.py tools/xenmgr/lib/server/messages.py tools/xenmgr/lib/server/netif.py tools/xenmgr/lib/server/params.py tools/xenmgr/lib/sxp.py tools/xenmgr/netfix tools/xenmgr/setup.py tools/xenmgr/xend tools/xenmgr/xenmgrd
line diff
     1.1 --- a/.rootkeys	Fri Jun 11 14:35:29 2004 +0000
     1.2 +++ b/.rootkeys	Fri Jun 11 14:40:53 2004 +0000
     1.3 @@ -174,6 +174,9 @@ 401d7e16NpnVrFSsR7lKKKfTwCYvWA tools/exa
     1.4  401d7e16RJj-lbtsVEjua6HYAIiKiA tools/examples/xc_dom_create.py
     1.5  403b7cf7J7FsSSoEPGhx6gXR4pIdZg tools/examples/xc_physinfo.py
     1.6  401d7e16X4iojyKopo_j63AyzYZd2A tools/examples/xc_vd_tool.py
     1.7 +40c9c4684Wfg8VgMKtRFa_ULi2e_tQ tools/examples/xm_dom_control.py
     1.8 +40c9c468pXANclL7slGaoD0kSrIwoQ tools/examples/xm_dom_create.py
     1.9 +40c9c468QKoqBHjb5Qwrm60pNVcVng tools/examples/xm_vd_tool.py
    1.10  3f776bd2Xd-dUcPKlPN2vG89VGtfvQ tools/misc/Makefile
    1.11  40ab2cfawIw8tsYo0dQKtp83h4qfTQ tools/misc/fakei386xen
    1.12  3f6dc136ZKOjd8PIqLbFBl_v-rnkGg tools/misc/miniterm/Makefile
    1.13 @@ -218,8 +221,10 @@ 3fbd0a40yT6G3M9hMpaz5xTUdl0E4g tools/xc/
    1.14  4055ee41IfFazrwadCH2J72nz-A9YA tools/xenctl/Makefile
    1.15  4055ee4b_4Rvns_KzE12csI14EKK6Q tools/xenctl/lib/__init__.py
    1.16  4055ee4dwy4l0MghZosxoiu6zmhc9Q tools/xenctl/lib/console_client.py
    1.17 +40c9c468IienauFHQ_xJIcqnPJ8giQ tools/xenctl/lib/ip.py
    1.18  4059c6a0pnxhG8hwSOivXybbGOwuXw tools/xenctl/lib/tempfile.py
    1.19  3fbd4bd6GtGwZGxYUJPOheYIR7bPaA tools/xenctl/lib/utils.py
    1.20 +40c9c468F36e06WH38kpYrD3JfXC0Q tools/xenctl/lib/vdisk.py
    1.21  4055ee44Bu6oP7U0WxxXypbUt4dNPQ tools/xenctl/setup.py
    1.22  40431ac64Hj4ixUnKmlugZKhXPFE_Q tools/xend/Makefile
    1.23  4055ad95Se-FqttgxollqOAAHB94zA tools/xend/lib/__init__.py
    1.24 @@ -232,6 +237,53 @@ 409ba2e729HhE7fEra4B5EqX-F8Xzw tools/xen
    1.25  40431ac8wrUEj-XM7B8smFtx_HA7lQ tools/xend/lib/utils.c
    1.26  4054a2fdkdATEnRw-U7AUlgu-6JiUA tools/xend/setup.py
    1.27  4056cd26Qyp09iNoOjrvzg8KYzSqOw tools/xend/xend
    1.28 +40c9c468icGyC5RAF1bRKsCXPDCvsA tools/xenmgr/Makefile
    1.29 +40c9c468SNuObE_YWARyS0hzTPSzKg tools/xenmgr/lib/Args.py
    1.30 +40c9c468Um_qc66OQeLEceIz1pgD5g tools/xenmgr/lib/EventServer.py
    1.31 +40c9c468U8EVl0d3G--8YXVg6VJD3g tools/xenmgr/lib/EventTypes.py
    1.32 +40c9c468QJTEuk9g4qHxGpmIi70PEQ tools/xenmgr/lib/PrettyPrint.py
    1.33 +40c9c4688m3eqnC8fhLu1APm36VOVA tools/xenmgr/lib/XendClient.py
    1.34 +40c9c468t6iIKTjwuYoe-UMCikDcOQ tools/xenmgr/lib/XendConsole.py
    1.35 +40c9c468WnXs6eOUSff23IIGI4kMfQ tools/xenmgr/lib/XendDB.py
    1.36 +40c9c468fSl3H3IypyT0ppkbb0ZT9A tools/xenmgr/lib/XendDomain.py
    1.37 +40c9c468bbKq3uC7_fuNUkiMMjArdw tools/xenmgr/lib/XendDomainConfig.py
    1.38 +40c9c4685ykq87_n1kVUbMr9flx9fg tools/xenmgr/lib/XendDomainInfo.py
    1.39 +40c9c46854nsHmuxHQHncKk5rAs5NA tools/xenmgr/lib/XendMigrate.py
    1.40 +40c9c468M96gA1EYDvNa5w5kQNYLFA tools/xenmgr/lib/XendNode.py
    1.41 +40c9c4686jruMyZIqiaZRMiMoqMJtg tools/xenmgr/lib/XendRoot.py
    1.42 +40c9c468P75aHqyIE156JXwc-5W92A tools/xenmgr/lib/XendVdisk.py
    1.43 +40c9c468xzANp6o2D_MeCYwNmOIUsQ tools/xenmgr/lib/XendVnet.py
    1.44 +40c9c468x191zetrVlMnExfsQWHxIQ tools/xenmgr/lib/__init__.py
    1.45 +40c9c468S2YnCEKmk4ey8XQIST7INg tools/xenmgr/lib/encode.py
    1.46 +40c9c468DCpMe542varOolW1Xc68ew tools/xenmgr/lib/server/SrvBase.py
    1.47 +40c9c468IxQabrKJSWs0aEjl-27mRQ tools/xenmgr/lib/server/SrvConsole.py
    1.48 +40c9c4689Io5bxfbYIfRiUvsiLX0EQ tools/xenmgr/lib/server/SrvConsoleDir.py
    1.49 +40c9c468woSmBByfeXA4o_jGf2gCgA tools/xenmgr/lib/server/SrvConsoleServer.py
    1.50 +40c9c468kACsmkqjxBWKHRo071L26w tools/xenmgr/lib/server/SrvDeviceDir.py
    1.51 +40c9c468EQZJVkCLds-OhesJVVyZbQ tools/xenmgr/lib/server/SrvDir.py
    1.52 +40c9c468TyHZUq8sk0FF_vxM6Sozrg tools/xenmgr/lib/server/SrvDomain.py
    1.53 +40c9c469WzajDjutou3X7FmL9hMf3g tools/xenmgr/lib/server/SrvDomainDir.py
    1.54 +40c9c469-8mYEJJTAR6w_ClrJRAfwQ tools/xenmgr/lib/server/SrvEventDir.py
    1.55 +40c9c4694eu5759Dehr4Uhakei0EMg tools/xenmgr/lib/server/SrvNode.py
    1.56 +40c9c469TaZ83ypsrktmPSHLEZiP5w tools/xenmgr/lib/server/SrvRoot.py
    1.57 +40c9c469W3sgDMbBJYQdz5wbQweL0Q tools/xenmgr/lib/server/SrvServer.py
    1.58 +40c9c469JlUVPkwGWZyVnqIsU8U6Bw tools/xenmgr/lib/server/SrvVdisk.py
    1.59 +40c9c469sG8iuyxjVH3zKw8XOAyxtQ tools/xenmgr/lib/server/SrvVdiskDir.py
    1.60 +40c9c469aq7oXrE1Ngqf3_lBqL0RoQ tools/xenmgr/lib/server/SrvVnetDir.py
    1.61 +40c9c469Y_aimoOFfUZoS-4eV8gEKg tools/xenmgr/lib/server/__init__.py
    1.62 +40c9c4692hckPol_EK0EGB16ZyDsyQ tools/xenmgr/lib/server/blkif.py
    1.63 +40c9c469N2-b3GqpLHHHPZykJPLVvA tools/xenmgr/lib/server/channel.py
    1.64 +40c9c469hJ_IlatRne-9QEa0-wlquw tools/xenmgr/lib/server/console.py
    1.65 +40c9c469UcNJh_NuLU0ytorM0Lk5Ow tools/xenmgr/lib/server/controller.py
    1.66 +40c9c469vHh-qLiiubdbKEQbJf18Zw tools/xenmgr/lib/server/cstruct.py
    1.67 +40c9c469yrm31i60pGKslTi2Zgpotg tools/xenmgr/lib/server/messages.py
    1.68 +40c9c46925x-Rjb0Cv2f1-l2jZrPYg tools/xenmgr/lib/server/netif.py
    1.69 +40c9c469ZqILEQ8x6yWy0_51jopiCg tools/xenmgr/lib/server/params.py
    1.70 +40c9c469LNxLVizOUpOjEaTKKCm8Aw tools/xenmgr/lib/sxp.py
    1.71 +40c9c469kT0H9COWzA4XzPBjWK0WsA tools/xenmgr/netfix
    1.72 +40c9c469n2RRwCmjWdjdyyVRWKmgWg tools/xenmgr/setup.py
    1.73 +40c9c4697z76HDfkCLdMhmaEwzFoNQ tools/xenmgr/xend
    1.74 +40c9c469JkN47d1oXi-e0RjAP-C6uQ tools/xenmgr/xenmgrd
    1.75  403a3edbrr8RE34gkbR40zep98SXbg tools/xentrace/Makefile
    1.76  40a107afN60pFdURgBv9KwEzgRl5mQ tools/xentrace/formats
    1.77  4050c413PhhLNAYk3TEwP37i_iLw9Q tools/xentrace/xentrace.8
     2.1 --- a/BitKeeper/etc/ignore	Fri Jun 11 14:35:29 2004 +0000
     2.2 +++ b/BitKeeper/etc/ignore	Fri Jun 11 14:40:53 2004 +0000
     2.3 @@ -30,3 +30,127 @@ linux-2.4.26-xen/.config.old
     2.4  linux-2.4.26-xen/.depend
     2.5  linux-2.4.26-xen/.hdepend
     2.6  linux-2.4.26-xen/.version
     2.7 +linux-2.4.26-xen/.config
     2.8 +linux-2.4.26-xen/COPYING
     2.9 +linux-2.4.26-xen/CREDITS
    2.10 +linux-2.4.26-xen/Documentation/00-INDEX
    2.11 +linux-2.4.26-xen/Documentation/BK-usage/00-INDEX
    2.12 +linux-2.4.26-xen/Documentation/BK-usage/bk-kernel-howto.txt
    2.13 +linux-2.4.26-xen/Documentation/BK-usage/bk-make-sum
    2.14 +linux-2.4.26-xen/Documentation/BK-usage/bksend
    2.15 +linux-2.4.26-xen/Documentation/BK-usage/bz64wrap
    2.16 +linux-2.4.26-xen/Documentation/BK-usage/cset-to-linus
    2.17 +linux-2.4.26-xen/Documentation/BK-usage/csets-to-patches
    2.18 +linux-2.4.26-xen/Documentation/BK-usage/unbz64wrap
    2.19 +linux-2.4.26-xen/Documentation/BUG-HUNTING
    2.20 +linux-2.4.26-xen/Documentation/Changes
    2.21 +linux-2.4.26-xen/Documentation/CodingStyle
    2.22 +linux-2.4.26-xen/Documentation/Configure.help
    2.23 +linux-2.4.26-xen/Documentation/DMA-mapping.txt
    2.24 +linux-2.4.26-xen/Documentation/DocBook/Makefile
    2.25 +linux-2.4.26-xen/Documentation/DocBook/deviceiobook.tmpl
    2.26 +linux-2.4.26-xen/Documentation/DocBook/journal-api.tmpl
    2.27 +linux-2.4.26-xen/Documentation/DocBook/kernel-api.tmpl
    2.28 +linux-2.4.26-xen/Documentation/DocBook/kernel-hacking.tmpl
    2.29 +linux-2.4.26-xen/Documentation/DocBook/kernel-locking.tmpl
    2.30 +linux-2.4.26-xen/Documentation/DocBook/mcabook.tmpl
    2.31 +linux-2.4.26-xen/Documentation/DocBook/mousedrivers.tmpl
    2.32 +linux-2.4.26-xen/Documentation/DocBook/parport-multi.fig
    2.33 +linux-2.4.26-xen/Documentation/DocBook/parport-share.fig
    2.34 +linux-2.4.26-xen/Documentation/DocBook/parport-structure.fig
    2.35 +linux-2.4.26-xen/Documentation/DocBook/parportbook.tmpl
    2.36 +linux-2.4.26-xen/Documentation/DocBook/procfs-guide.tmpl
    2.37 +linux-2.4.26-xen/Documentation/DocBook/procfs_example.c
    2.38 +linux-2.4.26-xen/Documentation/DocBook/sis900.tmpl
    2.39 +linux-2.4.26-xen/Documentation/DocBook/tulip-user.tmpl
    2.40 +linux-2.4.26-xen/Documentation/DocBook/via-audio.tmpl
    2.41 +linux-2.4.26-xen/Documentation/DocBook/videobook.tmpl
    2.42 +linux-2.4.26-xen/Documentation/DocBook/wanbook.tmpl
    2.43 +linux-2.4.26-xen/Documentation/DocBook/z8530book.tmpl
    2.44 +linux-2.4.26-xen/Documentation/IO-mapping.txt
    2.45 +linux-2.4.26-xen/Documentation/IPMI.txt
    2.46 +linux-2.4.26-xen/Documentation/IRQ-affinity.txt
    2.47 +linux-2.4.26-xen/Documentation/LVM-HOWTO
    2.48 +linux-2.4.26-xen/Documentation/README.DAC960
    2.49 +linux-2.4.26-xen/Documentation/README.moxa
    2.50 +linux-2.4.26-xen/Documentation/README.nsp32_cb.eng
    2.51 +linux-2.4.26-xen/Documentation/README.nsp_cs.eng
    2.52 +linux-2.4.26-xen/Documentation/SAK.txt
    2.53 +linux-2.4.26-xen/Documentation/SubmittingDrivers
    2.54 +linux-2.4.26-xen/Documentation/SubmittingPatches
    2.55 +linux-2.4.26-xen/Documentation/VGA-softcursor.txt
    2.56 +linux-2.4.26-xen/Documentation/arm/Booting
    2.57 +linux-2.4.26-xen/Documentation/arm/ConfigVars
    2.58 +linux-2.4.26-xen/Documentation/arm/MEMC
    2.59 +linux-2.4.26-xen/Documentation/arm/Netwinder
    2.60 +linux-2.4.26-xen/Documentation/arm/README
    2.61 +linux-2.4.26-xen/Documentation/arm/SA1100/ADSBitsy
    2.62 +linux-2.4.26-xen/Documentation/arm/SA1100/Assabet
    2.63 +linux-2.4.26-xen/Documentation/arm/SA1100/Brutus
    2.64 +linux-2.4.26-xen/Documentation/arm/SA1100/CERF
    2.65 +linux-2.4.26-xen/Documentation/arm/SA1100/DMA
    2.66 +linux-2.4.26-xen/Documentation/arm/SA1100/FreeBird
    2.67 +linux-2.4.26-xen/Documentation/arm/SA1100/GraphicsClient
    2.68 +linux-2.4.26-xen/Documentation/arm/SA1100/GraphicsMaster
    2.69 +linux-2.4.26-xen/Documentation/arm/SA1100/HUW_WEBPANEL
    2.70 +linux-2.4.26-xen/Documentation/arm/SA1100/Itsy
    2.71 +linux-2.4.26-xen/Documentation/arm/SA1100/LART
    2.72 +linux-2.4.26-xen/Documentation/arm/SA1100/PCMCIA
    2.73 +linux-2.4.26-xen/Documentation/arm/SA1100/PLEB
    2.74 +linux-2.4.26-xen/Documentation/arm/SA1100/Pangolin
    2.75 +linux-2.4.26-xen/Documentation/arm/SA1100/SA1100_USB
    2.76 +linux-2.4.26-xen/Documentation/arm/SA1100/Tifon
    2.77 +linux-2.4.26-xen/Documentation/arm/SA1100/Victor
    2.78 +linux-2.4.26-xen/Documentation/arm/SA1100/Yopy
    2.79 +linux-2.4.26-xen/Documentation/arm/SA1100/empeg
    2.80 +linux-2.4.26-xen/Documentation/arm/SA1100/nanoEngine
    2.81 +linux-2.4.26-xen/Documentation/arm/SA1100/serial_UART
    2.82 +linux-2.4.26-xen/Documentation/arm/Setup
    2.83 +linux-2.4.26-xen/Documentation/arm/empeg/README
    2.84 +linux-2.4.26-xen/Documentation/arm/empeg/ir.txt
    2.85 +linux-2.4.26-xen/Documentation/arm/empeg/mkdevs
    2.86 +linux-2.4.26-xen/Documentation/arm/nwfpe/NOTES
    2.87 +linux-2.4.26-xen/Documentation/arm/nwfpe/README
    2.88 +linux-2.4.26-xen/Documentation/arm/nwfpe/README.FPE
    2.89 +linux-2.4.26-xen/Documentation/arm/nwfpe/TODO
    2.90 +linux-2.4.26-xen/Documentation/binfmt_misc.txt
    2.91 +linux-2.4.26-xen/Documentation/cachetlb.txt
    2.92 +linux-2.4.26-xen/Documentation/cciss.txt
    2.93 +linux-2.4.26-xen/Documentation/cdrom/00-INDEX
    2.94 +linux-2.4.26-xen/Documentation/cdrom/Makefile
    2.95 +linux-2.4.26-xen/Documentation/cdrom/aztcd
    2.96 +linux-2.4.26-xen/Documentation/cdrom/cdrom-standard.tex
    2.97 +linux-2.4.26-xen/Documentation/cdrom/cdu31a
    2.98 +linux-2.4.26-xen/Documentation/cdrom/cm206
    2.99 +linux-2.4.26-xen/Documentation/cdrom/gscd
   2.100 +linux-2.4.26-xen/Documentation/cdrom/ide-cd
   2.101 +linux-2.4.26-xen/Documentation/cdrom/isp16
   2.102 +linux-2.4.26-xen/Documentation/cdrom/mcd
   2.103 +linux-2.4.26-xen/Documentation/cdrom/mcdx
   2.104 +linux-2.4.26-xen/Documentation/cdrom/optcd
   2.105 +linux-2.4.26-xen/Documentation/cdrom/sbpcd
   2.106 +linux-2.4.26-xen/Documentation/cdrom/sjcd
   2.107 +linux-2.4.26-xen/Documentation/cdrom/sonycd535
   2.108 +linux-2.4.26-xen/Documentation/computone.txt
   2.109 +linux-2.4.26-xen/Documentation/cpqarray.txt
   2.110 +linux-2.4.26-xen/Documentation/cris/README
   2.111 +linux-2.4.26-xen/Documentation/crypto/api-intro.txt
   2.112 +linux-2.4.26-xen/Documentation/crypto/descore-readme.txt
   2.113 +linux-2.4.26-xen/Documentation/devices.txt
   2.114 +linux-2.4.26-xen/Documentation/digiboard.txt
   2.115 +linux-2.4.26-xen/Documentation/digiepca.txt
   2.116 +linux-2.4.26-xen/Documentation/dnotify.txt
   2.117 +linux-2.4.26-xen/Documentation/exception.txt
   2.118 +linux-2.4.26-xen/Documentation/fb/00-INDEX
   2.119 +linux-2.4.26-xen/Documentation/fb/README-sstfb.txt
   2.120 +linux-2.4.26-xen/Documentation/fb/aty128fb.txt
   2.121 +linux-2.4.26-xen/Documentation/fb/clgenfb.txt
   2.122 +linux-2.4.26-xen/Documentation/fb/framebuffer.txt
   2.123 +linux-2.4.26-xen/Documentation/fb/internals.txt
   2.124 +linux-2.4.26-xen/Documentation/fb/matroxfb.txt
   2.125 +linux-2.4.26-xen/Documentation/fb/modedb.txt
   2.126 +linux-2.4.26-xen/Documentation/fb/pvr2fb.txt
   2.127 +linux-2.4.26-xen/Documentation/fb/sa1100fb.txt
   2.128 +tools/xenmgr/lib/server/blkif.py~
   2.129 +tools/xenmgr/lib/server/messages.py~
   2.130 +tools/xenmgr/lib/server/netif.py~
     3.1 --- a/tools/Makefile	Fri Jun 11 14:35:29 2004 +0000
     3.2 +++ b/tools/Makefile	Fri Jun 11 14:40:53 2004 +0000
     3.3 @@ -7,6 +7,7 @@ all:
     3.4  	$(MAKE) -C xentrace
     3.5  	$(MAKE) -C xenctl
     3.6  	$(MAKE) -C xend
     3.7 +	$(MAKE) -C xenmgr
     3.8  
     3.9  install: all
    3.10  	$(MAKE) -C balloon install
    3.11 @@ -16,6 +17,7 @@ install: all
    3.12  	$(MAKE) -C xentrace install
    3.13  	$(MAKE) -C xenctl install
    3.14  	$(MAKE) -C xend install
    3.15 +	$(MAKE) -C xenmgr install
    3.16  
    3.17  dist: $(TARGET)
    3.18  	$(MAKE) prefix=`pwd`/../../install dist=yes install
    3.19 @@ -30,4 +32,5 @@ clean:
    3.20  	$(MAKE) -C xentrace clean
    3.21  	$(MAKE) -C xenctl clean
    3.22  	$(MAKE) -C xend clean
    3.23 +	$(MAKE) -C xenmgr install
    3.24  
     4.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     4.2 +++ b/tools/examples/xm_dom_control.py	Fri Jun 11 14:40:53 2004 +0000
     4.3 @@ -0,0 +1,233 @@
     4.4 +#!/usr/bin/env python
     4.5 +
     4.6 +import sys
     4.7 +import re
     4.8 +import string
     4.9 +import time
    4.10 +import os
    4.11 +import os.path
    4.12 +import signal
    4.13 +
    4.14 +from xenmgr.XendClient import server
    4.15 +
    4.16 +# usage: xc_dom_control [command] <params>
    4.17 +#
    4.18 +# this script isn't very smart, but it'll do for now.
    4.19 +#
    4.20 +
    4.21 +def usage (rc=0):
    4.22 +    if rc:
    4.23 +        out = sys.stderr
    4.24 +    else:
    4.25 +        out = sys.stdout
    4.26 +    print >> out, """
    4.27 +Usage: %s [command] <params>
    4.28 +
    4.29 +  help                   -- print usage
    4.30 +  stop      [dom]        -- pause a domain
    4.31 +  start     [dom]        -- un-pause a domain
    4.32 +  shutdown  [dom] [[-w]] -- request a domain to shutdown (can specify 'all')
    4.33 +                            (optionally wait for complete shutdown)
    4.34 +  destroy   [dom]        -- immediately terminate a domain
    4.35 +  pincpu    [dom] [cpu]  -- pin a domain to the specified CPU
    4.36 +  suspend   [dom] [file] -- write domain's memory to a file and terminate
    4.37 +			    (resume by re-running xc_dom_create with -L option)
    4.38 +  unwatch   [dom]        -- kill the auto-restart daemon for a domain
    4.39 +  list                   -- print info about all domains
    4.40 +  listvbds               -- print info about all virtual block devs
    4.41 +  cpu_bvtset [dom] [mcuadv] [warp] [warpl] [warpu]
    4.42 +                         -- set BVT scheduling parameters for domain
    4.43 +  cpu_bvtslice [slice]   -- set default BVT scheduler slice
    4.44 +  cpu_atropos_set [dom] [period] [slice] [latency] [xtratime]
    4.45 +                         -- set Atropos scheduling parameters for domain
    4.46 +  cpu_rrobin_slice [slice] -- set Round Robin scheduler slice
    4.47 +  vif_stats [dom] [vif]  -- get stats for a given network vif
    4.48 +  vif_addip [dom] [vif] [ip]  -- add an IP address to a given vif
    4.49 +  vif_setsched [dom] [vif] [bytes] [usecs] -- rate limit vif bandwidth
    4.50 +  vif_getsched [dom] [vif] -- print vif's scheduling parameters
    4.51 +  vbd_add [dom] [uname] [dev] [mode] -- make disk/partition uname available to 
    4.52 +                            domain as dev e.g. 'vbd_add 2 phy:sda3 hda1 w'
    4.53 +  vbd_remove [dom] [dev] -- remove disk or partition attached as 'dev' 
    4.54 +""" % sys.argv[0]
    4.55 +    if rc: sys.exit(rc)
    4.56 +
    4.57 +if len(sys.argv) < 2: usage(1)
    4.58 +cmd = sys.argv[1]
    4.59 +
    4.60 +#todo: replace all uses of xc with the new api.
    4.61 +import Xc; xc = Xc.new()
    4.62 +
    4.63 +rc = ''
    4.64 +dom = None
    4.65 +
    4.66 +
    4.67 +def auto_restart_pid_file(dom):
    4.68 +    # The auto-restart daemon's pid file.
    4.69 +    return '/var/run/xendomains/%d.pid' % dom
    4.70 +
    4.71 +def auto_restart_pid(dom):
    4.72 +    watcher = auto_restart_pid_file(dom)
    4.73 +    if os.path.isfile(watcher):
    4.74 +        fd = open(watcher,'r')
    4.75 +        pid = int(fd.readline())
    4.76 +    else:
    4.77 +        pid = None
    4.78 +    return pid
    4.79 + 
    4.80 +def auto_restart_kill(dom):
    4.81 +    #todo: replace this - tell xend not to restart any more.
    4.82 +    # Kill a domain's auto restart daemon.
    4.83 +    pid = auto_restart_pid(dom)
    4.84 +    if pid:
    4.85 +        os.kill(pid, signal.SIGTERM)
    4.86 +
    4.87 +
    4.88 +if len( sys.argv ) > 2 and re.match('\d+$', sys.argv[2]):
    4.89 +    dom = long(sys.argv[2])
    4.90 +
    4.91 +if cmd == "help":
    4.92 +    usage()
    4.93 +    
    4.94 +elif cmd == 'stop':
    4.95 +    rc = server.xend_domain_stop(dom)
    4.96 +
    4.97 +elif cmd == 'start':
    4.98 +    rc = server.xend_domain_start(dom)    
    4.99 +
   4.100 +elif cmd == 'shutdown':
   4.101 +    doms = []
   4.102 +    shutdown = []
   4.103 +    if dom != None:
   4.104 +        doms = [ dom ]
   4.105 +    elif sys.argv[2] == 'all':
   4.106 +        doms = server.xend_domains()
   4.107 +        doms.remove('0')
   4.108 +    for d in doms:
   4.109 +        ret = server.xend_domain_shutdown(d)
   4.110 +        if ret == 0:
   4.111 +            shutdown.append(d)
   4.112 +        else:
   4.113 +            rc = ret
   4.114 +
   4.115 +    wait = (len(sys.argv) == 4 and sys.argv[3] == "-w")
   4.116 +    if wait:
   4.117 +        # wait for all domains we shut down to terminate
   4.118 +        for dom in shutdown:
   4.119 +            while True:
   4.120 +                info = server.xend_domain(dom)
   4.121 +                if not info: break
   4.122 +                time.sleep(1)
   4.123 +
   4.124 +elif cmd == 'destroy':
   4.125 +    rc = server.xend_domain_halt(dom)    
   4.126 +
   4.127 +elif cmd == 'pincpu':
   4.128 +    if len(sys.argv) < 4: usage(1)
   4.129 +    cpu = int(sys.argv[3])
   4.130 +    rc = server.xend_domain_pincpu(dom, cpu)
   4.131 +
   4.132 +elif cmd == 'list':
   4.133 +    print 'Dom  Name             Mem(MB)  CPU  State  Time(s)'
   4.134 +    for dom in server.xend_domains():
   4.135 +        info = server.xend_domain(dom)
   4.136 +        d = {}
   4.137 +        d['dom'] = dom
   4.138 +        d['name'] = sxp.get_child_value(info, 'name', '??')
   4.139 +        d['mem'] = int(sxp.get_child_value(info, 'memory', '0'))
   4.140 +        d['cpu'] = int(sxp.get_child_value(info, 'cpu', '0'))
   4.141 +        d['state'] = sxp.get_child_value(info, 'state', '??')
   4.142 +        d['cpu_time'] = sxp.get_child_value(info, 'cpu_time', '0')
   4.143 +        print ("%(dom)-4d %(name)-16s %(mem)7d %(cpu)3d %(state)5s %(cpu_time)8d"
   4.144 +               % d)
   4.145 +
   4.146 +elif cmd == 'unwatch':
   4.147 +    auto_restart_kill(dom)
   4.148 +
   4.149 +elif cmd == 'listvbds':
   4.150 +    print 'Dom   Dev   Mode   Size(MB)'
   4.151 +    for dom in server.xend_domains():
   4.152 +        for vbd in server.xend_domain_vbds(dom):
   4.153 +            info = server.xend_domain_vbd(vbd)
   4.154 +            v['vbd'] = vbd
   4.155 +            v['size'] = int(sxp.get_child_value(info, 'size', '0'))
   4.156 +            v['mode'] = sxp.get_child_value(info, 'mode', '??')
   4.157 +            vbd['size_mb'] = vbd['nr_sectors'] / 2048
   4.158 +            print ('%(dom)-4d  %(vbd)04x  %(mode)-2s      %(size)d' % v)
   4.159 +
   4.160 +elif cmd == 'suspend':
   4.161 +    if len(sys.argv) < 4: usage(1)
   4.162 +    file = os.path.abspath(sys.argv[3])
   4.163 +    auto_restart_kill(dom)
   4.164 +    rc = server.xend_domain_save(dom, file, progress=1)
   4.165 +
   4.166 +elif cmd == 'cpu_bvtslice':
   4.167 +    if len(sys.argv) < 3: usage(1)
   4.168 +    slice = sys.argv[2]
   4.169 +    rc = server.xend_node_cpu_bvt_slice_set(slice)
   4.170 +
   4.171 +elif cmd == 'cpu_bvtset':
   4.172 +    if len(sys.argv) < 7: usage(1)
   4.173 +    (mcuadv, warp, warpl, warpu) = map(int, sys.argv[3:7])
   4.174 +    
   4.175 +    rc = server.xend_domain_cpu_bvt_set(dom, mcuadv, warp, warpl, warpu)
   4.176 +    
   4.177 +elif cmd == 'vif_stats':
   4.178 +    if len(sys.argv) < 4: usage(1)
   4.179 +    vif = int(sys.argv[3])
   4.180 +
   4.181 +    print server.xend_domain_vif_stats(dom, vif)
   4.182 +
   4.183 +elif cmd == 'vif_addip':
   4.184 +    if len(sys.argv) < 5: usage(1)
   4.185 +    vif = int(sys.argv[3])
   4.186 +    ip  = sys.argv[4]
   4.187 +    rc = server.xend_domain_vif_addip(dom, vif, ip)
   4.188 +
   4.189 +elif cmd == 'vif_setsched':
   4.190 +    if len(sys.argv) < 6: usage(1)
   4.191 +    (vif, bytes, usecs) = map(int, sys.argv[3:6])
   4.192 +    rc = server.xend_domain_vif_scheduler_set(dom, vif, bytes, usecs)
   4.193 +
   4.194 +elif cmd == 'vif_getsched':
   4.195 +    if len(sys.argv) < 4: usage(1)
   4.196 +    vif = int(sys.argv[3])
   4.197 +    print server.xend_domain_vif_scheduler_get(dom, vif)
   4.198 +
   4.199 +elif cmd == 'vbd_add':
   4.200 +    if len(sys.argv) < 6: usage(1)
   4.201 +    uname = sys.argv[3]
   4.202 +    dev = sys.argv[4]
   4.203 +    mode = sys.argv[5]
   4.204 +    try:
   4.205 +        vbd = server.xend_domain_vbd_add(dom, uname, dev, mode)
   4.206 +    except StandardError, ex:
   4.207 +        print "Error:", ex
   4.208 +        sys.exit(1)
   4.209 +    print "Added disk/partition %s to domain %d as device %s (%x)" % (uname, dom, dev, vbd)
   4.210 +
   4.211 +elif cmd == 'vbd_remove':
   4.212 +    if len(sys.argv) < 4: usage(1)
   4.213 +    dev = sys.argv[3]
   4.214 +    vbd = server.xend_domain_vbd_remove(dom, dev)
   4.215 +    if vbd < 0:
   4.216 +	print "Failed"
   4.217 +	sys.exit(1)
   4.218 +    else:
   4.219 +	print "Removed disk/partition attached as device %s (%x) in domain %d" % (dev, vbd, dom)
   4.220 +
   4.221 +elif cmd == 'cpu_atropos_set': # args: dom period slice latency xtratime
   4.222 +    if len(sys.argv) < 6: usage(1)
   4.223 +    (period, slice, latency, xtratime) = map(int, sys.argv[3:7])
   4.224 +    rc = server.xend_domain_cpu_atropos_set(
   4.225 +        dom, period, slice, latency, xtratime)
   4.226 +
   4.227 +elif cmd == 'cpu_rrobin_slice':
   4.228 +    if len(sys.argv) < 3: usage(1)
   4.229 +    slice = int(sys.argv[2])
   4.230 +    rc = server.xend_node_rrobin_set(slice=slice)
   4.231 +
   4.232 +else:
   4.233 +    usage(1)
   4.234 +
   4.235 +if rc != '':
   4.236 +    print "return code %d" % rc
     5.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     5.2 +++ b/tools/examples/xm_dom_create.py	Fri Jun 11 14:40:53 2004 +0000
     5.3 @@ -0,0 +1,402 @@
     5.4 +#!/usr/bin/env python
     5.5 +
     5.6 +import string
     5.7 +import sys
     5.8 +import os
     5.9 +import os.path
    5.10 +import time
    5.11 +import socket
    5.12 +import getopt
    5.13 +import signal
    5.14 +import syslog
    5.15 +
    5.16 +import xenctl.console_client
    5.17 +
    5.18 +from xenmgr import sxp
    5.19 +from xenmgr import PrettyPrint
    5.20 +from xenmgr.XendClient import server
    5.21 +
    5.22 +config_dir  = '/etc/xc/'
    5.23 +config_file = xc_config_file = config_dir + 'defaults'
    5.24 +
    5.25 +def main_usage ():
    5.26 +    print >>sys.stderr,"""
    5.27 +Usage: %s <args>
    5.28 +
    5.29 +This tool is used to create and start new domains. It reads defaults
    5.30 +from a file written in Python, having allowed variables to be set and
    5.31 +passed into the file. Further command line arguments allow the
    5.32 +defaults to be overridden. The defaults for each parameter are listed
    5.33 +in [] brackets. Arguments are as follows:
    5.34 +
    5.35 +Arguments to control the parsing of the defaults file:
    5.36 + -f config_file   -- Use the specified defaults script. 
    5.37 +                     Default: ['%s']
    5.38 + -L state_file    -- Load virtual machine memory state from state_file
    5.39 + -D foo=bar       -- Set variable foo=bar before parsing config
    5.40 +                     E.g. '-D vmid=3;ip=1.2.3.4'
    5.41 + -h               -- Print extended help message, including all arguments
    5.42 + -n               -- Dry run only, don't actually create domain
    5.43 +                     Prints the config, suitable for -F.
    5.44 + -q               -- Quiet - write output only to the system log
    5.45 + -F domain_config -- Build domain using the config in the file.
    5.46 +                     Suitable files can be made using '-n' to output a config.
    5.47 +""" % (sys.argv[0], xc_config_file)
    5.48 +
    5.49 +def extra_usage ():
    5.50 +    print >>sys.stderr,"""
    5.51 +Arguments to override current config read from '%s':
    5.52 + -c               -- Turn into console terminal after domain is created
    5.53 + -k image         -- Path to kernel image ['%s']
    5.54 + -r ramdisk       -- Path to ramdisk (or empty) ['%s']
    5.55 + -b builder_fn    -- Function to use to build domain ['%s']
    5.56 + -m mem_size      -- Initial memory allocation in MB [%dMB]
    5.57 + -N domain_name   -- Set textual name of domain ['%s']
    5.58 + -a auto_restart  -- Restart domain on exit, yes/no ['%d']
    5.59 + -e vbd_expert    -- Safety catch to avoid some disk accidents ['%s'] 
    5.60 + -d udisk,dev,rw  -- Add disk, partition, or virtual disk to domain. E.g. to 
    5.61 +                     make partion sda4 available to the domain as hda1 with 
    5.62 +                     read-write access: '-d phy:sda4,hda1,rw' To add 
    5.63 +                     multiple disks use multiple -d flags or seperate with ';'
    5.64 +                     Default: ['%s']
    5.65 + -i vfr_ipaddr    -- Add IP address to the list which Xen will route to
    5.66 +                     the domain. Use multiple times to add more IP addrs.
    5.67 +		     Default: ['%s']
    5.68 +
    5.69 +Args to override the kernel command line, which is concatenated from these:
    5.70 + -I cmdline_ip    -- Override 'ip=ipaddr:nfsserv:gateway:netmask::eth0:off'
    5.71 +                     Default: ['%s']
    5.72 + -R cmdline_root  -- Override root device parameters.
    5.73 +                     Default: ['%s']
    5.74 + -E cmdline_extra -- Override extra kernel args and rc script env vars.
    5.75 +                     Default: ['%s']
    5.76 +
    5.77 +""" % (config_file,
    5.78 +       image, ramdisk, builder_fn, mem_size, domain_name, auto_restart,
    5.79 +       vbd_expert, 
    5.80 +       printvbds( vbd_list ), 
    5.81 +       reduce ( (lambda a,b: a+':'+b), vfr_ipaddr,'' )[1:],
    5.82 +       cmdline_ip, cmdline_root, cmdline_extra)
    5.83 +
    5.84 +def config_usage (): pass
    5.85 +
    5.86 +def answer ( s ):
    5.87 +    s = string.lower(s)
    5.88 +    if s == 'yes' or s == 'true' or s == '1': return 1
    5.89 +    return 0
    5.90 +
    5.91 +def printvbds ( v ):
    5.92 +    s=''
    5.93 +    for (a,b,c) in v:
    5.94 +	s = s + '; %s,%s,%s' % (a,b,c)
    5.95 +    return s[2:]
    5.96 +
    5.97 +def output(string):
    5.98 +    global quiet
    5.99 +    syslog.syslog(string)
   5.100 +    if not quiet:
   5.101 +        print string
   5.102 +    return
   5.103 +
   5.104 +bail=False; dryrun=False; extrahelp=False; quiet = False
   5.105 +image=''; ramdisk=''; builder_fn='linux'; restore=0; state_file=''
   5.106 +mem_size=0; domain_name=''; vfr_ipaddr=[];
   5.107 +vbd_expert='rr'; auto_restart=False;
   5.108 +vbd_list = []; cmdline_ip = ''; cmdline_root=''; cmdline_extra=''
   5.109 +pci_device_list = []; console_port = -1
   5.110 +auto_console = False
   5.111 +config_from_file = False
   5.112 +
   5.113 +##### Determine location of defaults file
   5.114 +#####
   5.115 +
   5.116 +try:
   5.117 +    opts, args = getopt.getopt(sys.argv[1:], "h?nqcf:F:D:k:r:b:m:N:a:e:d:i:I:R:E:L:" )
   5.118 +
   5.119 +    for opt in opts:
   5.120 +	if opt[0] == '-f': config_file= opt[1]
   5.121 +	if opt[0] == '-h' or opt[0] == '-?' : bail=True; extrahelp=True
   5.122 +	if opt[0] == '-n': dryrun=True
   5.123 +	if opt[0] == '-D': 
   5.124 +	    for o in string.split( opt[1], ';' ):
   5.125 +		(l,r) = string.split( o, '=' )
   5.126 +		exec "%s='%s'" % (l,r)
   5.127 +        if opt[0] == '-q': quiet = True
   5.128 +        if opt[0] == '-L': restore = True; state_file = opt[1]
   5.129 +        if opt[0] == '-F': config_from_file = True; domain_config = opt[1]
   5.130 +
   5.131 +
   5.132 +except getopt.GetoptError:
   5.133 +    bail=True
   5.134 +
   5.135 +if not config_from_file:
   5.136 +    try:
   5.137 +        os.stat( config_file )
   5.138 +    except:
   5.139 +        try:
   5.140 +            d = config_dir + config_file
   5.141 +            os.stat( d )
   5.142 +            config_file = d
   5.143 +        except:
   5.144 +            print >> sys.stderr, "Unable to open config file '%s'" % config_file
   5.145 +            bail = True
   5.146 +
   5.147 +
   5.148 +##### Parse the config file
   5.149 +#####
   5.150 +
   5.151 +if not config_from_file:
   5.152 +    if not quiet:
   5.153 +        print "Parsing config file '%s'" % config_file
   5.154 +
   5.155 +    try:
   5.156 +        execfile ( config_file )
   5.157 +    except (AssertionError,IOError):
   5.158 +        print >>sys.stderr,"Exiting %s" % sys.argv[0]
   5.159 +        bail = True
   5.160 +
   5.161 +##### Print out config if necessary 
   5.162 +##### 
   5.163 +
   5.164 +def bailout():
   5.165 +    global extrahelp
   5.166 +    main_usage()
   5.167 +    config_usage()
   5.168 +    if extrahelp: extra_usage()
   5.169 +    sys.exit(1)
   5.170 +
   5.171 +if bail:
   5.172 +    bailout()
   5.173 +
   5.174 +##### Parse any command line overrides 
   5.175 +##### 
   5.176 +
   5.177 +x_vbd_list = []
   5.178 +x_vfr_ipaddr  = []
   5.179 +
   5.180 +for opt in opts:
   5.181 +    if opt[0] == '-k': image = opt[1]
   5.182 +    if opt[0] == '-r': ramdisk = opt[1]
   5.183 +    if opt[0] == '-b': builder_fn = opt[1]  
   5.184 +    if opt[0] == '-m': mem_size = int(opt[1])
   5.185 +    if opt[0] == '-C': cpu = int(opt[1])
   5.186 +    if opt[0] == '-N': domain_name = opt[1]
   5.187 +    if opt[0] == '-a': auto_restart = answer(opt[1])
   5.188 +    if opt[0] == '-e': vbd_expert = opt[1]
   5.189 +    if opt[0] == '-I': cmdline_ip = opt[1]
   5.190 +    if opt[0] == '-R': cmdline_root = opt[1]
   5.191 +    if opt[0] == '-E': cmdline_extra = opt[1]
   5.192 +    if opt[0] == '-i': x_vfr_ipaddr.append(opt[1])
   5.193 +    if opt[0] == '-c': auto_console = True
   5.194 +    if opt[0] == '-d':
   5.195 +	try:
   5.196 +	    vv = string.split(opt[1],';')	    
   5.197 +	    for v in vv:
   5.198 +		(udisk,dev,mode) = string.split(v,',')
   5.199 +		x_vbd_list.append( (udisk,dev,mode) )
   5.200 +	except:
   5.201 +	    print >>sys.stderr, "Invalid block device specification : %s" % opt[1]
   5.202 +	    sys.exit(1)
   5.203 +
   5.204 +if x_vbd_list: vbd_list = x_vbd_list
   5.205 +if x_vfr_ipaddr: vfr_ipaddr = x_vfr_ipaddr
   5.206 +
   5.207 +syslog.openlog('xc_dom_create.py %s' % config_file, 0, syslog.LOG_DAEMON)
   5.208 +
   5.209 +def strip(pre, s):
   5.210 +    if s.startswith(pre):
   5.211 +        return s[len(pre):]
   5.212 +    else:
   5.213 +        return s
   5.214 +
   5.215 +def make_domain_config():
   5.216 +    global builder_fn, image, ramdisk, mem_size, domain_name
   5.217 +    global cpu
   5.218 +    global cmdline, cmdline_ip, cmdline_root
   5.219 +    global vfr_ipaddr, vbd_list, vbd_expert
   5.220 +    
   5.221 +    config = ['config',
   5.222 +              ['name', domain_name ],
   5.223 +              ['memory', mem_size ],
   5.224 +              ]
   5.225 +    if cpu:
   5.226 +        config.append(['cpu', cpu])
   5.227 +    
   5.228 +    config_image = [ builder_fn ]
   5.229 +    config_image.append([ 'kernel', os.path.abspath(image) ])
   5.230 +    if ramdisk:
   5.231 +        config_image.append([ 'ramdisk', os.path.abspath(ramdisk) ])
   5.232 +    if cmdline_ip:
   5.233 +        cmdline_ip = strip("ip=", cmdline_ip)
   5.234 +        config_image.append(['ip', cmdline_ip])
   5.235 +    if cmdline_root:
   5.236 +        cmdline_root = strip("root=", cmdline_root)
   5.237 +        config_image.append(['root', cmdline_root])
   5.238 +    if cmdline_extra:
   5.239 +        config_image.append(['args', cmdline_extra])
   5.240 +    config.append(['image', config_image ])
   5.241 +    	
   5.242 +    config_devs = []
   5.243 +    for (uname, dev, mode) in vbd_list:
   5.244 +        config_vbd = ['vbd',
   5.245 +                      ['uname', uname],
   5.246 +                      ['dev', dev ],
   5.247 +                      ['mode', mode ] ]
   5.248 +        if vbd_expert != 'rr':
   5.249 +            config_vbd.append(['sharing', vbd_expert])
   5.250 +        config_devs.append(['device', config_vbd])
   5.251 +
   5.252 +    for (bus, dev, func) in pci_device_list:
   5.253 +        config_pci = ['pci',
   5.254 +                      ['bus', bus ],
   5.255 +                      ['dev', dev ],
   5.256 +                      ['func', func] ]
   5.257 +        config_devs.append(['device', config_pci])
   5.258 +
   5.259 +    config += config_devs
   5.260 +    
   5.261 +    config_vfr = ['vfr']
   5.262 +    idx = 0 # No way of saying which IP is for which vif?
   5.263 +    for ip in vfr_ipaddr:
   5.264 +        config_vfr.append(['vif', ['id', idx], ['ip', ip]])
   5.265 +
   5.266 +    config.append(config_vfr)
   5.267 +    return config
   5.268 +
   5.269 +def parse_config_file(domain_file):
   5.270 +    config = None
   5.271 +    fin = None
   5.272 +    try:
   5.273 +        fin = file(domain_file, "rb")
   5.274 +        config = sxp.parse(fin)
   5.275 +        if len(config) >= 1:
   5.276 +            config = config[0]
   5.277 +        else:
   5.278 +            raise StandardError("Invalid configuration")
   5.279 +    except StandardError, ex:
   5.280 +        print >> sys.stderr, "Error :", ex
   5.281 +        sys.exit(1)
   5.282 +    #finally:
   5.283 +    if fin: fin.close()
   5.284 +    return config
   5.285 +
   5.286 +# This function creates, builds and starts a domain, using the values
   5.287 +# in the global variables, set above.  It is used in the subsequent
   5.288 +# code for starting the new domain and rebooting it if appropriate.
   5.289 +def make_domain(config):
   5.290 +    """Create, build and start a domain.
   5.291 +    Returns: [int] the ID of the new domain.
   5.292 +    """
   5.293 +    global restore
   5.294 +
   5.295 +    if restore:
   5.296 +        dominfo = server.xend_domain_restore(state_file, config)
   5.297 +    else:
   5.298 +        dominfo = server.xend_domain_create(config)
   5.299 +
   5.300 +    dom = int(sxp.child_value(dominfo, 'id'))
   5.301 +    console_info = sxp.child(dominfo, 'console')
   5.302 +    if console_info:
   5.303 +        console_port = int(sxp.child_value(console_info, 'port'))
   5.304 +    else:
   5.305 +        console_port = None
   5.306 +    
   5.307 +    if server.xend_domain_start(dom) < 0:
   5.308 +        print "Error starting domain"
   5.309 +        server.xend_domain_halt(dom)
   5.310 +        sys.exit()
   5.311 +
   5.312 +    return (dom, console_port)
   5.313 +
   5.314 +PID_DIR = '/var/run/xendomains/'
   5.315 +
   5.316 +def pidfile(dom):
   5.317 +    return PID_DIR + '%d.pid' % dom
   5.318 +
   5.319 +def mkpidfile():
   5.320 +    global current_id
   5.321 +    if not os.path.isdir(PID_DIR):
   5.322 +        os.mkdir(PID_DIR)
   5.323 +
   5.324 +    fd = open(pidfile(current_id), 'w')
   5.325 +    print >> fd, str(os.getpid())
   5.326 +    fd.close()
   5.327 +    return
   5.328 +
   5.329 +def rmpidfile():
   5.330 +    global current_id
   5.331 +    os.unlink(pidfile(current_id))
   5.332 +
   5.333 +def death_handler(dummy1,dummy2):
   5.334 +    global current_id
   5.335 +    os.unlink(pidfile(current_id))
   5.336 +    output('Auto-restart daemon: daemon PID = %d for domain %d is now exiting'
   5.337 +              % (os.getpid(), current_id))
   5.338 +    sys.exit(0)
   5.339 +    return
   5.340 +
   5.341 +#============================================================================
   5.342 +# The starting / monitoring of the domain actually happens here...
   5.343 +
   5.344 +if config_from_file:
   5.345 +    config = parse_config_file(domain_config)
   5.346 +else:
   5.347 +    config = make_domain_config()
   5.348 +
   5.349 +if dryrun:
   5.350 +    print "# %s" % ' '.join(sys.argv)
   5.351 +    PrettyPrint.prettyprint(config)
   5.352 +    sys.exit(0)
   5.353 +elif quiet:
   5.354 +    pass
   5.355 +else:
   5.356 +    PrettyPrint.prettyprint(config)
   5.357 +
   5.358 +# start the domain and record its ID number
   5.359 +(current_id, current_port) = make_domain(config)
   5.360 +
   5.361 +def start_msg(prefix, dom, port):
   5.362 +    output(prefix + "VM started in domain %d" % dom)
   5.363 +    if port:
   5.364 +        output(prefix + "Console I/O available on TCP port %d." % port)
   5.365 +
   5.366 +start_msg('', current_id, current_port)
   5.367 +
   5.368 +if current_port and auto_console:
   5.369 +    xenctl.console_client.connect('127.0.0.1', current_port)
   5.370 +
   5.371 +# if the auto_restart flag is set then keep polling to see if the domain is
   5.372 +# alive - restart if it is not by calling make_domain() again (it's necessary
   5.373 +# to update the id variable, since the new domain may have a new ID)
   5.374 +
   5.375 +#todo: Replace this - get xend to watch them.
   5.376 +if auto_restart:
   5.377 +    ARD = "Auto-restart daemon: "
   5.378 +    # turn ourselves into a background daemon
   5.379 +    try:
   5.380 +	pid = os.fork()
   5.381 +	if pid > 0:
   5.382 +	    sys.exit(0)
   5.383 +	os.setsid()
   5.384 +	pid = os.fork()
   5.385 +	if pid > 0:
   5.386 +            output(ARD + 'PID = %d' % pid)
   5.387 +	    sys.exit(0)
   5.388 +        signal.signal(signal.SIGTERM,death_handler)
   5.389 +    except OSError:
   5.390 +	print >> sys.stderr, ARD+'Startup failed'
   5.391 +	sys.exit(1)
   5.392 +
   5.393 +    mkpidfile()
   5.394 +
   5.395 +    while True:
   5.396 +	time.sleep(1)
   5.397 +        # todo: use new interface
   5.398 +        info = xc.domain_getinfo(current_id, 1)
   5.399 +	if info == [] or info[0]['dom'] != current_id:
   5.400 +	    output(ARD + "Domain %d terminated, restarting VM in new domain"
   5.401 +                                     % current_id)
   5.402 +            rmpidfile()
   5.403 +	    (current_id, current_port) = make_domain()
   5.404 +            mkpidfile()
   5.405 +            start_msg(ARD, current_id, current_port)
     6.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     6.2 +++ b/tools/examples/xm_vd_tool.py	Fri Jun 11 14:40:53 2004 +0000
     6.3 @@ -0,0 +1,157 @@
     6.4 +#!/usr/bin/env python
     6.5 +
     6.6 +import sys
     6.7 +import re
     6.8 +import string
     6.9 +
    6.10 +from xenctl import vdisk
    6.11 +
    6.12 +def usage():
    6.13 +
    6.14 +    print >>sys.stderr,"""
    6.15 +Usage: %s command <params>
    6.16 +
    6.17 +  initialise [dev] [[ext_size]] - init. a physcial partition to store vd's
    6.18 +  create [size] [[expiry]]      - allocate a vd of specified size (and expiry)
    6.19 +  enlarge [vdid] [extra_size]   - enlarge a specified vd by some amount
    6.20 +  delete [vdid]                 - delete a vd
    6.21 +  import [filename] [[expiry]]  - create a vd and populate w/ image from file
    6.22 +  export [vdid] [filename]      - copy vd's contents to a file
    6.23 +  setexpiry [vdid] [[expiry]]   - update the expiry time for a vd
    6.24 +  list                          - list all the unexpired virtual disks  
    6.25 +  undelete [vdid] [[expiry]]    - attempts to recover an expired vd
    6.26 +  freespace                     - print out the amount of space in free pool
    6.27 +
    6.28 +notes:
    6.29 +  vdid      - the virtual disk's identity string
    6.30 +  size      - measured in MB
    6.31 +  expiry    - is the expiry time of the virtual disk in seconds from now
    6.32 +               (0 = don't expire) 
    6.33 +  device    - physical partition to 'format' to hold vd's. e.g. hda4
    6.34 +  ext_size  - extent size (default 64MB)
    6.35 +""" % sys.argv[0]  
    6.36 +
    6.37 +if len(sys.argv) < 2: 
    6.38 +    usage()
    6.39 +    sys.exit(-1)
    6.40 +
    6.41 +rc=''
    6.42 +src=''
    6.43 +expiry_time = 0
    6.44 +cmd = sys.argv[1]
    6.45 +
    6.46 +if cmd == 'initialise':
    6.47 +
    6.48 +    dev = sys.argv[2]
    6.49 +
    6.50 +    if len(sys.argv) > 3:
    6.51 +	extent_size = int(sys.argv[3])
    6.52 +    else:
    6.53 +	print """No extent size specified - using default size of 64MB"""
    6.54 +	extent_size = 64
    6.55 +
    6.56 +    print "Formatting for virtual disks"
    6.57 +    print "Device: " + dev
    6.58 +    print "Extent size: " + str(extent_size) + "MB"
    6.59 +
    6.60 +    rc = vdisk.vd_format(dev, extent_size)
    6.61 +
    6.62 +elif cmd == 'create':
    6.63 + 
    6.64 +    size = int(sys.argv[2])
    6.65 +    
    6.66 +    if len(sys.argv) > 3:
    6.67 +	expiry_time = int(sys.argv[3])
    6.68 +
    6.69 +    print "Creating a virtual disk"
    6.70 +    print "Size: %d" % size
    6.71 +    print "Expiry time (seconds from now): %d" % expiry_time
    6.72 +
    6.73 +    src = vdisk.vd_create(size, expiry_time)
    6.74 +
    6.75 +elif cmd == 'enlarge':
    6.76 +
    6.77 +    id = sys.argv[2]
    6.78 +
    6.79 +    extra_size = int(sys.argv[3])
    6.80 +
    6.81 +    rc = vdisk.vd_enlarge(id, extra_size)
    6.82 +
    6.83 +elif cmd == 'delete':
    6.84 +
    6.85 +    id = sys.argv[2]
    6.86 +
    6.87 +    print "Deleting a virtual disk with ID: " + id
    6.88 +
    6.89 +    rc = vdisk.vd_delete(id)
    6.90 +
    6.91 +elif cmd == 'import':
    6.92 +
    6.93 +    file = sys.argv[2]
    6.94 +    
    6.95 +    if len(sys.argv) > 3:
    6.96 +	expiry_time = int(sys.argv[3])
    6.97 +
    6.98 +    print "Allocate new virtual disk and populate from file : %s" % file
    6.99 +
   6.100 +    print vdisk.vd_read_from_file(file, expiry_time)
   6.101 +
   6.102 +elif cmd == 'export':
   6.103 +
   6.104 +    id = sys.argv[2]
   6.105 +    file = sys.argv[3]
   6.106 +
   6.107 +    print "Dump contents of virtual disk to file : %s" % file
   6.108 +
   6.109 +    rc = vdisk.vd_cp_to_file(id, file )
   6.110 +
   6.111 +elif cmd == 'setexpiry':
   6.112 +
   6.113 +    id = sys.argv[2]
   6.114 +
   6.115 +    if len(sys.argv) > 3:
   6.116 +	expiry_time = int(sys.argv[3])
   6.117 +
   6.118 +    print "Refreshing a virtual disk"
   6.119 +    print "Id: " + id
   6.120 +    print "Expiry time (seconds from now [or 0]): " + str(expiry_time)
   6.121 +
   6.122 +    rc = vdisk.vd_refresh(id, expiry_time)
   6.123 +
   6.124 +elif cmd == 'list':
   6.125 +    print 'ID    Size(MB)      Expiry'
   6.126 +
   6.127 +    for vbd in vdisk.vd_list():
   6.128 +        vbd['size_mb'] = vbd['size'] / vdisk.VBD_SECTORS_PER_MB
   6.129 +        vbd['expiry'] = (vbd['expires'] and vbd['expiry_time']) or 'never'
   6.130 +        print '%(vdisk_id)-4s  %(size_mb)-12d  %(expiry)s' % vbd
   6.131 +
   6.132 +elif cmd == 'freespace':
   6.133 +
   6.134 +    print vdisk.vd_freespace()
   6.135 +
   6.136 +elif cmd == 'undelete':
   6.137 +
   6.138 +    id = sys.argv[2]
   6.139 +
   6.140 +    if len(sys.argv) > 3:
   6.141 +	expiry_time = int(sys.argv[3])
   6.142 +   
   6.143 +    if vdisk.vd_undelete(id, expiry_time):
   6.144 +	print "Undelete operation failed for virtual disk: " + id
   6.145 +    else:
   6.146 +	print "Undelete operation succeeded for virtual disk: " + id
   6.147 +
   6.148 +else:
   6.149 +    usage()
   6.150 +    sys.exit(-1)
   6.151 +
   6.152 +
   6.153 +if src != '':  
   6.154 +    print "Returned virtual disk id is : %s" % src
   6.155 +
   6.156 +if rc != '':
   6.157 +    print "return code %d" % rc
   6.158 +
   6.159 +
   6.160 +
     7.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     7.2 +++ b/tools/xenctl/lib/ip.py	Fri Jun 11 14:40:53 2004 +0000
     7.3 @@ -0,0 +1,95 @@
     7.4 +import os
     7.5 +import re
     7.6 +import socket
     7.7 +import struct
     7.8 +
     7.9 +##### Networking-related functions
    7.10 +
    7.11 +def get_current_ipaddr(dev='eth0'):
    7.12 +    """Return a string containing the primary IP address for the given
    7.13 +    network interface (default 'eth0').
    7.14 +    """
    7.15 +    fd = os.popen( '/sbin/ifconfig ' + dev + ' 2>/dev/null' )
    7.16 +    lines = readlines(fd)
    7.17 +    for line in lines:
    7.18 +        m = re.search( '^\s+inet addr:([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+).*',
    7.19 +                       line )
    7.20 +        if m:
    7.21 +            return m.group(1)
    7.22 +    return None
    7.23 +
    7.24 +def get_current_ipmask(dev='eth0'):
    7.25 +    """Return a string containing the primary IP netmask for the given
    7.26 +    network interface (default 'eth0').
    7.27 +    """
    7.28 +    fd = os.popen( '/sbin/ifconfig ' + dev + ' 2>/dev/null' )
    7.29 +    lines = readlines(fd)
    7.30 +    for line in lines:
    7.31 +        m = re.search( '^.+Mask:([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+).*',
    7.32 +                       line )
    7.33 +        if m:
    7.34 +            return m.group(1)
    7.35 +    return None
    7.36 +
    7.37 +def get_current_ipgw(dev='eth0'):
    7.38 +    """Return a string containing the IP gateway for the given
    7.39 +    network interface (default 'eth0').
    7.40 +    """
    7.41 +    fd = os.popen( '/sbin/route -n' )
    7.42 +    lines = readlines(fd)
    7.43 +    for line in lines:
    7.44 +        m = re.search( '^\S+\s+([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)' +
    7.45 +                       '\s+\S+\s+\S*G.*' + dev + '.*', line )
    7.46 +        if m:
    7.47 +            return m.group(1)
    7.48 +    return None
    7.49 +
    7.50 +def setup_vfr_rules_for_vif(dom,vif,addr):
    7.51 +    """Takes a tuple ( domain-id, vif-id, ip-addr ), where the ip-addr
    7.52 +    is expressed as a textual dotted quad, and set up appropriate routing
    7.53 +    rules in Xen. No return value.
    7.54 +    """
    7.55 +    fd = os.open( '/proc/xen/vfr', os.O_WRONLY )
    7.56 +    if ( re.search( '169\.254', addr) ):
    7.57 +        os.write( fd, 'ADD ACCEPT srcaddr=' + addr +
    7.58 +                  ' srcaddrmask=255.255.255.255' +
    7.59 +                  ' srcdom=' + str(dom) + ' srcidx=' + str(vif) +
    7.60 +                  ' dstdom=0 dstidx=0 proto=any\n' )
    7.61 +    else:
    7.62 +        os.write( fd, 'ADD ACCEPT srcaddr=' + addr +
    7.63 +                  ' srcaddrmask=255.255.255.255' +
    7.64 +                  ' srcdom=' + str(dom) + ' srcidx=' + str(vif) +
    7.65 +                  ' dst=PHYS proto=any\n' )
    7.66 +    os.write( fd, 'ADD ACCEPT dstaddr=' + addr +
    7.67 +              ' dstaddrmask=255.255.255.255' +
    7.68 +              ' src=ANY' +
    7.69 +              ' dstdom=' + str(dom) + ' dstidx=' + str(vif) +
    7.70 +              ' proto=any\n' )
    7.71 +    os.close( fd )
    7.72 +    return None
    7.73 +
    7.74 +def inet_aton(addr):
    7.75 +    """Convert an IP addr in IPv4 dot notation into an int.
    7.76 +    """
    7.77 +    b = socket.inet_aton(addr)
    7.78 +    return struct.unpack('!I', b)[0]
    7.79 +
    7.80 +def inet_ntoa(n):
    7.81 +    """Convert an int into an IP addr in IPv4 dot notation.
    7.82 +    """
    7.83 +    b = struct.pack('!I', n)
    7.84 +    return socket.inet_ntoa(b)
    7.85 +
    7.86 +def add_offset_to_ip(addr, offset):
    7.87 +    """Add a numerical offset to an IP addr in IPv4 dot notation.
    7.88 +    """
    7.89 +    n = inet_aton(addr)
    7.90 +    n += offset
    7.91 +    return inet_ntoa(n)
    7.92 +
    7.93 +def check_subnet( ip, network, netmask ):
    7.94 +    n_ip = inet_aton(ip)
    7.95 +    n_net = inet_aton(network)
    7.96 +    n_mask = inet_aton(netmask)
    7.97 +    return (n_ip & n_mask) == (n_net & n_mask)
    7.98 +
     8.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     8.2 +++ b/tools/xenctl/lib/vdisk.py	Fri Jun 11 14:40:53 2004 +0000
     8.3 @@ -0,0 +1,944 @@
     8.4 +import os
     8.5 +import re
     8.6 +import socket
     8.7 +import string
     8.8 +import sys
     8.9 +import tempfile
    8.10 +import struct
    8.11 +
    8.12 +##### Module variables
    8.13 +
    8.14 +"""Location of the Virtual Disk management database.
    8.15 +   defaults to /var/db/xen_vdisks.sqlite
    8.16 +"""
    8.17 +VD_DB_FILE = "/var/db/xen_vdisks.sqlite"
    8.18 +
    8.19 +"""VBD expertise level - determines the strictness of the sanity checking.
    8.20 +  This mode determines the level of complaints when disk sharing occurs
    8.21 +  through the current VBD mappings.
    8.22 +   0 - only allow shared mappings if both domains have r/o access (always OK)
    8.23 +   1 - also allow sharing with one dom r/w and the other r/o
    8.24 +   2 - allow sharing with both doms r/w
    8.25 +"""
    8.26 +VBD_SAFETY_RR = 0
    8.27 +VBD_SAFETY_RW = 1
    8.28 +VBD_SAFETY_WW = 2
    8.29 +
    8.30 +VBD_SECTORS_PER_MB = 2048
    8.31 +
    8.32 +##### Module initialisation
    8.33 +
    8.34 +try:
    8.35 +    # try to import sqlite (not everyone will have it installed)
    8.36 +    import sqlite
    8.37 +except ImportError:
    8.38 +    # on failure, just catch the error, don't do anything
    8.39 +    pass
    8.40 +
    8.41 +
    8.42 +
    8.43 +##### VBD-related Functions
    8.44 +
    8.45 +def blkdev_name_to_number(name):
    8.46 +    """Take the given textual block-device name (e.g., '/dev/sda1',
    8.47 +    'hda') and return the device number used by the OS. """
    8.48 +
    8.49 +    if not re.match( '/dev/', name ):
    8.50 +        name = '/dev/' + name
    8.51 +        
    8.52 +    return os.stat(name).st_rdev
    8.53 +
    8.54 +# lookup_blkdev_partn_info( '/dev/sda3' )
    8.55 +def lookup_raw_partn(partition):
    8.56 +    """Take the given block-device name (e.g., '/dev/sda1', 'hda')
    8.57 +    and return a dictionary { device, start_sector,
    8.58 +    nr_sectors, type }
    8.59 +        device:       Device number of the given partition
    8.60 +        start_sector: Index of first sector of the partition
    8.61 +        nr_sectors:   Number of sectors comprising this partition
    8.62 +        type:         'Disk' or identifying name for partition type
    8.63 +    """
    8.64 +
    8.65 +    if not re.match( '/dev/', partition ):
    8.66 +        partition = '/dev/' + partition
    8.67 +
    8.68 +    drive = re.split( '[0-9]', partition )[0]
    8.69 +
    8.70 +    if drive == partition:
    8.71 +        fd = os.popen( '/sbin/sfdisk -s ' + drive + ' 2>/dev/null' )
    8.72 +        line = readline(fd)
    8.73 +        if line:
    8.74 +            return [ { 'device' : blkdev_name_to_number(drive),
    8.75 +                       'start_sector' : long(0),
    8.76 +                       'nr_sectors' : long(line) * 2,
    8.77 +                       'type' : 'Disk' } ]
    8.78 +        return None
    8.79 +
    8.80 +    # determine position on disk
    8.81 +    fd = os.popen( '/sbin/sfdisk -d ' + drive + ' 2>/dev/null' )
    8.82 +
    8.83 +    #['/dev/sda3 : start= 16948575, size=16836120, Id=83, bootable\012']
    8.84 +    lines = readlines(fd)
    8.85 +    for line in lines:
    8.86 +        m = re.search( '^' + partition + '\s*: start=\s*([0-9]+), ' +
    8.87 +                       'size=\s*([0-9]+), Id=\s*(\S+).*$', line)
    8.88 +        if m:
    8.89 +            return [ { 'device' : blkdev_name_to_number(drive),
    8.90 +                       'start_sector' : long(m.group(1)),
    8.91 +                       'nr_sectors' : long(m.group(2)),
    8.92 +                       'type' : m.group(3) } ]
    8.93 +    
    8.94 +    return None
    8.95 +
    8.96 +def lookup_disk_uname( uname ):
    8.97 +    """Lookup a list of segments for either a physical or a virtual device.
    8.98 +    uname [string]:  name of the device in the format \'vd:id\' for a virtual
    8.99 +                     disk, or \'phy:dev\' for a physical device
   8.100 +    returns [list of dicts]: list of extents that make up the named device
   8.101 +    """
   8.102 +    ( type, d_name ) = string.split( uname, ':' )
   8.103 +
   8.104 +    if type == "phy":
   8.105 +        segments = lookup_raw_partn( d_name )
   8.106 +    elif type == "vd":
   8.107 +	segments = vd_lookup( d_name )
   8.108 +
   8.109 +    return segments
   8.110 +
   8.111 +
   8.112 +##### VD Management-related functions
   8.113 +
   8.114 +##### By Mark Williamson, <mark.a.williamson@intel.com>
   8.115 +##### (C) Intel Research Cambridge
   8.116 +
   8.117 +# TODO:
   8.118 +#
   8.119 +# Plenty of room for enhancement to this functionality (contributions
   8.120 +# welcome - and then you get to have your name in the source ;-)...
   8.121 +#
   8.122 +# vd_unformat() : want facilities to unallocate virtual disk
   8.123 +# partitions, possibly migrating virtual disks of them, with checks to see if
   8.124 +# it's safe and options to force it anyway
   8.125 +#
   8.126 +# vd_create() : should have an optional argument specifying a physical
   8.127 +# disk preference - useful to allocate for guest doms to do RAID
   8.128 +#
   8.129 +# vd_undelete() : add ability to "best effort" undelete as much of a
   8.130 +# vdisk as is left in the case that some of it has already been
   8.131 +# reallocated.  Some people might still be able to recover some of
   8.132 +# their data this way, even if some of the disk has disappeared.
   8.133 +#
   8.134 +# It'd be nice if we could wipe virtual disks for security purposes -
   8.135 +# should be easy to do this using dev if=/dev/{zero,random} on each
   8.136 +# extent in turn.  There could be another optional flag to vd_create
   8.137 +# in order to allow this.
   8.138 +#
   8.139 +# Error codes could be more expressive - i.e. actually tell why the
   8.140 +# error occurred rather than "it broke".  Currently the code avoids
   8.141 +# using exceptions to make control scripting simpler and more
   8.142 +# accessible to beginners - therefore probably should just use more
   8.143 +# return codes.
   8.144 +#
   8.145 +# Enhancements / additions to the example scripts are also welcome:
   8.146 +# some people will interact with this code mostly through those
   8.147 +# scripts.
   8.148 +#
   8.149 +# More documentation of how this stuff should be used is always nice -
   8.150 +# if you have a novel configuration that you feel isn't discussed
   8.151 +# enough in the HOWTO (which is currently a work in progress), feel
   8.152 +# free to contribute a walkthrough, or something more substantial.
   8.153 +#
   8.154 +
   8.155 +
   8.156 +def __vd_no_database():
   8.157 +    """Called when no database found - exits with an error
   8.158 +    """
   8.159 +    print >> sys.stderr, "ERROR: Could not locate the database file at " + VD_DB_FILE
   8.160 +    sys.exit(1)
   8.161 +
   8.162 +def readlines(fd):
   8.163 +    """Version of readlines safe against EINTR.
   8.164 +    """
   8.165 +    import errno
   8.166 +    
   8.167 +    lines = []
   8.168 +    while 1:
   8.169 +        try:
   8.170 +            line = fd.readline()
   8.171 +        except IOError, ex:
   8.172 +            if ex.errno == errno.EINTR:
   8.173 +                continue
   8.174 +            else:
   8.175 +                raise
   8.176 +        if line == '': break
   8.177 +        lines.append(line)
   8.178 +    return lines
   8.179 +
   8.180 +def readline(fd):
   8.181 +    """Version of readline safe against EINTR.
   8.182 +    """
   8.183 +    while 1:
   8.184 +        try:
   8.185 +            return fd.readline()
   8.186 +        except IOError, ex:
   8.187 +            if ex.errno == errno.EINTR:
   8.188 +                continue
   8.189 +            else:
   8.190 +                raise
   8.191 +        
   8.192 +
   8.193 +def vd_format(partition, extent_size_mb):
   8.194 +    """Format a partition or drive for use a virtual disk storage.
   8.195 +    partition [string]: device file representing the partition
   8.196 +    extent_size_mb [string]: extent size in megabytes to use on this disk
   8.197 +    """
   8.198 +
   8.199 +    if not os.path.isfile(VD_DB_FILE):
   8.200 +        vd_init_db(VD_DB_FILE)
   8.201 +    
   8.202 +    if not re.match( '/dev/', partition ):
   8.203 +        partition = '/dev/' + partition
   8.204 +
   8.205 +    cx = sqlite.connect(VD_DB_FILE)
   8.206 +    cu = cx.cursor()
   8.207 +
   8.208 +    cu.execute("select * from vdisk_part where partition = \'"
   8.209 +               + partition + "\'")
   8.210 +    row = cu.fetchone()
   8.211 +
   8.212 +    extent_size = extent_size_mb * VBD_SECTORS_PER_MB # convert megabytes to sectors
   8.213 +    
   8.214 +    if not row:
   8.215 +        part_info = lookup_raw_partn(partition)[0]
   8.216 +        
   8.217 +        cu.execute("INSERT INTO vdisk_part(partition, part_id, extent_size) " +
   8.218 +                   "VALUES ( \'" + partition + "\', "
   8.219 +                   + str(blkdev_name_to_number(partition))
   8.220 +                   + ", " + str(extent_size) + ")")
   8.221 +
   8.222 +
   8.223 +        cu.execute("SELECT max(vdisk_extent_no) FROM vdisk_extents "
   8.224 +                   + "WHERE vdisk_id = 0")
   8.225 +        
   8.226 +        max_id, = cu.fetchone()
   8.227 +
   8.228 +        if max_id != None:
   8.229 +            new_id = max_id + 1
   8.230 +        else:
   8.231 +            new_id = 0
   8.232 +
   8.233 +        num_extents = part_info['nr_sectors'] / extent_size
   8.234 +
   8.235 +        for i in range(num_extents):
   8.236 +            sql ="""INSERT INTO vdisk_extents(vdisk_extent_no, vdisk_id,
   8.237 +                                              part_id, part_extent_no)
   8.238 +                    VALUES ("""+ str(new_id + i) + ", 0, "\
   8.239 +                               + str(blkdev_name_to_number(partition))\
   8.240 +                               + ", " + str(num_extents - (i + 1)) + ")"
   8.241 +            cu.execute(sql)
   8.242 +
   8.243 +    cx.commit()
   8.244 +    cx.close()
   8.245 +    return 0
   8.246 +
   8.247 +
   8.248 +def vd_create(size_mb, expiry):
   8.249 +    """Create a new virtual disk.
   8.250 +    size_mb [int]: size in megabytes for the new virtual disk
   8.251 +    expiry [int]: expiry time in seconds from now
   8.252 +    """
   8.253 +
   8.254 +    if not os.path.isfile(VD_DB_FILE):
   8.255 +        __vd_no_database()
   8.256 +
   8.257 +    cx = sqlite.connect(VD_DB_FILE)
   8.258 +    cu = cx.cursor()
   8.259 +
   8.260 +    size = size_mb * VBD_SECTORS_PER_MB
   8.261 +
   8.262 +    cu.execute("SELECT max(vdisk_id) FROM vdisks")
   8.263 +    max_id, = cu.fetchone()
   8.264 +    new_id = int(max_id) + 1
   8.265 +
   8.266 +    # fetch a list of extents from the expired disks, along with information
   8.267 +    # about their size
   8.268 +    cu.execute("""SELECT vdisks.vdisk_id, vdisk_extent_no, part_extent_no,
   8.269 +                         vdisk_extents.part_id, extent_size
   8.270 +                  FROM vdisks NATURAL JOIN vdisk_extents
   8.271 +                                                  NATURAL JOIN vdisk_part
   8.272 +                  WHERE expires AND expiry_time <= datetime('now')
   8.273 +                  ORDER BY expiry_time ASC, vdisk_extent_no DESC
   8.274 +               """)  # aims to reuse the last extents
   8.275 +                     # from the longest-expired disks first
   8.276 +
   8.277 +    allocated = 0
   8.278 +
   8.279 +    if expiry:
   8.280 +        expiry_ts = "datetime('now', '" + str(expiry) + " seconds')"
   8.281 +        expires = 1
   8.282 +    else:
   8.283 +        expiry_ts = "NULL"
   8.284 +        expires = 0
   8.285 +
   8.286 +    # we'll use this to build the SQL statement we want
   8.287 +    building_sql = "INSERT INTO vdisks(vdisk_id, size, expires, expiry_time)" \
   8.288 +                   +" VALUES ("+str(new_id)+", "+str(size)+ ", "              \
   8.289 +                   + str(expires) + ", " + expiry_ts + "); "
   8.290 +
   8.291 +    counter = 0
   8.292 +
   8.293 +    while allocated < size:
   8.294 +        row = cu.fetchone()
   8.295 +        if not row:
   8.296 +            print "ran out of space, having allocated %d meg of %d" % (allocated, size)
   8.297 +            cx.close()
   8.298 +            return -1
   8.299 +        
   8.300 +
   8.301 +        (vdisk_id, vdisk_extent_no, part_extent_no, part_id, extent_size) = row
   8.302 +        allocated += extent_size
   8.303 +        building_sql += "UPDATE vdisk_extents SET vdisk_id = " + str(new_id) \
   8.304 +                        + ", " + "vdisk_extent_no = " + str(counter)         \
   8.305 +                        + " WHERE vdisk_extent_no = " + str(vdisk_extent_no) \
   8.306 +                        + " AND vdisk_id = " + str(vdisk_id) + "; "
   8.307 +
   8.308 +        counter += 1
   8.309 +        
   8.310 +
   8.311 +    # this will execute the SQL query we build to store details of the new
   8.312 +    # virtual disk and allocate space to it print building_sql
   8.313 +    cu.execute(building_sql)
   8.314 +    
   8.315 +    cx.commit()
   8.316 +    cx.close()
   8.317 +    return str(new_id)
   8.318 +
   8.319 +
   8.320 +def vd_lookup(id):
   8.321 +    """Lookup a Virtual Disk by ID.
   8.322 +    id [string]: a virtual disk identifier
   8.323 +    Returns [list of dicts]: a list of extents as dicts, containing fields:
   8.324 +                             device : Linux device number of host disk
   8.325 +                             start_sector : within the device
   8.326 +                             nr_sectors : size of this extent
   8.327 +                             type : set to \'VD Extent\'
   8.328 +                             
   8.329 +                             part_device : Linux device no of host partition
   8.330 +                             part_start_sector : within the partition
   8.331 +    """
   8.332 +
   8.333 +    if not os.path.isfile(VD_DB_FILE):
   8.334 +        __vd_no_database()
   8.335 +
   8.336 +    cx = sqlite.connect(VD_DB_FILE)
   8.337 +    cu = cx.cursor()
   8.338 +
   8.339 +    cu.execute("-- types int")
   8.340 +    cu.execute("""SELECT COUNT(*)
   8.341 +                  FROM vdisks
   8.342 +                  WHERE (expiry_time > datetime('now') OR NOT expires)
   8.343 +                              AND vdisk_id = """ + id)
   8.344 +    count, = cu.fetchone()
   8.345 +
   8.346 +    if not count:
   8.347 +        cx.close()
   8.348 +        return None
   8.349 +
   8.350 +    cu.execute("SELECT size from vdisks WHERE vdisk_id = " + id)
   8.351 +    real_size, = cu.fetchone()
   8.352 +  
   8.353 +    # This query tells PySQLite how to convert the data returned from the
   8.354 +    # following query - the use of the multiplication confuses it otherwise ;-)
   8.355 +    # This row is significant to PySQLite but is syntactically an SQL comment.
   8.356 +
   8.357 +    cu.execute("-- types str, int, int, int")
   8.358 +
   8.359 +    # This SQL statement is designed so that when the results are fetched they
   8.360 +    # will be in the right format to return immediately.
   8.361 +    cu.execute("""SELECT partition, vdisk_part.part_id,
   8.362 +                         round(part_extent_no * extent_size) as start,
   8.363 +                         extent_size
   8.364 +                         
   8.365 +                  FROM vdisks NATURAL JOIN vdisk_extents
   8.366 +                                             NATURAL JOIN vdisk_part
   8.367 +                                                
   8.368 +                  WHERE vdisk_extents.vdisk_id = """ + id
   8.369 +               + " ORDER BY vdisk_extents.vdisk_extent_no ASC"
   8.370 +               )
   8.371 +
   8.372 +    extent_tuples = cu.fetchall()
   8.373 +
   8.374 +    # use this function to map the results from the database into a dict
   8.375 +    # list of extents, for consistency with the rest of the code
   8.376 +    def transform ((partition, part_device, part_offset, nr_sectors)):
   8.377 +        return {
   8.378 +                 # the disk device this extent is on - for passing to Xen
   8.379 +                 'device' : lookup_raw_partn(partition)[0]['device'],
   8.380 +                 # the offset of this extent within the disk - for passing to Xen
   8.381 +                 'start_sector' : long(part_offset + lookup_raw_partn(partition)[0]['start_sector']),
   8.382 +                 # extent size, in sectors
   8.383 +                 'nr_sectors' : nr_sectors,
   8.384 +                 # partition device this extent is on (useful to know for xenctl.utils fns)
   8.385 +                 'part_device' : part_device,
   8.386 +                 # start sector within this partition (useful to know for xenctl.utils fns)
   8.387 +                 'part_start_sector' : part_offset,
   8.388 +                 # type of this extent - handy to know
   8.389 +                 'type' : 'VD Extent' }
   8.390 +
   8.391 +    cx.commit()
   8.392 +    cx.close()
   8.393 +
   8.394 +    extent_dicts = map(transform, extent_tuples)
   8.395 +
   8.396 +    # calculate the over-allocation in sectors (happens because
   8.397 +    # we allocate whole extents)
   8.398 +    allocated_size = 0
   8.399 +    for i in extent_dicts:
   8.400 +        allocated_size += i['nr_sectors']
   8.401 +
   8.402 +    over_allocation = allocated_size - real_size
   8.403 +
   8.404 +    # trim down the last extent's length so the resulting VBD will be the
   8.405 +    # size requested, rather than being rounded up to the nearest extent
   8.406 +    extent_dicts[len(extent_dicts) - 1]['nr_sectors'] -= over_allocation
   8.407 +
   8.408 +    return extent_dicts
   8.409 +
   8.410 +
   8.411 +def vd_enlarge(vdisk_id, extra_size_mb):
   8.412 +    """Create a new virtual disk.
   8.413 +    vdisk_id [string]   :    ID of the virtual disk to enlarge
   8.414 +    extra_size_mb  [int]:    size in megabytes to increase the allocation by
   8.415 +    returns  [int]      :    0 on success, otherwise non-zero
   8.416 +    """
   8.417 +
   8.418 +    if not os.path.isfile(VD_DB_FILE):
   8.419 +        __vd_no_database()
   8.420 +
   8.421 +    cx = sqlite.connect(VD_DB_FILE)
   8.422 +    cu = cx.cursor()
   8.423 +
   8.424 +    extra_size = extra_size_mb * VBD_SECTORS_PER_MB
   8.425 +
   8.426 +    cu.execute("-- types int")
   8.427 +    cu.execute("SELECT COUNT(*) FROM vdisks WHERE vdisk_id = " + vdisk_id
   8.428 +               + " AND (expiry_time > datetime('now') OR NOT expires)")
   8.429 +    count, = cu.fetchone()
   8.430 +
   8.431 +    if not count: # no such vdisk
   8.432 +        cx.close()
   8.433 +        return -1
   8.434 +
   8.435 +    cu.execute("-- types int")
   8.436 +    cu.execute("""SELECT SUM(extent_size)
   8.437 +                  FROM vdisks NATURAL JOIN vdisk_extents
   8.438 +                                         NATURAL JOIN vdisk_part
   8.439 +                  WHERE vdisks.vdisk_id = """ + vdisk_id)
   8.440 +
   8.441 +    real_size, = cu.fetchone() # get the true allocated size
   8.442 +
   8.443 +    cu.execute("-- types int")
   8.444 +    cu.execute("SELECT size FROM vdisks WHERE vdisk_id = " + vdisk_id)
   8.445 +
   8.446 +    old_size, = cu.fetchone()
   8.447 +
   8.448 +
   8.449 +    cu.execute("--- types int")
   8.450 +    cu.execute("""SELECT MAX(vdisk_extent_no)
   8.451 +                  FROM vdisk_extents
   8.452 +                  WHERE vdisk_id = """ + vdisk_id)
   8.453 +
   8.454 +    counter = cu.fetchone()[0] + 1 # this stores the extent numbers
   8.455 +
   8.456 +
   8.457 +    # because of the extent-based allocation, the VD may already have more
   8.458 +    # allocated space than they asked for.  Find out how much we really
   8.459 +    # need to add.
   8.460 +    add_size = extra_size + old_size - real_size
   8.461 +
   8.462 +    # fetch a list of extents from the expired disks, along with information
   8.463 +    # about their size
   8.464 +    cu.execute("""SELECT vdisks.vdisk_id, vdisk_extent_no, part_extent_no,
   8.465 +                         vdisk_extents.part_id, extent_size
   8.466 +                  FROM vdisks NATURAL JOIN vdisk_extents
   8.467 +                                                  NATURAL JOIN vdisk_part
   8.468 +                  WHERE expires AND expiry_time <= datetime('now')
   8.469 +                  ORDER BY expiry_time ASC, vdisk_extent_no DESC
   8.470 +               """)  # aims to reuse the last extents
   8.471 +                     # from the longest-expired disks first
   8.472 +
   8.473 +    allocated = 0
   8.474 +
   8.475 +    building_sql = "UPDATE vdisks SET size = " + str(old_size + extra_size)\
   8.476 +                   + " WHERE vdisk_id = " + vdisk_id + "; "
   8.477 +
   8.478 +    while allocated < add_size:
   8.479 +        row = cu.fetchone()
   8.480 +        if not row:
   8.481 +            cx.close()
   8.482 +            return -1
   8.483 +
   8.484 +        (dead_vd_id, vdisk_extent_no, part_extent_no, part_id, extent_size) = row
   8.485 +        allocated += extent_size
   8.486 +        building_sql += "UPDATE vdisk_extents SET vdisk_id = " + vdisk_id    \
   8.487 +                        + ", " + "vdisk_extent_no = " + str(counter)         \
   8.488 +                        + " WHERE vdisk_extent_no = " + str(vdisk_extent_no) \
   8.489 +                        + " AND vdisk_id = " + str(dead_vd_id) + "; "
   8.490 +
   8.491 +        counter += 1
   8.492 +        
   8.493 +
   8.494 +    # this will execute the SQL query we build to store details of the new
   8.495 +    # virtual disk and allocate space to it print building_sql
   8.496 +    cu.execute(building_sql)
   8.497 +    
   8.498 +    cx.commit()
   8.499 +    cx.close()
   8.500 +    return 0
   8.501 +
   8.502 +
   8.503 +def vd_undelete(vdisk_id, expiry_time):
   8.504 +    """Create a new virtual disk.
   8.505 +    vdisk_id      [int]: size in megabytes for the new virtual disk
   8.506 +    expiry_time   [int]: expiry time, in seconds from now
   8.507 +    returns       [int]: zero on success, non-zero on failure
   8.508 +    """
   8.509 +
   8.510 +    if not os.path.isfile(VD_DB_FILE):
   8.511 +        __vd_no_database()
   8.512 +
   8.513 +    if vdisk_id == '0': #  undeleting vdisk 0 isn't sane!
   8.514 +        return -1
   8.515 +
   8.516 +    cx = sqlite.connect(VD_DB_FILE)
   8.517 +    cu = cx.cursor()
   8.518 +
   8.519 +    cu.execute("-- types int")
   8.520 +    cu.execute("SELECT COUNT(*) FROM vdisks WHERE vdisk_id = " + vdisk_id)
   8.521 +    count, = cu.fetchone()
   8.522 +
   8.523 +    if not count:
   8.524 +        cx.close()
   8.525 +        return -1
   8.526 +
   8.527 +    cu.execute("-- types int")
   8.528 +    cu.execute("""SELECT SUM(extent_size)
   8.529 +                  FROM vdisks NATURAL JOIN vdisk_extents
   8.530 +                                         NATURAL JOIN vdisk_part
   8.531 +                  WHERE vdisks.vdisk_id = """ + vdisk_id)
   8.532 +
   8.533 +    real_size, = cu.fetchone() # get the true allocated size
   8.534 +
   8.535 +
   8.536 +    cu.execute("-- types int")
   8.537 +    cu.execute("SELECT size FROM vdisks WHERE vdisk_id = " + vdisk_id)
   8.538 +
   8.539 +    old_size, = cu.fetchone()
   8.540 +
   8.541 +    if real_size < old_size:
   8.542 +        cx.close()
   8.543 +        return -1
   8.544 +
   8.545 +    if expiry_time == 0:
   8.546 +        expires = '0'
   8.547 +    else:
   8.548 +        expires = '1'
   8.549 +
   8.550 +    # this will execute the SQL query we build to store details of the new
   8.551 +    # virtual disk and allocate space to it print building_sql
   8.552 +    cu.execute("UPDATE vdisks SET expiry_time = datetime('now','"
   8.553 +               + str(expiry_time) + " seconds'), expires = " + expires
   8.554 +               + " WHERE vdisk_id = " + vdisk_id)
   8.555 +    
   8.556 +    cx.commit()
   8.557 +    cx.close()
   8.558 +    return 0
   8.559 +
   8.560 +
   8.561 +
   8.562 +
   8.563 +def vd_list():
   8.564 +    """Lists all the virtual disks registered in the system.
   8.565 +    returns [list of dicts]
   8.566 +    """
   8.567 +    
   8.568 +    if not os.path.isfile(VD_DB_FILE):
   8.569 +        __vd_no_database()
   8.570 +
   8.571 +    cx = sqlite.connect(VD_DB_FILE)
   8.572 +    cu = cx.cursor()
   8.573 +
   8.574 +    cu.execute("""SELECT vdisk_id, size, expires, expiry_time
   8.575 +                  FROM vdisks
   8.576 +                  WHERE (NOT expires) OR expiry_time > datetime('now')
   8.577 +               """)
   8.578 +
   8.579 +    ret = cu.fetchall()
   8.580 +
   8.581 +    cx.close()
   8.582 +
   8.583 +    def makedicts((vdisk_id, size, expires, expiry_time)):
   8.584 +        return { 'vdisk_id' : str(vdisk_id), 'size': size,
   8.585 +                 'expires' : expires, 'expiry_time' : expiry_time }
   8.586 +
   8.587 +    return map(makedicts, ret)
   8.588 +
   8.589 +
   8.590 +def vd_refresh(id, expiry):
   8.591 +    """Change the expiry time of a virtual disk.
   8.592 +    id [string]  : a virtual disk identifier
   8.593 +    expiry [int] : expiry time in seconds from now (0 = never expire)
   8.594 +    returns [int]: zero on success, non-zero on failure
   8.595 +    """
   8.596 +
   8.597 +    if not os.path.isfile(VD_DB_FILE):
   8.598 +        __vd_no_database()
   8.599 +    
   8.600 +    cx = sqlite.connect(VD_DB_FILE)
   8.601 +    cu = cx.cursor()
   8.602 +
   8.603 +    cu.execute("-- types int")
   8.604 +    cu.execute("SELECT COUNT(*) FROM vdisks WHERE vdisk_id = " + id
   8.605 +               + " AND (expiry_time > datetime('now') OR NOT expires)")
   8.606 +    count, = cu.fetchone()
   8.607 +
   8.608 +    if not count:
   8.609 +        cx.close()
   8.610 +        return -1
   8.611 +
   8.612 +    if expiry:
   8.613 +        expires = 1
   8.614 +        expiry_ts = "datetime('now', '" + str(expiry) + " seconds')"
   8.615 +    else:
   8.616 +        expires = 0
   8.617 +        expiry_ts = "NULL"
   8.618 +
   8.619 +    cu.execute("UPDATE vdisks SET expires = " + str(expires)
   8.620 +               + ", expiry_time = " + expiry_ts
   8.621 +               + " WHERE (expiry_time > datetime('now') OR NOT expires)"
   8.622 +               + " AND vdisk_id = " + id)
   8.623 +
   8.624 +    cx.commit()
   8.625 +    cx.close()
   8.626 +    
   8.627 +    return 0
   8.628 +
   8.629 +
   8.630 +def vd_delete(id):
   8.631 +    """Deletes a Virtual Disk, making its extents available for future VDs.
   8.632 +       id [string]   : identifier for the virtual disk to delete
   8.633 +       returns [int] : 0 on success, -1 on failure (VD not found
   8.634 +                       or already deleted)
   8.635 +    """
   8.636 +
   8.637 +    if not os.path.isfile(VD_DB_FILE):
   8.638 +        __vd_no_database()
   8.639 +    
   8.640 +    cx = sqlite.connect(VD_DB_FILE)
   8.641 +    cu = cx.cursor()
   8.642 +
   8.643 +    cu.execute("-- types int")
   8.644 +    cu.execute("SELECT COUNT(*) FROM vdisks WHERE vdisk_id = " + id
   8.645 +               + " AND (expiry_time > datetime('now') OR NOT expires)")
   8.646 +    count, = cu.fetchone()
   8.647 +
   8.648 +    if not count:
   8.649 +        cx.close()
   8.650 +        return -1
   8.651 +
   8.652 +    cu.execute("UPDATE vdisks SET expires = 1, expiry_time = datetime('now')"
   8.653 +               + " WHERE vdisk_id = " + id)
   8.654 +
   8.655 +    cx.commit()
   8.656 +    cx.close()
   8.657 +    
   8.658 +    return 0
   8.659 +
   8.660 +
   8.661 +def vd_freespace():
   8.662 +    """Returns the amount of free space available for new virtual disks, in MB
   8.663 +    returns [int] : free space for VDs in MB
   8.664 +    """
   8.665 +
   8.666 +    if not os.path.isfile(VD_DB_FILE):
   8.667 +        __vd_no_database()
   8.668 + 
   8.669 +    cx = sqlite.connect(VD_DB_FILE)
   8.670 +    cu = cx.cursor()
   8.671 +
   8.672 +    cu.execute("-- types int")
   8.673 +
   8.674 +    cu.execute("""SELECT SUM(extent_size)
   8.675 +                  FROM vdisks NATURAL JOIN vdisk_extents
   8.676 +                                           NATURAL JOIN vdisk_part
   8.677 +                  WHERE expiry_time <= datetime('now') AND expires""")
   8.678 +
   8.679 +    sum, = cu.fetchone()
   8.680 +
   8.681 +    cx.close()
   8.682 +
   8.683 +    return sum / VBD_SECTORS_PER_MB
   8.684 +
   8.685 +
   8.686 +def vd_init_db(path):
   8.687 +    """Initialise the VD SQLite database
   8.688 +    path [string]: path to the SQLite database file
   8.689 +    """
   8.690 +
   8.691 +    cx = sqlite.connect(path)
   8.692 +    cu = cx.cursor()
   8.693 +
   8.694 +    cu.execute(
   8.695 +        """CREATE TABLE vdisk_extents
   8.696 +                           ( vdisk_extent_no INT,
   8.697 +                             vdisk_id INT,
   8.698 +                             part_id INT,
   8.699 +                             part_extent_no INT )
   8.700 +        """)
   8.701 +
   8.702 +    cu.execute(
   8.703 +        """CREATE TABLE vdisk_part
   8.704 +                           ( part_id INT,
   8.705 +                             partition VARCHAR,
   8.706 +                             extent_size INT )
   8.707 +        """)
   8.708 +
   8.709 +    cu.execute(
   8.710 +        """CREATE TABLE vdisks
   8.711 +                           ( vdisk_id INT,
   8.712 +                             size INT,
   8.713 +                             expires BOOLEAN,
   8.714 +                             expiry_time TIMESTAMP )
   8.715 +        """)
   8.716 +
   8.717 +
   8.718 +    cu.execute(
   8.719 +        """INSERT INTO vdisks ( vdisk_id, size, expires, expiry_time )
   8.720 +                       VALUES ( 0,        0,    1,       datetime('now') )
   8.721 +        """)
   8.722 +
   8.723 +    cx.commit()
   8.724 +    cx.close()
   8.725 +
   8.726 +    VD_DB_FILE = path
   8.727 +
   8.728 +
   8.729 +
   8.730 +def vd_cp_to_file(vdisk_id,filename):
   8.731 +    """Writes the contents of a specified vdisk out into a disk file, leaving
   8.732 +    the original copy in the virtual disk pool."""
   8.733 +
   8.734 +    cx = sqlite.connect(VD_DB_FILE)
   8.735 +    cu = cx.cursor()
   8.736 +
   8.737 +    extents = vd_lookup(vdisk_id)
   8.738 +
   8.739 +    if not extents:
   8.740 +        return -1
   8.741 +    
   8.742 +    file_idx = 0 # index into source file, in sectors
   8.743 +
   8.744 +    for i in extents:
   8.745 +        cu.execute("""SELECT partition, extent_size FROM vdisk_part
   8.746 +                      WHERE part_id =  """ + str(i['part_device']))
   8.747 +
   8.748 +        (partition, extent_size) = cu.fetchone()
   8.749 +
   8.750 +        os.system("dd bs=1b if=" + partition + " of=" + filename
   8.751 +                  + " skip=" + str(i['part_start_sector'])
   8.752 +                  + " seek=" + str(file_idx)
   8.753 +                  + " count=" + str(i['nr_sectors'])
   8.754 +                  + " > /dev/null")
   8.755 +
   8.756 +        file_idx += i['nr_sectors']
   8.757 +
   8.758 +    cx.close()
   8.759 +
   8.760 +    return 0 # should return -1 if something breaks
   8.761 +    
   8.762 +
   8.763 +def vd_mv_to_file(vdisk_id,filename):
   8.764 +    """Writes a vdisk out into a disk file and frees the space originally
   8.765 +    taken within the virtual disk pool.
   8.766 +    vdisk_id [string]: ID of the vdisk to write out
   8.767 +    filename [string]: file to write vdisk contents out to
   8.768 +    returns [int]: zero on success, nonzero on failure
   8.769 +    """
   8.770 +
   8.771 +    if vd_cp_to_file(vdisk_id,filename):
   8.772 +        return -1
   8.773 +
   8.774 +    if vd_delete(vdisk_id):
   8.775 +        return -1
   8.776 +
   8.777 +    return 0
   8.778 +
   8.779 +
   8.780 +def vd_read_from_file(filename,expiry):
   8.781 +    """Reads the contents of a file directly into a vdisk, which is
   8.782 +    automatically allocated to fit.
   8.783 +    filename [string]: file to read disk contents from
   8.784 +    returns [string] : vdisk ID for the destination vdisk
   8.785 +    """
   8.786 +
   8.787 +    size_bytes = os.stat(filename).st_size
   8.788 +
   8.789 +    (size_mb,leftover) =  divmod(size_bytes,1048580) # size in megabytes
   8.790 +    if leftover > 0: size_mb += 1 # round up if not an exact number of MB
   8.791 +
   8.792 +    vdisk_id = vd_create(size_mb, expiry)
   8.793 +
   8.794 +    if vdisk_id < 0:
   8.795 +        return -1
   8.796 +
   8.797 +    cx = sqlite.connect(VD_DB_FILE)
   8.798 +    cu = cx.cursor()
   8.799 +
   8.800 +    cu.execute("""SELECT partition, extent_size, part_extent_no
   8.801 +                  FROM vdisk_part NATURAL JOIN vdisk_extents
   8.802 +                  WHERE vdisk_id =  """ + vdisk_id + """
   8.803 +                  ORDER BY vdisk_extent_no ASC""")
   8.804 +
   8.805 +    extents = cu.fetchall()
   8.806 +
   8.807 +    size_sectors = size_mb * VBD_SECTORS_PER_MB # for feeding to dd
   8.808 +
   8.809 +    file_idx = 0 # index into source file, in sectors
   8.810 +
   8.811 +    def write_extent_to_vd((partition, extent_size, part_extent_no),
   8.812 +                           file_idx, filename):
   8.813 +        """Write an extent out to disk and update file_idx"""
   8.814 +
   8.815 +        os.system("dd bs=512 if=" + filename + " of=" + partition
   8.816 +                  + " skip=" + str(file_idx)
   8.817 +                  + " seek=" + str(part_extent_no * extent_size)
   8.818 +                  + " count=" + str(min(extent_size, size_sectors - file_idx))
   8.819 +                  + " > /dev/null")
   8.820 +
   8.821 +        return extent_size
   8.822 +
   8.823 +    for i in extents:
   8.824 +        file_idx += write_extent_to_vd(i, file_idx, filename)
   8.825 +
   8.826 +    cx.close()
   8.827 +
   8.828 +    return vdisk_id
   8.829 +    
   8.830 +
   8.831 +
   8.832 +
   8.833 +def vd_extents_validate(new_extents, new_writeable, safety=VBD_SAFETY_RR):
   8.834 +    """Validate the extents against the existing extents.
   8.835 +    Complains if the list supplied clashes against the extents that
   8.836 +    are already in use in the system.
   8.837 +    new_extents [list of dicts]: list of new extents, as dicts
   8.838 +    new_writeable [int]: 1 if they are to be writeable, 0 otherwise
   8.839 +    returns [int]: either the expertise level of the mapping if it doesn't
   8.840 +                   exceed VBD_EXPERT_MODE or -1 if it does (error)
   8.841 +    """
   8.842 +
   8.843 +    import Xc # this is only needed in this function
   8.844 +
   8.845 +    xc = Xc.new()
   8.846 +
   8.847 +    ##### Probe for explicitly created virtual disks and build a list
   8.848 +    ##### of extents for comparison with the ones that are being added
   8.849 +
   8.850 +    probe = xc.vbd_probe()
   8.851 +
   8.852 +    old_extents = [] # this will hold a list of all existing extents and
   8.853 +                     # their writeable status, as a list of (device,
   8.854 +                     # start, size, writeable?) tuples
   8.855 +
   8.856 +    for vbd in probe:
   8.857 +        this_vbd_extents = xc.vbd_getextents(vbd['dom'],vbd['vbd'])
   8.858 +        for vbd_ext in this_vbd_extents:
   8.859 +            vbd_ext['writeable'] = vbd['writeable']
   8.860 +            old_extents.append(vbd_ext)
   8.861 +            
   8.862 +    ##### Now scan /proc/mounts for compile a list of extents corresponding to
   8.863 +    ##### any devices mounted in DOM0.  This list is added on to old_extents
   8.864 +
   8.865 +    regexp = re.compile("/dev/(\S*) \S* \S* (..).*")
   8.866 +    fd = open('/proc/mounts', "r")
   8.867 +
   8.868 +    while True:
   8.869 +        line = readline(fd)
   8.870 +        if not line: # if we've run out of lines then stop reading
   8.871 +            break
   8.872 +        
   8.873 +        m = regexp.match(line)
   8.874 +
   8.875 +        # if the regexp didn't match then it's probably a line we don't
   8.876 +        # care about - skip to next line
   8.877 +        if not m:
   8.878 +            continue
   8.879 +
   8.880 +        # lookup the device
   8.881 +        ext_list = lookup_raw_partn(m.group(1))
   8.882 +
   8.883 +        # if lookup failed, skip to next mounted device
   8.884 +        if not ext_list:
   8.885 +            continue
   8.886 +
   8.887 +        # set a writeable flag as appropriate
   8.888 +        for ext in ext_list:
   8.889 +            ext['writeable'] = m.group(2) == 'rw'
   8.890 +
   8.891 +        # now we've got here, the contents of ext_list are in a
   8.892 +        # suitable format to be added onto the old_extents list, ready
   8.893 +        # for checking against the new extents
   8.894 +
   8.895 +        old_extents.extend(ext_list)
   8.896 +
   8.897 +    fd.close() # close /proc/mounts
   8.898 +
   8.899 +    ##### By this point, old_extents contains a list of extents, in
   8.900 +    ##### dictionary format corresponding to every extent of physical
   8.901 +    ##### disk that's either part of an explicitly created VBD, or is
   8.902 +    ##### mounted under DOM0.  We now check these extents against the
   8.903 +    ##### proposed additions in new_extents, to see if a conflict will
   8.904 +    ##### happen if they are added with write status new_writeable
   8.905 +
   8.906 +    level = 0 # this'll accumulate the max warning level
   8.907 +
   8.908 +    # Search for clashes between the new extents and the old ones
   8.909 +    # Takes time O(len(new_extents) * len(old_extents))
   8.910 +    for new_ext in new_extents:
   8.911 +        for old_ext in old_extents:
   8.912 +            if(new_ext['device'] == old_ext['device']):
   8.913 +
   8.914 +                new_ext_start = new_ext['start_sector']
   8.915 +                new_ext_end = new_ext_start + new_ext['nr_sectors'] - 1
   8.916 +                
   8.917 +                old_ext_start = old_ext['start_sector']
   8.918 +                old_ext_end = old_ext_start + old_ext['nr_sectors'] - 1
   8.919 +                
   8.920 +                if((old_ext_start <= new_ext_start <= old_ext_end) or
   8.921 +                   (old_ext_start <= new_ext_end <= old_ext_end)):
   8.922 +                    if (not old_ext['writeable']) and new_writeable:
   8.923 +                        level = max(1,level)
   8.924 +                    elif old_ext['writeable'] and (not new_writeable):
   8.925 +                        level = max(1,level)
   8.926 +                    elif old_ext['writeable'] and new_writeable:
   8.927 +                        level = max(2,level)
   8.928 +
   8.929 +
   8.930 +    ##### level now holds the warning level incurred by the current
   8.931 +    ##### VBD setup and we complain appropriately to the user
   8.932 +
   8.933 +
   8.934 +    if level == 1:
   8.935 +        print >> sys.stderr, """Warning: one or more hard disk extents
   8.936 +         writeable by one domain are also readable by another."""
   8.937 +    elif level == 2:
   8.938 +        print >> sys.stderr, """Warning: one or more hard disk extents are
   8.939 +         writeable by two or more domains simultaneously."""
   8.940 +
   8.941 +    if level > safety:
   8.942 +        print >> sys.stderr, """ERROR: This kind of disk sharing is not allowed
   8.943 +        at the current safety level (%d).""" % safety
   8.944 +        level = -1
   8.945 +
   8.946 +    return level
   8.947 +
     9.1 --- a/tools/xenctl/setup.py	Fri Jun 11 14:35:29 2004 +0000
     9.2 +++ b/tools/xenctl/setup.py	Fri Jun 11 14:40:53 2004 +0000
     9.3 @@ -2,7 +2,7 @@
     9.4  from distutils.core import setup, Extension
     9.5  import sys
     9.6  
     9.7 -modules = [ 'xenctl.console_client', 'xenctl.utils' ]
     9.8 +modules = [ 'xenctl.console_client', 'xenctl.utils', 'xenctl.ip' , 'xenctl.vdisk' ]
     9.9  
    9.10  # We need the 'tempfile' module from Python 2.3. We install this ourselves
    9.11  # if the installed Python is older than 2.3.
    10.1 --- a/tools/xend/lib/utils.c	Fri Jun 11 14:35:29 2004 +0000
    10.2 +++ b/tools/xend/lib/utils.c	Fri Jun 11 14:40:53 2004 +0000
    10.3 @@ -412,7 +412,8 @@ static PyObject *xu_message_get_payload(
    10.4          C2P(netif_fe_interface_status_changed_t, evtchn, Int, Long);
    10.5          return dict;
    10.6      case TYPE(CMSG_NETIF_FE, CMSG_NETIF_FE_DRIVER_STATUS_CHANGED):
    10.7 -        C2P(netif_fe_driver_status_changed_t, status, Int, Long);
    10.8 +        C2P(netif_fe_driver_status_changed_t, status,        Int, Long);
    10.9 +        C2P(netif_fe_driver_status_changed_t, nr_interfaces, Int, Long);
   10.10          return dict;
   10.11      case TYPE(CMSG_NETIF_FE, CMSG_NETIF_FE_INTERFACE_CONNECT):
   10.12          C2P(netif_fe_interface_connect_t, handle,         Int, Long);
   10.13 @@ -603,6 +604,9 @@ static PyObject *xu_message_new(PyObject
   10.14          P2C(netif_be_disconnect_t, domid,        u32);
   10.15          P2C(netif_be_disconnect_t, netif_handle, u32);
   10.16          break;
   10.17 +    case TYPE(CMSG_NETIF_FE, CMSG_NETIF_FE_DRIVER_STATUS_CHANGED):
   10.18 +        P2C(netif_fe_driver_status_changed_t, status,        u32);
   10.19 +        P2C(netif_fe_driver_status_changed_t, nr_interfaces, u32);
   10.20      }
   10.21  
   10.22      if ( dict_items_parsed != PyDict_Size(payload) )
    11.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    11.2 +++ b/tools/xenmgr/Makefile	Fri Jun 11 14:40:53 2004 +0000
    11.3 @@ -0,0 +1,19 @@
    11.4 +
    11.5 +all:
    11.6 +	python setup.py build
    11.7 +
    11.8 +install: all
    11.9 +	if [ "$(prefix)" = "" ]; then                   \
   11.10 +	    python setup.py install;                    \
   11.11 +	elif [ "$(dist)" = "yes" ]; then                \
   11.12 +	    python setup.py install --home="$(prefix)"; \
   11.13 +	else                                            \
   11.14 +	    python setup.py install --root="$(prefix)"; \
   11.15 +	fi
   11.16 +	mkdir -p $(prefix)/usr/sbin
   11.17 +	install -m0755 xenmgrd $(prefix)/usr/sbin
   11.18 +	install -m0755 xend $(prefix)/usr/sbin
   11.19 +	install -m0755 netfix $(prefix)/usr/sbin
   11.20 +
   11.21 +clean:
   11.22 +	rm -rf build *.pyc *.pyo *.o *.a *~
    12.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    12.2 +++ b/tools/xenmgr/lib/Args.py	Fri Jun 11 14:40:53 2004 +0000
    12.3 @@ -0,0 +1,126 @@
    12.4 +import sxp
    12.5 +
    12.6 +class ArgError(StandardError):
    12.7 +    pass
    12.8 +
    12.9 +class Args:
   12.10 +    """Argument encoding support for HTTP.
   12.11 +    """
   12.12 +    
   12.13 +    def __init__(self, paramspec, keyspec):
   12.14 +        self.arg_ord = []
   12.15 +        self.arg_dict = {}
   12.16 +        self.key_ord = []
   12.17 +        self.key_dict = {}
   12.18 +        for (name, type) in paramspec:
   12.19 +                self.arg_ord.append(name)
   12.20 +                self.arg_dict[name] = type
   12.21 +        for (name, type) in keyspec:
   12.22 +                self.key_ord.append(name)
   12.23 +                self.key_dict[name] = type
   12.24 +
   12.25 +    def get_args(self, d, xargs=None):
   12.26 +        args = {}
   12.27 +        keys = {}
   12.28 +        params = []
   12.29 +        if xargs:
   12.30 +            self.split_args(xargs, args, keys)
   12.31 +        self.split_args(d, args, keys)
   12.32 +        for a in self.arg_ord:
   12.33 +            if a in args:
   12.34 +                params.append(args[a])
   12.35 +            else:
   12.36 +                raise ArgError('Missing parameter: %s' % a)
   12.37 +        return (params, keys)
   12.38 +
   12.39 +    def split_args(self, d, args, keys):
   12.40 +        for (k, v) in d.items():
   12.41 +            if k in self.arg_dict:
   12.42 +                type = self.arg_dict[k]
   12.43 +                val = self.coerce(type, v)
   12.44 +                args[k] = val
   12.45 +            elif k in self.key_dict:
   12.46 +                type = self.key_dict[k]
   12.47 +                val = self.coerce(type, v)
   12.48 +                keys[k] = val
   12.49 +            else:
   12.50 +                raise ArgError('Invalid parameter: %s' % k)
   12.51 +
   12.52 +    def get_form_args(self, f, xargs=None):
   12.53 +        d = {}
   12.54 +        for (k, v) in f.items():
   12.55 +            n = len(v)
   12.56 +            if ((k not in self.arg_dict) and
   12.57 +                (k not in self.key_dict)):
   12.58 +                continue
   12.59 +            if n == 0:
   12.60 +                continue
   12.61 +            elif n == 1:
   12.62 +                d[k] = v[0]
   12.63 +            else:
   12.64 +                raise ArgError('Too many values for %s' % k)
   12.65 +        return self.get_args(d, xargs=xargs)
   12.66 +
   12.67 +    def coerce(self, type, v):
   12.68 +        try:
   12.69 +            if type == 'int':
   12.70 +                return int(v)
   12.71 +            if type == 'str':
   12.72 +                return str(v)
   12.73 +            if type == 'sxpr':
   12.74 +                return self.sxpr(v)
   12.75 +        except ArgError:
   12.76 +            raise
   12.77 +        except StandardError, ex:
   12.78 +            raise ArgError(str(ex))
   12.79 +
   12.80 +    def sxpr(self, v):
   12.81 +        if instanceof(v, types.ListType):
   12.82 +            return v
   12.83 +        if instanceof(v, types.File) or hasattr(v, 'readline'):
   12.84 +            return sxpr_file(v)
   12.85 +        if instanceof(v, types.StringType):
   12.86 +            return sxpr_file(StringIO(v))
   12.87 +        return str(v)
   12.88 +
   12.89 +    def sxpr_file(self, fin):
   12.90 +        try:
   12.91 +            vals = sxp.parse(fin)
   12.92 +        except:
   12.93 +            raise ArgError('Coercion to sxpr failed')
   12.94 +        if len(vals) == 1:
   12.95 +            return vals[0]
   12.96 +        else:
   12.97 +            raise ArgError('Too many sxprs')
   12.98 +
   12.99 +    def call_with_args(self, fn, args, xargs=None):
  12.100 +        (params, keys) = self.get_args(args, xargs=xargs)
  12.101 +        fn(*params, **keys)
  12.102 +
  12.103 +    def call_with_form_args(self, fn, fargs, xargs=None):
  12.104 +        (params, keys) = self.get_form_args(fargs, xargs=xargs)
  12.105 +        fn(*params, **keys)
  12.106 +
  12.107 +class ArgFn(Args):
  12.108 +    """Represent a remote HTTP operation as a function.
  12.109 +    Used on the client.
  12.110 +    """
  12.111 +
  12.112 +    def __init__(self, fn, paramspec, keyspec={}):
  12.113 +        Args.__init__(self, paramspec, keyspec)
  12.114 +        self.fn = fn
  12.115 +
  12.116 +    def __call__(self, fargs, xargs=None):
  12.117 +        return self.call_with_args(self.fn, fargs, xargs=xargs)
  12.118 +    
  12.119 +class FormFn(Args):
  12.120 +    """Represent an operation as a function over a form.
  12.121 +    Used in the HTTP server.
  12.122 +    """
  12.123 +
  12.124 +    def __init__(self, fn, paramspec, keyspec={}):
  12.125 +        Args.__init__(self, paramspec, keyspec)
  12.126 +        self.fn = fn
  12.127 +
  12.128 +    def __call__(self, fargs, xargs=None):
  12.129 +        return self.call_with_form_args(self.fn, fargs, xargs=xargs)
    13.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    13.2 +++ b/tools/xenmgr/lib/EventServer.py	Fri Jun 11 14:40:53 2004 +0000
    13.3 @@ -0,0 +1,204 @@
    13.4 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    13.5 +"""Simple publish/subscribe event server.
    13.6 +
    13.7 +"""
    13.8 +import string
    13.9 +
   13.10 +# subscribe a.b.c h: map a.b.c -> h
   13.11 +# subscribe a.b.* h: map a.b.* -> h
   13.12 +# subscribe a.b.? h: map a.b.? -> h
   13.13 +#
   13.14 +# for event a.b.c.d:
   13.15 +#
   13.16 +# lookup a.b.c.d, call handlers
   13.17 +#
   13.18 +# lookup a.b.c.?, call handlers
   13.19 +#
   13.20 +# lookup a.b.c.d.*, call handlers
   13.21 +# lookup a.b.c.*, call handlers
   13.22 +# lookup a.b.*, call handlers
   13.23 +# lookup a.*, call handlers
   13.24 +# lookup *, call handlers
   13.25 +
   13.26 +# a.b.c.d = (a b c d)
   13.27 +# a.b.c.? = (a b c _)
   13.28 +# a.b.c.* = (a b c . _)
   13.29 +
   13.30 +class EventServer:
   13.31 +
   13.32 +    DOT = '.'
   13.33 +    QUERY = '?'
   13.34 +    DOT_QUERY = DOT + QUERY
   13.35 +    STAR = '*'
   13.36 +    DOT_STAR = DOT + STAR
   13.37 +
   13.38 +    def __init__(self, run=0):
   13.39 +        self.handlers = {}
   13.40 +        self.run = run
   13.41 +        self.queue = []
   13.42 +
   13.43 +    def start(self):
   13.44 +        """Enable event handling. Sends any queued events.
   13.45 +        """
   13.46 +        self.run = 1
   13.47 +        for (e,v) in self.queue:
   13.48 +            self.inject(e, v)
   13.49 +        self.queue = []
   13.50 +
   13.51 +    def stop(self):
   13.52 +        """Suspend event handling. Events injected while suspended
   13.53 +        are queued until we are started again.
   13.54 +        """
   13.55 +        self.run = 0
   13.56 +
   13.57 +    def subscribe(self, event, handler):
   13.58 +        """Subscribe to an event. For example 'a.b.c.d'.
   13.59 +        A subcription like 'a.b.c.?' ending in '?' matches any value
   13.60 +        for the '?'. A subscription like 'a.b.c.*' ending in '*' matches
   13.61 +        any event type with the same prefix, 'a.b.c' in this case.
   13.62 +
   13.63 +        event	event name
   13.64 +        handler event handler fn(event, val)
   13.65 +        """
   13.66 +        hl = self.handlers.get(event)
   13.67 +        if hl is None:
   13.68 +            self.handlers[event] = [handler]
   13.69 +        else:
   13.70 +            hl.append(handler)
   13.71 +
   13.72 +    def unsubscribe_all(self, event=None):
   13.73 +        """Unsubscribe all handlers for a given event, or all handlers.
   13.74 +
   13.75 +        event	event (optional)
   13.76 +        """
   13.77 +        if event == None:
   13.78 +            self.handlers.clear()
   13.79 +        else:
   13.80 +            del self.handlers[event]
   13.81 +        
   13.82 +    def unsubscribe(self, event, handler):
   13.83 +        """Unsubscribe a given event and handler.
   13.84 +
   13.85 +        event	event
   13.86 +        handler handler
   13.87 +        """
   13.88 +        hl = self.handlers.get(event)
   13.89 +        if hl is None:
   13.90 +            return
   13.91 +        hl.remove(handler)
   13.92 +
   13.93 +    def inject(self, event, val):
   13.94 +        """Inject an event. Handlers for it are called if runing, otherwise
   13.95 +        it is queued.
   13.96 +
   13.97 +        event	event type
   13.98 +        val	event value
   13.99 +        """
  13.100 +        if self.run:
  13.101 +            #print ">event", event, val
  13.102 +            self.call_event_handlers(event, event, val)
  13.103 +            self.call_query_handlers(event, val)
  13.104 +            self.call_star_handlers(event, val)
  13.105 +        else:
  13.106 +            self.queue.append( (event, val) )
  13.107 +
  13.108 +    def call_event_handlers(self, key, event, val):
  13.109 +        """Call the handlers for an event.
  13.110 +        It is safe for handlers to subscribe or unsubscribe.
  13.111 +
  13.112 +        key	key for handler list
  13.113 +        event	event type
  13.114 +        val	event value
  13.115 +        """
  13.116 +        hl = self.handlers.get(key)
  13.117 +        if hl is None:
  13.118 +            return
  13.119 +        # Copy the handler list so that handlers can call
  13.120 +        # subscribe/unsubscribe safely - python list iteration
  13.121 +        # is not safe against list modification.
  13.122 +        for h in hl[:]:
  13.123 +            try:
  13.124 +                h(event, val)
  13.125 +            except:
  13.126 +                pass
  13.127 +        
  13.128 +    def call_query_handlers(self, event, val):
  13.129 +        """Call regex handlers for events matching 'event' that end in '?'.
  13.130 +
  13.131 +        event	event type
  13.132 +        val	event value
  13.133 +        """
  13.134 +        dot_idx = event.rfind(self.DOT)
  13.135 +        if dot_idx == -1:
  13.136 +            self.call_event_handlers(self.QUERY, event, val)
  13.137 +        else:
  13.138 +            event_query = event[0:dot_idx] + self.DOT_QUERY
  13.139 +            self.call_event_handlers(event_query, event, val)
  13.140 +
  13.141 +    def call_star_handlers(self, event, val):
  13.142 +        """Call regex handlers for events matching 'event' that end in '*'.
  13.143 +
  13.144 +        event	event type
  13.145 +        val	event value
  13.146 +        """
  13.147 +        etype = string.split(event, self.DOT)
  13.148 +        for i in range(len(etype), 0, -1):
  13.149 +            event_star = self.DOT.join(etype[0:i]) + self.DOT_STAR
  13.150 +            self.call_event_handlers(event_star, event, val)
  13.151 +        self.call_event_handlers(self.STAR, event, val)       
  13.152 +
  13.153 +def instance():
  13.154 +    global inst
  13.155 +    try:
  13.156 +        inst
  13.157 +    except:
  13.158 +        inst = EventServer()
  13.159 +        inst.start()
  13.160 +    return inst
  13.161 +
  13.162 +def main():
  13.163 +    def sys_star(event, val):
  13.164 +        print 'sys_star', event, val
  13.165 +
  13.166 +    def sys_foo(event, val):
  13.167 +        print 'sys_foo', event, val
  13.168 +        s.unsubscribe('sys.foo', sys_foo)
  13.169 +
  13.170 +    def sys_foo2(event, val):
  13.171 +        print 'sys_foo2', event, val
  13.172 +
  13.173 +    def sys_bar(event, val):
  13.174 +        print 'sys_bar', event, val
  13.175 +
  13.176 +    def sys_foo_bar(event, val):
  13.177 +        print 'sys_foo_bar', event, val
  13.178 +
  13.179 +    def foo_bar(event, val):
  13.180 +        print 'foo_bar', event, val
  13.181 +
  13.182 +    s = EventServer()
  13.183 +    s.start()
  13.184 +    s.subscribe('sys.*', sys_star)
  13.185 +    s.subscribe('sys.foo', sys_foo)
  13.186 +    s.subscribe('sys.foo', sys_foo2)
  13.187 +    s.subscribe('sys.bar', sys_bar)
  13.188 +    s.subscribe('sys.foo.bar', sys_foo_bar)
  13.189 +    s.subscribe('foo.bar', foo_bar)
  13.190 +    s.inject('sys.foo', 'hello')
  13.191 +    print
  13.192 +    s.inject('sys.bar', 'hello again')
  13.193 +    print
  13.194 +    s.inject('sys.foo.bar', 'hello again')
  13.195 +    print
  13.196 +    s.inject('foo.bar', 'hello again')
  13.197 +    print
  13.198 +    s.inject('foo', 'hello again')
  13.199 +    print
  13.200 +    s.start()
  13.201 +    s.unsubscribe('sys.*', sys_star)
  13.202 +    s.unsubscribe_all('sys.*')
  13.203 +    s.inject('sys.foo', 'hello')
  13.204 +
  13.205 +if __name__ == "__main__":
  13.206 +    main()
  13.207 +
    14.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    14.2 +++ b/tools/xenmgr/lib/EventTypes.py	Fri Jun 11 14:40:53 2004 +0000
    14.3 @@ -0,0 +1,34 @@
    14.4 +#   Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    14.5 +
    14.6 +## XEND_DOMAIN_CREATE = "xend.domain.create": dom
    14.7 +## create: 
    14.8 +## xend.domain.destroy: dom, reason:died/crashed
    14.9 +## xend.domain.up ?
   14.10 +
   14.11 +## xend.domain.start: dom
   14.12 +## xend.domain.stop: dom
   14.13 +## xend.domain.shutdown: dom
   14.14 +## xend.domain.halt: dom
   14.15 +
   14.16 +## xend.domain.migrate.begin: dom, to
   14.17 +## Begin tells: src host, src domain uri, dst host. Dst id known?
   14.18 +## err: src host, src domain uri, dst host, dst id if known, status (of domain: ok, dead,...), reason
   14.19 +## end: src host, src domain uri, dst host, dst uri
   14.20 +
   14.21 +## Events for both ends of migrate: for exporter and importer?
   14.22 +## Include migrate id so can tie together.
   14.23 +## Have uri /xend/migrate/<id> for migrate info (migrations in progress).
   14.24 +
   14.25 +## (xend.domain.migrate.begin (src <host>) (src.domain <id>)
   14.26 +##                            (dst <host>) (id <migrate id>))
   14.27 + 
   14.28 +## xend.domain.migrate.end:
   14.29 +## (xend.domain.migrate.end (domain <id>) (to <host>)
   14.30 +
   14.31 +## xend.node.up:  xend uri
   14.32 +## xend.node.down: xend uri
   14.33 +
   14.34 +## xend.error ?
   14.35 +
   14.36 +## format:
   14.37 +
    15.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    15.2 +++ b/tools/xenmgr/lib/PrettyPrint.py	Fri Jun 11 14:40:53 2004 +0000
    15.3 @@ -0,0 +1,299 @@
    15.4 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    15.5 +
    15.6 +"""General pretty-printer, including support for SXP.
    15.7 +
    15.8 +"""
    15.9 +import sys
   15.10 +import types
   15.11 +import StringIO
   15.12 +import sxp
   15.13 +
   15.14 +class PrettyItem:
   15.15 +
   15.16 +    def __init__(self, width):
   15.17 +        self.width = width
   15.18 +
   15.19 +    def insert(self, block):
   15.20 +        block.addtoline(self)
   15.21 +
   15.22 +    def get_width(self):
   15.23 +        return self.width
   15.24 +
   15.25 +    def output(self, out):
   15.26 +        print '***PrettyItem>output>', self
   15.27 +        pass
   15.28 +
   15.29 +    def prettyprint(self, out, width):
   15.30 +        print '***PrettyItem>prettyprint>', self
   15.31 +        return width
   15.32 +
   15.33 +class PrettyString(PrettyItem):
   15.34 +
   15.35 +    def __init__(self, x):
   15.36 +        PrettyItem.__init__(self, len(x))
   15.37 +        self.value = x
   15.38 +
   15.39 +    def output(self, out):
   15.40 +        out.write(self.value)
   15.41 +
   15.42 +    def prettyprint(self, line):
   15.43 +        line.output(self)
   15.44 +
   15.45 +    def show(self, out):
   15.46 +        print >> out, ("(string (width %d) '%s')" % (self.width, self.value))
   15.47 +
   15.48 +class PrettySpace(PrettyItem):
   15.49 +
   15.50 +    def output(self, out):
   15.51 +        out.write(' ' * self.width)
   15.52 +
   15.53 +    def prettyprint(self, line):
   15.54 +        line.output(self)
   15.55 +
   15.56 +    def show(self, out):
   15.57 +        print >> out, ("(space (width %d))" % self.width)
   15.58 +        
   15.59 +class PrettyBreak(PrettyItem):
   15.60 +
   15.61 +    def __init__(self, width, indent):
   15.62 +        PrettyItem.__init__(self, width)
   15.63 +        self.indent = indent
   15.64 +        self.space = 0
   15.65 +        self.active = 0
   15.66 +
   15.67 +    def output(self, out):
   15.68 +        out.write(' ' * self.width)
   15.69 +
   15.70 +    def prettyprint(self, line):
   15.71 +        if line.breaks(self.space):
   15.72 +            self.active = 1
   15.73 +            line.newline(self.indent)
   15.74 +        else:
   15.75 +            line.output(self)
   15.76 +
   15.77 +    def show(self, out):
   15.78 +        print >> out, ("(break (width %d) (indent %d) (space %d) (active %d))"
   15.79 +                       % (self.width, self.indent, self.space, self.lspace, self.active))
   15.80 +
   15.81 +class PrettyNewline(PrettySpace):
   15.82 +
   15.83 +    def __init__(self, indent):
   15.84 +        PrettySpace.__init__(self, indent)
   15.85 +
   15.86 +    def insert(self, block):
   15.87 +        block.newline()
   15.88 +        block.addtoline(self)
   15.89 +
   15.90 +    def output(self, out):
   15.91 +        out.write(' ' * self.width)
   15.92 +
   15.93 +    def prettyprint(self, line):
   15.94 +        line.newline(0)
   15.95 +        line.output(self)
   15.96 +
   15.97 +    def show(self, out):
   15.98 +        print >> out, ("(nl (indent %d))" % self.indent)
   15.99 +
  15.100 +class PrettyLine(PrettyItem):
  15.101 +    def __init__(self):
  15.102 +        PrettyItem.__init__(self, 0)
  15.103 +        self.content = []
  15.104 +
  15.105 +    def write(self, x):
  15.106 +        self.content.append(x)
  15.107 +
  15.108 +    def end(self):
  15.109 +        width = 0
  15.110 +        lastwidth = 0
  15.111 +        lastbreak = None
  15.112 +        for x in self.content:
  15.113 +            if isinstance(x, PrettyBreak):
  15.114 +                if lastbreak:
  15.115 +                    lastbreak.space = (width - lastwidth)
  15.116 +                lastbreak = x
  15.117 +                lastwidth = width
  15.118 +            width += x.get_width()
  15.119 +        if lastbreak:
  15.120 +            lastbreak.space = (width - lastwidth)
  15.121 +        self.width = width
  15.122 + 
  15.123 +    def prettyprint(self, line):
  15.124 +        for x in self.content:
  15.125 +            x.prettyprint(line)
  15.126 +
  15.127 +    def show(self, out):
  15.128 +        print >> out, '(LINE (width %d)' % self.width
  15.129 +        for x in self.content:
  15.130 +            x.show(out)
  15.131 +        print >> out, ')'
  15.132 +
  15.133 +class PrettyBlock(PrettyItem):
  15.134 +
  15.135 +    def __init__(self, all=0, parent=None):
  15.136 +        self.width = 0
  15.137 +        self.lines = []
  15.138 +        self.parent = parent
  15.139 +        self.indent = 0
  15.140 +        self.all = all
  15.141 +        self.broken = 0
  15.142 +        self.newline()
  15.143 +
  15.144 +    def add(self, item):
  15.145 +        item.insert(self)
  15.146 +
  15.147 +    def end(self):
  15.148 +        self.width = 0
  15.149 +        for l in self.lines:
  15.150 +            l.end()
  15.151 +            if self.width < l.width:
  15.152 +                self.width = l.width
  15.153 +
  15.154 +    def breaks(self, n):
  15.155 +        return self.all and self.broken
  15.156 +
  15.157 +    def newline(self):
  15.158 +        self.lines.append(PrettyLine())
  15.159 +
  15.160 +    def addtoline(self, x):
  15.161 +        self.lines[-1].write(x)
  15.162 +
  15.163 +    def prettyprint(self, line):
  15.164 +        self.indent = line.used
  15.165 +        line.block = self
  15.166 +        if not line.fits(self.width):
  15.167 +            self.broken = 1
  15.168 +        for l in self.lines:
  15.169 +            l.prettyprint(line)
  15.170 +        line.block = self.parent
  15.171 +
  15.172 +    def show(self, out):
  15.173 +        print >> out, ('(BLOCK (width %d) (indent %d) (all %d) (broken %d)' %
  15.174 +                       (self.width, self.indent, self.all, self.broken))
  15.175 +        for l in self.lines:
  15.176 +            l.show(out)
  15.177 +        print >> out, ')'
  15.178 +
  15.179 +class Line:
  15.180 +
  15.181 +    def __init__(self, out, width):
  15.182 +        self.out = out
  15.183 +        self.width = width
  15.184 +        self.used = 0
  15.185 +        self.space = self.width
  15.186 +
  15.187 +    def newline(self, indent):
  15.188 +        indent += self.block.indent
  15.189 +        self.out.write('\n')
  15.190 +        self.out.write(' ' * indent)
  15.191 +        self.used = indent
  15.192 +        self.space = self.width - self.used
  15.193 +
  15.194 +    def fits(self, n):
  15.195 +        return self.space - n >= 0
  15.196 +
  15.197 +    def breaks(self, n):
  15.198 +        return self.block.breaks(n) or not self.fits(n)
  15.199 +
  15.200 +    def output(self, x):
  15.201 +        n = x.get_width()
  15.202 +        self.space -= n
  15.203 +        self.used += n
  15.204 +        if self.space < 0:
  15.205 +            self.space = 0
  15.206 +        x.output(self.out)
  15.207 +
  15.208 +class PrettyPrinter:
  15.209 +    """A prettyprinter based on what I remember of Derek Oppen's
  15.210 +    prettyprint algorithm from TOPLAS way back.
  15.211 +    """
  15.212 +
  15.213 +    def __init__(self, width=40):
  15.214 +        self.width = width
  15.215 +        self.block = None
  15.216 +        self.top = None
  15.217 +
  15.218 +    def write(self, x):
  15.219 +        self.block.add(PrettyString(x))
  15.220 +
  15.221 +    def add(self, item):
  15.222 +        self.block.add(item)
  15.223 +
  15.224 +    def addbreak(self, width=1, indent=4):
  15.225 +        self.add(PrettyBreak(width, indent))
  15.226 +
  15.227 +    def addspace(self, width=1):
  15.228 +        self.add(PrettySpace(width))
  15.229 +
  15.230 +    def addnl(self, indent=0):
  15.231 +        self.add(PrettyNewline(indent))
  15.232 +
  15.233 +    def begin(self, all=0):
  15.234 +        block = PrettyBlock(all=all, parent=self.block)
  15.235 +        self.block = block
  15.236 +
  15.237 +    def end(self):
  15.238 +        self.block.end()
  15.239 +        if self.block.parent:
  15.240 +            self.block.parent.add(self.block)
  15.241 +        else:
  15.242 +            self.top = self.block
  15.243 +        self.block = self.block.parent
  15.244 +
  15.245 +    def prettyprint(self, out=sys.stdout):
  15.246 +        line = Line(out, self.width)
  15.247 +        self.top.prettyprint(line)
  15.248 +
  15.249 +class SXPPrettyPrinter(PrettyPrinter):
  15.250 +    """An SXP prettyprinter.
  15.251 +    """
  15.252 +    
  15.253 +    def pstring(self, x):
  15.254 +        io = StringIO.StringIO()
  15.255 +        sxp.show(x, out=io)
  15.256 +        io.seek(0)
  15.257 +        val = io.getvalue()
  15.258 +        io.close()
  15.259 +        return val
  15.260 +
  15.261 +    def pprint(self, l):
  15.262 +        if isinstance(l, types.ListType):
  15.263 +            self.begin(all=1)
  15.264 +            self.write('(')
  15.265 +            i = 0
  15.266 +            for x in l:
  15.267 +                if(i): self.addbreak()
  15.268 +                self.pprint(x)
  15.269 +                i += 1
  15.270 +            self.addbreak(width=0, indent=0)
  15.271 +            self.write(')')
  15.272 +            self.end()
  15.273 +        else:
  15.274 +            self.write(self.pstring(l))
  15.275 +
  15.276 +def prettyprint(sxpr, out=sys.stdout, width=80):
  15.277 +    """Prettyprint an SXP form.
  15.278 +
  15.279 +    sxpr	s-expression
  15.280 +    out		destination
  15.281 +    width	maximum output width
  15.282 +    """
  15.283 +    if isinstance(sxpr, types.ListType):
  15.284 +        pp = SXPPrettyPrinter(width=width)
  15.285 +        pp.pprint(sxpr)
  15.286 +        pp.prettyprint(out=out)
  15.287 +    else:
  15.288 +        sxp.show(sxpr, out=out)
  15.289 +    print >> out
  15.290 +
  15.291 +def main():
  15.292 +    pin = sxp.Parser()
  15.293 +    while 1:
  15.294 +        buf = sys.stdin.read(100)
  15.295 +        pin.input(buf)
  15.296 +        if buf == '': break
  15.297 +    l = pin.get_val()
  15.298 +    prettyprint(l, width=80)
  15.299 +
  15.300 +if __name__ == "__main__":
  15.301 +    main()
  15.302 +    
    16.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    16.2 +++ b/tools/xenmgr/lib/XendClient.py	Fri Jun 11 14:40:53 2004 +0000
    16.3 @@ -0,0 +1,368 @@
    16.4 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    16.5 +"""Client API for the HTTP interface on xend.
    16.6 +Callable as a script - see main().
    16.7 +"""
    16.8 +import sys
    16.9 +import httplib
   16.10 +import types
   16.11 +from StringIO import StringIO
   16.12 +import urlparse
   16.13 +
   16.14 +from encode import *
   16.15 +import sxp
   16.16 +import PrettyPrint
   16.17 +
   16.18 +DEBUG = 1
   16.19 +
   16.20 +class Foo(httplib.HTTPResponse):
   16.21 +
   16.22 +    def begin(self):
   16.23 +        fin = self.fp
   16.24 +        while(1):
   16.25 +            buf = fin.readline()
   16.26 +            print "***", buf
   16.27 +            if buf == '':
   16.28 +                print
   16.29 +                sys.exit()
   16.30 +
   16.31 +
   16.32 +def sxprio(sxpr):
   16.33 +    io = StringIO()
   16.34 +    sxp.show(sxpr, out=io)
   16.35 +    print >> io
   16.36 +    io.seek(0)
   16.37 +    return io
   16.38 +
   16.39 +def fileof(val):
   16.40 +    """Converter for passing configs.
   16.41 +    Handles lists, files directly.
   16.42 +    Assumes a string is a file name and passes its contents.
   16.43 +    """
   16.44 +    if isinstance(val, types.ListType):
   16.45 +        return sxprio(val)
   16.46 +    if isinstance(val, types.StringType):
   16.47 +        return file(val)
   16.48 +    if hasattr(val, 'readlines'):
   16.49 +        return val
   16.50 +
   16.51 +# todo: need to sort of what urls/paths are using for objects.
   16.52 +# e.g. for domains at the moment return '0'.
   16.53 +# should probably return abs path w.r.t. server, e.g. /xend/domain/0.
   16.54 +# As an arg, assume abs path is obj uri, otherwise just id.
   16.55 +
   16.56 +# Function to convert to full url: Xend.uri(path), e.g.
   16.57 +# maps /xend/domain/0 to http://wray-m-3.hpl.hp.com:8000/xend/domain/0
   16.58 +# And should accept urls for ids?
   16.59 +
   16.60 +def urljoin(location, root, prefix='', rest=''):
   16.61 +    base = 'http://' + location + root + prefix
   16.62 +    url = urlparse.urljoin(base, rest)
   16.63 +    return url
   16.64 +
   16.65 +def nodeurl(location, root, id=''):
   16.66 +    return urljoin(location, root, 'node/', id)
   16.67 +
   16.68 +def domainurl(location, root, id=''):
   16.69 +    return urljoin(location, root, 'domain/', id)
   16.70 +
   16.71 +def consoleurl(location, root, id=''):
   16.72 +    return urljoin(location, root, 'console/', id)
   16.73 +
   16.74 +def vbdurl(location, root, id=''):
   16.75 +    return urljoin(location, root, 'vbd/', id)
   16.76 +
   16.77 +def deviceurl(location, root, id=''):
   16.78 +    return urljoin(location, root, 'device/', id)
   16.79 +
   16.80 +def vneturl(location, root, id=''):
   16.81 +    return urljoin(location, root, 'vnet/', id)
   16.82 +
   16.83 +def eventurl(location, root, id=''):
   16.84 +    return urljoin(location, root, 'event/', id)
   16.85 +
   16.86 +def xend_request(url, method, data=None):
   16.87 +    urlinfo = urlparse.urlparse(url)
   16.88 +    (uproto, ulocation, upath, uparam, uquery, ufrag) = urlinfo
   16.89 +    if DEBUG: print url, urlinfo
   16.90 +    if uproto != 'http':
   16.91 +        raise StandardError('Invalid protocol: ' + uproto)
   16.92 +    if DEBUG: print '>xend_request', ulocation, upath, method, data
   16.93 +    (hdr, args) = encode_data(data)
   16.94 +    if data and method == 'GET':
   16.95 +        upath += '?' + args
   16.96 +        args = None
   16.97 +    if method == "POST" and upath.endswith('/'):
   16.98 +        upath = upath[:-1]
   16.99 +    if DEBUG: print "ulocation=", ulocation, "upath=", upath, "args=", args
  16.100 +    #hdr['User-Agent'] = 'Mozilla'
  16.101 +    #hdr['Accept'] = 'text/html,text/plain'
  16.102 +    conn = httplib.HTTPConnection(ulocation)
  16.103 +    #conn.response_class = Foo
  16.104 +    conn.set_debuglevel(1)
  16.105 +    conn.request(method, upath, args, hdr)
  16.106 +    resp = conn.getresponse()
  16.107 +    if DEBUG: print resp.status, resp.reason
  16.108 +    if DEBUG: print resp.msg.headers
  16.109 +    if resp.status in [204, 404]:
  16.110 +        return None
  16.111 +    if resp.status not in [200, 201, 202, 203]:
  16.112 +        raise RuntimeError(resp.reason)
  16.113 +    pin = sxp.Parser()
  16.114 +    data = resp.read()
  16.115 +    if DEBUG: print "***data" , data
  16.116 +    if DEBUG: print "***"
  16.117 +    pin.input(data);
  16.118 +    pin.input_eof()
  16.119 +    conn.close()
  16.120 +    val = pin.get_val()
  16.121 +    #if isinstance(val, types.ListType) and sxp.name(val) == 'val':
  16.122 +    #    val = val[1]
  16.123 +    if isinstance(val, types.ListType) and sxp.name(val) == 'err':
  16.124 +        raise RuntimeError(val[1])
  16.125 +    if DEBUG: print '**val='
  16.126 +    #sxp.show(val); print
  16.127 +    PrettyPrint.prettyprint(val)
  16.128 +    if DEBUG: print '**'
  16.129 +    return val
  16.130 +
  16.131 +def xend_get(url, args=None):
  16.132 +    return xend_request(url, "GET", args)
  16.133 +
  16.134 +def xend_call(url, data):
  16.135 +    return xend_request(url, "POST", data)
  16.136 +
  16.137 +class Xend:
  16.138 +
  16.139 +    SRV_DEFAULT = "localhost:8000"
  16.140 +    ROOT_DEFAULT = "/xend/"
  16.141 +
  16.142 +    def __init__(self, srv=None, root=None):
  16.143 +        self.bind(srv, root)
  16.144 +
  16.145 +    def bind(self, srv=None, root=None):
  16.146 +        if srv is None: srv = self.SRV_DEFAULT
  16.147 +        if root is None: root = self.ROOT_DEFAULT
  16.148 +        if not root.endswith('/'): root += '/'
  16.149 +        self.location = srv
  16.150 +        self.root = root
  16.151 +
  16.152 +    def nodeurl(self, id=''):
  16.153 +        return nodeurl(self.location, self.root, id)
  16.154 +
  16.155 +    def domainurl(self, id=''):
  16.156 +        return domainurl(self.location, self.root, id)
  16.157 +
  16.158 +    def consoleurl(self, id=''):
  16.159 +        return consoleurl(self.location, self.root, id)
  16.160 +
  16.161 +    def vbdurl(self, id=''):
  16.162 +        return vbdurl(self.location, self.root, id)
  16.163 +
  16.164 +    def deviceurl(self, id=''):
  16.165 +        return deviceurl(self.location, self.root, id)
  16.166 +
  16.167 +    def vneturl(self, id=''):
  16.168 +        return vneturl(self.location, self.root, id)
  16.169 +
  16.170 +    def eventurl(self, id=''):
  16.171 +        return eventurl(self.location, self.root, id)
  16.172 +
  16.173 +    def xend(self):
  16.174 +        return xend_get(urljoin(self.location, self.root))
  16.175 +
  16.176 +    def xend_node(self):
  16.177 +        return xend_get(self.nodeurl())
  16.178 +
  16.179 +    def xend_node_cpu_rrobin_slice_set(self, slice):
  16.180 +        return xend_call(self.nodeurl(),
  16.181 +                         {'op'      : 'cpu_rrobin_slice_set',
  16.182 +                          'slice'   : slice })
  16.183 +    
  16.184 +    def xend_node_cpu_bvt_slice_set(self, slice):
  16.185 +        return xend_call(self.nodeurl(),
  16.186 +                         {'op'      : 'cpu_bvt_slice_set',
  16.187 +                          'slice'   : slice })
  16.188 +
  16.189 +    def xend_domains(self):
  16.190 +        return xend_get(self.domainurl())
  16.191 +
  16.192 +    def xend_domain_create(self, conf):
  16.193 +        return xend_call(self.domainurl(),
  16.194 +                         {'op'      : 'create',
  16.195 +                          'config'  : fileof(conf) })
  16.196 +
  16.197 +    def xend_domain(self, id):
  16.198 +        return xend_get(self.domainurl(id))
  16.199 +
  16.200 +    def xend_domain_start(self, id):
  16.201 +        return xend_call(self.domainurl(id),
  16.202 +                         {'op'      : 'start'})
  16.203 +
  16.204 +    def xend_domain_stop(self, id):
  16.205 +        return xend_call(self.domainurl(id),
  16.206 +                         {'op'      : 'stop'})
  16.207 +
  16.208 +    def xend_domain_shutdown(self, id):
  16.209 +        return xend_call(self.domainurl(id),
  16.210 +                         {'op'      : 'shutdown'})
  16.211 +
  16.212 +    def xend_domain_halt(self, id):
  16.213 +        return xend_call(self.domainurl(id),
  16.214 +                         {'op'      : 'halt'})
  16.215 +
  16.216 +    def xend_domain_save(self, id, filename):
  16.217 +        return xend_call(self.domainurl(id),
  16.218 +                         {'op'      : 'save',
  16.219 +                          'file'    : filename})
  16.220 +
  16.221 +    def xend_domain_restore(self, id, filename, conf):
  16.222 +        return xend_call(self.domainurl(id),
  16.223 +                         {'op'      : 'restore',
  16.224 +                          'file'    : filename,
  16.225 +                          'config'  : fileof(conf) })
  16.226 +
  16.227 +    def xend_domain_migrate(self, id, dst):
  16.228 +        return xend_call(self.domainurl(id),
  16.229 +                         {'op'      : 'migrate',
  16.230 +                          'dst'     : dst})
  16.231 +
  16.232 +    def xend_domain_pincpu(self, id, cpu):
  16.233 +        return xend_call(self.domainurl(id),
  16.234 +                         {'op'      : 'pincpu',
  16.235 +                          'cpu'     : cpu})
  16.236 +
  16.237 +    def xend_domain_cpu_bvt_set(self, id, mcuadv, warp, warpl, warpu):
  16.238 +        return xend_call(self.domainurl(id),
  16.239 +                         {'op'      : 'cpu_bvt_set',
  16.240 +                          'mcuadv'  : mvuadv,
  16.241 +                          'warp'    : warp,
  16.242 +                          'warpl'   : warpl,
  16.243 +                          'warpu'   : warpu })
  16.244 +
  16.245 +    def xend_domain_cpu_atropos_set(self, id, period, slice, latency, xtratime):
  16.246 +        return xend_call(self.domainurl(id),
  16.247 +                         {'op'      : 'cpu_atropos_set',
  16.248 +                          'period'  : period,
  16.249 +                          'slice'   : slice,
  16.250 +                          'latency' : latency,
  16.251 +                          'xtratime': xtratime })
  16.252 +
  16.253 +    def xend_domain_vifs(self, id):
  16.254 +        return xend_get(self.domainurl(id),
  16.255 +                        { 'op'      : 'vifs' })
  16.256 +    
  16.257 +    def xend_domain_vif_stats(self, id, vif):
  16.258 +        return xend_get(self.domainurl(id),
  16.259 +                        { 'op'      : 'vif_stats',
  16.260 +                          'vif'     : vif})
  16.261 +
  16.262 +    def xend_domain_vif_ip_add(self, id, vif, ipaddr):
  16.263 +        return xend_call(self.domainurl(id),
  16.264 +                         {'op'      : 'vif_ip_add',
  16.265 +                          'vif'     : vif,
  16.266 +                          'ip'      : ipaddr })
  16.267 +        
  16.268 +    def xend_domain_vif_scheduler_set(id, vif, bytes, usecs):
  16.269 +        return xend_call(self.domainurl(id),
  16.270 +                         {'op'      : 'vif_scheduler_set',
  16.271 +                          'vif'     : vif,
  16.272 +                          'bytes'   : bytes,
  16.273 +                          'usecs'   : usecs })
  16.274 +
  16.275 +    def xend_domain_vif_scheduler_get(id, vif):
  16.276 +        return xend_get(self.domainurl(id),
  16.277 +                         {'op'      : 'vif_scheduler_get',
  16.278 +                          'vif'     : vif})
  16.279 +
  16.280 +    def xend_domain_vbds(self, id):
  16.281 +        return xend_get(self.domainurl(id),
  16.282 +                        {'op'       : 'vbds'})
  16.283 +
  16.284 +    def xend_domain_vbd(self, id, vbd):
  16.285 +        return xend_get(self.domainurl(id),
  16.286 +                        {'op'       : 'vbd',
  16.287 +                         'vbd'      : vbd})
  16.288 +
  16.289 +    def xend_domain_vbd_add(self, id, uname, dev, mode):
  16.290 +        return xend_call(self.domainurl(id),
  16.291 +                         {'op'      : 'vbd_add',
  16.292 +                          'uname'   : uname,
  16.293 +                          'dev'     : dev,
  16.294 +                          'mode'    : mode})
  16.295 +
  16.296 +    def xend_domain_vbd_remove(self, id, dev):
  16.297 +        return xend_call(self.domainurl(id),
  16.298 +                         {'op'      : 'vbd_remove',
  16.299 +                          'dev'     : dev})
  16.300 +
  16.301 +    def xend_consoles(self):
  16.302 +        return xend_get(self.consoleurl())
  16.303 +
  16.304 +    def xend_console(self, id):
  16.305 +        return xend_get(self.consoleurl(id))
  16.306 +
  16.307 +    def xend_vbds(self):
  16.308 +        return xend_get(self.vbdurl())
  16.309 +
  16.310 +    def xend_vbd_create(self, conf):
  16.311 +        return xend_call(self.vbdurl(),
  16.312 +                         {'op': 'create', 'config': fileof(conf) })
  16.313 +
  16.314 +    def xend_vbd(self, id):
  16.315 +        return xend_get(self.vbdurl(id))
  16.316 +
  16.317 +    def xend_vbd_delete(self, id):
  16.318 +        return xend_call(self.vbdurl(id),
  16.319 +                         {'op': 'delete'})
  16.320 +
  16.321 +    def xend_vbd_refresh(self, id, expiry):
  16.322 +        return xend_call(self.vbdurl(id),
  16.323 +                         {'op': 'refresh', 'expiry': expiry })
  16.324 +
  16.325 +    def xend_vbd_expand(self, id, size):
  16.326 +        return xend_call(self.vbdurl(id),
  16.327 +                         {'op': 'expand', 'size': size})
  16.328 +
  16.329 +    def xend_vnets(self):
  16.330 +        return xend_get(self.vneturl())
  16.331 +
  16.332 +    def xend_vnet_create(self, conf):
  16.333 +        return xend_call(self.vneturl(),
  16.334 +                         {'op': 'create', 'config': fileof(conf) })
  16.335 +
  16.336 +    def xend_vnet(self, id):
  16.337 +        return xend_get(self.vneturl(id))
  16.338 +
  16.339 +    def xend_vnet_delete(self, id):
  16.340 +        return xend_call(self.vneturl(id),
  16.341 +                         {'op': 'delete'})
  16.342 +
  16.343 +    def xend_event_inject(self, sxpr):
  16.344 +        val = xend_call(self.eventurl(),
  16.345 +                        {'op': 'inject', 'event': fileof(sxpr) })
  16.346 +    
  16.347 +
  16.348 +def main(argv):
  16.349 +    """Call an API function:
  16.350 +    
  16.351 +    python XendClient.py fn args...
  16.352 +
  16.353 +    The leading 'xend_' on the function can be omitted.
  16.354 +    Example:
  16.355 +
  16.356 +    > python XendClient.py domains
  16.357 +    (domain 0 8)
  16.358 +    > python XendClient.py domain 0
  16.359 +    (domain (id 0) (name Domain-0) (memory 128))
  16.360 +    """
  16.361 +    server = Xend()
  16.362 +    fn = argv[1]
  16.363 +    if not fn.startswith('xend'):
  16.364 +        fn = 'xend_' + fn
  16.365 +    args = argv[2:]
  16.366 +    getattr(server, fn)(*args)
  16.367 +
  16.368 +if __name__ == "__main__":
  16.369 +    main(sys.argv)
  16.370 +else:    
  16.371 +    server = Xend()
    17.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    17.2 +++ b/tools/xenmgr/lib/XendConsole.py	Fri Jun 11 14:40:53 2004 +0000
    17.3 @@ -0,0 +1,172 @@
    17.4 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    17.5 +
    17.6 +import socket
    17.7 +import Xc
    17.8 +xc = Xc.new()
    17.9 +
   17.10 +import sxp
   17.11 +import XendRoot
   17.12 +xroot = XendRoot.instance()
   17.13 +import XendDB
   17.14 +
   17.15 +import EventServer
   17.16 +eserver = EventServer.instance()
   17.17 +
   17.18 +from xenmgr.server import SrvConsoleServer
   17.19 +xcd = SrvConsoleServer.instance()
   17.20 +
   17.21 +class XendConsoleInfo:
   17.22 +    """Console information record.
   17.23 +    """
   17.24 +
   17.25 +    def __init__(self, console, dom1, port1, dom2, port2, conn=None):
   17.26 +        self.console = console
   17.27 +        self.dom1  = dom1
   17.28 +        self.port1 = port1
   17.29 +        self.dom2  = dom2
   17.30 +        self.port2 = port2
   17.31 +        self.conn  = conn
   17.32 +        #self.id = "%d.%d-%d.%d" % (self.dom1, self.port1, self.dom2, self.port2)
   17.33 +        self.id = str(port1)
   17.34 +
   17.35 +    def __str__(self):
   17.36 +        s = "console"
   17.37 +        s += " id=%s" % self.id
   17.38 +        s += " src=%d.%d" % (self.dom1, self.port1)
   17.39 +        s += " dst=%d.%d" % (self.dom2, self.port2)
   17.40 +        s += " port=%s" % self.console
   17.41 +        if self.conn:
   17.42 +            s += " conn=%s:%s" % (self.conn[0], self.conn[1])
   17.43 +        return s
   17.44 +
   17.45 +    def sxpr(self):
   17.46 +        sxpr = ['console',
   17.47 +                ['id', self.id],
   17.48 +                ['src', self.dom1, self.port1],
   17.49 +                ['dst', self.dom2, self.port2],
   17.50 +                ['port', self.console],
   17.51 +                ]
   17.52 +        if self.conn:
   17.53 +            sxpr.append(['connected', self.conn[0], self.conn[1]])
   17.54 +        return sxpr
   17.55 +
   17.56 +    def connection(self):
   17.57 +        return self.conn
   17.58 +
   17.59 +    def update(self, consinfo):
   17.60 +        conn = sxp.child(consinfo, 'connected')
   17.61 +        if conn:
   17.62 +            self.conn = conn[1:]
   17.63 +        else:
   17.64 +            self.conn = None
   17.65 +
   17.66 +    def uri(self):
   17.67 +        """Get the uri to use to connect to the console.
   17.68 +        This will be a telnet: uri.
   17.69 +
   17.70 +        return uri
   17.71 +        """
   17.72 +        host = socket.gethostname()
   17.73 +        return "telnet://%s:%s" % (host, self.console)
   17.74 +
   17.75 +class XendConsole:
   17.76 +
   17.77 +    dbpath = "console"
   17.78 +
   17.79 +    def  __init__(self):
   17.80 +        self.db = XendDB.XendDB(self.dbpath)
   17.81 +        self.console = {}
   17.82 +        self.console_db = self.db.fetchall("")
   17.83 +        if xroot.get_rebooted():
   17.84 +            print 'XendConsole> rebooted: removing all console info'
   17.85 +            self.rm_all()
   17.86 +        eserver.subscribe('xend.domain.died', self.onDomainDied)
   17.87 +
   17.88 +    def rm_all(self):
   17.89 +        """Remove all console info. Used after reboot.
   17.90 +        """
   17.91 +        for (k, v) in self.console_db.items():
   17.92 +            self._delete_console(k)
   17.93 +
   17.94 +    def refresh(self):
   17.95 +        consoles = xcd.consoles()
   17.96 +        cons = {}
   17.97 +        for consinfo in consoles:
   17.98 +            id = str(sxp.child_value(consinfo, 'id'))
   17.99 +            cons[id] = consinfo
  17.100 +            if id not in self.console:
  17.101 +                self._new_console(consinfo)
  17.102 +        for c in self.console.values():
  17.103 +            consinfo = cons.get(c.id)
  17.104 +            if consinfo:
  17.105 +                c.update(consinfo)
  17.106 +            else:
  17.107 +                self._delete_console(c.id)
  17.108 +
  17.109 +    def onDomainDied(self, event, val):
  17.110 +        dom = int(val)
  17.111 +        for c in self.consoles():
  17.112 +            if (c.dom1 == dom) or (c.dom2 == dom):
  17.113 +                self._delete_console(c.id)
  17.114 +
  17.115 +    def sync(self):
  17.116 +        self.db.saveall("", self.console_db)
  17.117 +
  17.118 +    def sync_console(self, id):
  17.119 +        self.db.save(id, self.console_db[id])
  17.120 +
  17.121 +    def _new_console(self, consinfo):
  17.122 +        # todo: xen needs a call to get current domain id.
  17.123 +        dom1 = 0
  17.124 +        port1 = sxp.child_value(consinfo, 'local_port')
  17.125 +        dom2 = sxp.child_value(consinfo, 'domain')
  17.126 +        port2 = sxp.child_value(consinfo, 'remote_port')
  17.127 +        console = sxp.child_value(consinfo, 'console_port')
  17.128 +        info = XendConsoleInfo(console, dom1, int(port1), int(dom2), int(port2))
  17.129 +        info.update(consinfo)
  17.130 +        self._add_console(info.id, info)
  17.131 +        return info
  17.132 +
  17.133 +    def _add_console(self, id, info):
  17.134 +        self.console[id] = info
  17.135 +        self.console_db[id] = info.sxpr()
  17.136 +        self.sync_console(id)
  17.137 +
  17.138 +    def _delete_console(self, id):
  17.139 +        if id in self.console:
  17.140 +            del self.console[id]
  17.141 +        if id in self.console_db:
  17.142 +            del self.console_db[id]
  17.143 +            self.db.delete(id)
  17.144 +
  17.145 +    def console_ls(self):
  17.146 +        self.refresh()
  17.147 +        return self.console.keys()
  17.148 +
  17.149 +    def consoles(self):
  17.150 +        self.refresh()
  17.151 +        return self.console.values()
  17.152 +    
  17.153 +    def console_create(self, dom):
  17.154 +        consinfo = xcd.console_create(dom)
  17.155 +        info = self._new_console(consinfo)
  17.156 +        return info
  17.157 +    
  17.158 +    def console_get(self, id):
  17.159 +        self.refresh()
  17.160 +        return self.console.get(id)
  17.161 +
  17.162 +    def console_delete(self, id):
  17.163 +        self._delete_console(id)
  17.164 +
  17.165 +    def console_disconnect(self, id):
  17.166 +        id = int(id)
  17.167 +        xcd.console_disconnect(id)
  17.168 +
  17.169 +def instance():
  17.170 +    global inst
  17.171 +    try:
  17.172 +        inst
  17.173 +    except:
  17.174 +        inst = XendConsole()
  17.175 +    return inst
    18.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    18.2 +++ b/tools/xenmgr/lib/XendDB.py	Fri Jun 11 14:40:53 2004 +0000
    18.3 @@ -0,0 +1,91 @@
    18.4 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    18.5 +
    18.6 +import os
    18.7 +import os.path
    18.8 +import errno
    18.9 +import dircache
   18.10 +import time
   18.11 +
   18.12 +import sxp
   18.13 +import XendRoot
   18.14 +xroot = XendRoot.instance()
   18.15 +
   18.16 +class XendDB:
   18.17 +    """Persistence for Xend. Stores data in files and directories.
   18.18 +    """
   18.19 +
   18.20 +    def __init__(self, path=None):
   18.21 +        self.dbpath = xroot.get_dbroot()
   18.22 +        if path:
   18.23 +            self.dbpath = os.path.join(self.dbpath, path)
   18.24 +        pass
   18.25 +
   18.26 +    def filepath(self, path):
   18.27 +        return os.path.join(self.dbpath, path)
   18.28 +        
   18.29 +    def fetch(self, path):
   18.30 +        fpath = self.filepath(path)
   18.31 +        return self.fetchfile(fpath)
   18.32 +
   18.33 +    def fetchfile(self, fpath):
   18.34 +        pin = sxp.Parser()
   18.35 +        fin = file(fpath, "rb")
   18.36 +        try:
   18.37 +            while 1:
   18.38 +                try:
   18.39 +                    buf = fin.read(1024)
   18.40 +                except IOError, ex:
   18.41 +                    if ex.errno == errno.EINTR:
   18.42 +                        continue
   18.43 +                    else:
   18.44 +                        raise
   18.45 +                pin.input(buf)
   18.46 +                if buf == '':
   18.47 +                    pin.input_eof()
   18.48 +                    break
   18.49 +        finally:
   18.50 +            fin.close()
   18.51 +        return pin.get_val()
   18.52 +
   18.53 +    def save(self, path, sxpr):
   18.54 +        fpath = self.filepath(path)
   18.55 +        return self.savefile(fpath, sxpr)
   18.56 +    
   18.57 +    def savefile(self, fpath, sxpr):
   18.58 +        fdir = os.path.dirname(fpath)
   18.59 +        if not os.path.isdir(fdir):
   18.60 +            os.makedirs(fdir)
   18.61 +        fout = file(fpath, "wb+")
   18.62 +        try:
   18.63 +            t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
   18.64 +            fout.write("# %s %s\n" % (fpath, t))
   18.65 +            sxp.show(sxpr, out=fout)
   18.66 +        finally:
   18.67 +            fout.close()
   18.68 +
   18.69 +    def fetchall(self, path):
   18.70 +        dpath = self.filepath(path)
   18.71 +        d = {}
   18.72 +        for k in dircache.listdir(dpath):
   18.73 +            try:
   18.74 +                v = self.fetchfile(os.path.join(dpath, k))
   18.75 +                d[k] = v
   18.76 +            except:
   18.77 +                pass
   18.78 +        return d
   18.79 +
   18.80 +    def saveall(self, path, d):
   18.81 +        for (k, v) in d.items():
   18.82 +            self.save(os.path.join(path, k), v)
   18.83 +
   18.84 +    def delete(self, path):
   18.85 +        dpath = self.filepath(path)
   18.86 +        os.unlink(dpath)
   18.87 +
   18.88 +    def ls(self, path):
   18.89 +        dpath = self.filepath(path)
   18.90 +        return dircache.listdir(dpath)
   18.91 +            
   18.92 +        
   18.93 +
   18.94 +        
    19.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    19.2 +++ b/tools/xenmgr/lib/XendDomain.py	Fri Jun 11 14:40:53 2004 +0000
    19.3 @@ -0,0 +1,347 @@
    19.4 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    19.5 +
    19.6 +"""Handler for domain operations.
    19.7 + Nothing here is persistent (across reboots).
    19.8 + Needs to be persistent for one uptime.
    19.9 +"""
   19.10 +import sys
   19.11 +
   19.12 +import Xc; xc = Xc.new()
   19.13 +import xenctl.ip
   19.14 +import xenctl.vdisk
   19.15 +
   19.16 +import sxp
   19.17 +import XendRoot
   19.18 +xroot = XendRoot.instance()
   19.19 +import XendDB
   19.20 +import XendDomainInfo
   19.21 +import XendConsole
   19.22 +import EventServer
   19.23 +
   19.24 +eserver = EventServer.instance()
   19.25 +
   19.26 +__all__ = [ "XendDomain" ]
   19.27 +        
   19.28 +class XendDomain:
   19.29 +    """Index of all domains. Singleton.
   19.30 +    """
   19.31 +    
   19.32 +    dbpath = "domain"
   19.33 +    domain = {}
   19.34 +    
   19.35 +    def __init__(self):
   19.36 +        self.xconsole = XendConsole.instance()
   19.37 +        # Table of domain info indexed by domain id.
   19.38 +        self.db = XendDB.XendDB(self.dbpath)
   19.39 +        #self.domain = {}
   19.40 +        self.domain_db = self.db.fetchall("")
   19.41 +        if xroot.get_rebooted():
   19.42 +            print 'XendDomain> rebooted: removing all domain info'
   19.43 +            self.rm_all()
   19.44 +        self.initial_refresh()
   19.45 +
   19.46 +    def rm_all(self):
   19.47 +        """Remove all domain info. Used after reboot.
   19.48 +        """
   19.49 +        for (k, v) in self.domain_db.items():
   19.50 +            self._delete_domain(k, notify=0)
   19.51 +            
   19.52 +    def initial_refresh(self):
   19.53 +        """Refresh initial domain info from domain_db.
   19.54 +        """
   19.55 +        domlist = xc.domain_getinfo()
   19.56 +        doms = {}
   19.57 +        for d in domlist:
   19.58 +            domid = str(d['dom'])
   19.59 +            doms[domid] = d
   19.60 +        for config in self.domain_db.values():
   19.61 +            domid = int(sxp.child_value(config, 'id'))
   19.62 +            if domid in doms:
   19.63 +                self._new_domain(config)
   19.64 +            else:
   19.65 +                self._delete_domain(domid)
   19.66 +        self.refresh()
   19.67 +
   19.68 +    def sync(self):
   19.69 +        """Sync domain db to disk.
   19.70 +        """
   19.71 +        self.db.saveall("", self.domain_db)
   19.72 +
   19.73 +    def sync_domain(self, dom):
   19.74 +        """Sync info for a domain to disk.
   19.75 +
   19.76 +        dom	domain id (string)
   19.77 +        """
   19.78 +        self.db.save(dom, self.domain_db[dom])
   19.79 +
   19.80 +    def close(self):
   19.81 +        pass
   19.82 +
   19.83 +    def _new_domain(self, info):
   19.84 +        """Create a domain entry from saved info.
   19.85 +        """
   19.86 +        console = None
   19.87 +        kernel = None
   19.88 +        id = sxp.child_value(info, 'id')
   19.89 +        dom = int(id)
   19.90 +        name = sxp.child_value(info, 'name')
   19.91 +        memory = int(sxp.child_value(info, 'memory'))
   19.92 +        consoleinfo = sxp.child(info, 'console')
   19.93 +        if consoleinfo:
   19.94 +            consoleid = sxp.child_value(consoleinfo, 'id')
   19.95 +            console = self.xconsole.console_get(consoleid)
   19.96 +        if dom and console is None:
   19.97 +            # Try to connect a console.
   19.98 +            console = self.xconsole.console_create(dom)
   19.99 +        config = sxp.child(info, 'config')
  19.100 +        if config:
  19.101 +            image = sxp.child(info, 'image')
  19.102 +            if image:
  19.103 +                image = sxp.child0(image)
  19.104 +                kernel = sxp.child_value(image, 'kernel')
  19.105 +        dominfo = XendDomainInfo.XendDomainInfo(
  19.106 +            config, dom, name, memory, kernel, console)
  19.107 +        self.domain[id] = dominfo
  19.108 +
  19.109 +    def _add_domain(self, id, info, notify=1):
  19.110 +        self.domain[id] = info
  19.111 +        self.domain_db[id] = info.sxpr()
  19.112 +        self.sync_domain(id)
  19.113 +        if notify: eserver.inject('xend.domain.created', id)
  19.114 +
  19.115 +    def _delete_domain(self, id, notify=1):
  19.116 +        if id in self.domain:
  19.117 +            if notify: eserver.inject('xend.domain.died', id)
  19.118 +            del self.domain[id]
  19.119 +        if id in self.domain_db:
  19.120 +            del self.domain_db[id]
  19.121 +            self.db.delete(id)
  19.122 +
  19.123 +    def refresh(self):
  19.124 +        """Refresh domain list from Xen.
  19.125 +        """
  19.126 +        domlist = xc.domain_getinfo()
  19.127 +        # Index the domlist by id.
  19.128 +        # Add entries for any domains we don't know about.
  19.129 +        doms = {}
  19.130 +        for d in domlist:
  19.131 +            id = str(d['dom'])
  19.132 +            doms[id] = d
  19.133 +            if id not in self.domain:
  19.134 +                config = None
  19.135 +                image = None
  19.136 +                newinfo = XendDomainInfo.XendDomainInfo(
  19.137 +                    config, d['dom'], d['name'], d['mem_kb']/1024, image)
  19.138 +                self._add_domain(id, newinfo)
  19.139 +        # Remove entries for domains that no longer exist.
  19.140 +        for d in self.domain.values():
  19.141 +            dominfo = doms.get(d.id)
  19.142 +            if dominfo:
  19.143 +                d.update(dominfo)
  19.144 +            else:
  19.145 +                self._delete_domain(d.id)
  19.146 +
  19.147 +    def refresh_domain(self, id):
  19.148 +        dom = int(id)
  19.149 +        dominfo = xc.domain_getinfo(dom, 1)
  19.150 +        if dominfo == [] or dominfo[0]['dom'] != dom:
  19.151 +            try:
  19.152 +                self._delete_domain(id)
  19.153 +            except:
  19.154 +                pass
  19.155 +        else:
  19.156 +            d = self.domain.get(id)
  19.157 +            if d:
  19.158 +                d.update(dominfo)
  19.159 +
  19.160 +    def domain_ls(self):
  19.161 +        # List domains.
  19.162 +        # Update info from kernel first.
  19.163 +        self.refresh()
  19.164 +        return self.domain.keys()
  19.165 +
  19.166 +    def domains(self):
  19.167 +        self.refresh()
  19.168 +        return self.domain.values()
  19.169 +    
  19.170 +    def domain_create(self, config):
  19.171 +        # Create domain, log it.
  19.172 +        deferred = XendDomainInfo.vm_create(config)
  19.173 +        def fn(dominfo):
  19.174 +            self._add_domain(dominfo.id, dominfo)
  19.175 +            return dominfo
  19.176 +        deferred.addCallback(fn)
  19.177 +        return deferred
  19.178 +    
  19.179 +    def domain_get(self, id):
  19.180 +        id = str(id)
  19.181 +        self.refresh_domain(id)
  19.182 +        return self.domain[id]
  19.183 +    
  19.184 +    def domain_start(self, id):
  19.185 +        """Start domain running.
  19.186 +        """
  19.187 +        dom = int(id)
  19.188 +        eserver.inject('xend.domain.start', id)
  19.189 +        return xc.domain_start(dom=dom)
  19.190 +    
  19.191 +    def domain_stop(self, id):
  19.192 +        """Stop domain running.
  19.193 +        """
  19.194 +        dom = int(id)
  19.195 +        return xc.domain_stop(dom=dom)
  19.196 +    
  19.197 +    def domain_shutdown(self, id):
  19.198 +        """Shutdown domain (nicely).
  19.199 +        """
  19.200 +        dom = int(id)
  19.201 +        if dom <= 0:
  19.202 +            return 0
  19.203 +        eserver.inject('xend.domain.shutdown', id)
  19.204 +        val = xc.domain_destroy(dom=dom, force=0)
  19.205 +        self.refresh()
  19.206 +        return val
  19.207 +    
  19.208 +    def domain_halt(self, id):
  19.209 +        """Shutdown domain immediately.
  19.210 +        """
  19.211 +        dom = int(id)
  19.212 +        if dom <= 0:
  19.213 +            return 0
  19.214 +        eserver.inject('xend.domain.halt', id)
  19.215 +        val = xc.domain_destroy(dom=dom, force=1)
  19.216 +        self.refresh()
  19.217 +        return val       
  19.218 +
  19.219 +    def domain_migrate(self, id, dst):
  19.220 +        """Start domain migration.
  19.221 +        """
  19.222 +        # Need a cancel too?
  19.223 +        pass
  19.224 +    
  19.225 +    def domain_save(self, id, dst, progress=0):
  19.226 +        """Save domain state to file, halt domain.
  19.227 +        """
  19.228 +        dom = int(id)
  19.229 +        self.domain_stop(id)
  19.230 +        eserver.inject('xend.domain.save', id)
  19.231 +        rc = xc.linux_save(dom=dom, state_file=dst, progress=progress)
  19.232 +        if rc == 0:
  19.233 +            self.domain_halt(id)
  19.234 +        return rc
  19.235 +    
  19.236 +    def domain_restore(self, src, config, progress=0):
  19.237 +        """Restore domain from file.
  19.238 +        """
  19.239 +        dominfo = XendDomainInfo.dom_restore(dom, config)
  19.240 +        self._add_domain(dominfo.id, dominfo)
  19.241 +        return dominfo
  19.242 +    
  19.243 +    def domain_device_add(self, id, info):
  19.244 +        """Add a device to a domain.
  19.245 +        """
  19.246 +        pass
  19.247 +    
  19.248 +    def domain_device_remove(self, id, dev):
  19.249 +        """Delete a device from a domain.
  19.250 +        """
  19.251 +        pass
  19.252 +    
  19.253 +    def domain_device_configure(self, id, dev, info):
  19.254 +        """Configure a domain device.
  19.255 +        """
  19.256 +        pass
  19.257 +
  19.258 +    #============================================================================
  19.259 +    # Backward compatibility stuff from here on.
  19.260 +
  19.261 +    def domain_pincpu(self, dom, cpu):
  19.262 +        dom = int(dom)
  19.263 +        return xc.domain_pincpu(dom, cpu)
  19.264 +
  19.265 +    def domain_cpu_bvt_set(self, dom, mcuadv, warp, warpl, warpu):
  19.266 +        dom = int(dom)
  19.267 +        return xc.bvtsched_domain_set(dom=dom, mcuadv=mcuadv,
  19.268 +                                      warp=warp, warpl=warpl, warpu=warpu)
  19.269 +
  19.270 +    def domain_cpu_bvt_get(self, dom):
  19.271 +        dom = int(dom)
  19.272 +        return xc.bvtsched_domain_get(dom)
  19.273 +    
  19.274 +    def domain_cpu_atropos_set(self, dom, period, slice, latency, xtratime):
  19.275 +        dom = int(dom)
  19.276 +        return xc.atropos_domain_set(dom, period, slice, latency, xtratime)
  19.277 +
  19.278 +    def domain_cpu_atropos_get(self, dom):
  19.279 +        dom = int(dom)
  19.280 +        return xc.atropos_domain_get(dom)
  19.281 +
  19.282 +    def domain_vif_ls(self, dom):
  19.283 +        dominfo = self.domain_get(dom)
  19.284 +        if not dominfo: return None
  19.285 +        devs = dominfo.get_devices('vif')
  19.286 +        return range(0, len(devs))
  19.287 +
  19.288 +    def domain_vif_get(self, dom, vif):
  19.289 +        dominfo = self.domain_get(dom)
  19.290 +        if not dominfo: return None
  19.291 +        return dominfo.get_device_by_index(vif)
  19.292 +
  19.293 +    def domain_vif_stats(self, dom, vif):
  19.294 +        dom = int(dom)
  19.295 +        return xc.vif_stats_get(dom=dom, vif=vif)
  19.296 +
  19.297 +    def domain_vif_ip_add(self, dom, vif, ip):
  19.298 +        dom = int(dom)
  19.299 +        return xenctl.ip.setup_vfr_rules_for_vif(dom, vif, ip)
  19.300 +
  19.301 +    def domain_vif_scheduler_set(self, dom, vif, bytes, usecs):
  19.302 +        dom = int(dom)
  19.303 +        return xc.xc_vif_scheduler_set(dom=dom, vif=vif,
  19.304 +                                       credit_bytes=bytes, credit_usecs=usecs)
  19.305 +
  19.306 +    def domain_vif_scheduler_get(self, dom, vif):
  19.307 +        dom = int(dom)
  19.308 +        return xc.vif_scheduler_get(dom=dom, vif=vif)
  19.309 +
  19.310 +    def domain_vbd_ls(self, dom):
  19.311 +        dominfo = self.domain_get(dom)
  19.312 +        if not dominfo: return []
  19.313 +        devs = dominfo.get_devices('vbd')
  19.314 +        return [ sxp.child_value(v, 'dev') for v in devs ]
  19.315 +
  19.316 +    def domain_vbd_get(self, dom, vbd):
  19.317 +        dominfo = self.domain_get(dom)
  19.318 +        if not dominfo: return None
  19.319 +        devs = dominfo.get_devices('vbd')
  19.320 +        for v in devs:
  19.321 +            if sxp.child_value(v, 'dev') == vbd:
  19.322 +                return v
  19.323 +        return None
  19.324 +
  19.325 +    def domain_vbd_add(self, dom, uname, dev, mode):
  19.326 +        dom = int(dom)
  19.327 +        vbd = vm.make_disk(dom, uname, dev, mode)
  19.328 +        return vbd
  19.329 +
  19.330 +    def domain_vbd_remove(self, dom, dev):
  19.331 +        dom = int(dom)
  19.332 +        vbd = xenctl.vdisk.blkdev_name_to_number(dev)
  19.333 +        if vbd < 0: return vbd
  19.334 +        err = xc.vbd_destroy(dom, vbd)
  19.335 +        if err < 0: return err
  19.336 +        return vbd
  19.337 +
  19.338 +    def domain_shadow_control(self, dom, op):
  19.339 +        dom = int(dom)
  19.340 +        return xc.shadow_control(dom, op)
  19.341 +
  19.342 +    #============================================================================
  19.343 +
  19.344 +def instance():
  19.345 +    global inst
  19.346 +    try:
  19.347 +        inst
  19.348 +    except:
  19.349 +        inst = XendDomain()
  19.350 +    return inst
    20.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    20.2 +++ b/tools/xenmgr/lib/XendDomainConfig.py	Fri Jun 11 14:40:53 2004 +0000
    20.3 @@ -0,0 +1,44 @@
    20.4 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    20.5 +
    20.6 +"""Handler for persistent domain configs.
    20.7 +
    20.8 +"""
    20.9 +
   20.10 +import sxp
   20.11 +import XendDB
   20.12 +import XendDomain
   20.13 +
   20.14 +__all__ = [ "XendDomainConfig" ]
   20.15 +
   20.16 +class XendDomainConfig:
   20.17 +
   20.18 +    dbpath = 'config'
   20.19 +
   20.20 +    def __init__(self):
   20.21 +        self.db = XendDB.XendDB(self.dbpath)
   20.22 +
   20.23 +    def domain_config_ls(self, path):
   20.24 +        return self.db.ls(path)
   20.25 +
   20.26 +    def domain_config_create(self, path, sxpr):
   20.27 +        self.db.save(path, sxpr)
   20.28 +        pass
   20.29 +
   20.30 +    def domain_config_delete(self, path):
   20.31 +        self.db.delete(path)
   20.32 +
   20.33 +    def domain_config_instance(self, path):
   20.34 +        """Create a domain from a config.
   20.35 +        """
   20.36 +        config = self.db.fetch(path)
   20.37 +        xd = XendDomain.instance()
   20.38 +        newdom = xd.domain_create(config)
   20.39 +        return newdom
   20.40 +
   20.41 +def instance():
   20.42 +    global inst
   20.43 +    try:
   20.44 +        inst
   20.45 +    except:
   20.46 +        inst = XendDomainConfig()
   20.47 +    return inst
    21.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    21.2 +++ b/tools/xenmgr/lib/XendDomainInfo.py	Fri Jun 11 14:40:53 2004 +0000
    21.3 @@ -0,0 +1,697 @@
    21.4 +#!/usr/bin/python
    21.5 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    21.6 +
    21.7 +"""Representation of a single domain.
    21.8 +Includes support for domain construction, using
    21.9 +open-ended configurations.
   21.10 +
   21.11 +Author: Mike Wray <mike.wray@hpl.hp.com>
   21.12 +
   21.13 +"""
   21.14 +
   21.15 +import sys
   21.16 +import os
   21.17 +
   21.18 +from twisted.internet import defer
   21.19 +
   21.20 +import Xc; xc = Xc.new()
   21.21 +
   21.22 +import xenctl.ip
   21.23 +import xenctl.vdisk
   21.24 +
   21.25 +import sxp
   21.26 +
   21.27 +import XendConsole
   21.28 +xendConsole = XendConsole.instance()
   21.29 +
   21.30 +import server.SrvConsoleServer
   21.31 +xend = server.SrvConsoleServer.instance()
   21.32 +
   21.33 +class VmError(ValueError):
   21.34 +    """Vm construction error."""
   21.35 +
   21.36 +    def __init__(self, value):
   21.37 +        self.value = value
   21.38 +
   21.39 +    def __str__(self):
   21.40 +        return self.value
   21.41 +
   21.42 +
   21.43 +class XendDomainInfo:
   21.44 +    """Virtual machine object."""
   21.45 +
   21.46 +    def __init__(self, config, dom, name, memory, image=None, console=None):
   21.47 +        """Construct a virtual machine object.
   21.48 +
   21.49 +        config   configuration
   21.50 +        dom      domain id
   21.51 +        name     name
   21.52 +        memory   memory size (in MB)
   21.53 +        image    image object
   21.54 +        """
   21.55 +        #todo: add info: runtime, state, ...
   21.56 +        self.config = config
   21.57 +        self.id = str(dom)
   21.58 +        self.dom = dom
   21.59 +        self.name = name
   21.60 +        self.memory = memory
   21.61 +        self.image = image
   21.62 +        self.console = console
   21.63 +        self.devices = {}
   21.64 +        self.configs = []
   21.65 +        self.info = None
   21.66 +
   21.67 +        #todo: state: running, suspended
   21.68 +        self.state = 'running'
   21.69 +        #todo: set to migrate info if migrating
   21.70 +        self.migrate = None
   21.71 +
   21.72 +    def update(self, info):
   21.73 +        """Update with  info from xc.domain_getinfo().
   21.74 +        """
   21.75 +        self.info = info
   21.76 +
   21.77 +    def __str__(self):
   21.78 +        s = "domain"
   21.79 +        s += " id=" + self.id
   21.80 +        s += " name=" + self.name
   21.81 +        s += " memory=" + str(self.memory)
   21.82 +        if self.console:
   21.83 +            s += " console=" + self.console.id
   21.84 +        if self.image:
   21.85 +            s += " image=" + self.image
   21.86 +        s += ""
   21.87 +        return s
   21.88 +
   21.89 +    __repr__ = __str__
   21.90 +
   21.91 +    def sxpr(self):
   21.92 +        sxpr = ['domain',
   21.93 +                ['id', self.id],
   21.94 +                ['name', self.name],
   21.95 +                ['memory', self.memory] ]
   21.96 +        if self.info:
   21.97 +            run = (self.info['running'] and 'r') or '-'
   21.98 +            stop = (self.info['stopped'] and 's') or '-'
   21.99 +            state = run + state
  21.100 +            sxpr.append(['cpu', self.info['cpu']])
  21.101 +            sxpr.append(['state', state])
  21.102 +            sxpr.append(['cpu_time', self.info['cpu_time']/1e8])
  21.103 +        if self.console:
  21.104 +            sxpr.append(self.console.sxpr())
  21.105 +        if self.config:
  21.106 +            sxpr.append(['config', self.config])
  21.107 +        return sxpr
  21.108 +
  21.109 +    def add_device(self, type, dev):
  21.110 +        """Add a device to a virtual machine.
  21.111 +
  21.112 +        dev      device to add
  21.113 +        """
  21.114 +        dl = self.devices.get(type, [])
  21.115 +        dl.append(dev)
  21.116 +        self.devices[type] = dl
  21.117 +
  21.118 +    def get_devices(self, type):
  21.119 +        val = self.devices.get(type, [])
  21.120 +        print 'get_devices', type; sxp.show(val); print
  21.121 +        return val
  21.122 +
  21.123 +    def get_device_by_id(self, type, id):
  21.124 +        """Get the device with the given id.
  21.125 +
  21.126 +        id       device id
  21.127 +
  21.128 +        returns  device or None
  21.129 +        """
  21.130 +        return sxp.child_with_id(self.get_devices(type), id)
  21.131 +
  21.132 +    def get_device_by_index(self, type, idx):
  21.133 +        dl = self.get_devices(type)
  21.134 +        if 0 <= idx < len(dl):
  21.135 +            return dl[idx]
  21.136 +        else:
  21.137 +            return None
  21.138 +
  21.139 +    def add_config(self, val):
  21.140 +        """Add configuration data to a virtual machine.
  21.141 +
  21.142 +        val      data to add
  21.143 +        """
  21.144 +        self.configs.append(val)
  21.145 +
  21.146 +    def destroy(self):
  21.147 +        if self.dom <= 0:
  21.148 +            return 0
  21.149 +        return xc.domain_destroy(dom=self.dom, force=1)
  21.150 +
  21.151 +    def show(self):
  21.152 +        """Print virtual machine info.
  21.153 +        """
  21.154 +        print "[VM dom=%d name=%s memory=%d" % (self.dom, self.name, self.memory)
  21.155 +        print "image:"
  21.156 +        sxp.show(self.image)
  21.157 +        print
  21.158 +        for dl in self.devices:
  21.159 +            for dev in dl:
  21.160 +                print "device:"
  21.161 +                sxp.show(dev)
  21.162 +                print
  21.163 +        for val in self.configs:
  21.164 +            print "config:"
  21.165 +            sxp.show(val)
  21.166 +            print
  21.167 +        print "]"
  21.168 +
  21.169 +def safety_level(sharing):
  21.170 +    if sharing == 'rw':
  21.171 +        return xenctl.vdisk.VBD_SAFETY_RW
  21.172 +    if sharing == 'ww':
  21.173 +        return xenctl.vdisk.VBD_SAFETY_WW
  21.174 +    return xenctl.vdisk.VBD_SAFETY_RR
  21.175 +
  21.176 +
  21.177 +def make_disk_old(dom, uname, dev, mode, sharing):
  21.178 +    writeable = ('w' in mode)
  21.179 +    safety = safety_level(sharing)
  21.180 +    vbd = xenctl.vdisk.blkdev_name_to_number(dev)
  21.181 +    extents = xenctl.vdisk.lookup_disk_uname(uname)
  21.182 +    if not extents:
  21.183 +        raise VmError("vbd: Extents not found: uname=%s" % uname)
  21.184 +
  21.185 +    # check that setting up this VBD won't violate the sharing
  21.186 +    # allowed by the current VBD expertise level
  21.187 +    if xenctl.vdisk.vd_extents_validate(extents, writeable, safety=safety) < 0:
  21.188 +        raise VmError("vbd: Extents invalid: uname=%s" % uname)
  21.189 +            
  21.190 +    if xc.vbd_create(dom=dom, vbd=vbd, writeable=writeable):
  21.191 +        raise VmError("vbd: Creating device failed: dom=%d uname=%s vbd=%d mode=%s"
  21.192 +                      % (dom, uname, vbdmode))
  21.193 +
  21.194 +    if xc.vbd_setextents(dom=dom, vbd=vbd, extents=extents):
  21.195 +        raise VMError("vbd: Setting extents failed: dom=%d uname=%s vbd=%d"
  21.196 +                      % (dom, uname, vbd))
  21.197 +    return vbd
  21.198 +
  21.199 +def make_disk(dom, uname, dev, mode, sharing):
  21.200 +    """Create a virtual disk device for a domain.
  21.201 +
  21.202 +    @returns Deferred
  21.203 +    """
  21.204 +    segments = xenctl.vdisk.lookup_disk_uname(uname)
  21.205 +    if not segments:
  21.206 +        raise VmError("vbd: Segments not found: uname=%s" % uname)
  21.207 +    if len(segments) > 1:
  21.208 +        raise VmError("vbd: Multi-segment vdisk: uname=%s" % uname)
  21.209 +    segment = segments[0]
  21.210 +    vdev = xenctl.vdisk.blkdev_name_to_number(dev)
  21.211 +    ctrl = xend.blkif_create(dom)
  21.212 +    
  21.213 +    def fn(ctrl):
  21.214 +        return xend.blkif_dev_create(dom, vdev, mode, segment)
  21.215 +    ctrl.addCallback(fn)
  21.216 +    return ctrl
  21.217 +        
  21.218 +def make_vif_old(dom, vif, vmac, vnet):
  21.219 +    return # todo: Not supported yet.
  21.220 +    err = xc.vif_setinfo(dom=dom, vif=vif, vmac=vmac, vnet=vnet)
  21.221 +    if err < 0:
  21.222 +        raise VmError('vnet: Error %d setting vif mac dom=%d vif=%d vmac=%s vnet=%d' %
  21.223 +                        (err, dom, vif, vmac, vnet))
  21.224 +
  21.225 +def make_vif(dom, vif, vmac):
  21.226 +    """Create a virtual network device for a domain.
  21.227 +
  21.228 +    
  21.229 +    @returns Deferred
  21.230 +    """
  21.231 +    xend.netif_create(dom)
  21.232 +    d = xend.netif_dev_create(dom, vif, vmac)
  21.233 +    return d
  21.234 +
  21.235 +def vif_up(iplist):
  21.236 +    #todo: Need a better way.
  21.237 +    # send an unsolicited ARP reply for all non link-local IPs
  21.238 +
  21.239 +    IP_NONLOCAL_BIND = '/proc/sys/net/ipv4/ip_nonlocal_bind'
  21.240 +    
  21.241 +    def get_ip_nonlocal_bind():
  21.242 +        return int(open(IP_NONLOCAL_BIND, 'r').read()[0])
  21.243 +
  21.244 +    def set_ip_nonlocal_bind(v):
  21.245 +        print >> open(IP_NONLOCAL_BIND, 'w'), str(v)
  21.246 +
  21.247 +    def link_local(ip):
  21.248 +        return xenctl.ip.check_subnet(ip, '169.254.0.0', '255.255.0.0')
  21.249 +
  21.250 +    def arping(ip, gw):
  21.251 +        cmd = '/usr/sbin/arping -A -b -I eth0 -c 1 -s %s %s' % (ip, gw)
  21.252 +        print cmd
  21.253 +        os.system(cmd)
  21.254 +        
  21.255 +    gateway = xenctl.ip.get_current_ipgw() or '255.255.255.255'
  21.256 +    nlb = get_ip_nonlocal_bind()
  21.257 +    if not nlb: set_ip_nonlocal_bind(1)
  21.258 +    try:
  21.259 +        for ip in iplist:
  21.260 +            if not link_local(ip):
  21.261 +                arping(ip, gateway)
  21.262 +    finally:
  21.263 +        if not nlb: set_ip_nonlocal_bind(0)
  21.264 +
  21.265 +def xen_domain_create(config, ostype, name, memory, kernel, ramdisk, cmdline, vifs_n):
  21.266 +    if not os.path.isfile(kernel):
  21.267 +        raise VmError('Kernel image does not exist: %s' % kernel)
  21.268 +    if ramdisk and not os.path.isfile(ramdisk):
  21.269 +        raise VMError('Kernel ramdisk does not exist: %s' % ramdisk)
  21.270 +
  21.271 +    cpu = int(sxp.child_value(config, 'cpu', '-1'))
  21.272 +    dom = xc.domain_create(mem_kb= memory * 1024, name= name, cpu= cpu)
  21.273 +    if dom <= 0:
  21.274 +        raise VmError('Creating domain failed: name=%s memory=%d kernel=%s'
  21.275 +                      % (name, memory, kernel))
  21.276 +    console = xendConsole.console_create(dom)
  21.277 +    buildfn = getattr(xc, '%s_build' % ostype)
  21.278 +    err = buildfn(dom            = dom,
  21.279 +                  image          = kernel,
  21.280 +                  control_evtchn = console.port2,
  21.281 +                  cmdline        = cmdline,
  21.282 +                  ramdisk        = ramdisk)
  21.283 +    if err != 0:
  21.284 +        raise VmError('Building domain failed: type=%s dom=%d err=%d'
  21.285 +                      % (ostype, dom, err))
  21.286 +    vm = XendDomainInfo(config, dom, name, memory, kernel, console)
  21.287 +    return vm
  21.288 +
  21.289 +config_handlers = {}
  21.290 +
  21.291 +def add_config_handler(name, h):
  21.292 +    """Add a handler for a config field.
  21.293 +
  21.294 +    name     field name
  21.295 +    h        handler: fn(vm, config, field, index)
  21.296 +    """
  21.297 +    config_handlers[name] = h
  21.298 +
  21.299 +def get_config_handler(name):
  21.300 +    """Get a handler for a config field.
  21.301 +
  21.302 +    returns handler or None
  21.303 +    """
  21.304 +    return config_handlers.get(name)
  21.305 +
  21.306 +"""Table of handlers for virtual machine images.
  21.307 +Indexed by image type.
  21.308 +"""
  21.309 +image_handlers = {}
  21.310 +
  21.311 +def add_image_handler(name, h):
  21.312 +    """Add a handler for an image type
  21.313 +    name     image type
  21.314 +    h        handler: fn(config, name, memory, image)
  21.315 +    """
  21.316 +    image_handlers[name] = h
  21.317 +
  21.318 +def get_image_handler(name):
  21.319 +    """Get the handler for an image type.
  21.320 +    name     image type
  21.321 +
  21.322 +    returns handler or None
  21.323 +    """
  21.324 +    return image_handlers.get(name)
  21.325 +
  21.326 +"""Table of handlers for devices.
  21.327 +Indexed by device type.
  21.328 +"""
  21.329 +device_handlers = {}
  21.330 +
  21.331 +def add_device_handler(name, h):
  21.332 +    """Add a handler for a device type.
  21.333 +
  21.334 +    name      device type
  21.335 +    h         handler: fn(vm, dev)
  21.336 +    """
  21.337 +    device_handlers[name] = h
  21.338 +
  21.339 +def get_device_handler(name):
  21.340 +    """Get the handler for a device type.
  21.341 +
  21.342 +    name      device type
  21.343 +
  21.344 +    returns handler or None
  21.345 +    """
  21.346 +    return device_handlers.get(name)
  21.347 +
  21.348 +def vm_create(config):
  21.349 +    """Create a VM from a configuration.
  21.350 +    If a vm has been partially created and there is an error it
  21.351 +    is destroyed.
  21.352 +
  21.353 +    config    configuration
  21.354 +
  21.355 +    returns Deferred
  21.356 +    raises VmError for invalid configuration
  21.357 +    """
  21.358 +    # todo - add support for scheduling params?
  21.359 +    print 'vm_create>'
  21.360 +    xenctl.vdisk.VBD_EXPERT_MODE = 0
  21.361 +    vm = None
  21.362 +    try:
  21.363 +        name = sxp.child_value(config, 'name')
  21.364 +        memory = int(sxp.child_value(config, 'memory', '128'))
  21.365 +        image = sxp.child_value(config, 'image')
  21.366 +        
  21.367 +        image_name = sxp.name(image)
  21.368 +        image_handler = get_image_handler(image_name)
  21.369 +        if image_handler is None:
  21.370 +            raise VmError('unknown image type: ' + image_name)
  21.371 +        vm = image_handler(config, name, memory, image)
  21.372 +        deferred = vm_configure(vm, config)
  21.373 +    except StandardError, ex:
  21.374 +        # Catch errors, cleanup and re-raise.
  21.375 +        if vm:
  21.376 +            vm.destroy()
  21.377 +        raise
  21.378 +    def cbok(x):
  21.379 +        print 'vm_create> cbok', x
  21.380 +        return x
  21.381 +    deferred.addCallback(cbok)
  21.382 +    print 'vm_create<'
  21.383 +    return deferred
  21.384 +
  21.385 +def vm_restore(src, config, progress=0):
  21.386 +    ostype = "linux" #todo set from config
  21.387 +    restorefn = getattr(xc, "%s_restore" % ostype)
  21.388 +    dom = restorefn(state_file=src, progress=progress)
  21.389 +    if dom < 0: return dom
  21.390 +    deferred = dom_configure(dom, config)
  21.391 +    return deferred
  21.392 +    
  21.393 +def dom_get(dom):
  21.394 +    domlist = xc.domain_getinfo(dom=dom)
  21.395 +    if domlist and dom == domlist[0]['dom']:
  21.396 +        return domlist[0]
  21.397 +    return None
  21.398 +    
  21.399 +def dom_configure(dom, config):
  21.400 +    d = dom_get(dom)
  21.401 +    if not d:
  21.402 +        raise VMError("Domain not found: %d" % dom)
  21.403 +    try:
  21.404 +        name = d['name']
  21.405 +        memory = d['memory']/1024
  21.406 +        image = None
  21.407 +        vm = VM(config, dom, name, memory, image)
  21.408 +        deferred = vm_configure(vm, config)
  21.409 +    except StandardError, ex:
  21.410 +        if vm:
  21.411 +            vm.destroy()
  21.412 +        raise
  21.413 +    return deferred
  21.414 +
  21.415 +def append_deferred(dlist, v):
  21.416 +    if isinstance(v, defer.Deferred):
  21.417 +        dlist.append(v)
  21.418 +
  21.419 +def vm_create_devices(vm, config):
  21.420 +    """Create the devices for a vm.
  21.421 +
  21.422 +    vm         virtual machine
  21.423 +    config     configuration
  21.424 +
  21.425 +    returns Deferred
  21.426 +    raises VmError for invalid devices
  21.427 +    """
  21.428 +    print '>vm_create_devices'
  21.429 +    dlist = []
  21.430 +    devices = sxp.children(config, 'device')
  21.431 +    index = {}
  21.432 +    for d in devices:
  21.433 +        dev = sxp.child0(d)
  21.434 +        if dev is None:
  21.435 +            raise VmError('invalid device')
  21.436 +        dev_name = sxp.name(dev)
  21.437 +        dev_index = index.get(dev_name, 0)
  21.438 +        dev_handler = get_device_handler(dev_name)
  21.439 +        if dev_handler is None:
  21.440 +            raise VmError('unknown device type: ' + dev_name)
  21.441 +        v = dev_handler(vm, dev, dev_index)
  21.442 +        append_deferred(dlist, v)
  21.443 +        index[dev_name] = dev_index + 1
  21.444 +    deferred = defer.DeferredList(dlist, fireOnOneErrback=1)
  21.445 +    print '<vm_create_devices'
  21.446 +    return deferred
  21.447 +
  21.448 +def vm_configure(vm, config):
  21.449 +    """Configure a vm.
  21.450 +
  21.451 +    vm         virtual machine
  21.452 +    config     configuration
  21.453 +
  21.454 +    returns Deferred - calls callback with vm
  21.455 +    """
  21.456 +    d = xend.blkif_create(vm.dom)
  21.457 +    d.addCallback(_vm_configure1, vm, config)
  21.458 +    return d
  21.459 +
  21.460 +def _vm_configure1(val, vm, config):
  21.461 +    d = vm_create_devices(vm, config)
  21.462 +    print '_vm_configure1> made devices...'
  21.463 +    def cbok(x):
  21.464 +        print '_vm_configure1> cbok', x
  21.465 +        return x
  21.466 +    d.addCallback(cbok)
  21.467 +    d.addCallback(_vm_configure2, vm, config)
  21.468 +    print '_vm_configure1<'
  21.469 +    return d
  21.470 +
  21.471 +def _vm_configure2(val, vm, config):
  21.472 +    print '>callback _vm_configure2...'
  21.473 +    dlist = []
  21.474 +    index = {}
  21.475 +    for field in sxp.children(config):
  21.476 +        field_name = sxp.name(field)
  21.477 +        field_index = index.get(field_name, 0)
  21.478 +        field_handler = get_config_handler(field_name)
  21.479 +        # Ignore unknown fields. Warn?
  21.480 +        if field_handler:
  21.481 +            v = field_handler(vm, config, field, field_index)
  21.482 +            append_deferred(dlist, v)
  21.483 +        index[field_name] = field_index + 1
  21.484 +    d = defer.DeferredList(dlist, fireOnOneErrback=1)
  21.485 +    def cbok(results):
  21.486 +        print '_vm_configure2> cbok', results
  21.487 +        return vm
  21.488 +    def cberr(err):
  21.489 +        print '_vm_configure2> cberr', err
  21.490 +        vm.destroy()
  21.491 +        return err
  21.492 +    d.addCallback(cbok)
  21.493 +    d.addErrback(cberr)
  21.494 +    print '<_vm_configure2'
  21.495 +    return d
  21.496 +
  21.497 +def config_devices(config, name):
  21.498 +    """Get a list of the 'device' nodes of a given type from a config.
  21.499 +
  21.500 +    config	configuration
  21.501 +    name	device type
  21.502 +    return list of device configs
  21.503 +    """
  21.504 +    devices = []
  21.505 +    for d in sxp.children(config, 'device'):
  21.506 +        dev = sxp.child0(d)
  21.507 +        if dev is None: continue
  21.508 +        if name == sxp.name(dev):
  21.509 +            devices.append(dev)
  21.510 +    return devices
  21.511 +        
  21.512 +def vm_image_linux(config, name, memory, image):
  21.513 +    """Create a VM for a linux image.
  21.514 +
  21.515 +    name      vm name
  21.516 +    memory    vm memory
  21.517 +    image     image config
  21.518 +
  21.519 +    returns vm
  21.520 +    """
  21.521 +    kernel = sxp.child_value(image, "kernel")
  21.522 +    cmdline = ""
  21.523 +    ip = sxp.child_value(image, "ip", "dhcp")
  21.524 +    if ip:
  21.525 +        cmdline += " ip=" + ip
  21.526 +    root = sxp.child_value(image, "root")
  21.527 +    if root:
  21.528 +        cmdline += " root=" + root
  21.529 +    args = sxp.child_value(image, "args")
  21.530 +    if args:
  21.531 +        cmdline += " " + args
  21.532 +    ramdisk = sxp.child_value(image, "ramdisk", '')
  21.533 +    vifs = config_devices(config, "vif")
  21.534 +    vm = xen_domain_create(config, "linux", name, memory, kernel,
  21.535 +                           ramdisk, cmdline, len(vifs))
  21.536 +    return vm
  21.537 +
  21.538 +def vm_image_netbsd(config, name, memory, image):
  21.539 +    """Create a VM for a bsd image.
  21.540 +
  21.541 +    name      vm name
  21.542 +    memory    vm memory
  21.543 +    image     image config
  21.544 +
  21.545 +    returns vm
  21.546 +    """
  21.547 +    #todo: Same as for linux. Is that right? If so can unify them.
  21.548 +    kernel = sxp.child_value(image, "kernel")
  21.549 +    cmdline = ""
  21.550 +    ip = sxp.child_value(image, "ip", "dhcp")
  21.551 +    if ip:
  21.552 +        cmdline += "ip=" + ip
  21.553 +    root = sxp.child_value(image, "root")
  21.554 +    if root:
  21.555 +        cmdline += "root=" + root
  21.556 +    args = sxp.child_value(image, "args")
  21.557 +    if args:
  21.558 +        cmdline += " " + args
  21.559 +    ramdisk = sxp.child_value(image, "ramdisk")
  21.560 +    vifs = config_devices(config, "vif")
  21.561 +    vm = xen_domain_create(config, "netbsd", name, memory, kernel,
  21.562 +                           ramdisk, cmdline, len(vifs))
  21.563 +    return vm
  21.564 +
  21.565 +
  21.566 +def vm_dev_vif(vm, val, index):
  21.567 +    """Create a virtual network interface (vif).
  21.568 +
  21.569 +    vm        virtual machine
  21.570 +    val       vif config
  21.571 +    index     vif index
  21.572 +    """
  21.573 +    vif = index #todo
  21.574 +    vmac = sxp.child_value(val, "mac")
  21.575 +    defer = make_vif(vm.dom, vif, vmac)
  21.576 +    def fn(id):
  21.577 +        dev = val + ['vif', vif]
  21.578 +        vm.add_device('vif', dev)
  21.579 +        print 'vm_dev_vif> created', dev
  21.580 +        return id
  21.581 +    defer.addCallback(fn)
  21.582 +    return defer
  21.583 +
  21.584 +def vm_dev_vbd(vm, val, index):
  21.585 +    """Create a virtual block device (vbd).
  21.586 +
  21.587 +    vm        virtual machine
  21.588 +    val       vbd config
  21.589 +    index     vbd index
  21.590 +    """
  21.591 +    uname = sxp.child_value(val, 'uname')
  21.592 +    if not uname:
  21.593 +        raise VMError('vbd: Missing uname')
  21.594 +    dev = sxp.child_value(val, 'dev')
  21.595 +    if not dev:
  21.596 +        raise VMError('vbd: Missing dev')
  21.597 +    mode = sxp.child_value(val, 'mode', 'r')
  21.598 +    sharing = sxp.child_value(val, 'sharing', 'rr')
  21.599 +    defer = make_disk(vm.dom, uname, dev, mode, sharing)
  21.600 +    def fn(vbd):
  21.601 +        vm.add_device('vbd', val)
  21.602 +        return vbd
  21.603 +    defer.addCallback(fn)
  21.604 +    return defer
  21.605 +
  21.606 +def vm_dev_pci(vm, val, index):
  21.607 +    bus = sxp.child_value(val, 'bus')
  21.608 +    if not bus:
  21.609 +        raise VMError('pci: Missing bus')
  21.610 +    dev = sxp.child_value(val, 'dev')
  21.611 +    if not dev:
  21.612 +        raise VMError('pci: Missing dev')
  21.613 +    func = sxp.child_value(val, 'func')
  21.614 +    if not func:
  21.615 +        raise VMError('pci: Missing func')
  21.616 +    rc = xc.physdev_pci_access_modify(dom=vm.dom, bus=bus, dev=dev, func=func, enable=1)
  21.617 +    if rc < 0:
  21.618 +        #todo non-fatal
  21.619 +        raise VMError('pci: Failed to configure device: bus=%s dev=%s func=%s' %
  21.620 +                      (bus, dev, func))
  21.621 +    return rc
  21.622 +    
  21.623 +
  21.624 +def vm_field_vfr(vm, config, val, index):
  21.625 +    """Handle a vfr field in a config.
  21.626 +
  21.627 +    vm        virtual machine
  21.628 +    config    vm config
  21.629 +    val       vfr field
  21.630 +    """
  21.631 +    # Get the rules and add them.
  21.632 +    # (vfr (vif (id foo) (ip x.x.x.x)) ... ) 
  21.633 +    list = sxp.children(val, 'vif')
  21.634 +    for v in list:
  21.635 +        id = sxp.child_value(v, 'id')
  21.636 +        if id is None:
  21.637 +            raise VmError('vfr: missing vif id')
  21.638 +        id = int(id)
  21.639 +        dev = vm.get_device_by_index('vif', id)
  21.640 +        if not dev:
  21.641 +            raise VmError('vfr: invalid vif id %d' % id)
  21.642 +        vif = sxp.child_value(dev, 'vif')
  21.643 +        ip = sxp.child_value(v, 'ip')
  21.644 +        if not ip:
  21.645 +            raise VmError('vfr: missing ip address')
  21.646 +        #Don't do this in new i/o model.
  21.647 +        #print 'vm_field_vfr> add rule', 'dom=', vm.dom, 'vif=', vif, 'ip=', ip
  21.648 +        #xenctl.ip.setup_vfr_rules_for_vif(vm.dom, vif, ip)
  21.649 +
  21.650 +def vnet_bridge(vnet, vmac, dom, idx):
  21.651 +    """Add the device for the vif to the bridge for its vnet.
  21.652 +    """
  21.653 +    vif = "vif%d.%d" % (dom, idx)
  21.654 +    try:
  21.655 +        cmd = "(vif.conn (vif %s) (vnet %s) (vmac %s))" % (vif, vnet, vmac)
  21.656 +        print "*** vnet_bridge>", cmd
  21.657 +        out = file("/proc/vnet/policy", "wb")
  21.658 +        out.write(cmd)
  21.659 +        err = out.close()
  21.660 +        print "vnet_bridge>", "err=", err
  21.661 +    except IOError, ex:
  21.662 +        print "vnet_bridge>", ex
  21.663 +    
  21.664 +def vm_field_vnet(vm, config, val, index):
  21.665 +    """Handle a vnet field in a config.
  21.666 +
  21.667 +    vm        virtual machine
  21.668 +    config    vm config
  21.669 +    val       vnet field
  21.670 +    index     index
  21.671 +    """
  21.672 +    # Get the vif children. For each vif look up the vif device
  21.673 +    # with the given id and configure its vnet.
  21.674 +    # (vnet (vif (id foo) (vnet 2) (mac x:x:x:x:x:x)) ... )
  21.675 +    vif_vnets = sxp.children(val, 'vif')
  21.676 +    for v in vif_vnets:
  21.677 +        id = sxp.child_value(v, 'id')
  21.678 +        if id is None:
  21.679 +            raise VmError('vnet: missing vif id')
  21.680 +        dev = vm.get_device_by_id('vif', id)
  21.681 +        if not sxp.elementp(dev, 'vif'):
  21.682 +            raise VmError('vnet: invalid vif id %s' % id)
  21.683 +        vnet = sxp.child_value(v, 'vnet', 1)
  21.684 +        mac = sxp.child_value(dev, 'mac')
  21.685 +        vif = sxp.child_value(dev, 'vif')
  21.686 +        vnet_bridge(vnet, mac, vm.dom, 0)
  21.687 +        vm.add_config([ 'vif.vnet', ['id', id], ['vnet', vnet], ['mac', mac]])
  21.688 +
  21.689 +# Register image handlers for linux and bsd.
  21.690 +add_image_handler('linux',  vm_image_linux)
  21.691 +add_image_handler('netbsd', vm_image_netbsd)
  21.692 +
  21.693 +# Register device handlers for vifs and vbds.
  21.694 +add_device_handler('vif',  vm_dev_vif)
  21.695 +add_device_handler('vbd',  vm_dev_vbd)
  21.696 +add_device_handler('pci',  vm_dev_pci)
  21.697 +
  21.698 +# Register config handlers for vfr and vnet.
  21.699 +add_config_handler('vfr',  vm_field_vfr)
  21.700 +add_config_handler('vnet', vm_field_vnet)
    22.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    22.2 +++ b/tools/xenmgr/lib/XendMigrate.py	Fri Jun 11 14:40:53 2004 +0000
    22.3 @@ -0,0 +1,103 @@
    22.4 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    22.5 +
    22.6 +import sys
    22.7 +import socket
    22.8 +
    22.9 +import sxp
   22.10 +import XendDB
   22.11 +import EventServer; eserver = EventServer.instance()
   22.12 +
   22.13 +class XendMigrateInfo:
   22.14 +
   22.15 +    # states: begin, active, failed, succeeded?
   22.16 +
   22.17 +    def __init__(self, id, dom, dst):
   22.18 +        self.id = id
   22.19 +        self.state = 'begin'
   22.20 +        self.src_host = socket.gethostname()
   22.21 +        self.src_dom = dom
   22.22 +        self.dst_host = dst
   22.23 +        self.dst_dom = None
   22.24 +        
   22.25 +    def set_state(self, state):
   22.26 +        self.state = state
   22.27 +
   22.28 +    def get_state(self):
   22.29 +        return self.state
   22.30 +
   22.31 +    def sxpr(self):
   22.32 +        sxpr = ['migrate', ['id', self.id], ['state', self.state] ]
   22.33 +        sxpr_src = ['src', ['host', self.src_host], ['domain', self.src_dom] ]
   22.34 +        sxpr.append(sxpr_src)
   22.35 +        sxpr_dst = ['dst', ['host', self.dst] ]
   22.36 +        if self.dst_dom:
   22.37 +            sxpr_dst.append(['domain', self.dst_dom])
   22.38 +        sxpr.append(sxpr_dst)
   22.39 +        return sxpr
   22.40 +    
   22.41 +
   22.42 +class XendMigrate:
   22.43 +    # Represents migration in progress.
   22.44 +    # Use log for indications of begin/end/errors?
   22.45 +    # Need logging of: domain create/halt, migrate begin/end/fail
   22.46 +    # Log via event server?
   22.47 +
   22.48 +    dbpath = "migrate"
   22.49 +    
   22.50 +    def __init__(self):
   22.51 +        self.db = XendDB.XendDB(self.dbpath)
   22.52 +        self.migrate = {}
   22.53 +        self.migrate_db = self.db.fetchall("")
   22.54 +        self.id = 0
   22.55 +
   22.56 +    def nextid(self):
   22.57 +        self.id += 1
   22.58 +        return "%d" % self.id
   22.59 +
   22.60 +    def sync(self):
   22.61 +        self.db.saveall("", self.migrate_db)
   22.62 +
   22.63 +    def sync_migrate(self, id):
   22.64 +        self.db.save(id, self.migrate_db[id])
   22.65 +
   22.66 +    def close(self):
   22.67 +        pass
   22.68 +
   22.69 +    def _add_migrate(self, id, info):
   22.70 +        self.migrate[id] = info
   22.71 +        self.migrate_db[id] = info.sxpr()
   22.72 +        self.sync_migrate(id)
   22.73 +        #eserver.inject('xend.migrate.begin', info.sxpr())
   22.74 +
   22.75 +    def _delete_migrate(self, id):
   22.76 +        #eserver.inject('xend.migrate.end', id)
   22.77 +        del self.migrate[id]
   22.78 +        del self.migrate_db[id]
   22.79 +        self.db.delete(id)
   22.80 +
   22.81 +    def migrate_ls(self):
   22.82 +        return self.migrate.keys()
   22.83 +
   22.84 +    def migrates(self):
   22.85 +        return self.migrate.values()
   22.86 +
   22.87 +    def migrate_get(self, id):
   22.88 +        return self.migrate.get(id)
   22.89 +    
   22.90 +    def migrate_begin(self, dom, dst):
   22.91 +        # Check dom for existence, not migrating already.
   22.92 +        # Create migrate info, tell xend to migrate it?
   22.93 +        # - or fork migrate command ourselves?
   22.94 +        # Subscribe to migrate notifications (for updating).
   22.95 +        id = self.nextid()
   22.96 +        info = XenMigrateInfo(id, dom, dst)
   22.97 +        self._add_migrate(id, info)
   22.98 +        return id
   22.99 +
  22.100 +def instance():
  22.101 +    global inst
  22.102 +    try:
  22.103 +        inst
  22.104 +    except:
  22.105 +        inst = XendMigrate()
  22.106 +    return inst
    23.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    23.2 +++ b/tools/xenmgr/lib/XendNode.py	Fri Jun 11 14:40:53 2004 +0000
    23.3 @@ -0,0 +1,55 @@
    23.4 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    23.5 +
    23.6 +"""Handler for node operations.
    23.7 + Has some persistent state:
    23.8 + - logs
    23.9 + - notification urls
   23.10 +
   23.11 +"""
   23.12 +
   23.13 +import Xc
   23.14 +
   23.15 +class XendNodeInfo:
   23.16 +    """Node information record.
   23.17 +    """
   23.18 +
   23.19 +    def __init__(self):
   23.20 +        pass
   23.21 +
   23.22 +class XendNode:
   23.23 +
   23.24 +    def __init__(self):
   23.25 +        self.xc = Xc.new()
   23.26 +
   23.27 +    def shutdown(self):
   23.28 +        return 0
   23.29 +
   23.30 +    def reboot(self):
   23.31 +        return 0
   23.32 +
   23.33 +    def notify(self, uri):
   23.34 +        return 0
   23.35 +    
   23.36 +    def cpu_bvt_slice_set(self, slice):
   23.37 +        ret = 0
   23.38 +        #ret = self.xc.bvtsched_global_set(ctx_allow=slice)
   23.39 +        return ret
   23.40 +
   23.41 +    def cpu_bvt_slice_get(self, slice):
   23.42 +        ret = 0
   23.43 +        #ret = self.xc.bvtsched_global_get()
   23.44 +        return ret
   23.45 +    
   23.46 +    def cpu_rrobin_slice_set(self, slice):
   23.47 +        ret = 0
   23.48 +        #ret = self.xc.rrobin_global_set(slice)
   23.49 +        return ret
   23.50 +
   23.51 +def instance():
   23.52 +    global inst
   23.53 +    try:
   23.54 +        inst
   23.55 +    except:
   23.56 +        inst = XendNode()
   23.57 +    return inst
   23.58 +
    24.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    24.2 +++ b/tools/xenmgr/lib/XendRoot.py	Fri Jun 11 14:40:53 2004 +0000
    24.3 @@ -0,0 +1,156 @@
    24.4 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    24.5 +
    24.6 +"""Xend root class.
    24.7 +Creates the event server and handles configuration.
    24.8 +"""
    24.9 +
   24.10 +import os
   24.11 +import os.path
   24.12 +import sys
   24.13 +import EventServer
   24.14 +
   24.15 +# Initial create of the event server.
   24.16 +eserver = EventServer.instance()
   24.17 +
   24.18 +import sxp
   24.19 +
   24.20 +def reboots():
   24.21 +    """Get a list of system reboots from wtmp.
   24.22 +    """
   24.23 +    out = os.popen('/usr/bin/last reboot', 'r')
   24.24 +    list = [ x.strip() for x in out if x.startswith('reboot') ]
   24.25 +    return list
   24.26 +
   24.27 +def last_reboot():
   24.28 +    """Get the last known system reboot.
   24.29 +    """
   24.30 +    l = reboots()
   24.31 +    return (l and l[-1]) or None
   24.32 +
   24.33 +class XendRoot:
   24.34 +    """Root of the management classes."""
   24.35 +
   24.36 +    lastboot_default = "/etc/xen/xend/lastboot"
   24.37 +
   24.38 +    """Default path to the root of the database."""
   24.39 +    dbroot_default = "/etc/xen/xend/xenmgr-db"
   24.40 +
   24.41 +    """Default path to the config file."""
   24.42 +    config_default = "/etc/xen/xenmgr-config.sxp"
   24.43 +
   24.44 +    """Environment variable used to override config_default."""
   24.45 +    config_var     = "XEND_CONFIG"
   24.46 +
   24.47 +    def __init__(self):
   24.48 +        self.rebooted = 0
   24.49 +        self.last_reboot = None
   24.50 +        self.dbroot = None
   24.51 +        self.config_path = None
   24.52 +        self.config = None
   24.53 +        self.configure()
   24.54 +        self.check_lastboot()
   24.55 +        eserver.subscribe('xend.*', self.event_handler)
   24.56 +        #eserver.subscribe('xend.domain.created', self.event_handler)
   24.57 +        #eserver.subscribe('xend.domain.died', self.event_handler)
   24.58 +
   24.59 +    def start(self):
   24.60 +        eserver.inject('xend.start', self.rebooted)
   24.61 +
   24.62 +    def event_handler(self, event, val):
   24.63 +        print >> sys.stderr, "EVENT>", event, val
   24.64 +
   24.65 +    def read_lastboot(self):
   24.66 +        try:
   24.67 +            val = file(self.lastboot, 'rb').readlines()[0]
   24.68 +        except StandardError, ex:
   24.69 +            print 'warning: Error reading', self.lastboot, ex
   24.70 +            val = None
   24.71 +        return val
   24.72 +
   24.73 +    def write_lastboot(self, val):
   24.74 +        if not val: return
   24.75 +        try:
   24.76 +            fdir = os.path.dirname(self.lastboot)
   24.77 +            if not os.path.isdir(fdir):
   24.78 +                os.makedirs(fdir)
   24.79 +            out = file(self.lastboot, 'wb+')
   24.80 +            out.write(val)
   24.81 +            out.close()
   24.82 +        except IOError, ex:
   24.83 +            print 'warning: Error writing', self.lastboot, ex
   24.84 +            pass
   24.85 +
   24.86 +    def check_lastboot(self):
   24.87 +        """Check if there has been a system reboot since we saved lastboot.
   24.88 +        """
   24.89 +        last_val = self.read_lastboot()
   24.90 +        this_val = last_reboot()
   24.91 +        if this_val == last_val:
   24.92 +            self.rebooted = 0
   24.93 +        else:
   24.94 +            self.rebooted = 1
   24.95 +            self.write_lastboot(this_val)
   24.96 +        self.last_reboot = this_val
   24.97 +
   24.98 +    def get_last_reboot(self):
   24.99 +        return self.last_reboot
  24.100 +
  24.101 +    def get_rebooted(self):
  24.102 +        return self.rebooted
  24.103 +
  24.104 +    def configure(self):
  24.105 +        self.set_config()
  24.106 +        self.dbroot = self.get_config_value("dbroot", self.dbroot_default)
  24.107 +        self.lastboot = self.get_config_value("lastboot", self.lastboot_default)
  24.108 +
  24.109 +    def get_dbroot(self):
  24.110 +        """Get the path to the database root.
  24.111 +        """
  24.112 +        return self.dbroot
  24.113 +
  24.114 +    def set_config(self):
  24.115 +        """If the config file exists, read it. If not, ignore it.
  24.116 +
  24.117 +        The config file is a sequence of sxp forms.
  24.118 +        """
  24.119 +        self.config_path = os.getenv(self.config_var, self.config_default)
  24.120 +        if os.path.exists(self.config_path):
  24.121 +            fin = file(self.config_path, 'rb')
  24.122 +            try:
  24.123 +                config = sxp.parse(fin)
  24.124 +                config.insert(0, 'config')
  24.125 +                self.config = config
  24.126 +            finally:
  24.127 +                fin.close()
  24.128 +        else:
  24.129 +            self.config = ['config']
  24.130 +
  24.131 +    def get_config(self, name=None):
  24.132 +        """Get the configuration element with the given name, or
  24.133 +        the whole configuration if no name is given.
  24.134 +
  24.135 +        name	element name (optional)
  24.136 +        returns config or none
  24.137 +        """
  24.138 +        if name is None:
  24.139 +            val = self.config
  24.140 +        else:
  24.141 +            val = sxp.child(self.config, name)
  24.142 +        return val
  24.143 +
  24.144 +    def get_config_value(self, name, val=None):
  24.145 +        """Get the value of an atomic configuration element.
  24.146 +
  24.147 +        name	element name
  24.148 +        val	default value (optional, defaults to None)
  24.149 +        returns value
  24.150 +        """
  24.151 +        return sxp.child_value(self.config, name, val=val)
  24.152 +
  24.153 +def instance():
  24.154 +    global inst
  24.155 +    try:
  24.156 +        inst
  24.157 +    except:
  24.158 +        inst = XendRoot()
  24.159 +    return inst
    25.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    25.2 +++ b/tools/xenmgr/lib/XendVdisk.py	Fri Jun 11 14:40:53 2004 +0000
    25.3 @@ -0,0 +1,111 @@
    25.4 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    25.5 +
    25.6 +"""Handler for vdisk operations.
    25.7 +
    25.8 +"""
    25.9 +
   25.10 +import os
   25.11 +import os.path
   25.12 +
   25.13 +from xenctl import vdisk
   25.14 +    
   25.15 +import sxp
   25.16 +
   25.17 +class XendVdiskInfo:
   25.18 +
   25.19 +    def __init__(self, info):
   25.20 +        self.info = info
   25.21 +        self.id = info['vdisk_id']
   25.22 +
   25.23 +    def __str__(self):
   25.24 +        return ("vdisk id=%(vdisk_id)s size=%(size)d expires=%(expires)d expiry_time=%(expiry_time)d"
   25.25 +                % self.info)
   25.26 +
   25.27 +    def sxpr(self):
   25.28 +        val = ['vdisk']
   25.29 +        for (k,v) in self.info.items():
   25.30 +            val.append([k, str(v)])
   25.31 +        return val     
   25.32 +
   25.33 +class XendVdisk:
   25.34 +    """Index of all vdisks. Singleton.
   25.35 +    """
   25.36 +
   25.37 +    dbpath = "vdisk"
   25.38 +
   25.39 +    def __init__(self):
   25.40 +        # Table of vdisk info indexed by vdisk id.
   25.41 +        self.vdisk = {}
   25.42 +        if not os.path.isfile(vdisk.VD_DB_FILE):
   25.43 +            vdisk.vd_init_db(vdisk.VD_DB_FILE)
   25.44 +        self.vdisk_refresh()
   25.45 +
   25.46 +    def vdisk_refresh(self):
   25.47 +        # vdisk = {vdisk_id, size, expires, expiry_time}
   25.48 +        try:
   25.49 +            vdisks = vdisk.vd_list()
   25.50 +        except:
   25.51 +            vdisks = []
   25.52 +        for vdisk in vdisks:
   25.53 +            vdiskinfo = XendVdiskInfo(vdisk)
   25.54 +            self.vdisk[vdiskinfo.id] = vdiskinfo
   25.55 +
   25.56 +    def vdisk_ls(self):
   25.57 +        """List all vdisk ids.
   25.58 +        """
   25.59 +        return self.vdisk.keys()
   25.60 +
   25.61 +    def vdisks(self):
   25.62 +        return self.vdisk.values()
   25.63 +    
   25.64 +    def vdisk_get(self, id):
   25.65 +        """Get a vdisk.
   25.66 +
   25.67 +        id	vdisk id
   25.68 +        """
   25.69 +        return self.vdisk.get(id)
   25.70 +
   25.71 +    def vdisk_create(self, info):
   25.72 +        """Create a vdisk.
   25.73 +
   25.74 +        info	config
   25.75 +        """
   25.76 +        # Need to configure for real.
   25.77 +        # vdisk.vd_create(size, expiry)
   25.78 +
   25.79 +    def vdisk_configure(self, info):
   25.80 +        """Configure a vdisk.
   25.81 +        id	vdisk id
   25.82 +        info	config
   25.83 +        """
   25.84 +        # Need to configure for real.
   25.85 +        # Make bigger: vdisk.vd_enlarge(id, extra_size)
   25.86 +        # Update expiry time: vdisk.vd_refresh(id, expiry)
   25.87 +        # Try to recover an expired vdisk : vdisk.vd_undelete(id, expiry)
   25.88 +        
   25.89 +
   25.90 +    def vdisk_delete(self, id):
   25.91 +        """Delete a vdisk.
   25.92 +
   25.93 +        id	vdisk id
   25.94 +        """
   25.95 +        # Need to delete vdisk for real. What if fails?
   25.96 +        del self.vdisk[id]
   25.97 +        vdisk.vd_delete(id)
   25.98 +
   25.99 +    # def vdisk_copy: copy contents to file, vdisk still exists
  25.100 +    # def vdisk_export: copy contents to file then delete the vdisk 
  25.101 +    # def vdisk_import: create a vdisk from a file
  25.102 +    # def vdisk_space: space left for new vdisks
  25.103 +
  25.104 +    # def vdisk_recover: recover an expired vdisk
  25.105 +
  25.106 +    # def vdisk_init_partition: setup a physical partition for vdisks
  25.107 +
  25.108 +def instance():
  25.109 +    global inst
  25.110 +    try:
  25.111 +        inst
  25.112 +    except:
  25.113 +        inst = XendVdisk()
  25.114 +    return inst
    26.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    26.2 +++ b/tools/xenmgr/lib/XendVnet.py	Fri Jun 11 14:40:53 2004 +0000
    26.3 @@ -0,0 +1,69 @@
    26.4 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    26.5 +
    26.6 +"""Handler for vnet operations.
    26.7 +"""
    26.8 +
    26.9 +import sxp
   26.10 +import XendDB
   26.11 +
   26.12 +class XendVnet:
   26.13 +    """Index of all vnets. Singleton.
   26.14 +    """
   26.15 +
   26.16 +    dbpath = "vnet"
   26.17 +
   26.18 +    def __init__(self):
   26.19 +        # Table of vnet info indexed by vnet id.
   26.20 +        self.vnet = {}
   26.21 +        self.db = XendDB.XendDB(self.dbpath)
   26.22 +        self.vnet = self.db.fetchall("")
   26.23 +
   26.24 +    def vnet_ls(self):
   26.25 +        """List all vnets.
   26.26 +        """
   26.27 +        return self.vnet.keys()
   26.28 +
   26.29 +    def vnets(self):
   26.30 +        return self.vnet.values()
   26.31 +
   26.32 +    def vnet_get(self, id):
   26.33 +        """Get a vnet.
   26.34 +
   26.35 +        id	vnet id
   26.36 +        """
   26.37 +        return self.vnet.get(id)
   26.38 +
   26.39 +    def vnet_create(self, info):
   26.40 +        """Create a vnet.
   26.41 +
   26.42 +        info	config
   26.43 +        """
   26.44 +        self.vnet_configure(info)
   26.45 +
   26.46 +    def vnet_configure(self, info):
   26.47 +        """Configure a vnet.
   26.48 +        id	vnet id
   26.49 +        info	config
   26.50 +        """
   26.51 +        # Need to configure for real.
   26.52 +        # Only sync if succeeded - otherwise need to back out.
   26.53 +        self.vnet[info.id] = info
   26.54 +        self.db.save(info.id, info)
   26.55 +
   26.56 +    def vnet_delete(self, id):
   26.57 +        """Delete a vnet.
   26.58 +
   26.59 +        id	vnet id
   26.60 +        """
   26.61 +        # Need to delete for real. What if fails?
   26.62 +        if id in self.vnet:
   26.63 +            del self.vnet[id]
   26.64 +            self.db.delete(id)
   26.65 +
   26.66 +def instance():
   26.67 +    global inst
   26.68 +    try:
   26.69 +        inst
   26.70 +    except:
   26.71 +        inst = XendVnet()
   26.72 +    return inst
    27.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    27.2 +++ b/tools/xenmgr/lib/__init__.py	Fri Jun 11 14:40:53 2004 +0000
    27.3 @@ -0,0 +1,1 @@
    27.4 + 
    28.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    28.2 +++ b/tools/xenmgr/lib/encode.py	Fri Jun 11 14:40:53 2004 +0000
    28.3 @@ -0,0 +1,165 @@
    28.4 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    28.5 +"""Encoding for arguments to HTTP calls.
    28.6 +   Uses the url-encoding with MIME type 'application/x-www-form-urlencoded'
    28.7 +   if the data does not include files. Otherwise it uses the encoding with
    28.8 +   MIME type 'multipart/form-data'. See the HTML4 spec for details.
    28.9 +
   28.10 +   """
   28.11 +import sys
   28.12 +import types
   28.13 +from StringIO import StringIO
   28.14 +
   28.15 +import urllib
   28.16 +import httplib
   28.17 +import random
   28.18 +import md5
   28.19 +
   28.20 +# Extract from HTML4 spec.
   28.21 +## The following example illustrates "multipart/form-data"
   28.22 +## encoding. Suppose we have the following form:
   28.23 +
   28.24 +##  <FORM action="http://server.com/cgi/handle"
   28.25 +##        enctype="multipart/form-data"
   28.26 +##        method="post">
   28.27 +##    <P>
   28.28 +##    What is your name? <INPUT type="text" name="submit-name"><BR>
   28.29 +##    What files are you sending? <INPUT type="file" name="files"><BR>
   28.30 +##    <INPUT type="submit" value="Send"> <INPUT type="reset">
   28.31 +##  </FORM>
   28.32 +
   28.33 +## If the user enters "Larry" in the text input, and selects the text
   28.34 +## file "file1.txt", the user agent might send back the following data:
   28.35 +
   28.36 +##    Content-Type: multipart/form-data; boundary=AaB03x
   28.37 +
   28.38 +##    --AaB03x
   28.39 +##    Content-Disposition: form-data; name="submit-name"
   28.40 +
   28.41 +##    Larry
   28.42 +##    --AaB03x
   28.43 +##    Content-Disposition: form-data; name="files"; filename="file1.txt"
   28.44 +##    Content-Type: text/plain
   28.45 +
   28.46 +##    ... contents of file1.txt ...
   28.47 +##    --AaB03x--
   28.48 +
   28.49 +## If the user selected a second (image) file "file2.gif", the user agent
   28.50 +## might construct the parts as follows:
   28.51 +
   28.52 +##    Content-Type: multipart/form-data; boundary=AaB03x
   28.53 +
   28.54 +##    --AaB03x
   28.55 +##    Content-Disposition: form-data; name="submit-name"
   28.56 +
   28.57 +##    Larry
   28.58 +##    --AaB03x
   28.59 +##    Content-Disposition: form-data; name="files"
   28.60 +##    Content-Type: multipart/mixed; boundary=BbC04y
   28.61 +
   28.62 +##    --BbC04y
   28.63 +##    Content-Disposition: file; filename="file1.txt"
   28.64 +##    Content-Type: text/plain
   28.65 +
   28.66 +##    ... contents of file1.txt ...
   28.67 +##    --BbC04y
   28.68 +##    Content-Disposition: file; filename="file2.gif"
   28.69 +##    Content-Type: image/gif
   28.70 +##    Content-Transfer-Encoding: binary
   28.71 +
   28.72 +##    ...contents of file2.gif...
   28.73 +##    --BbC04y--
   28.74 +##    --AaB03x--
   28.75 +
   28.76 +__all__ = ['encode_data', 'encode_multipart', 'encode_form', 'mime_boundary' ]
   28.77 +
   28.78 +def data_values(d):
   28.79 +    if isinstance(d, types.DictType):
   28.80 +        return d.items()
   28.81 +    else:
   28.82 +        return d
   28.83 +
   28.84 +def encode_data(d):
   28.85 +    """Encode some data for HTTP transport.
   28.86 +    The encoding used is stored in 'Content-Type' in the headers.
   28.87 +
   28.88 +    d	data - sequence of tuples or dictionary
   28.89 +    returns a 2-tuple of the headers and the encoded data
   28.90 +    """
   28.91 +    val = ({}, None)
   28.92 +    if d is None: return val
   28.93 +    multipart = 0
   28.94 +    for (k, v) in data_values(d):
   28.95 +        if encode_isfile(v):
   28.96 +            multipart = 1
   28.97 +            break
   28.98 +    if multipart:
   28.99 +        val = encode_multipart(d)
  28.100 +    else:
  28.101 +        val = encode_form(d)
  28.102 +    return val
  28.103 +
  28.104 +def encode_isfile(v):
  28.105 +    if isinstance(v, types.FileType):
  28.106 +        return 1
  28.107 +    if hasattr(v, 'readlines'):
  28.108 +        return 1
  28.109 +    return 0
  28.110 +
  28.111 +def encode_multipart(d):
  28.112 +    boundary = mime_boundary()
  28.113 +    hdr = { 'Content-Type': 'multipart/form-data; boundary=' + boundary }
  28.114 +    out = StringIO()
  28.115 +    for (k,v) in data_values(d):
  28.116 +        out.write('--')
  28.117 +        out.write(boundary)
  28.118 +        out.write('\r\n')
  28.119 +        if encode_isfile(v):
  28.120 +            out.write('Content-Disposition: form-data; name="')
  28.121 +            out.write(k)
  28.122 +            if hasattr(v, 'name'):
  28.123 +                out.write('"; filename="')
  28.124 +                out.write(v.name)
  28.125 +            out.write('"\r\n')
  28.126 +            out.write('Content-Type: application/octet-stream\r\n')
  28.127 +            out.write('\r\n')
  28.128 +            for l in v.readlines():
  28.129 +               out.write(l)  
  28.130 +        else:
  28.131 +            out.write('Content-Disposition: form-data; name="')
  28.132 +            out.write(k)
  28.133 +            out.write('"\r\n')
  28.134 +            out.write('\r\n')
  28.135 +            out.write(str(v))
  28.136 +            out.write('\r\n')
  28.137 +    out.write('--')
  28.138 +    out.write(boundary)
  28.139 +    out.write('--')
  28.140 +    out.write('\r\n')
  28.141 +    return (hdr, out.getvalue())
  28.142 +
  28.143 +def mime_boundary():
  28.144 +    random.seed()
  28.145 +    m = md5.new()
  28.146 +    for i in range(0, 10):
  28.147 +        c = chr(random.randint(1, 255))
  28.148 +        m.update(c)
  28.149 +    b = m.hexdigest()
  28.150 +    return b[0:16]
  28.151 +
  28.152 +def encode_form(d):
  28.153 +    hdr = { 'Content-Type': 'application/x-www-form-urlencoded' }
  28.154 +    val = urllib.urlencode(d)
  28.155 +    return (hdr, val)
  28.156 +
  28.157 +def main():
  28.158 +    #d = {'a': 1, 'b': 'x y', 'c': file('conf.sxp') }
  28.159 +    #d = {'a': 1, 'b': 'x y' }
  28.160 +    d = [ ('a', 1), ('b', 'x y'), ('c', file('conf.sxp')) ]
  28.161 +    #d = [ ('a', 1), ('b', 'x y')]
  28.162 +    v = encode_data(d)
  28.163 +    print v[0]
  28.164 +    sys.stdout.write(v[1])
  28.165 +    print
  28.166 +
  28.167 +if __name__ == "__main__":
  28.168 +    main()
    29.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    29.2 +++ b/tools/xenmgr/lib/server/SrvBase.py	Fri Jun 11 14:40:53 2004 +0000
    29.3 @@ -0,0 +1,137 @@
    29.4 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    29.5 +
    29.6 +import cgi
    29.7 +
    29.8 +import os
    29.9 +import sys
   29.10 +import types
   29.11 +import StringIO
   29.12 +
   29.13 +from twisted.internet import defer
   29.14 +from twisted.internet import reactor
   29.15 +from twisted.web import error
   29.16 +from twisted.web import resource
   29.17 +from twisted.web import server
   29.18 +
   29.19 +from xenmgr import sxp
   29.20 +from xenmgr import PrettyPrint
   29.21 +
   29.22 +def uri_pathlist(p):
   29.23 +    """Split a path into a list.
   29.24 +    p		path
   29.25 +    return list of path elements
   29.26 +    """
   29.27 +    l = []
   29.28 +    for x in p.split('/'):
   29.29 +        if x == '': continue
   29.30 +        l.append(x)
   29.31 +    return l
   29.32 +
   29.33 +class SrvBase(resource.Resource):
   29.34 +    """Base class for services.
   29.35 +    """
   29.36 +
   29.37 +    def parse_form(self, req, method):
   29.38 +        """Parse the data for a request, GET using the URL, POST using encoded data.
   29.39 +        Posts should use enctype='multipart/form-data' in the <form> tag,
   29.40 +        rather than 'application/x-www-form-urlencoded'. Only 'multipart/form-data'
   29.41 +        handles file upload.
   29.42 +
   29.43 +        req		request
   29.44 +        returns a cgi.FieldStorage instance
   29.45 +        """
   29.46 +        env = {}
   29.47 +        env['REQUEST_METHOD'] = method
   29.48 +        if self.query:
   29.49 +            env['QUERY_STRING'] = self.query
   29.50 +        val = cgi.FieldStorage(fp=req.rfile, headers=req.headers, environ=env)
   29.51 +        return val
   29.52 +    
   29.53 +    def use_sxp(self, req):
   29.54 +        """Determine whether to send an SXP response to a request.
   29.55 +        Uses SXP if there is no User-Agent, no Accept, or application/sxp is in Accept.
   29.56 +
   29.57 +        req		request
   29.58 +        returns 1 for SXP, 0 otherwise
   29.59 +        """
   29.60 +        ok = 0
   29.61 +        user_agent = req.getHeader('User-Agent')
   29.62 +        accept = req.getHeader('Accept')
   29.63 +        if (not user_agent) or (not accept) or (accept.find(sxp.mime_type) >= 0):
   29.64 +            ok = 1
   29.65 +        return ok
   29.66 +
   29.67 +    def get_op_method(self, op):
   29.68 +        """Get the method for an operation.
   29.69 +        For operation 'foo' looks for 'op_foo'.
   29.70 +
   29.71 +        op	operation name
   29.72 +        returns method or None
   29.73 +        """
   29.74 +        op_method_name = 'op_' + op
   29.75 +        return getattr(self, op_method_name, None)
   29.76 +        
   29.77 +    def perform(self, req):
   29.78 +        """General operation handler for posted operations.
   29.79 +        For operation 'foo' looks for a method op_foo and calls
   29.80 +        it with op_foo(op, req). Replies with code 500 if op_foo
   29.81 +        is not found.
   29.82 +
   29.83 +        The method must return a list when req.use_sxp is true
   29.84 +        and an HTML string otherwise (or list).
   29.85 +        Methods may also return a Deferred (for incomplete processing).
   29.86 +
   29.87 +        req	request
   29.88 +        """
   29.89 +        op = req.args.get('op')
   29.90 +        if op is None or len(op) != 1:
   29.91 +            req.setResponseCode(404, "Invalid")
   29.92 +            return ''
   29.93 +        op = op[0]
   29.94 +        op_method = self.get_op_method(op)
   29.95 +        if op_method is None:
   29.96 +            req.setResponseCode(501, "Not implemented")
   29.97 +            req.setHeader("Content-Type", "text/plain")
   29.98 +            req.write("Not implemented: " + op)
   29.99 +            return ''
  29.100 +        else:
  29.101 +            val = op_method(op, req)
  29.102 +            if isinstance(val, defer.Deferred):
  29.103 +                val.addCallback(self._cb_perform, req, 1)
  29.104 +                return server.NOT_DONE_YET
  29.105 +            else:
  29.106 +                self._cb_perform(val, req, 0)
  29.107 +                return ''
  29.108 +
  29.109 +    def _cb_perform(self, val, req, dfr):
  29.110 +        """Callback to complete the request.
  29.111 +        May be called from a Deferred.
  29.112 +        """
  29.113 +        if isinstance(val, error.ErrorPage):
  29.114 +            req.write(val.render(req))
  29.115 +        elif self.use_sxp(req):
  29.116 +            req.setHeader("Content-Type", sxp.mime_type)
  29.117 +            sxp.show(val, req)
  29.118 +        else:
  29.119 +            req.write('<html><head></head><body>')
  29.120 +            self.print_path(req)
  29.121 +            if isinstance(val, types.ListType):
  29.122 +                req.write('<code><pre>')
  29.123 +                PrettyPrint.prettyprint(val, out=req)
  29.124 +                req.write('</pre></code>')
  29.125 +            else:
  29.126 +                req.write(str(val))
  29.127 +            req.write('</body></html>')
  29.128 +        if dfr:
  29.129 +            req.finish()
  29.130 +
  29.131 +    def print_path(self, req):
  29.132 +        """Print the path with hyperlinks.
  29.133 +        """
  29.134 +        pathlist = [x for x in req.prepath if x != '' ]
  29.135 +        s = "/"
  29.136 +        req.write('<h1><a href="/">/</a>')
  29.137 +        for x in pathlist:
  29.138 +            s += x + "/"
  29.139 +            req.write(' <a href="%s">%s</a>/' % (s, x))
  29.140 +        req.write("</h1>")
    30.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    30.2 +++ b/tools/xenmgr/lib/server/SrvConsole.py	Fri Jun 11 14:40:53 2004 +0000
    30.3 @@ -0,0 +1,42 @@
    30.4 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    30.5 +
    30.6 +from xenmgr import sxp
    30.7 +from xenmgr import XendConsole
    30.8 +from SrvDir import SrvDir
    30.9 +
   30.10 +class SrvConsole(SrvDir):
   30.11 +    """An individual console.
   30.12 +    """
   30.13 +
   30.14 +    def __init__(self, info):
   30.15 +        SrvDir.__init__(self)
   30.16 +        self.info = info
   30.17 +        self.xc = XendConsole.instance()
   30.18 +
   30.19 +    def op_disconnect(self, op, req):
   30.20 +        val = self.xc.console_disconnect(self.info.id)
   30.21 +        return val
   30.22 +
   30.23 +    def render_POST(self, req):
   30.24 +        return self.perform(req)
   30.25 +        
   30.26 +    def render_GET(self, req):
   30.27 +        if self.use_sxp(req):
   30.28 +            req.setHeader("Content-Type", sxp.mime_type)
   30.29 +            sxp.show(self.info.sxpr(), out=req)
   30.30 +        else:
   30.31 +            req.write('<html><head></head><body>')
   30.32 +            self.print_path(req)
   30.33 +            #self.ls()
   30.34 +            req.write('<p>%s</p>' % self.info)
   30.35 +            req.write('<p><a href="%s">Connect to domain %d</a></p>'
   30.36 +                      % (self.info.uri(), self.info.dom2))
   30.37 +            self.form(req)
   30.38 +            req.write('</body></html>')
   30.39 +        return ''
   30.40 +
   30.41 +    def form(self, req):
   30.42 +        req.write('<form method="post" action="%s">' % req.prePathURL())
   30.43 +        if self.info.connection():
   30.44 +            req.write('<input type="submit" name="op" value="disconnect">')
   30.45 +        req.write('</form>')
    31.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    31.2 +++ b/tools/xenmgr/lib/server/SrvConsoleDir.py	Fri Jun 11 14:40:53 2004 +0000
    31.3 @@ -0,0 +1,58 @@
    31.4 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    31.5 +
    31.6 +from SrvDir import SrvDir
    31.7 +from SrvConsole import SrvConsole
    31.8 +from xenmgr import XendConsole
    31.9 +from xenmgr import sxp
   31.10 +
   31.11 +class SrvConsoleDir(SrvDir):
   31.12 +    """Console directory.
   31.13 +    """
   31.14 +
   31.15 +    def __init__(self):
   31.16 +        SrvDir.__init__(self)
   31.17 +        self.xconsole = XendConsole.instance()
   31.18 +
   31.19 +    def console(self, x):
   31.20 +        val = None
   31.21 +        try:
   31.22 +            info = self.xconsole.console_get(x)
   31.23 +            val = SrvConsole(info)
   31.24 +        except KeyError:
   31.25 +            pass
   31.26 +        return val
   31.27 +
   31.28 +    def get(self, x):
   31.29 +        v = SrvDir.get(self, x)
   31.30 +        if v is not None:
   31.31 +            return v
   31.32 +        v = self.console(x)
   31.33 +        return v
   31.34 +
   31.35 +    def render_GET(self, req):
   31.36 +        if self.use_sxp(req):
   31.37 +            req.setHeader("Content-Type", sxp.mime_type)
   31.38 +            self.ls_console(req, 1)
   31.39 +        else:
   31.40 +            req.write("<html><head></head><body>")
   31.41 +            self.print_path(req)
   31.42 +            self.ls(req)
   31.43 +            self.ls_console(req)
   31.44 +            #self.form(req.wfile)
   31.45 +            req.write("</body></html>")
   31.46 +        return ''
   31.47 +
   31.48 +    def ls_console(self, req, use_sxp=0):
   31.49 +        url = req.prePathURL()
   31.50 +        if not url.endswith('/'):
   31.51 +            url += '/'
   31.52 +        if use_sxp:
   31.53 +            consoles = self.xconsole.console_ls()
   31.54 +            sxp.show(consoles, out=req)
   31.55 +        else:
   31.56 +            consoles = self.xconsole.consoles()
   31.57 +            consoles.sort(lambda x, y: cmp(x.id, y.id))
   31.58 +            req.write('<ul>')
   31.59 +            for c in consoles:
   31.60 +                req.write('<li><a href="%s%s"> %s</a></li>' % (url, c.id, c))
   31.61 +            req.write('</ul>')
    32.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    32.2 +++ b/tools/xenmgr/lib/server/SrvConsoleServer.py	Fri Jun 11 14:40:53 2004 +0000
    32.3 @@ -0,0 +1,631 @@
    32.4 +###########################################################
    32.5 +## Xen controller daemon
    32.6 +## Copyright (c) 2004, K A Fraser (University of Cambridge)
    32.7 +## Copyright (C) 2004, Mike Wray <mike.wray@hp.com>
    32.8 +###########################################################
    32.9 +
   32.10 +import os
   32.11 +import os.path
   32.12 +import signal
   32.13 +import sys
   32.14 +import socket
   32.15 +import pwd
   32.16 +import re
   32.17 +import StringIO
   32.18 +
   32.19 +from twisted.internet import pollreactor
   32.20 +pollreactor.install()
   32.21 +
   32.22 +from twisted.internet import reactor
   32.23 +from twisted.internet import protocol
   32.24 +from twisted.internet import abstract
   32.25 +from twisted.internet import defer
   32.26 +
   32.27 +import xend.utils
   32.28 +
   32.29 +from xenmgr import sxp
   32.30 +from xenmgr import PrettyPrint
   32.31 +from xenmgr import EventServer
   32.32 +eserver = EventServer.instance()
   32.33 +
   32.34 +from xenmgr.server import SrvServer
   32.35 +
   32.36 +import channel
   32.37 +import blkif
   32.38 +import netif
   32.39 +import console
   32.40 +from params import *
   32.41 +
   32.42 +DEBUG = 1
   32.43 +
   32.44 +class MgmtProtocol(protocol.DatagramProtocol):
   32.45 +    """Handler for the management socket (unix-domain).
   32.46 +    """
   32.47 +
   32.48 +    def __init__(self, daemon):
   32.49 +        #protocol.DatagramProtocol.__init__(self)
   32.50 +        self.daemon = daemon
   32.51 +    
   32.52 +    def write(self, data, addr):
   32.53 +        return self.transport.write(data, addr)
   32.54 +
   32.55 +    def datagramReceived(self, data, addr):
   32.56 +        if DEBUG: print 'datagramReceived> addr=', addr, 'data=', data
   32.57 +        io = StringIO.StringIO(data)
   32.58 +        try:
   32.59 +            vals = sxp.parse(io)
   32.60 +            res = self.dispatch(vals[0])
   32.61 +            self.send_result(addr, res)
   32.62 +        except SystemExit:
   32.63 +            raise
   32.64 +        except:
   32.65 +            if DEBUG:
   32.66 +                raise
   32.67 +            else:
   32.68 +                self.send_error(addr)
   32.69 +
   32.70 +    def send_reply(self, addr, sxpr):
   32.71 +        io = StringIO.StringIO()
   32.72 +        sxp.show(sxpr, out=io)
   32.73 +        io.seek(0)
   32.74 +        self.write(io.getvalue(), addr)
   32.75 +
   32.76 +    def send_result(self, addr, res):
   32.77 +        
   32.78 +        def fn(res, self=self, addr=addr):
   32.79 +            self.send_reply(addr, ['ok', res])
   32.80 +            
   32.81 +        if isinstance(res, defer.Deferred):
   32.82 +            res.addCallback(fn)
   32.83 +        else:
   32.84 +            fn(res)
   32.85 +
   32.86 +    def send_error(self, addr):
   32.87 +        (extype, exval) = sys.exc_info()[:2]
   32.88 +        self.send_reply(addr, ['err',
   32.89 +                               ['type',  str(extype) ],
   32.90 +                               ['value', str(exval)  ] ] )
   32.91 +
   32.92 +    def opname(self, name):
   32.93 +        """Get the name of the method for an operation.
   32.94 +        """
   32.95 +        return 'op_' + name.replace('.', '_')
   32.96 +
   32.97 +    def operror(self, name, v):
   32.98 +        """Default operation handler - signals an error.
   32.99 +        """
  32.100 +        raise NotImplementedError('Invalid operation: ' +name)
  32.101 +
  32.102 +    def dispatch(self, req):
  32.103 +        """Dispatch a request to its handler.
  32.104 +        """
  32.105 +        op_name = sxp.name(req)
  32.106 +        op_method_name = self.opname(op_name)
  32.107 +        op_method = getattr(self, op_method_name, self.operror)
  32.108 +        return op_method(op_name, req)
  32.109 +
  32.110 +    def op_console_create(self, name, req):
  32.111 +        """Create a new control interface - console for a domain.
  32.112 +        """
  32.113 +        print name, req
  32.114 +        dom = sxp.child_value(req, 'domain')
  32.115 +        if not dom: raise ValueError('Missing domain')
  32.116 +        dom = int(dom)
  32.117 +        console_port = sxp.child_value(req, 'console_port')
  32.118 +        if console_port:
  32.119 +            console_port = int(console_port)
  32.120 +        resp = self.daemon.console_create(dom, console_port)
  32.121 +        print name, resp
  32.122 +        return resp
  32.123 +
  32.124 +    def op_consoles(self, name, req):
  32.125 +        """Get a list of the consoles.
  32.126 +        """
  32.127 +        return self.daemon.consoles()
  32.128 +
  32.129 +    def op_console_disconnect(self, name, req):
  32.130 +        id = sxp.child_value(req, 'id')
  32.131 +        if not id:
  32.132 +            raise ValueError('Missing console id')
  32.133 +        id = int(id)
  32.134 +        console = self.daemon.get_console(id)
  32.135 +        if not console:
  32.136 +            raise ValueError('Invalid console id')
  32.137 +        if console.conn:
  32.138 +            console.conn.loseConnection()
  32.139 +        return ['ok']
  32.140 +
  32.141 +    def op_blkifs(self, name, req):
  32.142 +        pass
  32.143 +    
  32.144 +    def op_blkif_devs(self, name, req):
  32.145 +        pass
  32.146 +
  32.147 +    def op_blkif_create(self, name, req):
  32.148 +        pass
  32.149 +    
  32.150 +    def op_blkif_dev_create(self, name, req):
  32.151 +        pass
  32.152 +
  32.153 +    def op_netifs(self, name, req):
  32.154 +        pass
  32.155 +
  32.156 +    def op_netif_devs(self, name, req):
  32.157 +        pass
  32.158 +
  32.159 +    def op_netif_create(self, name, req):
  32.160 +        pass
  32.161 +
  32.162 +    def op_netif_dev_create(self, name, req):
  32.163 +        pass
  32.164 +
  32.165 +class NotifierProtocol(protocol.Protocol):
  32.166 +    """Asynchronous handler for i/o on the notifier (event channel).
  32.167 +    """
  32.168 +
  32.169 +    def __init__(self, channelFactory):
  32.170 +        self.channelFactory = channelFactory
  32.171 +
  32.172 +    def notificationReceived(self, idx, type):
  32.173 +        #print 'NotifierProtocol>notificationReceived>', idx, type
  32.174 +        channel = self.channelFactory.getChannel(idx)
  32.175 +        if not channel:
  32.176 +            return
  32.177 +        #print 'NotifierProtocol>notificationReceived> channel', channel
  32.178 +        channel.notificationReceived(type)
  32.179 +
  32.180 +    def connectionLost(self, reason=None):
  32.181 +        pass
  32.182 +
  32.183 +    def doStart(self):
  32.184 +        pass
  32.185 +
  32.186 +    def doStop(self):
  32.187 +        pass
  32.188 +
  32.189 +    def startProtocol(self):
  32.190 +        pass
  32.191 +
  32.192 +    def stopProtocol(self):
  32.193 +        pass
  32.194 +
  32.195 +class NotifierPort(abstract.FileDescriptor):
  32.196 +    """Transport class for the event channel.
  32.197 +    """
  32.198 +
  32.199 +    def __init__(self, daemon, notifier, proto, reactor=None):
  32.200 +        assert isinstance(proto, NotifierProtocol)
  32.201 +        abstract.FileDescriptor.__init__(self, reactor)
  32.202 +        self.daemon = daemon
  32.203 +        self.notifier = notifier
  32.204 +        self.protocol = proto
  32.205 +
  32.206 +    def startListening(self):
  32.207 +        self._bindNotifier()
  32.208 +        self._connectToProtocol()
  32.209 +
  32.210 +    def stopListening(self):
  32.211 +        if self.connected:
  32.212 +            result = self.d = defer.Deferred()
  32.213 +        else:
  32.214 +            result = None
  32.215 +        self.loseConnection()
  32.216 +        return result
  32.217 +
  32.218 +    def fileno(self):
  32.219 +        return self.notifier.fileno()
  32.220 +
  32.221 +    def _bindNotifier(self):
  32.222 +        self.connected = 1
  32.223 +
  32.224 +    def _connectToProtocol(self):
  32.225 +        self.protocol.makeConnection(self)
  32.226 +        self.startReading()
  32.227 +
  32.228 +    def loseConnection(self):
  32.229 +        if self.connected:
  32.230 +            self.stopReading()
  32.231 +            self.disconnecting = 1
  32.232 +            reactor.callLater(0, self.connectionLost)
  32.233 +
  32.234 +    def connectionLost(self, reason=None):
  32.235 +        abstract.FileDescriptor.connectionLost(self, reason)
  32.236 +        if hasattr(self, 'protocol'):
  32.237 +            self.protocol.doStop()
  32.238 +        self.connected = 0
  32.239 +        #self.notifier.close() # Not implemented.
  32.240 +        os.close(self.fileno())
  32.241 +        del self.notifier
  32.242 +        if hasattr(self, 'd'):
  32.243 +            self.d.callback(None)
  32.244 +            del self.d
  32.245 +        
  32.246 +    def doRead(self):
  32.247 +        #print 'NotifierPort>doRead>', self
  32.248 +        count = 0
  32.249 +        while 1:            
  32.250 +            #print 'NotifierPort>doRead>', count
  32.251 +            notification = self.notifier.read()
  32.252 +            if not notification:
  32.253 +                break
  32.254 +            (idx, type) = notification
  32.255 +            self.protocol.notificationReceived(idx, type)
  32.256 +            self.notifier.unmask(idx)
  32.257 +            count += 1
  32.258 +        #print 'NotifierPort>doRead<'
  32.259 +
  32.260 +class EventProtocol(protocol.Protocol):
  32.261 +    """Asynchronous handler for a connected event socket.
  32.262 +    """
  32.263 +
  32.264 +    def __init__(self, daemon):
  32.265 +        #protocol.Protocol.__init__(self)
  32.266 +        self.daemon = daemon
  32.267 +        # Event queue.
  32.268 +        self.queue = []
  32.269 +        # Subscribed events.
  32.270 +        self.events = []
  32.271 +        self.parser = sxp.Parser()
  32.272 +        self.pretty = 0
  32.273 +
  32.274 +        # For debugging subscribe to everything and make output pretty.
  32.275 +        self.subscribe(['*'])
  32.276 +        self.pretty = 1
  32.277 +
  32.278 +    def dataReceived(self, data):
  32.279 +        try:
  32.280 +            self.parser.input(data)
  32.281 +            if self.parser.ready():
  32.282 +                val = self.parser.get_val()
  32.283 +                res = self.dispatch(val)
  32.284 +                self.send_result(res)
  32.285 +            if self.parser.at_eof():
  32.286 +                self.loseConnection()
  32.287 +        except SystemExit:
  32.288 +            raise
  32.289 +        except:
  32.290 +            if DEBUG:
  32.291 +                raise
  32.292 +            else:
  32.293 +                self.send_error()
  32.294 +
  32.295 +    def connectionLost(self, reason=None):
  32.296 +        self.unsubscribe()
  32.297 +
  32.298 +    def send_reply(self, sxpr):
  32.299 +        io = StringIO.StringIO()
  32.300 +        if self.pretty:
  32.301 +            PrettyPrint.prettyprint(sxpr, out=io)
  32.302 +        else:
  32.303 +            sxp.show(sxpr, out=io)
  32.304 +        print >> io
  32.305 +        io.seek(0)
  32.306 +        return self.transport.write(io.getvalue())
  32.307 +
  32.308 +    def send_result(self, res):
  32.309 +        return self.send_reply(['ok', res])
  32.310 +
  32.311 +    def send_error(self):
  32.312 +        (extype, exval) = sys.exc_info()[:2]
  32.313 +        return self.send_reply(['err',
  32.314 +                                ['type', str(extype)],
  32.315 +                                ['value', str(exval)]])
  32.316 +
  32.317 +    def send_event(self, val):
  32.318 +        return self.send_reply(['event', val[0], val[1]])
  32.319 +
  32.320 +    def unsubscribe(self):
  32.321 +        for event in self.events:
  32.322 +            eserver.unsubscribe(event, self.queue_event)
  32.323 +
  32.324 +    def subscribe(self, events):
  32.325 +        self.unsubscribe()
  32.326 +        for event in events:
  32.327 +            eserver.subscribe(event, self.queue_event)
  32.328 +        self.events = events
  32.329 +
  32.330 +    def queue_event(self, name, v):
  32.331 +        # Despite the name we dont' queue the event here.
  32.332 +        # We send it because the transport will queue it.
  32.333 +        self.send_event([name, v])
  32.334 +        
  32.335 +    def opname(self, name):
  32.336 +         return 'op_' + name.replace('.', '_')
  32.337 +
  32.338 +    def operror(self, name, req):
  32.339 +        raise NotImplementedError('Invalid operation: ' +name)
  32.340 +
  32.341 +    def dispatch(self, req):
  32.342 +        op_name = sxp.name(req)
  32.343 +        op_method_name = self.opname(op_name)
  32.344 +        op_method = getattr(self, op_method_name, self.operror)
  32.345 +        return op_method(op_name, req)
  32.346 +
  32.347 +    def op_help(self, name, req):
  32.348 +        def nameop(x):
  32.349 +            if x.startswith('op_'):
  32.350 +                return x[3:].replace('_', '.')
  32.351 +            else:
  32.352 +                return x
  32.353 +        
  32.354 +        l = [ nameop(k) for k in dir(self) if k.startswith('op_') ]
  32.355 +        return l
  32.356 +
  32.357 +    def op_quit(self, name, req):
  32.358 +        self.loseConnection()
  32.359 +
  32.360 +    def op_exit(self, name, req):
  32.361 +        sys.exit(0)
  32.362 +
  32.363 +    def op_pretty(self, name, req):
  32.364 +        self.pretty = 1
  32.365 +        return ['ok']
  32.366 +
  32.367 +    def op_console_disconnect(self, name, req):
  32.368 +        id = sxp.child_value(req, 'id')
  32.369 +        if not id:
  32.370 +            raise ValueError('Missing console id')
  32.371 +        self.daemon.console_disconnect(id)
  32.372 +        return ['ok']
  32.373 +
  32.374 +    def op_info(self, name, req):
  32.375 +        val = self.daemon.consoles()
  32.376 +        return val
  32.377 +
  32.378 +    def op_sys_subscribe(self, name, v):
  32.379 +        # (sys.subscribe event*)
  32.380 +        # Subscribe to the events:
  32.381 +        self.subscribe(v[1:])
  32.382 +        return ['ok']
  32.383 +
  32.384 +    def op_sys_inject(self, name, v):
  32.385 +        # (sys.inject event)
  32.386 +        event = v[1]
  32.387 +        eserver.inject(sxp.name(event), event)
  32.388 +        return ['ok']
  32.389 +
  32.390 +
  32.391 +class EventFactory(protocol.Factory):
  32.392 +    """Asynchronous handler for the event server socket.
  32.393 +    """
  32.394 +    protocol = EventProtocol
  32.395 +    service = None
  32.396 +
  32.397 +    def __init__(self, daemon):
  32.398 +        #protocol.Factory.__init__(self)
  32.399 +        self.daemon = daemon
  32.400 +
  32.401 +    def buildProtocol(self, addr):
  32.402 +        proto = self.protocol(self.daemon)
  32.403 +        proto.factory = self
  32.404 +        return proto
  32.405 +
  32.406 +class Daemon:
  32.407 +    """The xend daemon.
  32.408 +    """
  32.409 +    def __init__(self):
  32.410 +        self.shutdown = 0
  32.411 +
  32.412 +    def daemon_pids(self):
  32.413 +        pids = []
  32.414 +        pidex = '(?P<pid>\d+)'
  32.415 +        pythonex = '(?P<python>\S*python\S*)'
  32.416 +        cmdex = '(?P<cmd>.*)'
  32.417 +        procre = re.compile('^\s*' + pidex + '\s*' + pythonex + '\s*' + cmdex + '$')
  32.418 +        xendre = re.compile('^/usr/sbin/xend\s*(start|restart)\s*.*$')
  32.419 +        procs = os.popen('ps -e -o pid,args 2>/dev/null')
  32.420 +        for proc in procs:
  32.421 +            pm = procre.match(proc)
  32.422 +            if not pm: continue
  32.423 +            xm = xendre.match(pm.group('cmd'))
  32.424 +            if not xm: continue
  32.425 +            #print 'pid=', pm.group('pid'), 'cmd=', pm.group('cmd')
  32.426 +            pids.append(int(pm.group('pid')))
  32.427 +        return pids
  32.428 +
  32.429 +    def new_cleanup(self, kill=0):
  32.430 +        err = 0
  32.431 +        pids = self.daemon_pids()
  32.432 +        if kill:
  32.433 +            for pid in pids:
  32.434 +                print "Killing daemon pid=%d" % pid
  32.435 +                os.kill(pid, signal.SIGHUP)
  32.436 +        elif pids:
  32.437 +            err = 1
  32.438 +            print "Daemon already running: ", pids
  32.439 +        return err
  32.440 +            
  32.441 +    def cleanup(self, kill=False):
  32.442 +        # No cleanup to do if PID_FILE is empty.
  32.443 +        if not os.path.isfile(PID_FILE) or not os.path.getsize(PID_FILE):
  32.444 +            return 0
  32.445 +        # Read the pid of the previous invocation and search active process list.
  32.446 +        pid = open(PID_FILE, 'r').read()
  32.447 +        lines = os.popen('ps ' + pid + ' 2>/dev/null').readlines()
  32.448 +        for line in lines:
  32.449 +            if re.search('^ *' + pid + '.+xend', line):
  32.450 +                if not kill:
  32.451 +                    print "Daemon is already running (pid %d)" % int(pid)
  32.452 +                    return 1
  32.453 +                # Old daemon is still active: terminate it.
  32.454 +                os.kill(int(pid), 1)
  32.455 +        # Delete the stale PID_FILE.
  32.456 +        os.remove(PID_FILE)
  32.457 +        return 0
  32.458 +
  32.459 +    def install_child_reaper(self):
  32.460 +        #signal.signal(signal.SIGCHLD, self.onSIGCHLD)
  32.461 +        # Ensure that zombie children are automatically reaped.
  32.462 +        xend.utils.autoreap()
  32.463 +
  32.464 +    def onSIGCHLD(self, signum, frame):
  32.465 +        code = 1
  32.466 +        while code > 0:
  32.467 +            code = os.waitpid(-1, os.WNOHANG)
  32.468 +
  32.469 +    def start(self):
  32.470 +        if self.cleanup(kill=False):
  32.471 +            return 1
  32.472 +
  32.473 +        # Detach from TTY.
  32.474 +        if not DEBUG:
  32.475 +            os.setsid()
  32.476 +
  32.477 +        if self.set_user():
  32.478 +            return 1
  32.479 +
  32.480 +        self.install_child_reaper()
  32.481 +
  32.482 +        # Fork -- parent writes PID_FILE and exits.
  32.483 +        pid = os.fork()
  32.484 +        if pid:
  32.485 +            # Parent
  32.486 +            pidfile = open(PID_FILE, 'w')
  32.487 +            pidfile.write(str(pid))
  32.488 +            pidfile.close()
  32.489 +            return 0
  32.490 +        # Child
  32.491 +        logfile = self.open_logfile()
  32.492 +        self.redirect_output(logfile)
  32.493 +        self.run()
  32.494 +        return 0
  32.495 +
  32.496 +    def open_logfile(self):
  32.497 +        if not os.path.exists(CONTROL_DIR):
  32.498 +            os.makedirs(CONTROL_DIR)
  32.499 +
  32.500 +        # Open log file. Truncate it if non-empty, and request line buffering.
  32.501 +        if os.path.isfile(LOG_FILE):
  32.502 +            os.rename(LOG_FILE, LOG_FILE+'.old')
  32.503 +        logfile = open(LOG_FILE, 'w+', 1)
  32.504 +        return logfile
  32.505 +
  32.506 +    def set_user(self):
  32.507 +        # Set the UID.
  32.508 +        try:
  32.509 +            os.setuid(pwd.getpwnam(USER)[2])
  32.510 +            return 0
  32.511 +        except KeyError, error:
  32.512 +            print "Error: no such user '%s'" % USER
  32.513 +            return 1
  32.514 +
  32.515 +    def redirect_output(self, logfile):
  32.516 +        if DEBUG: return
  32.517 +        # Close down standard file handles
  32.518 +        try:
  32.519 +            os.close(0) # stdin
  32.520 +            os.close(1) # stdout
  32.521 +            os.close(2) # stderr
  32.522 +        except:
  32.523 +            pass
  32.524 +        # Redirect output to log file.
  32.525 +        sys.stdout = sys.stderr = logfile
  32.526 +
  32.527 +    def stop(self):
  32.528 +        return self.cleanup(kill=True)
  32.529 +
  32.530 +    def run(self):
  32.531 +        self.createFactories()
  32.532 +        self.listenMgmt()
  32.533 +        self.listenEvent()
  32.534 +        self.listenNotifier()
  32.535 +        SrvServer.create()
  32.536 +        reactor.run()
  32.537 +
  32.538 +    def createFactories(self):
  32.539 +        self.channelF = channel.channelFactory()
  32.540 +        self.blkifCF = blkif.BlkifControllerFactory()
  32.541 +        self.netifCF = netif.NetifControllerFactory()
  32.542 +        self.consoleCF = console.ConsoleControllerFactory()
  32.543 +
  32.544 +    def listenMgmt(self):
  32.545 +        protocol = MgmtProtocol(self)
  32.546 +        s = os.path.join(CONTROL_DIR, MGMT_SOCK)
  32.547 +        if os.path.exists(s):
  32.548 +            os.unlink(s)
  32.549 +        return reactor.listenUNIXDatagram(s, protocol)
  32.550 +
  32.551 +    def listenEvent(self):
  32.552 +        protocol = EventFactory(self)
  32.553 +        return reactor.listenTCP(EVENT_PORT, protocol)
  32.554 +
  32.555 +    def listenNotifier(self):
  32.556 +        protocol = NotifierProtocol(self.channelF)
  32.557 +        p = NotifierPort(self, self.channelF.notifier, protocol, reactor)
  32.558 +        p.startListening()
  32.559 +        return p
  32.560 +
  32.561 +    def exit(self):
  32.562 +        reactor.diconnectAll()
  32.563 +        sys.exit(0)
  32.564 +
  32.565 +    def blkif_create(self, dom):
  32.566 +        """Create a block device interface controller.
  32.567 +        
  32.568 +        Returns Deferred
  32.569 +        """
  32.570 +        d = self.blkifCF.createInstance(dom)
  32.571 +        return d
  32.572 +
  32.573 +    def blkif_dev_create(self, dom, vdev, mode, segment):
  32.574 +        """Create a block device.
  32.575 +        
  32.576 +        Returns Deferred
  32.577 +        """
  32.578 +        ctrl = self.blkifCF.getInstanceByDom(dom)
  32.579 +        if not ctrl:
  32.580 +            raise ValueError('No blkif controller: %d' % dom)
  32.581 +        print 'blkif_dev_create>', dom, vdev, mode, segment
  32.582 +        d = ctrl.attach_device(vdev, mode, segment)
  32.583 +        return d
  32.584 +
  32.585 +    def netif_create(self, dom):
  32.586 +        """Create a network interface controller.
  32.587 +        
  32.588 +        """
  32.589 +        return self.netifCF.createInstance(dom)
  32.590 +
  32.591 +    def netif_dev_create(self, dom, vif, vmac):
  32.592 +        """Create a network device.
  32.593 +
  32.594 +        todo
  32.595 +        """
  32.596 +        ctrl = self.netifCF.getInstanceByDom(dom)
  32.597 +        if not ctrl:
  32.598 +            raise ValueError('No netif controller: %d' % dom)
  32.599 +        d = ctrl.attach_device(vif, vmac)
  32.600 +        return d
  32.601 +
  32.602 +    def console_create(self, dom, console_port=None):
  32.603 +        """Create a console for a domain.
  32.604 +        """
  32.605 +        console = self.consoleCF.getInstanceByDom(dom)
  32.606 +        if console is None:
  32.607 +            console = self.consoleCF.createInstance(dom, console_port)
  32.608 +        return console.sxpr()
  32.609 +
  32.610 +    def consoles(self):
  32.611 +        return [ c.sxpr() for c in self.consoleCF.getInstances() ]
  32.612 +
  32.613 +    def get_console(self, id):
  32.614 +        return self.consoleCF.getInstance(id)
  32.615 +
  32.616 +    def get_domain_console(self, dom):
  32.617 +        return self.consoleCF.getInstanceByDom(dom)
  32.618 +
  32.619 +    def console_disconnect(self, id):
  32.620 +        """Disconnect any connected console client.
  32.621 +        """
  32.622 +        console = self.get_console(id)
  32.623 +        if not console:
  32.624 +            raise ValueError('Invalid console id')
  32.625 +        if console.conn:
  32.626 +            console.conn.loseConnection()
  32.627 +
  32.628 +def instance():
  32.629 +    global inst
  32.630 +    try:
  32.631 +        inst
  32.632 +    except:
  32.633 +        inst = Daemon()
  32.634 +    return inst
    33.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    33.2 +++ b/tools/xenmgr/lib/server/SrvDeviceDir.py	Fri Jun 11 14:40:53 2004 +0000
    33.3 @@ -0,0 +1,9 @@
    33.4 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    33.5 +
    33.6 +from SrvDir import SrvDir
    33.7 +
    33.8 +class SrvDeviceDir(SrvDir):
    33.9 +    """Device directory.
   33.10 +    """
   33.11 +
   33.12 +    pass
    34.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    34.2 +++ b/tools/xenmgr/lib/server/SrvDir.py	Fri Jun 11 14:40:53 2004 +0000
    34.3 @@ -0,0 +1,91 @@
    34.4 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    34.5 +
    34.6 +from twisted.web import error
    34.7 +from xenmgr import sxp
    34.8 +from SrvBase import SrvBase
    34.9 +
   34.10 +class SrvConstructor:
   34.11 +    """Delayed constructor for sub-servers.
   34.12 +    Does not import the sub-server class or create the object until needed.
   34.13 +    """
   34.14 +    
   34.15 +    def __init__(self, klass):
   34.16 +        """Create a constructor. It is assumed that the class
   34.17 +        should be imported as 'import klass from klass'.
   34.18 +
   34.19 +        klass	name of its class
   34.20 +        """
   34.21 +        self.klass = klass
   34.22 +        self.obj = None
   34.23 +
   34.24 +    def getobj(self):
   34.25 +        """Get the sub-server object, importing its class and instantiating it if
   34.26 +        necessary.
   34.27 +        """
   34.28 +        if not self.obj:
   34.29 +            exec 'from %s import %s' % (self.klass, self.klass)
   34.30 +            klassobj = eval(self.klass)
   34.31 +            self.obj = klassobj()
   34.32 +        return self.obj
   34.33 +
   34.34 +class SrvDir(SrvBase):
   34.35 +    """Base class for directory servlets.
   34.36 +    """
   34.37 +    isLeaf = False
   34.38 +    
   34.39 +    def __init__(self):
   34.40 +        SrvBase.__init__(self)
   34.41 +        self.table = {}
   34.42 +        self.order = []
   34.43 +
   34.44 +    def getChild(self, x, req):
   34.45 +        if x == '': return self
   34.46 +        val = self.get(x)
   34.47 +        if val is None:
   34.48 +            return error.NoResource('Not found')
   34.49 +        else:
   34.50 +            return val
   34.51 +
   34.52 +    def get(self, x):
   34.53 +        val = self.table.get(x)
   34.54 +        if val is not None:
   34.55 +            val = val.getobj()
   34.56 +        return val
   34.57 +
   34.58 +    def add(self, x, xclass = None):
   34.59 +        if xclass is None:
   34.60 +            xclass = 'SrvDir'
   34.61 +        self.table[x] = SrvConstructor(xclass)
   34.62 +        self.order.append(x)
   34.63 +
   34.64 +    def render_GET(self, req):
   34.65 +        if self.use_sxp(req):
   34.66 +            req.setHeader("Content-type", sxp.mime_type)
   34.67 +            self.ls(req, 1)
   34.68 +        else:
   34.69 +            req.write('<html><head></head><body>')
   34.70 +            self.print_path(req)
   34.71 +            self.ls(req)
   34.72 +            self.form(req)
   34.73 +            req.write('</body></html>')
   34.74 +        return ''
   34.75 +            
   34.76 +    def ls(self, req, use_sxp=0):
   34.77 +        url = req.prePathURL()
   34.78 +        if not url.endswith('/'):
   34.79 +            url += '/'
   34.80 +        if use_sxp:
   34.81 +           req.write('(ls ')
   34.82 +           for k in self.order:
   34.83 +               req.write(' ' + k)
   34.84 +           req.write(')')
   34.85 +        else:
   34.86 +            req.write('<ul>')
   34.87 +            for k in self.order:
   34.88 +                v = self.get(k)
   34.89 +                req.write('<li><a href="%s%s">%s</a></li>'
   34.90 +                          % (url, k, k))
   34.91 +            req.write('</ul>')
   34.92 +
   34.93 +    def form(self, req):
   34.94 +        pass
    35.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    35.2 +++ b/tools/xenmgr/lib/server/SrvDomain.py	Fri Jun 11 14:40:53 2004 +0000
    35.3 @@ -0,0 +1,202 @@
    35.4 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    35.5 +
    35.6 +from xenmgr import sxp
    35.7 +from xenmgr import XendDomain
    35.8 +from xenmgr import XendConsole
    35.9 +from xenmgr import PrettyPrint
   35.10 +from xenmgr.Args import FormFn
   35.11 +
   35.12 +from SrvDir import SrvDir
   35.13 +
   35.14 +class SrvDomain(SrvDir):
   35.15 +    """Service managing a single domain.
   35.16 +    """
   35.17 +
   35.18 +    def __init__(self, dom):
   35.19 +        SrvDir.__init__(self)
   35.20 +        self.dom = dom
   35.21 +        self.xd = XendDomain.instance()
   35.22 +        self.xconsole = XendConsole.instance()
   35.23 +
   35.24 +    def op_start(self, op, req):
   35.25 +        val = self.xd.domain_start(self.dom.id)
   35.26 +        return val
   35.27 +        
   35.28 +    def op_stop(self, op, req):
   35.29 +        val = self.xd.domain_stop(self.dom.id)
   35.30 +        return val
   35.31 +
   35.32 +    def op_shutdown(self, op, req):
   35.33 +        val = self.xd.domain_shutdown(self.dom.id)
   35.34 +        req.setResponseCode(202)
   35.35 +        req.setHeader("Location", "%s/.." % req.prePathURL())
   35.36 +        return val
   35.37 +
   35.38 +    def op_halt(self, op, req):
   35.39 +        val = self.xd.domain_halt(self.dom.id)
   35.40 +        req.setHeader("Location", "%s/.." % req.prePathURL())
   35.41 +        return val
   35.42 +
   35.43 +    def op_save(self, op, req):
   35.44 +        fn = FormFn(self.xd.domain_save,
   35.45 +                    [['dom', 'int'],
   35.46 +                     ['dst', 'str']])
   35.47 +        val = fn(req.args, {'dom': self.dom.id})
   35.48 +        return val
   35.49 +
   35.50 +    def op_restore(self, op, req):
   35.51 +        fn = FormFn(self.xd.domain_restore,
   35.52 +                    [['dom', 'int'],
   35.53 +                     ['src', 'str']])
   35.54 +        val = fn(req.args, {'dom': self.dom.id})
   35.55 +        return val
   35.56 +        
   35.57 +    def op_migrate(self, op, req):
   35.58 +        fn = FormFn(self.xd.domain_migrate,
   35.59 +                    [['dom', 'int'],
   35.60 +                     ['destination', 'str']])
   35.61 +        val = fn(req.args, {'dom': self.dom.id})
   35.62 +        val = 0 # Some migrate id.
   35.63 +        req.setResponseCode(202)
   35.64 +        #req.send_header("Location", "%s/.." % self.path) # Some migrate url.
   35.65 +        return val
   35.66 +
   35.67 +    def op_pincpu(self, op, req):
   35.68 +        fn = FormFn(self.xd.domain_migrate,
   35.69 +                    [['dom', 'int'],
   35.70 +                     ['cpu', 'int']])
   35.71 +        val = fn(req.args, {'dom': self.dom.id})
   35.72 +        return val
   35.73 +
   35.74 +    def op_cpu_bvt_set(self, op, req):
   35.75 +        fn = FormFn(self.xd.domain_cpu_bvt_set,
   35.76 +                    [['dom', 'int'],
   35.77 +                     ['mcuadv', 'int'],
   35.78 +                     ['warp', 'int'],
   35.79 +                     ['warpl', 'int'],
   35.80 +                     ['warpu', 'int']])
   35.81 +        val = fn(req.args, {'dom': self.dom.id})
   35.82 +        return val
   35.83 +
   35.84 +    def op_cpu_atropos_set(self, op, req):
   35.85 +        fn = FormFn(self.xd.domain_cpu_atropos_set,
   35.86 +                    [['dom', 'int'],
   35.87 +                     ['period', 'int'],
   35.88 +                     ['slice', 'int'],
   35.89 +                     ['latency', 'int'],
   35.90 +                     ['xtratime', 'int']])
   35.91 +        val = fn(req.args, {'dom': self.dom.id})
   35.92 +        return val
   35.93 +
   35.94 +    def op_vifs(self, op, req):
   35.95 +        return self.xd.domain_vif_ls(self.dom.id)
   35.96 +
   35.97 +    def op_vif(self, op, req):
   35.98 +        fn = FormFn(self.xd.domain_vif_get,
   35.99 +                    [['dom', 'int'],
  35.100 +                     ['vif', 'int']])
  35.101 +        val = fn(req.args, {'dom': self.dom.id})
  35.102 +        return val
  35.103 +
  35.104 +    def op_vif_stats(self, op, req):
  35.105 +        #todo
  35.106 +        fn = FormFn(self.xd.domain_vif_stats,
  35.107 +                    [['dom', 'int'],
  35.108 +                     ['vif', 'int']])
  35.109 +        #val = fn(req.args, {'dom': self.dom.id})
  35.110 +        val = 999
  35.111 +        #return val
  35.112 +        return val
  35.113 +
  35.114 +    def op_vif_ip_add(self, op, req):
  35.115 +        fn = FormFn(self.xd.domain_vif_ip_add,
  35.116 +                    [['dom', 'int'],
  35.117 +                     ['vif', 'int'],
  35.118 +                     ['ip', 'str']])
  35.119 +        val = fn(req.args, {'dom': self.dom.id})
  35.120 +        return val
  35.121 +
  35.122 +    def op_vif_scheduler_set(self, op, req):
  35.123 +        fn = FormFn(self.xd.domain_vif_scheduler_set,
  35.124 +                    [['dom', 'int'],
  35.125 +                     ['vif', 'int'],
  35.126 +                     ['bytes', 'int'],
  35.127 +                     ['usecs', 'int']])
  35.128 +        val = fn(req.args, {'dom': self.dom.id})
  35.129 +        return val
  35.130 +
  35.131 +    def op_vif_scheduler_get(self, op, req):
  35.132 +        fn = FormFn(self.xd.domain_vif_scheduler_set,
  35.133 +                    [['dom', 'int'],
  35.134 +                     ['vif', 'int']])
  35.135 +        val = fn(req.args, {'dom': self.dom.id})
  35.136 +        return val
  35.137 +
  35.138 +    def op_vbds(self, op, req):
  35.139 +        return self.xd.domain_vbd_ls(self.dom.id)
  35.140 +
  35.141 +    def op_vbd(self, op, req):
  35.142 +        fn = FormFn(self.xd.domain_vbd_get,
  35.143 +                    [['dom', 'int'],
  35.144 +                     ['vbd', 'int']])
  35.145 +        val = fn(req.args, {'dom': self.dom.id})
  35.146 +        return val
  35.147 +
  35.148 +    def op_vbd_add(self, op, req):
  35.149 +        fn = FormFn(self.xd.domain_vbd_add,
  35.150 +                    [['dom', 'int'],
  35.151 +                     ['uname', 'str'],
  35.152 +                     ['dev', 'str'],
  35.153 +                     ['mode', 'str']])
  35.154 +        val = fn(req.args, {'dom': self.dom.id})
  35.155 +        return val
  35.156 +
  35.157 +    def op_vbd_remove(self, op, req):
  35.158 +        fn = FormFn(self.xd.domain_vbd_remove,
  35.159 +                    [['dom', 'int'],
  35.160 +                     ['dev', 'str']])
  35.161 +        val = fn(req.args, {'dom': self.dom.id})
  35.162 +        return val
  35.163 +
  35.164 +    def render_POST(self, req):
  35.165 +        return self.perform(req)
  35.166 +        
  35.167 +    def render_GET(self, req):
  35.168 +        op = req.args.get('op')
  35.169 +        if op and op[0] in ['vifs', 'vif', 'vif_stats', 'vbds', 'vbd']:
  35.170 +            return self.perform(req)
  35.171 +        if self.use_sxp(req):
  35.172 +            req.setHeader("Content-Type", sxp.mime_type)
  35.173 +            sxp.show(self.dom.sxpr(), out=req)
  35.174 +        else:
  35.175 +            req.write('<html><head></head><body>')
  35.176 +            self.print_path(req)
  35.177 +            #self.ls()
  35.178 +            req.write('<p>%s</p>' % self.dom)
  35.179 +            if self.dom.console:
  35.180 +                cinfo = self.dom.console
  35.181 +                cid = cinfo.id
  35.182 +                #todo: Local xref: need to know server prefix.
  35.183 +                req.write('<p><a href="/xend/console/%s">Console %s</a></p>'
  35.184 +                          % (cid, cid))
  35.185 +                req.write('<p><a href="%s">Connect to console</a></p>'
  35.186 +                          % cinfo.uri())
  35.187 +            if self.dom.config:
  35.188 +                req.write("<code><pre>")
  35.189 +                PrettyPrint.prettyprint(self.dom.config, out=req)
  35.190 +                req.write("</pre></code>")
  35.191 +            req.write('<a href="%s?op=vif_stats&vif=0">vif 0 stats</a>'
  35.192 +                      % req.prePathURL())
  35.193 +            self.form(req)
  35.194 +            req.write('</body></html>')
  35.195 +        return ''
  35.196 +
  35.197 +    def form(self, req):
  35.198 +        req.write('<form method="post" action="%s">' % req.prePathURL())
  35.199 +        req.write('<input type="submit" name="op" value="start">')
  35.200 +        req.write('<input type="submit" name="op" value="stop">')
  35.201 +        req.write('<input type="submit" name="op" value="shutdown">')
  35.202 +        req.write('<input type="submit" name="op" value="halt">')
  35.203 +        req.write('<br><input type="submit" name="op" value="migrate">')
  35.204 +        req.write('To: <input type="text" name="destination">')
  35.205 +        req.write('</form>')
    36.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    36.2 +++ b/tools/xenmgr/lib/server/SrvDomainDir.py	Fri Jun 11 14:40:53 2004 +0000
    36.3 @@ -0,0 +1,130 @@
    36.4 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    36.5 +
    36.6 +from StringIO import StringIO
    36.7 +
    36.8 +from twisted.protocols import http
    36.9 +from twisted.web import error
   36.10 +
   36.11 +from xenmgr import sxp
   36.12 +from xenmgr import XendDomain
   36.13 +
   36.14 +from SrvDir import SrvDir
   36.15 +from SrvDomain import SrvDomain
   36.16 +
   36.17 +class SrvDomainDir(SrvDir):
   36.18 +    """Service that manages the domain directory.
   36.19 +    """
   36.20 +
   36.21 +    def __init__(self):
   36.22 +        SrvDir.__init__(self)
   36.23 +        self.xd = XendDomain.instance()
   36.24 +
   36.25 +    def domain(self, x):
   36.26 +        val = None
   36.27 +        try:
   36.28 +            dom = self.xd.domain_get(x)
   36.29 +            val = SrvDomain(dom)
   36.30 +        except KeyError:
   36.31 +            pass
   36.32 +        return val
   36.33 +
   36.34 +    def get(self, x):
   36.35 +        v = SrvDir.get(self, x)
   36.36 +        if v is not None:
   36.37 +            return v
   36.38 +        v = self.domain(x)
   36.39 +        return v
   36.40 +
   36.41 +    def op_create(self, op, req):
   36.42 +        ok = 0
   36.43 +        try:
   36.44 +            configstring = req.args.get('config')[0]
   36.45 +            print 'config:', configstring
   36.46 +            pin = sxp.Parser()
   36.47 +            pin.input(configstring)
   36.48 +            pin.input_eof()
   36.49 +            config = pin.get_val()
   36.50 +            ok = 1
   36.51 +        except Exception, ex:
   36.52 +            print ex
   36.53 +        if not ok:
   36.54 +            req.setResponseCode(http.BAD_REQUEST, "Invalid configuration")
   36.55 +            return "Invalid configuration"
   36.56 +            return error.ErrorPage(http.BAD_REQUEST,
   36.57 +                                   "Invalid",
   36.58 +                                   "Invalid configuration")
   36.59 +        try:
   36.60 +            deferred = self.xd.domain_create(config)
   36.61 +            deferred.addCallback(self._cb_op_create, configstring, req)
   36.62 +            return deferred
   36.63 +        except Exception, ex:
   36.64 +            raise
   36.65 +            #return ['err', str(ex) ]
   36.66 +            #req.setResponseCode(http.BAD_REQUEST, "Error creating domain")
   36.67 +            #return str(ex)
   36.68 +            #return error.ErrorPage(http.BAD_REQUEST,
   36.69 +            #                       "Error creating domain",
   36.70 +            #                       str(ex))
   36.71 +                                   
   36.72 +
   36.73 +    def _cb_op_create(self, dominfo, configstring, req):
   36.74 +        """Callback to handle deferred domain creation.
   36.75 +        """
   36.76 +        dom = dominfo.id
   36.77 +        domurl = "%s/%s" % (req.prePathURL(), dom)
   36.78 +        req.setResponseCode(201, "created")
   36.79 +        req.setHeader("Location", domurl)
   36.80 +        if self.use_sxp(req):
   36.81 +            return dominfo.sxpr()
   36.82 +        else:
   36.83 +            out = StringIO()
   36.84 +            print >> out, ('<p> Created <a href="%s">Domain %s</a></p>'
   36.85 +                           % (domurl, dom))
   36.86 +            print >> out, '<p><pre>'
   36.87 +            print >> out, configstring
   36.88 +            print >> out, '</pre></p>'
   36.89 +            val = out.getvalue()
   36.90 +            out.close()
   36.91 +            return val
   36.92 +
   36.93 +    def render_POST(self, req):
   36.94 +        return self.perform(req)
   36.95 +
   36.96 +    def render_GET(self, req):
   36.97 +        if self.use_sxp(req):
   36.98 +            req.setHeader("Content-Type", sxp.mime_type)
   36.99 +            self.ls_domain(req, 1)
  36.100 +        else:
  36.101 +            req.write("<html><head></head><body>")
  36.102 +            self.print_path(req)
  36.103 +            self.ls(req)
  36.104 +            self.ls_domain(req)
  36.105 +            self.form(req)
  36.106 +            req.write("</body></html>")
  36.107 +        return ''
  36.108 +
  36.109 +    def ls_domain(self, req, use_sxp=0):
  36.110 +        url = req.prePathURL()
  36.111 +        if not url.endswith('/'):
  36.112 +            url += '/'
  36.113 +        if use_sxp:
  36.114 +            domains = self.xd.domain_ls()
  36.115 +            sxp.show(domains, out=req)
  36.116 +        else:
  36.117 +            domains = self.xd.domains()
  36.118 +            domains.sort(lambda x, y: cmp(x.id, y.id))
  36.119 +            req.write('<ul>')
  36.120 +            for d in domains:
  36.121 +               req.write('<li><a href="%s%s"> Domain %s</a>'
  36.122 +                         % (url, d.id, d.id))
  36.123 +               req.write('name=%s' % d.name)
  36.124 +               req.write('memory=%d'% d.memory)
  36.125 +               req.write('</li>')
  36.126 +            req.write('</ul>')
  36.127 +
  36.128 +    def form(self, req):
  36.129 +        req.write('<form method="post" action="%s" enctype="multipart/form-data">'
  36.130 +                  % req.prePathURL())
  36.131 +        req.write('<button type="submit" name="op" value="create">Create Domain</button>')
  36.132 +        req.write('Config <input type="file" name="config"><br>')
  36.133 +        req.write('</form>')
    37.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    37.2 +++ b/tools/xenmgr/lib/server/SrvEventDir.py	Fri Jun 11 14:40:53 2004 +0000
    37.3 @@ -0,0 +1,41 @@
    37.4 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    37.5 +
    37.6 +from xenmgr import sxp
    37.7 +from xenmgr import EventServer
    37.8 +from SrvDir import SrvDir
    37.9 +
   37.10 +class SrvEventDir(SrvDir):
   37.11 +    """Event directory.
   37.12 +    """
   37.13 +
   37.14 +    def __init__(self):
   37.15 +        SrvDir.__init__(self)
   37.16 +        self.eserver = EventServer.instance()
   37.17 +
   37.18 +    def op_inject(self, op, req):
   37.19 +        eventstring = req.args.get('event')
   37.20 +        pin = sxp.Parser()
   37.21 +        pin.input(eventstring)
   37.22 +        pin.input_eof()
   37.23 +        sxpr = pin.get_val()
   37.24 +        self.eserver.inject(sxp.name(sxpr), sxpr)
   37.25 +        if req.use_sxp:
   37.26 +            sxp.name(sxpr)
   37.27 +        else:
   37.28 +            return '<code>' + eventstring + '</code>'
   37.29 +        
   37.30 +    def render_POST(self, req):
   37.31 +        return self.perform(req)
   37.32 +
   37.33 +    def form(self, req):
   37.34 +        action = req.prePathURL()
   37.35 +        req.write('<form method="post" action="%s" enctype="multipart/form-data">'
   37.36 +                  % action)
   37.37 +        req.write('<button type="submit" name="op" value="inject">Inject</button>')
   37.38 +        req.write('Event <input type="text" name="event" size="40"><br>')
   37.39 +        req.write('</form>')
   37.40 +        req.write('<form method="post" action="%s" enctype="multipart/form-data">'
   37.41 +                  % action)
   37.42 +        req.write('<button type="submit" name="op" value="inject">Inject</button>')
   37.43 +        req.write('Event file<input type="file" name="event"><br>')
   37.44 +        req.write('</form>')
    38.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    38.2 +++ b/tools/xenmgr/lib/server/SrvNode.py	Fri Jun 11 14:40:53 2004 +0000
    38.3 @@ -0,0 +1,59 @@
    38.4 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    38.5 +
    38.6 +import os
    38.7 +from SrvDir import SrvDir
    38.8 +from xenmgr import sxp
    38.9 +from xenmgr import XendNode
   38.10 +
   38.11 +class SrvNode(SrvDir):
   38.12 +    """Information about the node.
   38.13 +    """
   38.14 +
   38.15 +    def __init__(self):
   38.16 +        SrvDir.__init__(self)
   38.17 +        self.xn = XendNode.instance()
   38.18 +
   38.19 +    def op_shutdown(self, op, req):
   38.20 +        val = self.xn.shutdown()
   38.21 +        return val
   38.22 +
   38.23 +    def op_reboot(self, op, req):
   38.24 +        val = self.xn.reboot()
   38.25 +        return val
   38.26 +
   38.27 +    def op_cpu_rrobin_slice_set(self, op, req):
   38.28 +        fn = FormFn(self.xn.cpu_rrobin_slice_set,
   38.29 +                    [['slice', 'int']])
   38.30 +        val = fn(req.args, {})
   38.31 +        return val
   38.32 +
   38.33 +    def op_cpu_bvt_slice_set(self, op, req):
   38.34 +        fn = FormFn(self.xn.cpu_bvt_slice_set,
   38.35 +                    [['slice', 'int']])
   38.36 +        val = fn(req.args, {})
   38.37 +        return val
   38.38 +
   38.39 +    def render_POST(self, req):
   38.40 +        return self.perform(req)
   38.41 +
   38.42 +    def render_GET(self, req):
   38.43 +        if self.use_sxp(req):
   38.44 +            req.setHeader("Content-Type", sxp.mime_type)
   38.45 +            sxp.show(['node'] + self.info(), out=req)
   38.46 +        else:
   38.47 +            req.write('<html><head></head><body>')
   38.48 +            self.print_path(req)
   38.49 +            req.write('<ul>')
   38.50 +            for d in self.info():
   38.51 +                req.write('<li> %10s: %s' % (d[0], d[1]))
   38.52 +            req.write('</ul>')
   38.53 +            req.write('</body></html>')
   38.54 +        return ''
   38.55 +            
   38.56 +    def info(self):
   38.57 +        (sys, host, rel, ver, mch) = os.uname()
   38.58 +        return [['system',  sys],
   38.59 +                ['host',    host],
   38.60 +                ['release', rel],
   38.61 +                ['version', ver],
   38.62 +                ['machine', mch]]
    39.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    39.2 +++ b/tools/xenmgr/lib/server/SrvRoot.py	Fri Jun 11 14:40:53 2004 +0000
    39.3 @@ -0,0 +1,31 @@
    39.4 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    39.5 +
    39.6 +from xenmgr import XendRoot
    39.7 +xroot = XendRoot.instance()
    39.8 +from SrvDir import SrvDir
    39.9 +
   39.10 +class SrvRoot(SrvDir):
   39.11 +    """The root of the xend server.
   39.12 +    """
   39.13 +
   39.14 +    """Server sub-components. Each entry is (name, class), where
   39.15 +    'name' is the entry name and  'class' is the name of its class.
   39.16 +    """
   39.17 +    #todo Get this list from the XendRoot config.
   39.18 +    subdirs = [
   39.19 +        ('node',    'SrvNode'       ),
   39.20 +        ('domain',  'SrvDomainDir'  ),
   39.21 +        ('console', 'SrvConsoleDir' ),
   39.22 +        ('event',   'SrvEventDir'   ),
   39.23 +        ('vdisk',   'SrvVdiskDir'   ),
   39.24 +        ('device',  'SrvDeviceDir'  ),
   39.25 +        ('vnet',    'SrvVnetDir'    ),
   39.26 +        ]
   39.27 +
   39.28 +    def __init__(self):
   39.29 +        SrvDir.__init__(self)
   39.30 +        for (name, klass) in self.subdirs:
   39.31 +            self.add(name, klass)
   39.32 +        for (name, klass) in self.subdirs:
   39.33 +            self.get(name)
   39.34 +        xroot.start()
    40.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    40.2 +++ b/tools/xenmgr/lib/server/SrvServer.py	Fri Jun 11 14:40:53 2004 +0000
    40.3 @@ -0,0 +1,53 @@
    40.4 +#!/usr/bin/python2
    40.5 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    40.6 +
    40.7 +"""Example xend HTTP and console server.
    40.8 +
    40.9 +   Can be accessed from a browser or from a program.
   40.10 +   Do 'python SrvServer.py' to run the server.
   40.11 +   Then point a web browser at http://localhost:8000/xend and follow the links.
   40.12 +   Most are stubs, except /domain which has a list of domains and a 'create domain'
   40.13 +   button.
   40.14 +
   40.15 +   You can also access the server from a program.
   40.16 +   Do 'python XendClient.py' to run a few test operations.
   40.17 +
   40.18 +   The data served differs depending on the client (as defined by User-Agent
   40.19 +   and Accept in the HTTP headers). If the client is a browser, data
   40.20 +   is returned in HTML, with interactive forms. If the client is a program,
   40.21 +   data is returned in SXP format, with no forms.
   40.22 +
   40.23 +   The server serves to the world by default. To restrict it to the local host
   40.24 +   change 'interface' in main().
   40.25 +
   40.26 +   Mike Wray <mike.wray@hp.com>
   40.27 +"""
   40.28 +# todo Support security settings etc. in the config file.
   40.29 +# todo Support command-line args.
   40.30 +
   40.31 +from twisted.web import server
   40.32 +from twisted.web import resource
   40.33 +from twisted.internet import reactor
   40.34 +
   40.35 +from xenmgr import XendRoot
   40.36 +xroot = XendRoot.instance()
   40.37 +
   40.38 +from SrvRoot import SrvRoot
   40.39 +
   40.40 +def create(port=None, interface=None):
   40.41 +    if port is None: port = 8000
   40.42 +    if interface is None: interface = ''
   40.43 +    root = resource.Resource()
   40.44 +    xend = SrvRoot()
   40.45 +    root.putChild('xend', xend)
   40.46 +    site = server.Site(root)
   40.47 +    reactor.listenTCP(port, site, interface=interface)
   40.48 +    
   40.49 +
   40.50 +def main(port=None, interface=None):
   40.51 +    create(port, interface)
   40.52 +    reactor.run()
   40.53 +
   40.54 +
   40.55 +if __name__ == '__main__':
   40.56 +    main()
    41.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    41.2 +++ b/tools/xenmgr/lib/server/SrvVdisk.py	Fri Jun 11 14:40:53 2004 +0000
    41.3 @@ -0,0 +1,12 @@
    41.4 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    41.5 +
    41.6 +from xenmgr import XendVdisk
    41.7 +from SrvVdiskDir import SrvVdiskDir
    41.8 +
    41.9 +class SrvVdisk(SrvDir):
   41.10 +    """A virtual disk.
   41.11 +    """
   41.12 +
   41.13 +    def __init__(self):
   41.14 +        SrvDir.__init__(self)
   41.15 +        self.xvdisk = XendVdisk.instance()
    42.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    42.2 +++ b/tools/xenmgr/lib/server/SrvVdiskDir.py	Fri Jun 11 14:40:53 2004 +0000
    42.3 @@ -0,0 +1,28 @@
    42.4 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    42.5 +
    42.6 +from xenmgr import XendVdisk
    42.7 +from SrvDir import SrvDir
    42.8 +
    42.9 +class SrvVdiskDir(SrvDir):
   42.10 +    """Virtual disk directory.
   42.11 +    """
   42.12 +
   42.13 +    def __init__(self):
   42.14 +        SrvDir.__init__(self)
   42.15 +        self.xvdisk = XendVdisk.instance()
   42.16 +
   42.17 +    def vdisk(self, x):
   42.18 +        val = None
   42.19 +        try:
   42.20 +            dom = self.xvdisk.vdisk_get(x)
   42.21 +            val = SrvVdisk(dom)
   42.22 +        except KeyError:
   42.23 +            pass
   42.24 +        return val
   42.25 +
   42.26 +    def get(self, x):
   42.27 +        v = SrvDir.get(self, x)
   42.28 +        if v is not None:
   42.29 +            return v
   42.30 +        v = self.vdisk(x)
   42.31 +        return v
    43.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    43.2 +++ b/tools/xenmgr/lib/server/SrvVnetDir.py	Fri Jun 11 14:40:53 2004 +0000
    43.3 @@ -0,0 +1,9 @@
    43.4 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    43.5 +
    43.6 +from SrvDir import SrvDir
    43.7 +
    43.8 +class SrvVnetDir(SrvDir):
    43.9 +    """Vnet directory.
   43.10 +    """
   43.11 +
   43.12 +    pass
    44.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    44.2 +++ b/tools/xenmgr/lib/server/__init__.py	Fri Jun 11 14:40:53 2004 +0000
    44.3 @@ -0,0 +1,1 @@
    44.4 +
    45.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    45.2 +++ b/tools/xenmgr/lib/server/blkif.py	Fri Jun 11 14:40:53 2004 +0000
    45.3 @@ -0,0 +1,232 @@
    45.4 +import channel
    45.5 +import controller
    45.6 +from messages import *
    45.7 +
    45.8 +class BlkifControllerFactory(controller.ControllerFactory):
    45.9 +    """Factory for creating block device interface controllers.
   45.10 +    Also handles the 'back-end' channel to dom0.
   45.11 +    """
   45.12 +
   45.13 +    # todo: add support for setting dom controlling blkifs (don't assume 0).
   45.14 +    # todo: add support for 'recovery'.
   45.15 +
   45.16 +    def __init__(self):
   45.17 +        controller.ControllerFactory.__init__(self)
   45.18 +
   45.19 +        self.majorTypes = [ CMSG_BLKIF_BE ]
   45.20 +
   45.21 +        self.subTypes = {
   45.22 +            CMSG_BLKIF_BE_CREATE     : self.recv_be_create,
   45.23 +            CMSG_BLKIF_BE_CONNECT    : self.recv_be_connect,
   45.24 +            CMSG_BLKIF_BE_VBD_CREATE : self.recv_be_vbd_create,
   45.25 +            CMSG_BLKIF_BE_VBD_GROW   : self.recv_be_vbd_grow,
   45.26 +            CMSG_BLKIF_BE_DRIVER_STATUS_CHANGED: self.recv_be_driver_status_changed,
   45.27 +            }
   45.28 +        self.attached = 1
   45.29 +        self.registerChannel()
   45.30 +
   45.31 +    def createInstance(self, dom):
   45.32 +        d = self.addDeferred()
   45.33 +        blkif = self.getInstanceByDom(dom)
   45.34 +        if blkif:
   45.35 +            self.callDeferred(blkif)
   45.36 +        else:
   45.37 +            blkif = BlkifController(self, dom)
   45.38 +            self.addInstance(blkif)
   45.39 +            blkif.send_be_create()
   45.40 +        return d
   45.41 +
   45.42 +    def setControlDomain(self, dom):
   45.43 +        if self.channel:
   45.44 +            self.deregisterChannel()
   45.45 +            self.attached = 0
   45.46 +        self.dom = dom
   45.47 +        self.registerChannel()
   45.48 +        #
   45.49 +        #if xend.blkif.be_port:
   45.50 +        #    xend.blkif.recovery = True
   45.51 +        #xend.blkif.be_port = xend.main.port_from_dom(dom)
   45.52 +
   45.53 +    def recv_be_create(self, msg, req):
   45.54 +        #print 'recv_be_create>'
   45.55 +        val = unpackMsg('blkif_be_create_t', msg)
   45.56 +        blkif = self.getInstanceByDom(val['domid'])
   45.57 +        self.callDeferred(blkif)
   45.58 +    
   45.59 +    def recv_be_connect(self, msg, req):
   45.60 +        #print 'recv_be_create>'
   45.61 +        val = unpackMsg('blkif_be_connect_t', msg)
   45.62 +        blkif = self.getInstanceByDom(val['domid'])
   45.63 +        if blkif:
   45.64 +            blkif.send_fe_interface_status_changed()
   45.65 +        else:
   45.66 +            pass
   45.67 +    
   45.68 +    def recv_be_vbd_create(self, msg, req):
   45.69 +        #print 'recv_be_vbd_create>'
   45.70 +        val = unpackMsg('blkif_be_vbd_create_t', msg)
   45.71 +        blkif = self.getInstanceByDom(val['domid'])
   45.72 +        if blkif:
   45.73 +            blkif.send_be_vbd_grow(val['vdevice'])
   45.74 +        else:
   45.75 +            pass
   45.76 +    
   45.77 +    def recv_be_vbd_grow(self, msg, req):
   45.78 +        #print 'recv_be_vbd_grow>'
   45.79 +        val = unpackMsg('blkif_be_vbd_grow_t', msg)
   45.80 +        # Check status?
   45.81 +        if self.attached:
   45.82 +            self.callDeferred(0)
   45.83 +        else:
   45.84 +            self.reattach_device(val['domid'], val['vdevice'])
   45.85 +
   45.86 +    def reattach_device(self, dom, vdev):
   45.87 +        blkif = self.getInstanceByDom(dom)
   45.88 +        if blkif:
   45.89 +            blkif.reattach_device(vdev)
   45.90 +        attached = 1
   45.91 +        for blkif in self.getInstances():
   45.92 +            if not blkif.attached:
   45.93 +                attached = 0
   45.94 +                break
   45.95 +        self.attached = attached
   45.96 +        if self.attached:
   45.97 +            self.reattached()
   45.98 +
   45.99 +    def reattached(self):
  45.100 +        for blkif in self.getInstances():
  45.101 +            blkif.reattached()
  45.102 +
  45.103 +    def recv_be_driver_status_changed(self, msg, req):
  45.104 +        val = unpackMsg('blkif_be_driver_status_changed_t'. msg)
  45.105 +        status = val['status']
  45.106 +        if status == BLKIF_DRIVER_STATUS_UP and not self.attached:
  45.107 +            for blkif in self.getInstances():
  45.108 +                blkif.detach()
  45.109 +
  45.110 +class BlkDev:
  45.111 +    """Info record for a block device.
  45.112 +    """
  45.113 +
  45.114 +    def __init__(self, vdev, mode, segment):
  45.115 +        self.vdev = vdev
  45.116 +        self.mode = mode
  45.117 +        self.device = segment['device']
  45.118 +        self.start_sector = segment['start_sector']
  45.119 +        self.nr_sectors = segment['nr_sectors']
  45.120 +        self.attached = 1
  45.121 +
  45.122 +    def readonly(self):
  45.123 +        return 'w' not in self.mode
  45.124 +        
  45.125 +class BlkifController(controller.Controller):
  45.126 +    """Block device interface controller. Handles all block devices
  45.127 +    for a domain.
  45.128 +    """
  45.129 +    
  45.130 +    def __init__(self, factory, dom):
  45.131 +        #print 'BlkifController> dom=', dom
  45.132 +        controller.Controller.__init__(self, factory, dom)
  45.133 +        self.devices = {}
  45.134 +
  45.135 +        self.majorTypes = [ CMSG_BLKIF_FE ]
  45.136 +
  45.137 +        self.subTypes = {
  45.138 +            CMSG_BLKIF_FE_DRIVER_STATUS_CHANGED:
  45.139 +                self.recv_fe_driver_status_changed,
  45.140 +            CMSG_BLKIF_FE_INTERFACE_CONNECT    :
  45.141 +                self.recv_fe_interface_connect,
  45.142 +            }
  45.143 +        self.attached = 1
  45.144 +        self.registerChannel()
  45.145 +        #print 'BlkifController<', 'dom=', self.dom, 'idx=', self.idx
  45.146 +
  45.147 +    def attach_device(self, vdev, mode, segment):
  45.148 +        """Attach a device to the specified interface.
  45.149 +        """
  45.150 +        #print 'BlkifController>attach_device>', self.dom, vdev, mode, segment
  45.151 +        if vdev in self.devices: return -1
  45.152 +        dev = BlkDev(vdev, mode, segment)
  45.153 +        self.devices[vdev] = dev
  45.154 +        self.send_be_vbd_create(vdev)
  45.155 +        return self.factory.addDeferred()
  45.156 +
  45.157 +    def detach(self):
  45.158 +        self.attached = 0
  45.159 +        for dev in self.devices.values():
  45.160 +            dev.attached = 0
  45.161 +            self.send_be_vbd_create(vdev)
  45.162 +
  45.163 +    def reattach_device(self, vdev):
  45.164 +        dev = self.devices[vdev]
  45.165 +        dev.attached = 1
  45.166 +        attached = 1
  45.167 +        for dev in self.devices.values():
  45.168 +            if not dev.attached:
  45.169 +                attached = 0
  45.170 +                break
  45.171 +        self.attached = attached
  45.172 +        return self.attached
  45.173 +
  45.174 +    def reattached(self):
  45.175 +        msg = packMsg('blkif_fe_interface_status_changed_t',
  45.176 +                      { 'handle' : 0,
  45.177 +                        'status' : BLKIF_INTERFACE_STATUS_DISCONNECTED})
  45.178 +        self.writeRequest(msg)
  45.179 +
  45.180 +    def recv_fe_driver_status_changed(self, msg, req):
  45.181 +        msg = packMsg('blkif_fe_interface_status_changed_t',
  45.182 +                      { 'handle' : 0,
  45.183 +                        'status' : BLKIF_INTERFACE_STATUS_DISCONNECTED,
  45.184 +                        'evtchn' : 0 })
  45.185 +        self.writeRequest(msg)
  45.186 +    
  45.187 +    def recv_fe_interface_connect(self, msg, req):
  45.188 +        val = unpackMsg('blkif_fe_interface_connect_t', msg)
  45.189 +        self.evtchn = channel.eventChannel(0, self.dom)
  45.190 +        msg = packMsg('blkif_be_connect_t',
  45.191 +                      { 'domid'        : self.dom,
  45.192 +                        'blkif_handle' : val['handle'],
  45.193 +                        'evtchn'       : self.evtchn['port1'],
  45.194 +                        'shmem_frame'  : val['shmem_frame'] })
  45.195 +        self.factory.writeRequest(msg)
  45.196 +        pass
  45.197 +
  45.198 +    #def recv_fe_interface_status_changed(self, msg, req):
  45.199 +    #    (hnd, status, chan) = unpackMsg('blkif_fe_interface_status_changed_t', msg)
  45.200 +    #    print 'recv_fe_interface_status_changed>', hnd, status, chan
  45.201 +    #   pass
  45.202 +
  45.203 +    def send_fe_interface_status_changed(self):
  45.204 +        msg = packMsg('blkif_fe_interface_status_changed_t',
  45.205 +                      { 'handle' : 0,
  45.206 +                        'status' : BLKIF_INTERFACE_STATUS_CONNECTED,
  45.207 +                        'evtchn' : self.evtchn['port2'] })
  45.208 +        self.writeRequest(msg)
  45.209 +
  45.210 +    def send_be_create(self):
  45.211 +        msg = packMsg('blkif_be_create_t',
  45.212 +                      { 'domid'        : self.dom,
  45.213 +                        'blkif_handle' : 0 })
  45.214 +        self.factory.writeRequest(msg)
  45.215 +
  45.216 +    def send_be_vbd_create(self, vdev):
  45.217 +        dev = self.devices[vdev]
  45.218 +        msg = packMsg('blkif_be_vbd_create_t',
  45.219 +                      { 'domid'        : self.dom,
  45.220 +                        'blkif_handle' : 0,
  45.221 +                        'vdevice'      : dev.vdev,
  45.222 +                        'readonly'     : dev.readonly() })
  45.223 +        self.factory.writeRequest(msg)
  45.224 +        
  45.225 +    def send_be_vbd_grow(self, vdev):
  45.226 +        dev = self.devices[vdev]
  45.227 +        msg = packMsg('blkif_be_vbd_grow_t',
  45.228 +                      { 'domid'                : self.dom,
  45.229 +                        'blkif_handle'         : 0,
  45.230 +                        'vdevice'              : dev.vdev,
  45.231 +                        'extent.device'        : dev.device,
  45.232 +                        'extent.sector_start'  : dev.start_sector,
  45.233 +                        'extent.sector_length' : dev.nr_sectors })
  45.234 +        self.factory.writeRequest(msg)
  45.235 +    
    46.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    46.2 +++ b/tools/xenmgr/lib/server/channel.py	Fri Jun 11 14:40:53 2004 +0000
    46.3 @@ -0,0 +1,259 @@
    46.4 +import Xc; xc = Xc.new()
    46.5 +import xend.utils
    46.6 +from messages import msgTypeName
    46.7 +
    46.8 +def eventChannel(dom1, dom2):
    46.9 +    return xc.evtchn_bind_interdomain(dom1=dom1, dom2=dom2)
   46.10 +
   46.11 +class ChannelFactory:
   46.12 +    """Factory for creating channels.
   46.13 +    Maintains a table of channels.
   46.14 +    """
   46.15 +    
   46.16 +    channels = {}
   46.17 +
   46.18 +    def __init__(self):
   46.19 +        self.notifier = xend.utils.notifier()
   46.20 +    
   46.21 +    def addChannel(self, channel):
   46.22 +        idx = channel.idx
   46.23 +        self.channels[idx] = channel
   46.24 +        self.notifier.bind(idx)
   46.25 +        # Try to wake it up
   46.26 +        #self.notifier.unmask(idx)
   46.27 +        #channel.notify()
   46.28 +
   46.29 +    def getChannel(self, idx):
   46.30 +        return self.channels.get(idx)
   46.31 +
   46.32 +    def delChannel(self, idx):
   46.33 +        if idx in self.channels:
   46.34 +            del self.channels[idx]
   46.35 +            self.notifier.unbind(idx)
   46.36 +
   46.37 +    def domChannel(self, dom):
   46.38 +        for chan in self.channels.values():
   46.39 +            if chan.dom == dom:
   46.40 +                return chan
   46.41 +        chan = Channel(self, dom)
   46.42 +        self.addChannel(chan)
   46.43 +        return chan
   46.44 +
   46.45 +    def channelClosed(self, channel):
   46.46 +        self.delChannel(channel.idx)
   46.47 +
   46.48 +    def createPort(self, dom):
   46.49 +        return xend.utils.port(dom)
   46.50 +
   46.51 +def channelFactory():
   46.52 +    global inst
   46.53 +    try:
   46.54 +        inst
   46.55 +    except:
   46.56 +        inst = ChannelFactory()
   46.57 +    return inst
   46.58 +
   46.59 +class Channel:
   46.60 +    """A control channel to a domain. Messages for the domain device controllers
   46.61 +    are multiplexed over the channel (console, block devs, net devs).
   46.62 +    """
   46.63 +
   46.64 +    def __init__(self, factory, dom):
   46.65 +        self.factory = factory
   46.66 +        self.dom = dom
   46.67 +        self.port = self.factory.createPort(dom)
   46.68 +        self.idx = self.port.local_port
   46.69 +        self.devs = []
   46.70 +        self.devs_by_type = {}
   46.71 +        self.closed = 0
   46.72 +        self.queue = []
   46.73 +
   46.74 +    def getIndex(self):
   46.75 +        return self.idx
   46.76 +
   46.77 +    def getLocalPort(self):
   46.78 +        return self.port.local_port
   46.79 +
   46.80 +    def getRemotePort(self):
   46.81 +        return self.port.remote_port
   46.82 +
   46.83 +    def close(self):
   46.84 +        for d in self.devs:
   46.85 +            d.lostChannel()
   46.86 +        self.factory.channelClosed(self)
   46.87 +        del self.devs
   46.88 +        del self.devs_by_type
   46.89 +
   46.90 +    def registerDevice(self, types, dev):
   46.91 +        """Register a device controller.
   46.92 +
   46.93 +        @param types message types the controller handles
   46.94 +        @param dev   device controller
   46.95 +        """
   46.96 +        self.devs.append(dev)
   46.97 +        for ty in types:
   46.98 +            self.devs_by_type[ty] = dev
   46.99 +
  46.100 +    def unregisterDevice(self, dev):
  46.101 +        """Remove the registration for a device controller.
  46.102 +
  46.103 +        @param dev device controller
  46.104 +        """
  46.105 +        self.devs.remove(dev)
  46.106 +        types = [ ty for (ty, d) in self.devs_by_type.items()
  46.107 +                  if d == dev ]
  46.108 +        for ty in types:
  46.109 +            del devs_by_type[ty]
  46.110 +
  46.111 +    def getDevice(self, type):
  46.112 +        """Get the device controller handling a message type.
  46.113 +
  46.114 +        @param type message type
  46.115 +        @returns controller or None
  46.116 +        """
  46.117 +        return self.devs_by_type.get(type)
  46.118 +
  46.119 +    def getMessageType(self, msg):
  46.120 +        hdr = msg.get_header()
  46.121 +        return (hdr['type'], hdr.get('subtype'))
  46.122 +
  46.123 +    def __repr__(self):
  46.124 +        return ('<Channel dom=%d ports=%d:%d>'
  46.125 +                % (self.dom,
  46.126 +                   self.port.local_port,
  46.127 +                   self.port.remote_port))
  46.128 +
  46.129 +    def notificationReceived(self, type):
  46.130 +        #print 'notificationReceived> type=', type, self
  46.131 +        if self.closed: return
  46.132 +        if type == self.factory.notifier.EXCEPTION:
  46.133 +            print 'notificationReceived> EXCEPTION'
  46.134 +            info = xc.evtchn_status(self.idx)
  46.135 +            if info['status'] == 'unbound':
  46.136 +                print 'notificationReceived> EXCEPTION closing...'
  46.137 +                self.close()
  46.138 +                return
  46.139 +        work = 0
  46.140 +        work += self.handleRequests()
  46.141 +        work += self.handleResponses()
  46.142 +        work += self.handleWrites()
  46.143 +        if work:
  46.144 +            self.notify()
  46.145 +        #print 'notificationReceived<', work
  46.146 +
  46.147 +    def notify(self):
  46.148 +        #print 'notify>', self
  46.149 +        self.port.notify()
  46.150 +
  46.151 +    def handleRequests(self):
  46.152 +        #print 'handleRequests>'
  46.153 +        work = 0
  46.154 +        while 1:
  46.155 +            #print 'handleRequests>', work
  46.156 +            msg = self.readRequest()
  46.157 +            #print 'handleRequests> msg=', msg
  46.158 +            if not msg: break
  46.159 +            self.requestReceived(msg)
  46.160 +            work += 1
  46.161 +        #print 'handleRequests<', work
  46.162 +        return work
  46.163 +
  46.164 +    def requestReceived(self, msg):
  46.165 +        (ty, subty) = self.getMessageType(msg)
  46.166 +        #print 'requestReceived>', ty, subty, self
  46.167 +        #todo:  Must respond before writing any more messages.
  46.168 +        #todo:  Should automate this (respond on write)
  46.169 +        self.port.write_response(msg)
  46.170 +        dev = self.getDevice(ty)
  46.171 +        if dev:
  46.172 +            dev.requestReceived(msg, ty, subty)
  46.173 +        else:
  46.174 +            print ("requestReceived> No device: Message type %s %d:%d"
  46.175 +                   % (msgTypeName(ty, subty), ty, subty)), self
  46.176 +
  46.177 +    def handleResponses(self):
  46.178 +        #print 'handleResponses>', self
  46.179 +        work = 0
  46.180 +        while 1:
  46.181 +            #print 'handleResponses>', work
  46.182 +            msg = self.readResponse()
  46.183 +            #print 'handleResponses> msg=', msg
  46.184 +            if not msg: break
  46.185 +            self.responseReceived(msg)
  46.186 +            work += 1
  46.187 +        #print 'handleResponses<', work
  46.188 +        return work
  46.189 +
  46.190 +    def responseReceived(self, msg):
  46.191 +        (ty, subty) = self.getMessageType(msg)
  46.192 +        #print 'responseReceived>', ty, subty
  46.193 +        dev = self.getDevice(ty)
  46.194 +        if dev:
  46.195 +            dev.responseReceived(msg, ty, subty)
  46.196 +        else:
  46.197 +            print ("responseReceived> No device: Message type %d:%d"
  46.198 +                   % (msgTypeName(ty, subty), ty, subty)), self
  46.199 +
  46.200 +    def handleWrites(self):
  46.201 +        #print 'handleWrites>', self
  46.202 +        work = 0
  46.203 +        # Pull data from producers.
  46.204 +        #print 'handleWrites> pull...'
  46.205 +        for dev in self.devs:
  46.206 +            work += dev.produceRequests()
  46.207 +        # Flush the queue.
  46.208 +        #print 'handleWrites> flush...'
  46.209 +        while self.queue and self.port.space_to_write_request():
  46.210 +            msg = self.queue.pop(0)
  46.211 +            self.port.write_request(msg)
  46.212 +            work += 1
  46.213 +        #print 'handleWrites<', work
  46.214 +        return work
  46.215 +
  46.216 +    def writeRequest(self, msg, notify=1):
  46.217 +        #print 'writeRequest>', self
  46.218 +        if self.closed:
  46.219 +            val = -1
  46.220 +        elif self.writeReady():
  46.221 +            self.port.write_request(msg)
  46.222 +            if notify: self.notify()
  46.223 +            val = 1
  46.224 +        else:
  46.225 +            self.queue.append(msg)
  46.226 +            val = 0
  46.227 +        #print 'writeRequest<', val
  46.228 +        return val
  46.229 +
  46.230 +    def writeResponse(self, msg):
  46.231 +        #print 'writeResponse>', self
  46.232 +        if self.closed: return -1
  46.233 +        self.port.write_response(msg)
  46.234 +        return 1
  46.235 +
  46.236 +    def writeReady(self):
  46.237 +        if self.closed or self.queue: return 0
  46.238 +        return self.port.space_to_write_request()
  46.239 +
  46.240 +    def readRequest(self):
  46.241 +        #print 'readRequest>', self
  46.242 +        if self.closed:
  46.243 +            #print 'readRequest> closed'
  46.244 +            return None
  46.245 +        if self.port.request_to_read():
  46.246 +            val = self.port.read_request()
  46.247 +        else:
  46.248 +            val = None
  46.249 +        #print 'readRequest< ', val
  46.250 +        return val
  46.251 +        
  46.252 +    def readResponse(self):
  46.253 +        #print 'readResponse>', self
  46.254 +        if self.closed:
  46.255 +            #print 'readResponse> closed'
  46.256 +            return None
  46.257 +        if self.port.response_to_read():
  46.258 +            val = self.port.read_response()
  46.259 +        else:
  46.260 +            val = None
  46.261 +        #print 'readResponse<', val
  46.262 +        return val
    47.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    47.2 +++ b/tools/xenmgr/lib/server/console.py	Fri Jun 11 14:40:53 2004 +0000
    47.3 @@ -0,0 +1,220 @@
    47.4 +
    47.5 +from twisted.internet import reactor
    47.6 +from twisted.internet import protocol
    47.7 +from twisted.protocols import telnet
    47.8 +
    47.9 +import xend.utils
   47.10 +
   47.11 +from xenmgr import EventServer
   47.12 +eserver = EventServer.instance()
   47.13 +
   47.14 +import controller
   47.15 +from messages import *
   47.16 +from params import *
   47.17 +
   47.18 +"""Telnet binary option."""
   47.19 +TRANSMIT_BINARY = '0'
   47.20 +WILL = chr(251)
   47.21 +IAC = chr(255)
   47.22 +
   47.23 +class ConsoleProtocol(protocol.Protocol):
   47.24 +    """Asynchronous handler for a console TCP socket.
   47.25 +    """
   47.26 +
   47.27 +    def __init__(self, controller, idx):
   47.28 +        self.controller = controller
   47.29 +        self.idx = idx
   47.30 +        self.addr = None
   47.31 +        self.binary = 0
   47.32 +
   47.33 +    def connectionMade(self):
   47.34 +        peer = self.transport.getPeer()
   47.35 +        self.addr = (peer.host, peer.port)
   47.36 +        if self.controller.connect(self.addr, self):
   47.37 +            self.transport.write("Cannot connect to console %d on domain %d\n"
   47.38 +                                 % (self.idx, self.controller.dom))
   47.39 +            self.loseConnection()
   47.40 +            return
   47.41 +        else:
   47.42 +            self.transport.write("Connected to console %d on domain %d\n"
   47.43 +                                 % (self.idx, self.controller.dom))
   47.44 +            self.setTelnetTransmitBinary()
   47.45 +            eserver.inject('xend.console.connect',
   47.46 +                           [self.idx, self.addr[0], self.addr[1]])
   47.47 +
   47.48 +    def setTelnetTransmitBinary(self):
   47.49 +        """Send the sequence to set the telnet TRANSMIT-BINARY option.
   47.50 +        """
   47.51 +        self.write(IAC + WILL + TRANSMIT_BINARY)
   47.52 +
   47.53 +    def dataReceived(self, data):
   47.54 +        if self.controller.handleInput(self, data):
   47.55 +            self.loseConnection()
   47.56 +
   47.57 +    def write(self, data):
   47.58 +        #if not self.connected: return -1
   47.59 +        self.transport.write(data)
   47.60 +        return len(data)
   47.61 +
   47.62 +    def connectionLost(self, reason=None):
   47.63 +        eserver.inject('xend.console.disconnect',
   47.64 +                       [self.idx, self.addr[0], self.addr[1]])
   47.65 +        self.controller.disconnect()
   47.66 +
   47.67 +    def loseConnection(self):
   47.68 +        self.transport.loseConnection()
   47.69 +
   47.70 +class ConsoleFactory(protocol.ServerFactory):
   47.71 +    """Asynchronous handler for a console server socket.
   47.72 +    """
   47.73 +    protocol = ConsoleProtocol
   47.74 +    
   47.75 +    def __init__(self, controller, idx):
   47.76 +        #protocol.ServerFactory.__init__(self)
   47.77 +        self.controller = controller
   47.78 +        self.idx = idx
   47.79 +
   47.80 +    def buildProtocol(self, addr):
   47.81 +        proto = self.protocol(self.controller, self.idx)
   47.82 +        proto.factory = self
   47.83 +        return proto
   47.84 +
   47.85 +class ConsoleControllerFactory(controller.ControllerFactory):
   47.86 +    """Factory for creating console controllers.
   47.87 +    """
   47.88 +
   47.89 +    def createInstance(self, dom, console_port=None):
   47.90 +        if console_port is None:
   47.91 +            console_port = CONSOLE_PORT_BASE + dom
   47.92 +        console = ConsoleController(self, dom, console_port)
   47.93 +        self.addInstance(console)
   47.94 +        eserver.inject('xend.console.create',
   47.95 +                       [console.idx, console.dom, console.console_port])
   47.96 +        return console
   47.97 +        
   47.98 +    def consoleClosed(self, console):
   47.99 +        eserver.inject('xend.console.close', console.idx)
  47.100 +        self.delInstance(console)
  47.101 +
  47.102 +class ConsoleController(controller.Controller):
  47.103 +    """Console controller for a domain.
  47.104 +    Does not poll for i/o itself, but relies on the notifier to post console
  47.105 +    output and the connected TCP sockets to post console input.
  47.106 +    """
  47.107 +
  47.108 +    def __init__(self, factory, dom, console_port):
  47.109 +        #print 'ConsoleController> dom=', dom
  47.110 +        controller.Controller.__init__(self, factory, dom)
  47.111 +        self.majorTypes = [ CMSG_CONSOLE ]
  47.112 +        self.status = "new"
  47.113 +        self.addr = None
  47.114 +        self.conn = None
  47.115 +        self.rbuf = xend.utils.buffer()
  47.116 +        self.wbuf = xend.utils.buffer()
  47.117 +        self.console_port = console_port
  47.118 +
  47.119 +        self.registerChannel()
  47.120 +        self.listener = None
  47.121 +        self.listen()
  47.122 +        #print 'ConsoleController<', 'dom=', self.dom, 'idx=', self.idx
  47.123 +
  47.124 +    def sxpr(self):
  47.125 +        val =['console',
  47.126 +              ['id',           self.idx ],
  47.127 +              ['domain',       self.dom ],
  47.128 +              ['local_port',   self.channel.getLocalPort() ],
  47.129 +              ['remote_port',  self.channel.getRemotePort() ],
  47.130 +              ['console_port', self.console_port ] ]
  47.131 +        if self.addr:
  47.132 +            val.append(['connected', self.addr[0], self.addr[1]])
  47.133 +        return val
  47.134 +
  47.135 +    def ready(self):
  47.136 +        return not (self.closed() or self.rbuf.empty())
  47.137 +
  47.138 +    def closed(self):
  47.139 +        return self.status == 'closed'
  47.140 +
  47.141 +    def connected(self):
  47.142 +        return self.status == 'connected'
  47.143 +
  47.144 +    def close(self):
  47.145 +        self.status = "closed"
  47.146 +        self.listener.stopListening()
  47.147 +        self.deregisterChannel()
  47.148 +        self.lostChannel()
  47.149 +
  47.150 +    def listen(self):
  47.151 +        """Listen for TCP connections to the console port..
  47.152 +        """
  47.153 +        if self.closed(): return
  47.154 +        self.status = "listening"
  47.155 +        if self.listener:
  47.156 +            #self.listener.startListening()
  47.157 +            pass
  47.158 +        else:
  47.159 +            f = ConsoleFactory(self, self.idx)
  47.160 +            self.listener = reactor.listenTCP(self.console_port, f)
  47.161 +
  47.162 +    def connect(self, addr, conn):
  47.163 +        if self.closed(): return -1
  47.164 +        if self.connected(): return -1
  47.165 +        self.addr = addr
  47.166 +        self.conn = conn
  47.167 +        self.status = "connected"
  47.168 +        self.handleOutput()
  47.169 +        return 0
  47.170 +
  47.171 +    def disconnect(self):
  47.172 +        self.addr = None
  47.173 +        self.conn = None
  47.174 +        self.listen()
  47.175 +
  47.176 +    def requestReceived(self, msg, type, subtype):
  47.177 +        #print '***Console', self.dom, msg.get_payload()
  47.178 +        self.rbuf.write(msg.get_payload())
  47.179 +        self.handleOutput()
  47.180 +        
  47.181 +    def responseReceived(self, msg, type, subtype):
  47.182 +        pass
  47.183 +
  47.184 +    def produceRequests(self):
  47.185 +        # Send as much pending console data as there is room for.
  47.186 +        work = 0
  47.187 +        while not self.wbuf.empty() and self.channel.writeReady():
  47.188 +            msg = xend.utils.message(CMSG_CONSOLE, 0, 0)
  47.189 +            msg.append_payload(self.wbuf.read(msg.MAX_PAYLOAD))
  47.190 +            work += self.channel.writeRequest(msg, notify=0)
  47.191 +        return work
  47.192 +
  47.193 +    def handleInput(self, conn, data):
  47.194 +        """Handle some external input aimed at the console.
  47.195 +        Called from a TCP connection (conn).
  47.196 +        """
  47.197 +        if self.closed(): return -1
  47.198 +        if conn != self.conn: return 0
  47.199 +        self.wbuf.write(data)
  47.200 +        if self.produceRequests():
  47.201 +            self.channel.notify()
  47.202 +        return 0
  47.203 +
  47.204 +    def handleOutput(self):
  47.205 +        """Handle buffered output from the console.
  47.206 +        Sends it to the connected console (if any).
  47.207 +        """
  47.208 +        if self.closed():
  47.209 +            #print 'Console>handleOutput> closed'
  47.210 +            return -1
  47.211 +        if not self.conn:
  47.212 +            #print 'Console>handleOutput> not connected'
  47.213 +            return 0
  47.214 +        while not self.rbuf.empty():
  47.215 +            try:
  47.216 +                #print 'Console>handleOutput> writing...'
  47.217 +                bytes = self.conn.write(self.rbuf.peek())
  47.218 +                if bytes > 0:
  47.219 +                    self.rbuf.discard(bytes)
  47.220 +            except socket.error, error:
  47.221 +                pass
  47.222 +        #print 'Console>handleOutput<'
  47.223 +        return 0
    48.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    48.2 +++ b/tools/xenmgr/lib/server/controller.py	Fri Jun 11 14:40:53 2004 +0000
    48.3 @@ -0,0 +1,133 @@
    48.4 +from twisted.internet import defer
    48.5 +
    48.6 +import channel
    48.7 +from messages import msgTypeName
    48.8 +
    48.9 +class CtrlMsgRcvr:
   48.10 +    """Abstract class for things that deal with a control interface to a domain.
   48.11 +    """
   48.12 +
   48.13 +
   48.14 +    def __init__(self):
   48.15 +        self.channelFactory = channel.channelFactory()
   48.16 +        self.majorTypes = [ ]
   48.17 +        self.subTypes = {}
   48.18 +        self.dom = None
   48.19 +        self.channel = None
   48.20 +        self.idx = None
   48.21 +
   48.22 +    def requestReceived(self, msg, type, subtype):
   48.23 +        method = self.subTypes.get(subtype)
   48.24 +        if method:
   48.25 +            method(msg, 1)
   48.26 +        else:
   48.27 +            print ('requestReceived> No handler: Message type %s %d:%d'
   48.28 +                   % (msgTypeName(type, subtype), type, subtype)), self
   48.29 +        
   48.30 +    def responseReceived(self, msg, type, subtype):
   48.31 +        method = self.subTypes.get(subtype)
   48.32 +        if method:
   48.33 +            method(msg, 0)
   48.34 +        else:
   48.35 +            print ('responseReceived> No handler: Message type %s %d:%d'
   48.36 +                   % (msgTypeName(type, subtype), type, subtype)), self
   48.37 +
   48.38 +    def lostChannel(self):
   48.39 +        pass
   48.40 +    
   48.41 +    def registerChannel(self):
   48.42 +        self.channel = self.channelFactory.domChannel(self.dom)
   48.43 +        #print 'registerChannel> channel=', self.channel, self
   48.44 +        self.idx = self.channel.getIndex()
   48.45 +        #print 'registerChannel> idx=', self.idx
   48.46 +        if self.majorTypes:
   48.47 +            self.channel.registerDevice(self.majorTypes, self)
   48.48 +        
   48.49 +    def deregisterChannel(self):
   48.50 +        if self.channel:
   48.51 +            self.channel.deregisterDevice(self)
   48.52 +            del self.channel
   48.53 +
   48.54 +    def produceRequests(self):
   48.55 +        return 0
   48.56 +
   48.57 +    def writeRequest(self, msg):
   48.58 +        if self.channel:
   48.59 +            self.channel.writeRequest(msg)
   48.60 +        else:
   48.61 +            print 'CtrlMsgRcvr>writeRequest>', 'no channel!', self
   48.62 +
   48.63 +    def writeResponse(self, msg):
   48.64 +        if self.channel:
   48.65 +            self.channel.writeResponse(msg)
   48.66 +        else:
   48.67 +            print 'CtrlMsgRcvr>writeResponse>', 'no channel!', self
   48.68 +            
   48.69 +class ControllerFactory(CtrlMsgRcvr):
   48.70 +    """Abstract class for factories creating controllers.
   48.71 +    Maintains a table of instances.
   48.72 +    """
   48.73 +
   48.74 +    def __init__(self):
   48.75 +        CtrlMsgRcvr.__init__(self)
   48.76 +        self.instances = {}
   48.77 +        self.dlist = []
   48.78 +        self.dom = 0
   48.79 +        
   48.80 +    def addInstance(self, instance):
   48.81 +        self.instances[instance.idx] = instance
   48.82 +
   48.83 +    def getInstance(self, idx):
   48.84 +        return self.instances.get(idx)
   48.85 +
   48.86 +    def getInstances(self):
   48.87 +        return self.instances.values()
   48.88 +
   48.89 +    def getInstanceByDom(self, dom):
   48.90 +        for inst in self.instances.values():
   48.91 +            if inst.dom == dom:
   48.92 +                return inst
   48.93 +        return None
   48.94 +
   48.95 +    def delInstance(self, instance):
   48.96 +        if instance in self.instances:
   48.97 +            del self.instances[instance.idx]
   48.98 +
   48.99 +    def createInstance(self, dom):
  48.100 +        raise NotImplementedError()
  48.101 +
  48.102 +    def instanceClosed(self, instance):
  48.103 +        self.delInstance(instance)
  48.104 +
  48.105 +    def addDeferred(self):
  48.106 +        d = defer.Deferred()
  48.107 +        self.dlist.append(d)
  48.108 +        return d
  48.109 +
  48.110 +    def callDeferred(self, *args):
  48.111 +        if self.dlist:
  48.112 +            d = self.dlist.pop(0)
  48.113 +            d.callback(*args)
  48.114 +
  48.115 +    def errDeferred(self, *args):
  48.116 +        if self.dlist:
  48.117 +            d = self.dlist.pop(0)
  48.118 +            d.errback(*args)
  48.119 +
  48.120 +class Controller(CtrlMsgRcvr):
  48.121 +    """Abstract class for a device controller attached to a domain.
  48.122 +    """
  48.123 +
  48.124 +    def __init__(self, factory, dom):
  48.125 +        CtrlMsgRcvr.__init__(self)
  48.126 +        self.factory = factory
  48.127 +        self.dom = dom
  48.128 +        self.channel = None
  48.129 +        self.idx = None
  48.130 +
  48.131 +    def close(self):
  48.132 +        self.deregisterChannel()
  48.133 +        self.lostChannel(self)
  48.134 +
  48.135 +    def lostChannel(self):
  48.136 +        self.factory.instanceClosed(self)
    49.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    49.2 +++ b/tools/xenmgr/lib/server/cstruct.py	Fri Jun 11 14:40:53 2004 +0000
    49.3 @@ -0,0 +1,269 @@
    49.4 +import struct
    49.5 +
    49.6 +class Struct:
    49.7 +
    49.8 +    maxDepth = 10
    49.9 +
   49.10 +    base = ['x', 'B', 'H', 'I', 'L', 'Q', 'c', 'h', 'i', 'l', 'q', ]
   49.11 +
   49.12 +    sizes = {'B': 1,
   49.13 +            'H': 2,
   49.14 +            'I': 4,
   49.15 +            'L': 4,
   49.16 +            'Q': 8,
   49.17 +            'c': 1,
   49.18 +            'h': 2,
   49.19 +            'i': 4,
   49.20 +            'l': 4,
   49.21 +            'q': 8,
   49.22 +            'x': 1,
   49.23 +            }
   49.24 +
   49.25 +    formats = {
   49.26 +        'int8'          : 'B',
   49.27 +        'int16'         : 'H',
   49.28 +        'int32'         : 'I',
   49.29 +        'int64'         : 'Q',
   49.30 +        'u8'            : 'B',
   49.31 +        'u16'           : 'H',
   49.32 +        'u32'           : 'I',
   49.33 +        'u64'           : 'Q'
   49.34 +        }
   49.35 +
   49.36 +    def typedef(self, name, val):
   49.37 +        self.formats[name] = val
   49.38 +
   49.39 +    def struct(self, name, *f):
   49.40 +        self.typedef(name, StructInfo(self, f))
   49.41 +        
   49.42 +    def getType(self, name):
   49.43 +        return self.formats[name]
   49.44 +
   49.45 +    def format(self, ty):
   49.46 +        d = 0
   49.47 +        f = ty
   49.48 +        while d < self.maxDepth:
   49.49 +            d += 1
   49.50 +            f = self.formats[f]
   49.51 +            if isinstance(f, StructInfo):
   49.52 +                return f.format()
   49.53 +            if f in self.base:
   49.54 +                return f
   49.55 +        return -1
   49.56 +
   49.57 +    def alignedformat(self, ty):
   49.58 +        fmt = self.format(ty)
   49.59 +        #print 'alignedformat> %s |%s|' %(ty, fmt)
   49.60 +        afmt = self.align(fmt)
   49.61 +        #print 'alignedformat< %s |%s| |%s|' % (ty, fmt, afmt)
   49.62 +        return afmt
   49.63 +
   49.64 +    def align(self, fmt):
   49.65 +        n1 = 0
   49.66 +        afmt = ''
   49.67 +        for a in fmt:
   49.68 +            n2 = self.getSize(a)
   49.69 +            m = n1 % n2
   49.70 +            if m:
   49.71 +                d = (n2 - m)
   49.72 +                afmt += 'x' * d
   49.73 +                n1 += d
   49.74 +            afmt += a
   49.75 +            n1 += n2
   49.76 +        return afmt
   49.77 +
   49.78 +    def fmtsize(self, fmt):
   49.79 +        s = 0
   49.80 +        for f in fmt:
   49.81 +            s += self.getSize(f)
   49.82 +        return s
   49.83 +
   49.84 +    def getSize(self, f):
   49.85 +        return self.sizes[f]
   49.86 +
   49.87 +    def pack(self, ty, data):
   49.88 +        return self.getType(ty).pack(data)
   49.89 +
   49.90 +    def unpack(self, ty, data):
   49.91 +        return self.getType(ty).unpack(data)
   49.92 +
   49.93 +    def show(self):
   49.94 +        l = self.formats.keys()
   49.95 +        l.sort()
   49.96 +        for v in l:
   49.97 +            print "%-35s %-10s %s" % (v, self.format(v), self.alignedformat(v))
   49.98 +
   49.99 +
  49.100 +class StructInfo:
  49.101 +
  49.102 +    def __init__(self, s, f):
  49.103 +        self.fmt = None
  49.104 +        self.structs = s
  49.105 +        self.fields = f
  49.106 +
  49.107 +    def alignedformat(self):
  49.108 +        if self.afmt: return self.afmt
  49.109 +        self.afmt = self.structs.align(self.format())
  49.110 +        return self.afmt
  49.111 +    
  49.112 +    def format(self):
  49.113 +        if self.fmt: return self.fmt
  49.114 +        fmt = ""
  49.115 +        for (ty, name) in self.fields:
  49.116 +            fmt += self.formatString(ty)
  49.117 +        self.fmt = fmt
  49.118 +        return fmt
  49.119 +
  49.120 +    def formatString(self, ty):
  49.121 +        if ty in self.fields:
  49.122 +            ty = self.fields[ty]
  49.123 +        return self.structs.format(ty)
  49.124 +
  49.125 +    def pack(self, *args):
  49.126 +        return struct.pack(self.alignedformat(), *args)
  49.127 +
  49.128 +    def unpack(self, data):
  49.129 +        return struct.unpack(self.alignedformat(), data)
  49.130 +
  49.131 +types = Struct()
  49.132 +
  49.133 +types.typedef('short'         , 'h')
  49.134 +types.typedef('int'           , 'i')
  49.135 +types.typedef('long'          , 'l')
  49.136 +types.typedef('unsigned short', 'H')
  49.137 +types.typedef('unsigned int'  , 'I')
  49.138 +types.typedef('unsigned long' , 'L')
  49.139 +types.typedef('domid_t'       , 'u64')
  49.140 +types.typedef('blkif_vdev_t'  , 'u16')
  49.141 +types.typedef('blkif_pdev_t'  , 'u16')
  49.142 +types.typedef('blkif_sector_t', 'u64')
  49.143 +
  49.144 +types.struct('u8[6]',
  49.145 +             ('u8', 'a1'),
  49.146 +             ('u8', 'a2'),
  49.147 +             ('u8', 'a3'),
  49.148 +             ('u8', 'a4'),
  49.149 +             ('u8', 'a5'),
  49.150 +             ('u8', 'a6'))
  49.151 +             
  49.152 +types.struct('blkif_fe_interface_status_changed_t',
  49.153 +    ('unsigned int',    'handle'),
  49.154 +    ('unsigned int',    'status'),
  49.155 +    ('unsigned int',    'evtchn'))
  49.156 +
  49.157 +types.struct('blkif_fe_driver_status_changed_t',
  49.158 +    ('unsigned int',    'status'),
  49.159 +    ('unsigned int',    'nr_interfaces'))
  49.160 +
  49.161 +types.struct('blkif_fe_interface_connect_t',
  49.162 +    ('unsigned int' ,   'handle'),
  49.163 +    ('unsigned long',   'shmem_frame'))
  49.164 +
  49.165 +types.struct('blkif_fe_interface_disconnect_t',
  49.166 +    ('unsigned int',   'handle'))
  49.167 +
  49.168 +types.struct('blkif_extent_t',
  49.169 +    ('blkif_pdev_t'  , 'device'),
  49.170 +    ('blkif_sector_t', 'sector_start'),
  49.171 +    ('blkif_sector_t', 'sector_length'))
  49.172 +
  49.173 +types.struct('blkif_be_create_t', 
  49.174 +    ('domid_t'     ,   'domid'),
  49.175 +    ('unsigned int',   'blkif_handle'),
  49.176 +    ('unsigned int',   'status'))
  49.177 +             
  49.178 +types.struct('blkif_be_destroy_t',
  49.179 +    ('domid_t'     ,   'domid'),
  49.180 +    ('unsigned int',   'blkif_handle'),
  49.181 +    ('unsigned int',   'status'))
  49.182 +
  49.183 +types.struct('blkif_be_connect_t',
  49.184 +    ('domid_t'      ,  'domid'),
  49.185 +    ('unsigned int' ,  'blkif_handle'),
  49.186 +    ('unsigned int' ,  'evtchn'),
  49.187 +    ('unsigned long',  'shmem_frame'),
  49.188 +    ('unsigned int' ,  'status'))
  49.189 +
  49.190 +types.struct('blkif_be_disconnect_t',
  49.191 +    ('domid_t'     ,   'domid'),
  49.192 +    ('unsigned int',   'blkif_handle'),
  49.193 +    ('unsigned int',   'status'))
  49.194 +
  49.195 +types.struct('blkif_be_vbd_create_t', 
  49.196 +    ('domid_t'     ,   'domid'),         #Q
  49.197 +    ('unsigned int',   'blkif_handle'),  #I
  49.198 +    ('blkif_vdev_t',   'vdevice'),       #H
  49.199 +    ('int'         ,   'readonly'),      #i
  49.200 +    ('unsigned int',   'status'))        #I
  49.201 +
  49.202 +types.struct('blkif_be_vbd_destroy_t', 
  49.203 +    ('domid_t'     ,   'domid'),
  49.204 +    ('unsigned int',   'blkif_handle'),
  49.205 +    ('blkif_vdev_t',   'vdevice'),
  49.206 +    ('unsigned int',   'status'))
  49.207 +
  49.208 +types.struct('blkif_be_vbd_grow_t', 
  49.209 +    ('domid_t'       , 'domid'),         #Q
  49.210 +    ('unsigned int'  , 'blkif_handle'),  #I
  49.211 +    ('blkif_vdev_t'  , 'vdevice'),       #H   
  49.212 +    ('blkif_extent_t', 'extent'),        #HQQ
  49.213 +    ('unsigned int'  , 'status'))        #I
  49.214 +
  49.215 +types.struct('blkif_be_vbd_shrink_t', 
  49.216 +    ('domid_t'     ,   'domid'),
  49.217 +    ('unsigned int',   'blkif_handle'),
  49.218 +    ('blkif_vdev_t',   'vdevice'),
  49.219 +    ('unsigned int',   'status'))
  49.220 +
  49.221 +types.struct('blkif_be_driver_status_changed_t',
  49.222 +    ('unsigned int',   'status'),
  49.223 +    ('unsigned int',   'nr_interfaces'))
  49.224 +
  49.225 +types.struct('netif_fe_interface_status_changed_t',
  49.226 +    ('unsigned int',   'handle'),
  49.227 +    ('unsigned int',   'status'),
  49.228 +    ('unsigned int',   'evtchn'),
  49.229 +    ('u8[6]',          'mac'))
  49.230 +
  49.231 +types.struct('netif_fe_driver_status_changed_t',
  49.232 +    ('unsigned int',   'status'),
  49.233 +    ('unsigned int',   'nr_interfaces'))
  49.234 +
  49.235 +types.struct('netif_fe_interface_connect_t',
  49.236 +    ('unsigned int',   'handle'),
  49.237 +    ('unsigned long',  'tx_shmem_frame'),
  49.238 +    ('unsigned long',  'rx_shmem_frame'))
  49.239 +
  49.240 +types.struct('netif_fe_interface_disconnect_t',
  49.241 +    ('unsigned int',   'handle'))
  49.242 +
  49.243 +types.struct('netif_be_create_t', 
  49.244 +    ('domid_t'     ,   'domid'),
  49.245 +    ('unsigned int',   'netif_handle'),
  49.246 +    ('u8[6]'       ,   'mac'),
  49.247 +    ('unsigned int',   'status'))
  49.248 +
  49.249 +types.struct('netif_be_destroy_t',
  49.250 +    ('domid_t'     ,   'domid'),
  49.251 +    ('unsigned int',   'netif_handle'),
  49.252 +    ('unsigned int',   'status'))
  49.253 +
  49.254 +types.struct('netif_be_connect_t', 
  49.255 +    ('domid_t'      ,  'domid'),
  49.256 +    ('unsigned int' ,  'netif_handle'),
  49.257 +    ('unsigned int' ,  'evtchn'),
  49.258 +    ('unsigned long',  'tx_shmem_frame'),
  49.259 +    ('unsigned long',  'rx_shmem_frame'),
  49.260 +    ('unsigned int' ,  'status'))
  49.261 +
  49.262 +types.struct('netif_be_disconnect_t',
  49.263 +    ('domid_t'     ,   'domid'),
  49.264 +    ('unsigned int',   'netif_handle'),
  49.265 +    ('unsigned int',   'status'))
  49.266 +
  49.267 +types.struct('netif_be_driver_status_changed_t',
  49.268 +    ('unsigned int',   'status'),
  49.269 +    ('unsigned int',   'nr_interfaces'))
  49.270 +
  49.271 +if 1 or __name__ == "__main__":
  49.272 +    types.show()
    50.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    50.2 +++ b/tools/xenmgr/lib/server/messages.py	Fri Jun 11 14:40:53 2004 +0000
    50.3 @@ -0,0 +1,186 @@
    50.4 +import struct
    50.5 +
    50.6 +import xend.utils
    50.7 +
    50.8 +""" All message formats.
    50.9 +Added to incrementally for the various message types.
   50.10 +See below.
   50.11 +"""
   50.12 +msg_formats = {}
   50.13 +
   50.14 +#============================================================================
   50.15 +# Console message types.
   50.16 +#============================================================================
   50.17 +
   50.18 +CMSG_CONSOLE  = 0
   50.19 +
   50.20 +console_formats = { 'console_data': (CMSG_CONSOLE, 0, "?") }
   50.21 +
   50.22 +msg_formats.update(console_formats)
   50.23 +
   50.24 +#============================================================================
   50.25 +# Block interface message types.
   50.26 +#============================================================================
   50.27 +
   50.28 +CMSG_BLKIF_BE = 1
   50.29 +CMSG_BLKIF_FE = 2
   50.30 +
   50.31 +CMSG_BLKIF_FE_INTERFACE_STATUS_CHANGED =  0
   50.32 +CMSG_BLKIF_FE_DRIVER_STATUS_CHANGED    = 32
   50.33 +CMSG_BLKIF_FE_INTERFACE_CONNECT        = 33
   50.34 +CMSG_BLKIF_FE_INTERFACE_DISCONNECT     = 34
   50.35 +
   50.36 +CMSG_BLKIF_BE_CREATE      = 0
   50.37 +CMSG_BLKIF_BE_DESTROY     = 1
   50.38 +CMSG_BLKIF_BE_CONNECT     = 2
   50.39 +CMSG_BLKIF_BE_DISCONNECT  = 3
   50.40 +CMSG_BLKIF_BE_VBD_CREATE  = 4
   50.41 +CMSG_BLKIF_BE_VBD_DESTROY = 5
   50.42 +CMSG_BLKIF_BE_VBD_GROW    = 6
   50.43 +CMSG_BLKIF_BE_VBD_SHRINK  = 7
   50.44 +CMSG_BLKIF_BE_DRIVER_STATUS_CHANGED    = 32
   50.45 +
   50.46 +BLKIF_DRIVER_STATUS_DOWN  = 0
   50.47 +BLKIF_DRIVER_STATUS_UP    = 1
   50.48 +
   50.49 +BLKIF_INTERFACE_STATUS_DESTROYED    = 0 #/* Interface doesn't exist.    */
   50.50 +BLKIF_INTERFACE_STATUS_DISCONNECTED = 1 #/* Exists but is disconnected. */
   50.51 +BLKIF_INTERFACE_STATUS_CONNECTED    = 2 #/* Exists and is connected.    */
   50.52 +
   50.53 +BLKIF_BE_STATUS_OKAY                = 0
   50.54 +BLKIF_BE_STATUS_ERROR               = 1
   50.55 +BLKIF_BE_STATUS_INTERFACE_EXISTS    = 2
   50.56 +BLKIF_BE_STATUS_INTERFACE_NOT_FOUND = 3
   50.57 +BLKIF_BE_STATUS_INTERFACE_CONNECTED = 4
   50.58 +BLKIF_BE_STATUS_VBD_EXISTS          = 5
   50.59 +BLKIF_BE_STATUS_VBD_NOT_FOUND       = 6
   50.60 +BLKIF_BE_STATUS_OUT_OF_MEMORY       = 7
   50.61 +BLKIF_BE_STATUS_EXTENT_NOT_FOUND    = 8
   50.62 +BLKIF_BE_STATUS_MAPPING_ERROR       = 9
   50.63 +
   50.64 +blkif_formats = {
   50.65 +    'blkif_be_connect_t':
   50.66 +    (CMSG_BLKIF_BE, CMSG_BLKIF_BE_CONNECT, "QIILI"),
   50.67 +
   50.68 +    'blkif_be_create_t':
   50.69 +    (CMSG_BLKIF_BE, CMSG_BLKIF_BE_CREATE, "QII"),
   50.70 +
   50.71 +    'blkif_be_destroy_t':
   50.72 +    (CMSG_BLKIF_BE, CMSG_BLKIF_BE_DESTROY, "QII"),
   50.73 +
   50.74 +    'blkif_be_vbd_create_t':
   50.75 +    (CMSG_BLKIF_BE, CMSG_BLKIF_BE_VBD_CREATE, "QIHII"),
   50.76 +
   50.77 +    'blkif_be_vbd_grow_t':
   50.78 +    (CMSG_BLKIF_BE, CMSG_BLKIF_BE_VBD_GROW , "QIHHHQQI"),
   50.79 +
   50.80 +    'blkif_fe_interface_status_changed_t':
   50.81 +    (CMSG_BLKIF_FE, CMSG_BLKIF_FE_INTERFACE_STATUS_CHANGED, "III"),
   50.82 +
   50.83 +    'blkif_fe_driver_status_changed_t':
   50.84 +    (CMSG_BLKIF_FE, CMSG_BLKIF_FE_DRIVER_STATUS_CHANGED, "?"),
   50.85 +
   50.86 +    'blkif_fe_interface_connect_t':
   50.87 +    (CMSG_BLKIF_FE, CMSG_BLKIF_FE_INTERFACE_CONNECT, "IL"),
   50.88 +}
   50.89 +
   50.90 +msg_formats.update(blkif_formats)
   50.91 +
   50.92 +#============================================================================
   50.93 +# Network interface message types.
   50.94 +#============================================================================
   50.95 +
   50.96 +CMSG_NETIF_BE = 3
   50.97 +CMSG_NETIF_FE = 4
   50.98 +
   50.99 +CMSG_NETIF_FE_INTERFACE_STATUS_CHANGED =  0
  50.100 +CMSG_NETIF_FE_DRIVER_STATUS_CHANGED    = 32
  50.101 +CMSG_NETIF_FE_INTERFACE_CONNECT        = 33
  50.102 +CMSG_NETIF_FE_INTERFACE_DISCONNECT     = 34
  50.103 +
  50.104 +CMSG_NETIF_BE_CREATE      = 0
  50.105 +CMSG_NETIF_BE_DESTROY     = 1
  50.106 +CMSG_NETIF_BE_CONNECT     = 2
  50.107 +CMSG_NETIF_BE_DISCONNECT  = 3
  50.108 +CMSG_NETIF_BE_DRIVER_STATUS_CHANGED    = 32
  50.109 +
  50.110 +NETIF_INTERFACE_STATUS_DESTROYED    = 0 #/* Interface doesn't exist.    */
  50.111 +NETIF_INTERFACE_STATUS_DISCONNECTED = 1 #/* Exists but is disconnected. */
  50.112 +NETIF_INTERFACE_STATUS_CONNECTED    = 2 #/* Exists and is connected.    */
  50.113 +
  50.114 +NETIF_DRIVER_STATUS_DOWN   = 0
  50.115 +NETIF_DRIVER_STATUS_UP     = 1
  50.116 +
  50.117 +netif_formats = {
  50.118 +    'netif_be_connect_t':
  50.119 +    (CMSG_NETIF_BE, CMSG_NETIF_BE_CONNECT, "QIILLI"),
  50.120 +
  50.121 +    'netif_be_create_t':
  50.122 +    (CMSG_NETIF_BE, CMSG_NETIF_BE_CREATE, "QIBBBBBBBBI"),
  50.123 +
  50.124 +    'netif_be_destroy_t':
  50.125 +    (CMSG_NETIF_BE, CMSG_NETIF_BE_DESTROY, "QII"),
  50.126 +
  50.127 +    'netif_be_disconnect_t':
  50.128 +    (CMSG_NETIF_BE, CMSG_NETIF_BE_DISCONNECT, "QII"),
  50.129 +
  50.130 +    'netif_be_driver_status_changed_t':
  50.131 +    (CMSG_NETIF_BE, CMSG_NETIF_BE_DRIVER_STATUS_CHANGED, "QII"),
  50.132 +
  50.133 +    'netif_fe_driver_status_changed_t':
  50.134 +    (CMSG_NETIF_FE, CMSG_NETIF_FE_DRIVER_STATUS_CHANGED, "II"),
  50.135 +
  50.136 +    'netif_fe_interface_connect_t':
  50.137 +    (CMSG_NETIF_FE, CMSG_NETIF_FE_INTERFACE_CONNECT, "ILL"),
  50.138 +
  50.139 +    'netif_fe_interface_status_changed_t':
  50.140 +    (CMSG_NETIF_FE, CMSG_NETIF_FE_INTERFACE_STATUS_CHANGED, "IIIBBBBBBBB"),
  50.141 +    }
  50.142 +
  50.143 +msg_formats.update(netif_formats)
  50.144 +
  50.145 +#============================================================================
  50.146 +
  50.147 +class Msg:
  50.148 +    pass
  50.149 +
  50.150 +def packMsg(ty, params):
  50.151 +    print '>packMsg', ty, params
  50.152 +    (major, minor, packing) = msg_formats[ty]
  50.153 +    args = {}
  50.154 +    for (k, v) in params.items():
  50.155 +        if k == 'mac':
  50.156 +            for i in range(0, 6):
  50.157 +                args['mac[%d]' % i] = v[i]
  50.158 +        else:
  50.159 +            args[k] = v
  50.160 +    for (k, v) in args.items():
  50.161 +        print 'packMsg>', k, v, type(v)
  50.162 +    msgid = 0
  50.163 +    msg = xend.utils.message(major, minor, msgid, args)
  50.164 +    return msg
  50.165 +
  50.166 +def unpackMsg(ty, msg):
  50.167 +    args = msg.get_payload()
  50.168 +    mac = [0, 0, 0, 0, 0, 0]
  50.169 +    macs = []
  50.170 +    for (k, v) in args.items():
  50.171 +        if k.startswith('mac['):
  50.172 +            macs += k
  50.173 +            i = int(k[4:5])
  50.174 +            mac[i] = v
  50.175 +        else:
  50.176 +            pass
  50.177 +    if macs:
  50.178 +        args['mac'] = mac
  50.179 +        for k in macs:
  50.180 +            del args[k]
  50.181 +    print '<unpackMsg', ty, args
  50.182 +    return args
  50.183 +
  50.184 +def msgTypeName(ty, subty):
  50.185 +    for (name, info) in msg_formats.items():
  50.186 +        if info[0] == ty and info[1] == subty:
  50.187 +            return name
  50.188 +    return None
  50.189 +
    51.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    51.2 +++ b/tools/xenmgr/lib/server/netif.py	Fri Jun 11 14:40:53 2004 +0000
    51.3 @@ -0,0 +1,205 @@
    51.4 +import random
    51.5 +
    51.6 +import channel
    51.7 +import controller
    51.8 +from messages import *
    51.9 +
   51.10 +class NetifControllerFactory(controller.ControllerFactory):
   51.11 +    """Factory for creating network interface controllers.
   51.12 +    Also handles the 'back-end' channel to dom0.
   51.13 +    """
   51.14 +    # todo: add support for setting dom controlling blkifs (don't assume 0).
   51.15 +    # todo: add support for 'recovery'.
   51.16 +
   51.17 +    def __init__(self):
   51.18 +        controller.ControllerFactory.__init__(self)
   51.19 +
   51.20 +        self.majorTypes = [ CMSG_NETIF_BE ]
   51.21 +
   51.22 +        self.subTypes = {
   51.23 +            CMSG_NETIF_BE_CREATE : self.recv_be_create,
   51.24 +            CMSG_NETIF_BE_CONNECT: self.recv_be_connect,
   51.25 +            CMSG_NETIF_BE_DRIVER_STATUS_CHANGED: self.recv_be_driver_status_changed,
   51.26 +            }
   51.27 +        self.attached = 1
   51.28 +        self.registerChannel()
   51.29 +
   51.30 +    def createInstance(self, dom):
   51.31 +        #print 'netif>createInstance> dom=', dom
   51.32 +        netif = self.getInstanceByDom(dom)
   51.33 +        if netif is None:
   51.34 +            netif = NetifController(self, dom)
   51.35 +            self.addInstance(netif)
   51.36 +        return netif
   51.37 +        
   51.38 +    def setControlDomain(self, dom):
   51.39 +        self.deregisterChannel()
   51.40 +        self.attached = 0
   51.41 +        self.dom = dom
   51.42 +        self.registerChannel()
   51.43 +        #
   51.44 +        #if xend.netif.be_port.remote_dom != 0:
   51.45 +        #    xend.netif.recovery = True
   51.46 +        #    xend.netif.be_port = xend.main.port_from_dom(dom)
   51.47 +        #
   51.48 +        pass
   51.49 +
   51.50 +    def recv_be_create(self, msg, req):
   51.51 +        self.callDeferred(0)
   51.52 +    
   51.53 +    def recv_be_connect(self, msg, req):
   51.54 +        val = unpackMsg('netif_be_connect_t', msg)
   51.55 +        dom = val['domid']
   51.56 +        vif = val['netif_handle']
   51.57 +        netif = self.getInstanceByDom(dom)
   51.58 +        if netif:
   51.59 +            netif.send_interface_connected(vif)
   51.60 +        else:
   51.61 +            print "recv_be_connect> unknown vif=", vif
   51.62 +            pass
   51.63 +
   51.64 +    def recv_be_driver_status_changed(self, msg, req):
   51.65 +        val = unpackMsg('netif_be_driver_status_changed_t', msg)
   51.66 +        status = val['status']
   51.67 +        if status == NETIF_DRIVER_STATUS_UP and not self.attached:
   51.68 +            for netif in self.getInstances():
   51.69 +                netif.reattach_devices()
   51.70 +            self.attached = 1
   51.71 +
   51.72 +##         pl = msg.get_payload()
   51.73 +##         status = pl['status']
   51.74 +##         if status == NETIF_DRIVER_STATUS_UP:
   51.75 +##             if xend.netif.recovery:
   51.76 +##                 print "New netif backend now UP, notifying guests:"
   51.77 +##                 for netif_key in interface.list.keys():
   51.78 +##                     netif = interface.list[netif_key]
   51.79 +##                     netif.create()
   51.80 +##                     print "  Notifying %d" % netif.dom
   51.81 +##                     msg = xend.utils.message(
   51.82 +##                         CMSG_NETIF_FE,
   51.83 +##                         CMSG_NETIF_FE_INTERFACE_STATUS_CHANGED, 0,
   51.84 +##                         { 'handle' : 0, 'status' : 1 })
   51.85 +##                     netif.ctrlif_tx_req(xend.main.port_from_dom(netif.dom),msg)
   51.86 +##                 print "Done notifying guests"
   51.87 +##                 recovery = False
   51.88 +                
   51.89 +class NetDev:
   51.90 +    """Info record for a network device.
   51.91 +    """
   51.92 +
   51.93 +    def __init__(self, vif, mac):
   51.94 +        self.vif = vif
   51.95 +        self.mac = mac
   51.96 +        self.evtchn = None
   51.97 +    
   51.98 +class NetifController(controller.Controller):
   51.99 +    """Network interface controller. Handles all network devices for a domain.
  51.100 +    """
  51.101 +    
  51.102 +    def __init__(self, factory, dom):
  51.103 +        #print 'NetifController> dom=', dom
  51.104 +        controller.Controller.__init__(self, factory, dom)
  51.105 +        self.devices = {}
  51.106 +        
  51.107 +        self.majorTypes = [ CMSG_NETIF_FE ]
  51.108 +
  51.109 +        self.subTypes = {
  51.110 +            CMSG_NETIF_FE_DRIVER_STATUS_CHANGED:
  51.111 +                self.recv_fe_driver_status_changed,
  51.112 +            CMSG_NETIF_FE_INTERFACE_CONNECT    :
  51.113 +                self.recv_fe_interface_connect,
  51.114 +            }
  51.115 +        self.registerChannel()
  51.116 +        #print 'NetifController<', 'dom=', self.dom, 'idx=', self.idx
  51.117 +
  51.118 +
  51.119 +    def randomMAC(self):
  51.120 +        # VIFs get a random MAC address with a "special" vendor id.
  51.121 +        # 
  51.122 +        # NB. The vendor is currently an "obsolete" one that used to belong
  51.123 +        # to DEC (AA-00-00). Using it is probably a bit rude :-)
  51.124 +        # 
  51.125 +        # NB2. The first bit of the first random octet is set to zero for
  51.126 +        # all dynamic MAC addresses. This may allow us to manually specify
  51.127 +        # MAC addresses for some VIFs with no fear of clashes.
  51.128 +        mac = [ 0xaa, 0x00, 0x00,
  51.129 +                random.randint(0x00, 0x7f),
  51.130 +                random.randint(0x00, 0xff),
  51.131 +                random.randint(0x00, 0xff) ]
  51.132 +        return mac
  51.133 +
  51.134 +    def attach_device(self, vif, vmac):
  51.135 +        if vmac is None:
  51.136 +            mac = self.randomMAC()
  51.137 +        else:
  51.138 +            mac = [ int(x, 16) for x in vmac.split(':') ]
  51.139 +        if len(mac) != 6: raise ValueError("invalid mac")
  51.140 +        #print "attach_device>", "vif=", vif, "mac=", mac
  51.141 +        self.devices[vif] = NetDev(vif, mac)
  51.142 +        d = self.factory.addDeferred()
  51.143 +        self.send_be_create(vif)
  51.144 +        return d
  51.145 +
  51.146 +    def reattach_devices(self):
  51.147 +        d = self.factory.addDeferred()
  51.148 +        self.send_be_create(vif)
  51.149 +        self.attach_fe_devices(0)
  51.150 +
  51.151 +    def attach_fe_devices(self):
  51.152 +        for dev in self.devices.values():
  51.153 +            msg = packMsg('netif_fe_interface_status_changed_t',
  51.154 +                          { 'handle' : dev.vif,
  51.155 +                            'status' : NETIF_INTERFACE_STATUS_DISCONNECTED,
  51.156 +                            'evtchn' : 0,
  51.157 +                            'mac'    : dev.mac })
  51.158 +            self.writeRequest(msg)
  51.159 +    
  51.160 +    def recv_fe_driver_status_changed(self, msg, req):
  51.161 +        if not req: return
  51.162 +        msg = packMsg('netif_fe_driver_status_changed_t',
  51.163 +                      { 'status'        : NETIF_DRIVER_STATUS_UP,
  51.164 +                        'nr_interfaces' : len(self.devices) })
  51.165 +        self.writeRequest(msg)
  51.166 +        self.attach_fe_devices()
  51.167 +
  51.168 +    def recv_fe_interface_connect(self, msg, req):
  51.169 +        val = unpackMsg('netif_fe_interface_connect_t', msg)
  51.170 +        dev = self.devices[val['handle']]
  51.171 +        dev.evtchn = channel.eventChannel(0, self.dom)
  51.172 +        msg = packMsg('netif_be_connect_t',
  51.173 +                      { 'domid'          : self.dom,
  51.174 +                        'netif_handle'   : dev.vif,
  51.175 +                        'evtchn'         : dev.evtchn['port1'],
  51.176 +                        'tx_shmem_frame' : val['tx_shmem_frame'],
  51.177 +                        'rx_shmem_frame' : val['rx_shmem_frame'] })
  51.178 +        self.factory.writeRequest(msg)
  51.179 +
  51.180 +    #def recv_fe_interface_status_changed(self):
  51.181 +    #    print 'recv_fe_interface_status_changed>'
  51.182 +    #    pass
  51.183 +    
  51.184 +    def send_interface_connected(self, vif):
  51.185 +        dev = self.devices[vif]
  51.186 +        msg = packMsg('netif_fe_interface_status_changed_t',
  51.187 +                      { 'handle' : dev.vif,
  51.188 +                        'status' : NETIF_INTERFACE_STATUS_CONNECTED,
  51.189 +                        'evtchn' : dev.evtchn['port2'],
  51.190 +                        'mac'    : dev.mac })
  51.191 +        self.writeRequest(msg)
  51.192 +
  51.193 +    def send_be_create(self, vif):
  51.194 +        dev = self.devices[vif]
  51.195 +        msg = packMsg('netif_be_create_t',
  51.196 +                      { 'domid'        : self.dom,
  51.197 +                        'netif_handle' : dev.vif,
  51.198 +                        'mac'          : dev.mac })
  51.199 +        self.factory.writeRequest(msg)
  51.200 +
  51.201 +    def send_be_destroy(self, vif):
  51.202 +        print 'send_be_destroy>', 'dom=', self.dom, 'vif=', vif
  51.203 +        dev = self.devices[vif]
  51.204 +        del self.devices[vif]
  51.205 +        msg = packMsg('netif_be_destroy_t',
  51.206 +                      { 'domid'        : self.dom,
  51.207 +                        'netif_handle' : vif })
  51.208 +        self.factory.writeRequest(msg)
    52.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    52.2 +++ b/tools/xenmgr/lib/server/params.py	Fri Jun 11 14:40:53 2004 +0000
    52.3 @@ -0,0 +1,10 @@
    52.4 +# The following parameters could be placed in a configuration file.
    52.5 +PID_FILE  = '/var/run/xend.pid'
    52.6 +LOG_FILE  = '/var/log/xend.log'
    52.7 +USER = 'root'
    52.8 +CONTROL_DIR  = '/var/run/xend'
    52.9 +MGMT_SOCK    = 'xenmgrsock' # relative to CONTROL_DIR
   52.10 +EVENT_PORT = 8001
   52.11 +
   52.12 +CONSOLE_PORT_BASE = 9600
   52.13 +
    53.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    53.2 +++ b/tools/xenmgr/lib/sxp.py	Fri Jun 11 14:40:53 2004 +0000
    53.3 @@ -0,0 +1,557 @@
    53.4 +#!/usr/bin/python2
    53.5 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    53.6 +"""
    53.7 +Input-driven parsing for s-expression (sxp) format.
    53.8 +Create a parser: pin = Parser();
    53.9 +Then call pin.input(buf) with your input.
   53.10 +Call pin.input_eof() when done.
   53.11 +Use pin.read() to see if a value has been parsed, pin.get_val()
   53.12 +to get a parsed value. You can call ready and get_val at any time -
   53.13 +you don't have to wait until after calling input_eof.
   53.14 +
   53.15 +"""
   53.16 +from __future__ import generators
   53.17 +
   53.18 +import sys
   53.19 +import types
   53.20 +import errno
   53.21 +import string
   53.22 +
   53.23 +__all__ = [
   53.24 +    "mime_type", 
   53.25 +    "ParseError", 
   53.26 +    "Parser", 
   53.27 +    "atomp", 
   53.28 +    "show", 
   53.29 +    "show_xml", 
   53.30 +    "elementp", 
   53.31 +    "name", 
   53.32 +    "attributes", 
   53.33 +    "attribute", 
   53.34 +    "children", 
   53.35 +    "child", 
   53.36 +    "child_at", 
   53.37 +    "child0", 
   53.38 +    "child1", 
   53.39 +    "child2", 
   53.40 +    "child3", 
   53.41 +    "child4", 
   53.42 +    "child_value", 
   53.43 +    "has_id", 
   53.44 +    "with_id", 
   53.45 +    "child_with_id", 
   53.46 +    "elements", 
   53.47 +    "parse", 
   53.48 +    ]
   53.49 +
   53.50 +mime_type = "application/sxp"
   53.51 +
   53.52 +escapes = {
   53.53 +    'a': '\a',
   53.54 +    'b': '\b',
   53.55 +    't': '\t',
   53.56 +    'n': '\n',
   53.57 +    'v': '\v',
   53.58 +    'f': '\f',
   53.59 +    'r': '\r',
   53.60 +    '\\': '\\',
   53.61 +    '\'': '\'',
   53.62 +    '\"': '\"'}
   53.63 +
   53.64 +k_list_open  = "("
   53.65 +k_list_close = ")"
   53.66 +k_attr_open  = "@"
   53.67 +k_eval       = "!"
   53.68 +
   53.69 +escapes_rev = {}
   53.70 +for k in escapes:
   53.71 +    escapes_rev[escapes[k]] = k
   53.72 +
   53.73 +class ParseError(StandardError):
   53.74 +
   53.75 +    def __init__(self, parser, value):
   53.76 +        self.parser = parser
   53.77 +        self.value = value
   53.78 +
   53.79 +    def __str__(self):
   53.80 +        return self.value
   53.81 +
   53.82 +class ParserState:
   53.83 +
   53.84 +    def __init__(self, fn, parent=None):
   53.85 +        self.parent = parent
   53.86 +        self.buf = ''
   53.87 +        self.val = []
   53.88 +        self.delim = None
   53.89 +        self.fn = fn
   53.90 +
   53.91 +    def push(self, fn):
   53.92 +        return ParserState(fn, parent=self)
   53.93 +    
   53.94 +class Parser:
   53.95 +
   53.96 +    def __init__(self):
   53.97 +        self.error = sys.stderr
   53.98 +        self.reset()
   53.99 +
  53.100 +    def reset(self):
  53.101 +        self.val = []
  53.102 +        self.eof = 0
  53.103 +        self.err = 0
  53.104 +        self.line_no = 0
  53.105 +        self.char_no = 0
  53.106 +        self.state = None
  53.107 +
  53.108 +    def push_state(self, fn):
  53.109 +        self.state = self.state.push(fn)
  53.110 +
  53.111 +    def pop_state(self):
  53.112 +        val = self.state
  53.113 +        self.state = self.state.parent
  53.114 +        if self.state and self.state.fn == self.state_start:
  53.115 +            # Return to start state - produce the value.
  53.116 +            self.val += self.state.val
  53.117 +            self.state.val = []
  53.118 +        return val
  53.119 +
  53.120 +    def in_class(self, c, s):
  53.121 +        return s.find(c) >= 0
  53.122 +        
  53.123 +    def in_space_class(self, c):
  53.124 +        return self.in_class(c, ' \t\n\v\f\r')
  53.125 +
  53.126 +    def is_separator(self, c):
  53.127 +        return self.in_class(c, '{}()<>[]!;')
  53.128 +
  53.129 +    def in_comment_class(self, c):
  53.130 +        return self.in_class(c, '#')
  53.131 +
  53.132 +    def in_string_quote_class(self, c):
  53.133 +        return self.in_class(c, '"\'')
  53.134 +
  53.135 +    def in_printable_class(self, c):
  53.136 +        return self.in_class(c, string.printable)
  53.137 +
  53.138 +    def set_error_stream(self, error):
  53.139 +        self.error = error
  53.140 +
  53.141 +    def has_error(self):
  53.142 +        return self.err > 0
  53.143 +
  53.144 +    def at_eof(self):
  53.145 +        return self.eof
  53.146 +
  53.147 +    def input_eof(self):
  53.148 +        self.eof = 1
  53.149 +        self.input_char(-1)
  53.150 +
  53.151 +    def input(self, buf):
  53.152 +        if not buf or len(buf) == 0:
  53.153 +            self.input_eof()
  53.154 +        else:
  53.155 +            for c in buf:
  53.156 +                self.input_char(c)
  53.157 +
  53.158 +    def input_char(self, c):
  53.159 +        if self.at_eof():
  53.160 +            pass
  53.161 +        elif c == '\n':
  53.162 +            self.line_no += 1
  53.163 +            self.char_no = 0
  53.164 +        else:
  53.165 +           self.char_no += 1 
  53.166 +
  53.167 +        if self.state is None:
  53.168 +            self.begin_start(None)
  53.169 +        self.state.fn(c)
  53.170 +
  53.171 +    def ready(self):
  53.172 +        return len(self.val) > 0
  53.173 +
  53.174 +    def get_val(self):
  53.175 +        v = self.val[0]
  53.176 +        self.val = self.val[1:]
  53.177 +        return v
  53.178 +
  53.179 +    def get_all(self):
  53.180 +        return self.val
  53.181 +
  53.182 +    def begin_start(self, c):
  53.183 +        self.state = ParserState(self.state_start)
  53.184 +
  53.185 +    def end_start(self):
  53.186 +        self.val += self.state.val
  53.187 +        self.pop_state()
  53.188 +    
  53.189 +    def state_start(self, c):
  53.190 +        if self.at_eof():
  53.191 +            self.end_start()
  53.192 +        elif self.in_space_class(c):
  53.193 +            pass
  53.194 +        elif self.in_comment_class(c):
  53.195 +            self.begin_comment(c)
  53.196 +        elif c == k_list_open:
  53.197 +            self.begin_list(c)
  53.198 +        elif c == k_list_close:
  53.199 +            raise ParseError(self, "syntax error: "+c)
  53.200 +        elif self.in_string_quote_class(c):
  53.201 +            self.begin_string(c)
  53.202 +        elif self.in_printable_class(c):
  53.203 +            self.begin_atom(c)
  53.204 +        elif c == chr(4):
  53.205 +            # ctrl-D, EOT: end-of-text.
  53.206 +            self.input_eof()
  53.207 +        else:
  53.208 +            raise ParseError(self, "invalid character: code %d" % ord(c))
  53.209 +
  53.210 +    def begin_comment(self, c):
  53.211 +        self.push_state(self.state_comment)
  53.212 +        self.state.buf += c
  53.213 +
  53.214 +    def end_comment(self):
  53.215 +        self.pop_state()
  53.216 +    
  53.217 +    def state_comment(self, c):
  53.218 +        if c == '\n' or self.at_eof():
  53.219 +            self.end_comment()
  53.220 +        else:
  53.221 +            self.state.buf += c
  53.222 +
  53.223 +    def begin_string(self, c):
  53.224 +        self.push_state(self.state_string)
  53.225 +        self.state.delim = c
  53.226 +
  53.227 +    def end_string(self):
  53.228 +        val = self.state.buf
  53.229 +        self.state.parent.val.append(val)
  53.230 +        self.pop_state()
  53.231 +        
  53.232 +    def state_string(self, c):
  53.233 +        if self.at_eof():
  53.234 +            raise ParseError(self, "unexpected EOF")
  53.235 +        elif c == self.state.delim:
  53.236 +            self.end_string()
  53.237 +        elif c == '\\':
  53.238 +            self.push_state(self.state_escape)
  53.239 +        else:
  53.240 +            self.state.buf += c
  53.241 +
  53.242 +    def state_escape(self, c):
  53.243 +        if self.at_eof():
  53.244 +            raise ParseError(self, "unexpected EOF")
  53.245 +        d = escapes.get(c)
  53.246 +        if d:
  53.247 +            self.state.parent.buf += d
  53.248 +            self.pop_state()
  53.249 +        elif c == 'x':
  53.250 +            self.state.fn = self.state_hex
  53.251 +            self.state.val = 0
  53.252 +        else:
  53.253 +            self.state.fn = self.state_octal
  53.254 +            self.state.val = 0
  53.255 +            self.input_char(c)
  53.256 +
  53.257 +    def state_octal(self, c):
  53.258 +        def octaldigit(c):
  53.259 +            self.state.val *= 8
  53.260 +            self.state.val += ord(c) - ord('0')
  53.261 +            self.state.buf += c
  53.262 +            if self.state.val < 0 or self.state.val > 0xff:
  53.263 +                raise ParseError(self, "invalid octal escape: out of range " + self.state.buf)
  53.264 +            if len(self.state.buf) == 3:
  53.265 +               octaldone()
  53.266 +               
  53.267 +        def octaldone():
  53.268 +            d = chr(self.state.val)
  53.269 +            self.state.parent.buf += d
  53.270 +            self.pop_state()
  53.271 +            
  53.272 +        if self.at_eof():
  53.273 +            raise ParseError(self, "unexpected EOF")
  53.274 +        elif '0' <= c <= '7':
  53.275 +            octaldigit(c)
  53.276 +        elif len(self.buf):
  53.277 +            octaldone()
  53.278 +            self.input_char(c)
  53.279 +
  53.280 +    def state_hex(self, c):
  53.281 +        def hexdone():
  53.282 +            d = chr(self.state.val)
  53.283 +            self.state.parent.buf += d
  53.284 +            self.pop_state()
  53.285 +            
  53.286 +        def hexdigit(c, d):
  53.287 +            self.state.val *= 16
  53.288 +            self.state.val += ord(c) - ord(d)
  53.289 +            self.state.buf += c
  53.290 +            if self.state.val < 0 or self.state.val > 0xff:
  53.291 +                raise ParseError(self, "invalid hex escape: out of range " + self.state.buf)
  53.292 +            if len(self.state.buf) == 2:
  53.293 +                hexdone()
  53.294 +            
  53.295 +        if self.at_eof():
  53.296 +            raise ParseError(self, "unexpected EOF")
  53.297 +        elif '0' <= c <= '9':
  53.298 +            hexdigit(c, '0')
  53.299 +        elif 'A' <= c <= 'F':
  53.300 +            hexdigit(c, 'A')
  53.301 +        elif 'a' <= c <= 'f':
  53.302 +            hexdigit(c, 'a')
  53.303 +        elif len(buf):
  53.304 +            hexdone()
  53.305 +            self.input_char(c)
  53.306 +
  53.307 +    def begin_atom(self, c):
  53.308 +        self.push_state(self.state_atom)
  53.309 +        self.state.buf = c
  53.310 +
  53.311 +    def end_atom(self):
  53.312 +        val = self.state.buf
  53.313 +        self.state.parent.val.append(val)
  53.314 +        self.pop_state()
  53.315 +    
  53.316 +    def state_atom(self, c):
  53.317 +        if self.at_eof():
  53.318 +            self.end_atom()
  53.319 +        elif (self.is_separator(c) or
  53.320 +              self.in_space_class(c) or
  53.321 +              self.in_comment_class(c)):
  53.322 +            self.end_atom()
  53.323 +            self.input_char(c)
  53.324 +        else:
  53.325 +            self.state.buf += c
  53.326 +
  53.327 +    def begin_list(self, c):
  53.328 +        self.push_state(self.state_list)
  53.329 +
  53.330 +    def end_list(self):
  53.331 +        val = self.state.val
  53.332 +        self.state.parent.val.append(val)
  53.333 +        self.pop_state()
  53.334 +
  53.335 +    def state_list(self, c):
  53.336 +        if self.at_eof():
  53.337 +            raise ParseError(self, "unexpected EOF")
  53.338 +        elif c == k_list_close:
  53.339 +            self.end_list()
  53.340 +        else:
  53.341 +            self.state_start(c)
  53.342 +
  53.343 +def atomp(sxpr):
  53.344 +    if sxpr.isalnum() or sxpr == '@':
  53.345 +        return 1
  53.346 +    for c in sxpr:
  53.347 +        if c in string.whitespace: return 0
  53.348 +        if c in '"\'\\(){}[]<>$#&%^': return 0
  53.349 +        if c in string.ascii_letters: continue
  53.350 +        if c in string.digits: continue
  53.351 +        if c in '.-_:/~': continue
  53.352 +        return 0
  53.353 +    return 1
  53.354 +    
  53.355 +def show(sxpr, out=sys.stdout):
  53.356 +    if isinstance(sxpr, types.ListType):
  53.357 +        out.write(k_list_open)
  53.358 +        i = 0
  53.359 +        for x in sxpr:
  53.360 +            if i: out.write(' ')
  53.361 +            show(x, out)
  53.362 +            i += 1
  53.363 +        out.write(k_list_close)
  53.364 +    elif isinstance(sxpr, types.StringType) and atomp(sxpr):
  53.365 +        out.write(sxpr)
  53.366 +    else:
  53.367 +        #out.write("'" + str(sxpr) + "'")
  53.368 +        out.write(repr(str(sxpr)))
  53.369 +
  53.370 +def show_xml(sxpr, out=sys.stdout):
  53.371 +    if isinstance(sxpr, types.ListType):
  53.372 +        element = name(sxpr)
  53.373 +        out.write('<%s' % element)
  53.374 +        for attr in attributes(sxpr):
  53.375 +            out.write(' %s=%s' % (attr[0], attr[1]))
  53.376 +        out.write('>')
  53.377 +        i = 0
  53.378 +        for x in children(sxpr):
  53.379 +            if i: out.write(' ')
  53.380 +            show_xml(x, out)
  53.381 +            i += 1
  53.382 +        out.write('</%s>' % element)
  53.383 +    elif isinstance(sxpr, types.StringType) and atomp(sxpr):
  53.384 +        out.write(sxpr)
  53.385 +    else:
  53.386 +        out.write(str(sxpr))
  53.387 +
  53.388 +def elementp(sxpr, elt=None):
  53.389 +    return (isinstance(sxpr, types.ListType)
  53.390 +            and len(sxpr)
  53.391 +            and (None == elt or sxpr[0] == elt))
  53.392 +
  53.393 +def name(sxpr):
  53.394 +    val = None
  53.395 +    if isinstance(sxpr, types.StringType):
  53.396 +        val = sxpr
  53.397 +    elif isinstance(sxpr, types.ListType) and len(sxpr):
  53.398 +        val = sxpr[0]
  53.399 +    return val
  53.400 +
  53.401 +def attributes(sxpr):
  53.402 +    val = []
  53.403 +    if isinstance(sxpr, types.ListType) and len(sxpr) > 1:
  53.404 +        attr = sxpr[1]
  53.405 +        if elementp(attr, k_attr_open):
  53.406 +            val = attr[1:]
  53.407 +    return val
  53.408 +
  53.409 +def attribute(sxpr, key, val=None):
  53.410 +    for x in attributes(sxpr):
  53.411 +        if x[0] == key:
  53.412 +            val = x[1]
  53.413 +            break
  53.414 +    return val
  53.415 +
  53.416 +def children(sxpr, elt=None):
  53.417 +    val = []
  53.418 +    if isinstance(sxpr, types.ListType) and len(sxpr) > 1:
  53.419 +        i = 1
  53.420 +        x = sxpr[i]
  53.421 +        if elementp(x, k_attr_open):
  53.422 +            i += 1
  53.423 +        val = sxpr[i : ]
  53.424 +    if elt:
  53.425 +        def iselt(x):
  53.426 +            return elementp(x, elt)
  53.427 +        val = filter(iselt, val)
  53.428 +    return val
  53.429 +
  53.430 +def child(sxpr, elt, val=None):
  53.431 +    for x in children(sxpr):
  53.432 +        if elementp(x, elt):
  53.433 +            val = x
  53.434 +            break
  53.435 +    return val
  53.436 +
  53.437 +def child_at(sxpr, index, val=None):
  53.438 +    kids = children(sxpr)
  53.439 +    if len(kids) > index:
  53.440 +        val = kids[index]
  53.441 +    return val
  53.442 +
  53.443 +def child0(sxpr, val=None):
  53.444 +    return child_at(sxpr, 0, val)
  53.445 +
  53.446 +def child1(sxpr, val=None):
  53.447 +    return child_at(sxpr, 1, val)
  53.448 +
  53.449 +def child2(sxpr, val=None):
  53.450 +    return child_at(sxpr, 2, val)
  53.451 +
  53.452 +def child3(sxpr, val=None):
  53.453 +    return child_at(sxpr, 3, val)
  53.454 +
  53.455 +def child4(sxpr, val=None):
  53.456 +    return child_at(sxpr, 4, val)
  53.457 +
  53.458 +def child_value(sxpr, elt, val=None):
  53.459 +    kid = child(sxpr, elt)
  53.460 +    if kid:
  53.461 +        val = child_at(kid, 0, val)
  53.462 +    return val
  53.463 +
  53.464 +def has_id(sxpr, id):
  53.465 +    """Test if an s-expression has a given id.
  53.466 +    """
  53.467 +    return attribute(sxpr, 'id') == id
  53.468 +
  53.469 +def with_id(sxpr, id, val=None):
  53.470 +    """Find the first s-expression with a given id, at any depth.
  53.471 +
  53.472 +    sxpr   s-exp or list
  53.473 +    id     id
  53.474 +    val    value if not found (default None)
  53.475 +
  53.476 +    return s-exp or val
  53.477 +    """
  53.478 +    if isinstance(sxpr, types.ListType):
  53.479 +        for n in sxpr:
  53.480 +            if has_id(n, id):
  53.481 +                val = n
  53.482 +                break
  53.483 +            v = with_id(n, id)
  53.484 +            if v is None: continue
  53.485 +            val = v
  53.486 +            break
  53.487 +    return val
  53.488 +
  53.489 +def child_with_id(sxpr, id, val=None):
  53.490 +    """Find the first child with a given id.
  53.491 +
  53.492 +    sxpr   s-exp or list
  53.493 +    id     id
  53.494 +    val    value if not found (default None)
  53.495 +
  53.496 +    return s-exp or val
  53.497 +    """
  53.498 +    if isinstance(sxpr, types.ListType):
  53.499 +        for n in sxpr:
  53.500 +            if has_id(n, id):
  53.501 +                val = n
  53.502 +                break
  53.503 +    return val
  53.504 +
  53.505 +def elements(sxpr, ctxt=None):
  53.506 +    """Generate elements (at any depth).
  53.507 +    Visit elements in pre-order.
  53.508 +    Values generated are (node, context)
  53.509 +    The context is None if there is no parent, otherwise
  53.510 +    (index, parent, context) where index is the node's index w.r.t its parent,
  53.511 +    and context is the parent's context.
  53.512 +
  53.513 +    sxpr   s-exp
  53.514 +
  53.515 +    returns generator
  53.516 +    """
  53.517 +    yield (sxpr, ctxt)
  53.518 +    i = 0
  53.519 +    for n in children(sxpr):
  53.520 +        if isinstance(n, types.ListType):
  53.521 +            # Calling elements() recursively does not generate recursively,
  53.522 +            # it just returns a generator object. So we must iterate over it.
  53.523 +            for v in elements(n, (i, sxpr, ctxt)):
  53.524 +                yield v
  53.525 +        i += 1
  53.526 +
  53.527 +def parse(io):
  53.528 +    """Completely parse all input from 'io'.
  53.529 +
  53.530 +    io	input file object
  53.531 +    returns list of values, None if incomplete
  53.532 +    raises ParseError on parse error
  53.533 +    """
  53.534 +    pin = Parser()
  53.535 +    while 1:
  53.536 +        buf = io.readline()
  53.537 +        pin.input(buf)
  53.538 +        if len(buf) == 0:
  53.539 +            break
  53.540 +    if pin.ready():
  53.541 +        val = pin.get_all()
  53.542 +    else:
  53.543 +        val = None
  53.544 +    return val
  53.545 +   
  53.546 +
  53.547 +if __name__ == '__main__':
  53.548 +    print ">main"
  53.549 +    pin = Parser()
  53.550 +    while 1:
  53.551 +        buf = sys.stdin.read(1024)
  53.552 +        #buf = sys.stdin.readline()
  53.553 +        pin.input(buf)
  53.554 +        while pin.ready():
  53.555 +            val = pin.get_val()
  53.556 +            print
  53.557 +            print '****** val=', val
  53.558 +        if len(buf) == 0:
  53.559 +            break
  53.560 +
    54.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    54.2 +++ b/tools/xenmgr/netfix	Fri Jun 11 14:40:53 2004 +0000
    54.3 @@ -0,0 +1,150 @@
    54.4 +#!/usr/bin/python
    54.5 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    54.6 +#============================================================================
    54.7 +# Move the IP address from eth0 onto the Xen bridge (nbe-br).
    54.8 +# Works best if the bridge control utils (brctl) have been installed.
    54.9 +#============================================================================
   54.10 +import os
   54.11 +import os.path
   54.12 +import re
   54.13 +import sys
   54.14 +
   54.15 +from getopt import getopt
   54.16 +
   54.17 +CMD_IFCONFIG = '/sbin/ifconfig'
   54.18 +CMD_ROUTE    = '/sbin/route'
   54.19 +CMD_BRCTL    = '/usr/local/sbin/brctl'
   54.20 +
   54.21 +def routes():
   54.22 +    """Return a list of the routes.
   54.23 +    """
   54.24 +    fin = os.popen(CMD_ROUTE + ' -n', 'r')
   54.25 +    routes = []
   54.26 +    for x in fin:
   54.27 +        if x.startswith('Kernel'): continue
   54.28 +        if x.startswith('Destination'): continue
   54.29 +        x = x.strip()
   54.30 +        y = x.split()
   54.31 +        z = { 'destination': y[0],
   54.32 +              'gateway'    : y[1],
   54.33 +              'mask'       : y[2],
   54.34 +              'flags'      : y[3],
   54.35 +              'metric'     : y[4],
   54.36 +              'ref'        : y[5],
   54.37 +              'use'        : y[6],
   54.38 +              'interface'  : y[7] }
   54.39 +        routes.append(z)
   54.40 +    return routes
   54.41 +
   54.42 +def cmd(p, s):
   54.43 +    """Print and execute command 'p' with args 's'.
   54.44 +    """
   54.45 +    global opts
   54.46 +    c = p + ' ' + s
   54.47 +    if opts.verbose: print c
   54.48 +    if not opts.dryrun:
   54.49 +        os.system(c)
   54.50 +
   54.51 +def ifconfig(interface):
   54.52 +    """Return the ip config for an interface,
   54.53 +    """
   54.54 +    fin = os.popen(CMD_IFCONFIG + ' %s' % interface, 'r')
   54.55 +    inetre = re.compile('\s*inet\s*addr:(?P<address>\S*)\s*Bcast:(?P<broadcast>\S*)\s*Mask:(?P<mask>\S*)')
   54.56 +    info = None
   54.57 +    for x in fin:
   54.58 +        m = inetre.match(x)
   54.59 +        if not m: continue
   54.60 +        info = m.groupdict()
   54.61 +        info['interface'] = interface
   54.62 +        break
   54.63 +    return info
   54.64 +
   54.65 +def reconfigure(interface, bridge):
   54.66 +    """Reconfigure an interface to be attached to a bridge, and give the bridge
   54.67 +    the IP address etc. from interface. Move the default route to the interface
   54.68 +    to the bridge.
   54.69 +    """
   54.70 +    intf_info = ifconfig(interface)
   54.71 +    if not intf_info:
   54.72 +        print 'Interface not found:', interface
   54.73 +        return
   54.74 +    #bridge_info = ifconfig(bridge)
   54.75 +    #if not bridge_info:
   54.76 +    #    print 'Bridge not found:', bridge
   54.77 +    #    return
   54.78 +    route_info = routes()
   54.79 +    intf_info['bridge'] = bridge
   54.80 +    intf_info['gateway'] = None
   54.81 +    for r in route_info:
   54.82 +        if (r['destination'] == '0.0.0.0' and
   54.83 +            'G' in r['flags'] and
   54.84 +            r['interface'] == interface):
   54.85 +            intf_info['gateway'] = r['gateway']
   54.86 +    if not intf_info['gateway']:
   54.87 +        print 'Gateway not found: ', interface
   54.88 +        return
   54.89 +    cmd(CMD_IFCONFIG, '%(interface)s 0.0.0.0' % intf_info)
   54.90 +    cmd(CMD_IFCONFIG, '%(bridge)s %(address)s netmask %(mask)s broadcast %(broadcast)s up' % intf_info)
   54.91 +    cmd(CMD_ROUTE, 'add default gateway %(gateway)s dev %(bridge)s' % intf_info)
   54.92 +    if os.path.exists(CMD_BRCTL):
   54.93 +        cmd(CMD_BRCTL, 'addif %(bridge)s %(interface)s' % intf_info)
   54.94 +
   54.95 +defaults = {
   54.96 +    'interface': 'eth0',
   54.97 +    'bridge'   : 'nbe-br',
   54.98 +    'verbose'  : 1,
   54.99 +    'dryrun'   : 0,
  54.100 +    }
  54.101 +
  54.102 +short_options = 'hvqni:b:'
  54.103 +long_options  = ['help', 'verbose', 'quiet', 'interface=', 'bridge=']
  54.104 +
  54.105 +def usage():
  54.106 +    print """Usage:
  54.107 +    %s [options]
  54.108 +
  54.109 +    Reconfigure routing so that <bridge> has the IP address from
  54.110 +    <interface>. This lets IP carry on working when <interface>
  54.111 +    is attached to <bridge> for virtual networking.
  54.112 +    If brctl is available, <interface> is added to <bridge>,
  54.113 +    so this can be run before any domains have been created.
  54.114 +    """ % sys.argv[0]
  54.115 +    print """
  54.116 +    -i, --interface <interface>    interface, default %(interface)s.
  54.117 +    -b, --bridge <bridge>          bridge, default %(bridge)s.
  54.118 +    -v, --verbose                  Print commands.
  54.119 +    -q, --quiet                    Don't print commands.
  54.120 +    -n, --dry-run                  Don't execute commands.
  54.121 +    -h, --help                     Print this help.
  54.122 +    """ % defaults
  54.123 +    sys.exit(1)
  54.124 +
  54.125 +class Opts:
  54.126 +
  54.127 +    def __init__(self, defaults):
  54.128 +        for (k, v) in defaults.items():
  54.129 +            setattr(self, k, v)
  54.130 +        pass
  54.131 +
  54.132 +def main():
  54.133 +    global opts
  54.134 +    opts = Opts(defaults)
  54.135 +    (options, args) = getopt(sys.argv[1:], short_options, long_options)
  54.136 +    if args: usage()
  54.137 +    for k, v in options:
  54.138 +        if k in ['-h', '--help']:
  54.139 +            usage()
  54.140 +        elif k in ['-i', '--interface']:
  54.141 +            opts.interface = v
  54.142 +        elif k in ['-b', '--bridge']:
  54.143 +            opts.bridge = v
  54.144 +        elif k in ['-q', '--quiet']:
  54.145 +            opts.verbose = 0
  54.146 +        elif k in ['-v', '--verbose']:
  54.147 +            opts.verbose = 1
  54.148 +        elif k in ['-n', '--dry-run']:
  54.149 +            opts.dryrun = 1
  54.150 +    reconfigure(opts.interface, opts.bridge)
  54.151 +
  54.152 +if __name__ == '__main__':
  54.153 +    main()
    55.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    55.2 +++ b/tools/xenmgr/setup.py	Fri Jun 11 14:40:53 2004 +0000
    55.3 @@ -0,0 +1,14 @@
    55.4 +
    55.5 +from distutils.core import setup, Extension
    55.6 +
    55.7 +PACKAGE = 'xenmgr'
    55.8 +VERSION = '1.0'
    55.9 +
   55.10 +setup(name            = PACKAGE,
   55.11 +      version         = VERSION,
   55.12 +      description     = 'Xen Management API',
   55.13 +      author          = 'Mike Wray',
   55.14 +      author_email    = 'mike.wray@hp.com',
   55.15 +      packages        = [ PACKAGE, PACKAGE + '.server' ],
   55.16 +      package_dir     = { PACKAGE: 'lib' },
   55.17 +      )
    56.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    56.2 +++ b/tools/xenmgr/xend	Fri Jun 11 14:40:53 2004 +0000
    56.3 @@ -0,0 +1,40 @@
    56.4 +#!/usr/bin/python
    56.5 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    56.6 +
    56.7 +"""Xen management daemon. Lives in /usr/sbin.
    56.8 +   Provides console server and HTTP management api.
    56.9 +
   56.10 +   Run:
   56.11 +
   56.12 +   xend start
   56.13 +
   56.14 +   The daemon is stopped with:
   56.15 +
   56.16 +   xend stop
   56.17 +
   56.18 +   Unfortunately restarting it upsets the channel to dom0 and
   56.19 +   domain management stops working - needs a reboot to fix.
   56.20 +"""
   56.21 +import os
   56.22 +import sys
   56.23 +from xenmgr.server import SrvConsoleServer
   56.24 +
   56.25 +def main():
   56.26 +    daemon = SrvConsoleServer.instance()
   56.27 +    if not sys.argv[1:]:
   56.28 +        print 'usage: %s {start|stop|restart}' % sys.argv[0]
   56.29 +    elif os.fork():
   56.30 +        pid, status = os.wait()
   56.31 +        return status >> 8
   56.32 +    elif sys.argv[1] == 'start':
   56.33 +        return daemon.start()
   56.34 +    elif sys.argv[1] == 'stop':
   56.35 +        return daemon.stop()
   56.36 +    elif sys.argv[1] == 'restart':
   56.37 +        return daemon.stop() or daemon.start()
   56.38 +    else:
   56.39 +        print 'not an option:', sys.argv[1]
   56.40 +    return 1
   56.41 +
   56.42 +if __name__ == '__main__':
   56.43 +    sys.exit(main())
    57.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    57.2 +++ b/tools/xenmgr/xenmgrd	Fri Jun 11 14:40:53 2004 +0000
    57.3 @@ -0,0 +1,10 @@
    57.4 +#!/usr/bin/python
    57.5 +# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>
    57.6 +
    57.7 +"""Xen management daemon. Lives in /usr/sbin.
    57.8 +   Run after running xend to provide http access to the management API.
    57.9 +
   57.10 +   NO LONGER NEEDED.
   57.11 +"""
   57.12 +from xenmgr.server import SrvServer
   57.13 +SrvServer.main()