#!/usr/bin/env python
#===========================================================================
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#============================================================================
# Copyright (C) 2006 International Business Machines Corp.
# Author: Reiner Sailer
#============================================================================
# use 'yum install wxPython' to get wx or download from www.wxpython.org
import sys, time, string
import wx
import wx.lib.buttons as buttons
"""
This program creates a default policy based on names of organizations and departments.
The resulting policy can be refined using the policy generation tool (xensec_gen).
"""

helpprovider = wx.SimpleHelpProvider()
wx.HelpProvider_Set(helpprovider)

ID_CS_START=1000

realm_bmp = None
workload_bmp = None
conflict_bmp = None
realm_icon = None
workload_icon = None

ACM_LABEL_UNLABELED = '__UNLABELED__'

class orgTreeCtrl(wx.TreeCtrl):

    event = None

    def __init__(self, parent, id, pos, size, style, validator, name):
        wx.TreeCtrl.__init__(self, parent, id, pos, size, style,
                             validator, name)
        self.parent = parent
        orgs_root = self.AddRoot(text="Organization / Department")
        self.SetItemBackgroundColour(orgs_root, wx.LIGHT_GREY)


    def LabelExists(self, label, item):
        for i in iterchildren(self.GetItemParent(item)):
            if (self.GetItemText(i) == label) and (i != item):
                return True
        return False


    def _OrgEdt(self, event):
        item = self.event.GetItem()
        self.OrgEdt(item)


    def OrgEdt(self, item):
        oldlabel= self.GetItemText(item)
        #get new name
        dlg = wx.TextEntryDialog(self, "Please enter org/dept name:",
                                 "Naming a Workload",
                                 style=wx.CANCEL | wx.OK | wx.CENTRE | wx.TE_NOHIDESEL)
        dlg.SetValue(oldlabel)
        ret = dlg.ShowModal()
        newlabel = dlg.GetValue()
        dlg.Destroy()
        if (ret == wx.ID_CANCEL) or (newlabel == ''):
            return False

        #now check if the new name is permissible
        if self.LabelExists(newlabel, item):
            dlg = wx.MessageDialog(self, 'Item with name ' + newlabel + ' already exists!',
                                   'Rename', style=wx.OK)
            dlg.ShowModal()
            dlg.Destroy()
            return False

        #all checkspassed, change item and adapt runtime exclusion rules
        self.SetItemText(item, newlabel)
        app.win.LabelReplaceInConflictsets(item, oldlabel, newlabel)
        return True


    def _OrgRAdd(self, event):
        self.OrgRAdd()


    def OrgRAdd(self):
        new = self.AppendItem(self.GetRootItem(), text="")
        self.SetItemBold(new, True)
        self.SetItemImage(new, realm_icon, wx.TreeItemIcon_Normal)
        self.EnsureVisible(new)
        if not self.OrgEdt(new):
            self.Delete(new)


    def _OrgWAdd(self, event):
        item = self.event.GetItem()
        self.OrgWAdd(item)


    def OrgWAdd(self, item):
        new = self.AppendItem(item, text="")
        self.Expand(item)
        self.SetItemImage(new, workload_icon, wx.TreeItemIcon_Normal)
        self.EnsureVisible(new)
        if not self.OrgEdt(new):
            self.Delete(new)


class OrgsPanel(wx.Panel):
    ID_CONSADDBTN = 145
    ID_REALMADDBTN = 144

    def __init__(self, parent, ID):
        global realm_icon, workload_icon

        wx.Panel.__init__(self, parent, -1)

        #create image list
        imagelist = wx.ImageList(16, 17, True)
        #define generic function and use it for all input
        realm_icon = imagelist.Add(realm_bmp)
        workload_icon = imagelist.Add(workload_bmp)

        #left tree control for organizations / workload definitions
        orgshdrbox = wx.StaticBox(self, -1, "")
        orgshdrboxsizer = wx.StaticBoxSizer(orgshdrbox, wx.HORIZONTAL)
        orgshdr = wx.StaticText(self, -1, "Organization / Department Definition",
                                style=wx.ALIGN_CENTER)
        orgshdr.SetHelpText(RealmWorkloadPanelHelp)
        points = orgshdr.GetFont().GetPointSize()  # get the current size
        hdrfont = wx.Font(points + 2, family=wx.DEFAULT,
                          style=wx.FONTSTYLE_NORMAL, weight=wx.BOLD)
        orgshdr.SetFont(hdrfont)
        orgshdr.SetForegroundColour('MEDIUMBLUE')
        orgshdr.SetBackgroundColour('SNOW')
        orgshdrboxsizer.Add(orgshdr, proportion=1, flag=wx.EXPAND | wx.ALL | wx.ALIGN_LEFT, border=5)
        addorgsbutton = wx.Button(self, self.ID_REALMADDBTN, "New Org", style=wx.BU_EXACTFIT)
        addorgsbutton.SetToolTipString("Add A New Organization")
        addorgsbutton.SetHelpText(NewRealmButtonHelp)
        addorgsbutton.SetForegroundColour('MEDIUMBLUE')
        addfont = wx.Font(points, family=wx.DEFAULT,
                          style=wx.FONTSTYLE_NORMAL, weight=wx.BOLD)
        addorgsbutton.SetFont(addfont)
        orgshdrboxsizer.Add(addorgsbutton, proportion=0, flag=wx.EXPAND | wx.ALL | wx.ALIGN_RIGHT, border=0)

        self.orgs = orgTreeCtrl(self, -1,
                                pos=wx.DefaultPosition,
                                size=wx.DefaultSize,
                                style=wx.TR_HAS_BUTTONS | wx.TR_HIDE_ROOT | wx.TR_NO_LINES
                                | wx.TR_MULTIPLE,
                                validator=wx.DefaultValidator,
                                name="orgs")
        self.orgs.AssignImageList(imagelist)
        self.orgs.SetHelpText(RealmWorkloadPanelHelp)

        self.addconsbutton = wx.Button(self, self.ID_CONSADDBTN,
                                       "Create run-time exclusion rule from selection -->",
                                       style=wx.BU_EXACTFIT)
        self.addconsbutton.SetToolTipString("Create New Exclusion rule From Above Workload Selection")
        self.addconsbutton.SetHelpText(CreateRunTimeButtonHelp)
        self.addconsbutton.SetForegroundColour('MEDIUMBLUE')
        addfont = wx.Font(points, family=wx.DEFAULT,
                          style=wx.FONTSTYLE_NORMAL, weight=wx.BOLD)
        self.addconsbutton.SetFont(addfont)
        self.addconsbutton.Bind(wx.EVT_BUTTON, self._AddConflict, id=self.ID_CONSADDBTN)

        orgsvbox = wx.BoxSizer(wx.VERTICAL)
        orgsvbox.Add(orgshdrboxsizer, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)
        orgsvbox.Add(self.orgs, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
        orgsvbox.Add(self.addconsbutton, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)
        self.SetSizer(orgsvbox)
        addorgsbutton.Bind(wx.EVT_BUTTON, self.orgs._OrgRAdd, id= self.ID_REALMADDBTN)


    def _AddConflict(self, event):
        app.win.conspanel._AddNewConflict(event)


class ConsPanel(wx.Panel):
    ID_CONSSELECT = 151
    ID_CONSADD = 152
    ID_CONSRENAME = 153
    ID_CONSDEL = 154
    ID_CONSSELECTSUB= 155

    conflictMAX = ID_CS_START

    def __init__(self, parent, ID):
        self.conflictsets = []
        self.parent = parent
        wx.Panel.__init__(self, parent, -1)
        #header
        conshdrbox = wx.StaticBox(self, -1, "")
        conshdrboxsizer = wx.StaticBoxSizer(conshdrbox, wx.HORIZONTAL)
        conshdr = wx.StaticText(self, -1, "Run-time Exclusion Rules", style=wx.ALIGN_CENTER)
        conshdr.SetHelpText(RunTimeExclusionPanelHelp)
        points = conshdr.GetFont().GetPointSize()  # get the current size
        hdrfont = wx.Font(points + 2, family=wx.DEFAULT,
                          style=wx.FONTSTYLE_NORMAL, weight=wx.BOLD)
        conshdr.SetFont(hdrfont)
        conshdr.SetForegroundColour('ORANGERED')

        #context help button
        ctxHelp = wx.ContextHelpButton(self)
        ctxHelp.SetHelpText("Context Help Button.")
        ctxHelp.SetToolTipString("Context Help: Press this button, then press any other button or panel to get help.")


        conshdrboxsizer.Add(conshdr, proportion=1, flag=wx.EXPAND | wx.ALL | wx.ALIGN_LEFT, border=5)
        conshdrboxsizer.Add(ctxHelp, proportion=0, flag=wx.EXPAND | wx.ALL | wx.ALIGN_RIGHT, border=0)
        #scrolledwindow for all the run-time exclusion rules
        conflictspanel = wx.ScrolledWindow(self, -1, (0,0),
                                           style = wx.FULL_REPAINT_ON_RESIZE |
                                                   wx.VSCROLL )
        conflictspanel.SetVirtualSize((1000, 1000))
        conflictspanel.SetScrollRate(5,5)
        self.conflictsboxsizer = wx.BoxSizer(wx.VERTICAL)

        #self.conflictsboxsizer.Fit(self)
        conflictspanel.SetSizer(self.conflictsboxsizer)
        consvbox = wx.BoxSizer(wx.VERTICAL)
        consvbox.Add(conshdrboxsizer, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)
        consvbox.Add(conflictspanel, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
        self.SetSizer(consvbox)
        self.consvbox = consvbox
        self.conflictspanel=conflictspanel

        self.cmenu = wx.Menu()
        self.cmenu.Append(self.ID_CONSRENAME, "Rename Run-time Exclusion Rule", "Rename Run-time Exclusion Rule")
        self.cmenu.AppendSeparator()
        self.cmenu.Append(self.ID_CONSDEL,    "Delete Run-time Exclusion Rule", "Delete Run-time Exclusion Rule")
        self.Bind(wx.EVT_MENU, self._CSRename, id=self.ID_CONSRENAME)
        self.Bind(wx.EVT_MENU, self._CSDelete, id=self.ID_CONSDEL)


    #Helper methods called from anywhere
    def New(self):
        #delete all run-time exclusion rules
        for i in self.conflictsets:
            i.Disable()
            i.Destroy()
        self.conflictsets = []
        self.conflictsboxsizer.Layout()
        size=self.GetSize()
        self.Fit()
        self.SetSize(size)


    def DelCSById(self, delid):
        #delete CS representation
        delpos, item = self.GetCSBox(delid)
        if item:
            self.DelCSByItem(item)


    def DelCSByItem(self, item):
        #delete CS representation
        self.conflictsets.remove(item)
        exists = self.conflictsboxsizer.Detach(item)
        if exists:
            item.Destroy()
        self.RefreshMe()


    def RefreshMe(self):
        size=self.parent.GetSize()
        self.parent.Fit()
        self.parent.SetSize(size + (1,1))
        self.parent.SetSize(size)


    def GetOrgSelection(self):
        (tree, selection) = GetOrgsSelection()
        if not len(selection):
            dlg = wx.MessageDialog(self, 'You must select first at least one Organization/Department workload!',
                                   'Creating A New Run-time  Rule', wx.OK | wx.ICON_ERROR)
            dlg.ShowModal()
            dlg.Destroy()
            return None,None
        # now rewrite selection (realm.workload extension, check consistency)
        alist = []
        for i in selection:
            if isRealm(i):
                alist.append(tree.GetItemText(i))
            else:
                alist.append(tree.GetItemText(tree.GetItemParent(i))
                            + "." + tree.GetItemText(i))

            if isRealm(i):
                for j in selection:
                    if tree.GetItemParent(j) == i:
                        violation = ("[ " + tree.GetItemText(i) + ", " +
                                     tree.GetItemText(i) + "." + tree.GetItemText(j) + " ]")
                        dlg = wx.MessageDialog(self,
                                               'Invalid Selection ' + violation + '.\n\n' +
                                               'You can only select EITHER an Organization OR specific Department!',
                                   'Creating A New Run-time Exclusion Rule', wx.OK | wx.ICON_ERROR)
                        dlg.ShowModal()
                        dlg.Destroy()
                        return None,None
        return (alist, selection)


    def AddConflict(self, name, types):
        csbox = myCSPanel(self, self.conflictMAX, name, types)
        self.conflictsboxsizer.Add(csbox, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)
        self.conflictsets.append(csbox)
        self.conflictMAX = self.conflictMAX+3
        self.RefreshMe()
        csbox.RefreshMe()


    def GetCSBox(self, id):
        pos = -1
        i = 0
        while self.conflictsboxsizer.GetItem(i):
            item = self.conflictsboxsizer.GetItem(i).GetWindow()
            if ((item.cbmp.GetId() == id) or
                (item.add_selection.GetId() == id) or
                (item.del_selection.GetId() == id)):
                pos = i
                box = item
                break
            i = i +  1
        if pos < 0:
            print "Run-time Exclusion Rule Not Found ERROR!"
            return (None, None)
        else:
            return (pos, box)


    #bind methods
    def _AddNewConflict(self, event):
        # first get the conflicting workload types with current selection
        types, items = self.GetOrgSelection()
        if not types:
            return
        #get name for conflict set
        dlg = wx.TextEntryDialog(
            self, 'Please enter a name for the Run-time Exclusion Rule:', 'Creating A New Run-time Exclusion Rule')
        dlg.SetValue("")
        ret = dlg.ShowModal()
        name = dlg.GetValue()
        dlg.Destroy()
        if ret != wx.ID_OK:
            return
        self.AddConflict(name, types)


    def _OnClick(self, event):
        self.event = event
        app.win.SetStatusText("")
        self.PopupMenu(self.cmenu)


    def _CSRename(self, event):
        delpos, item = self.GetCSBox(self.event.GetId())
        if not item:
            return
        #allow to name the conflict set
        dlg = wx.TextEntryDialog(
            self, 'Please enter a new name for the Conflict Set:', 'Renaming A Run-time Exclusion Rule')
        dlg.SetValue(item.box.GetLabel())
        ret = dlg.ShowModal()
        name = dlg.GetValue()
        dlg.Destroy()
        if ret != wx.ID_OK:
            return
        item.box.SetLabel(name)
        item.box.SetFont(wx.Font(item.GetFont().GetPointSize(), family=wx.DEFAULT,
                                style=wx.FONTSTYLE_NORMAL, weight=wx.BOLD))


    def _CSDelete(self, event):
        delid = self.event.GetId()
        self.DelCSById(delid)


    def _AddOrgSelection(self, event):
        addid = event.GetId()
        addpos, item = self.GetCSBox(addid)
        alist, items = self.GetOrgSelection()
        if not alist:
            return
        existing = []
        for i in range(0, item.clb.GetCount()):
            existing.append(item.clb.GetString(i))

        #now make sure that we don't get realm + workload into the same CS
        for i in items:
            if isRealm(i):
                #ensure no workload of this realm is already in CS
                realm = app.win.orgs.GetItemText(i)
                for j in iterchildren(i):
                    workload = app.win.orgs.GetItemText(j)
                    try:
                        idx = existing.index (realm + "." + workload)
                    except:
                        #ok, does not exist
                        continue
                    #nok, exists already
                    violation = ("[ " + realm + ", " +
                                  realm + "." + workload + " ]")
                    dlg = wx.MessageDialog(self,
                            'Invalid Selection ' + violation + '.\n\n' +
                            'You can only have EITHER an Organization OR a specific Department workload\n' +
                            'in a single Run-time Exclusion Rule',
                            'Adding Orgs/Depts workloads to a Run-time Exclusion Rule',
                            wx.OK | wx.ICON_ERROR)
                    dlg.ShowModal()
                    dlg.Destroy()
                    return

            else:
                #ensure realm of this workload is not in CS
                realm = app.win.orgs.GetItemText(app.win.orgs.GetItemParent(i))
                try:
                    idx = existing.index(realm)
                except:
                    #ok, does not exist
                    continue
                #nok, exists already
                violation = ("[ " + realm + "." + app.win.orgs.GetItemText(i) +
                                 ", " + realm + " ]")
                dlg = wx.MessageDialog(self,
                            'Invalid Selection ' + violation + '.\n\n' +
                            'You can only have EITHER an Organization OR a specific Department workload\n' +
                            'in a single Run-time Exclusion Rule',
                            'Adding Orgs/Depts workloads to a Run-time Exclusion Rule',
                            wx.OK | wx.ICON_ERROR)
                dlg.ShowModal()
                dlg.Destroy()
                return
        #check if any of the selections are already in the conflict set
        overlap=[]
        for l in alist:
            for e in existing:
                if l == e:
                    overlap.append(str(l))
        if len(overlap):
            if len(overlap) == 1:
                message = "Selected item " + str(overlap) +\
                    " is already in the Run-time Exclusion rule and will be ignored.\n\n Continue?"
            else:
                message = "Selected items " + str(overlap) +\
                    " are already in the Run-time Exclusion rule and will be ignored.\n\n Continue?"
            dlg = wx.MessageDialog(self,
                            message, 'Adding Orgs/Depts workloads to a Run-time Exclusion rule',
                            wx.YES | wx.NO | wx.ICON_EXCLAMATION)
            ret = dlg.ShowModal()
            dlg.Destroy()
            if ret != wx.ID_YES:
                return

        for s in alist:
            try:
                existing.index(s)
            except Exception:
                # s not yet in list box, add it
                item.AddTypes([s])
        self.RefreshMe()


    def _DelConSelection(self, event):
        eventid = event.GetId()
        pos, item = self.GetCSBox(eventid)
        idtuple = item.clb.GetSelections()
        idlist = []
        for i in idtuple:
            idlist.append(i)
        #delete reverse, otherwise item mubers get messed up while deleting
        idlist.reverse()
        for i in idlist:
            item.clb.Delete(i)
        item.RefreshMe()
        if item.clb.GetCount() < 2:
            dlg = wx.MessageDialog(self,
                    """Run-time exclusion set has less than two types.\n\n
                    Do you want to delete this rule?""",
                    'Deleting Orgs/Depts workloads from a Run-time Exclusion rule',
                    wx.YES| wx.NO | wx.ICON_QUESTION)
            ret = dlg.ShowModal()
            dlg.Destroy()
            if ret == wx.ID_YES:
                self.DelCSById(eventid)
            return
        else:
            for i in item.clb.GetSelections():
                item.clb.Deselect(i)
        self.RefreshMe()


class myCSPanel(wx.Panel):
    def __init__(self, parent, ID, title, list=[]):
        wx.Panel.__init__(self, parent.conflictspanel, -1)
        self.parent = parent
        cspansizer = wx.BoxSizer(wx.VERTICAL)
        self.box = wx.StaticBox(self, -1, title)
        csboxsizer = wx.StaticBoxSizer(self.box, wx.HORIZONTAL)
        #left: type add/del
        typesizer = wx.BoxSizer(wx.VERTICAL)
        self.add_selection = wx.Button(self, ID+1, "--> Add", style=wx.BU_EXACTFIT)
        self.add_selection.SetToolTipString("Add Workload Selection To Run-time Exclusion rule")
        self.add_selection.SetHelpText(AddToExclusionButtonHelp)
        self.add_selection.SetForegroundColour('MEDIUMBLUE')
        points = self.add_selection.GetFont().GetPointSize()
        addfont = wx.Font(points, family=wx.DEFAULT,
                          style=wx.FONTSTYLE_NORMAL, weight=wx.BOLD)
        self.add_selection.SetFont(addfont)
        self.box.SetFont(addfont)
        typesizer.Add(self.add_selection, proportion = 0, flag = wx.EXPAND | wx.ALL,border=0)
        typesizer.Add((5,5))
        self.del_selection = wx.Button(self, ID+2, "<-- Del", style=wx.BU_EXACTFIT)
        self.del_selection.SetToolTipString("Delete Workload Selection From Run-time Exclusion Rule")
        self.del_selection.SetHelpText(DelFromExclusionButtonHelp)
        self.del_selection.SetForegroundColour('ORANGERED')
        self.del_selection.SetFont(addfont)
        typesizer.Add(self.del_selection, proportion = 0, flag = wx.EXPAND | wx.ALL, border=0)
        csboxsizer.Add(typesizer, proportion = 0, border=0)
        csboxsizer.Add((5,5))
        #middle: types
        self.clb = wx.ListBox(self, id=-1, choices=list,
                              style= wx.LB_MULTIPLE | wx.LB_SORT )
        self.clb.SetHelpText(ExclusionSetHelp)
        csboxsizer.Add(self.clb, proportion=1, flag=wx.EXPAND | wx.ALL, border=0)
        csboxsizer.Add((5,5))
        #right: Conflictset-global ops button
        bmpsizer = wx.BoxSizer(wx.VERTICAL)
        self.cbmp = buttons.GenBitmapButton(self, ID, conflict_bmp, style=wx.BU_EXACTFIT)
        self.cbmp.SetHelpText(ManageExclusionButtonHelp)
        self.cbmp.SetToolTipString("Rename/Delete\nAssociated Run-time Exclusion Rule")
        bmpsizer.Add(self.cbmp, proportion = 0, flag = wx.EXPAND | wx.ALL, border=0)
        csboxsizer.Add(bmpsizer, proportion=0, border=5)
        cspansizer.Add(csboxsizer,  proportion=0, flag=wx.EXPAND | wx.ALL, border=0)
        self.csboxsizer=csboxsizer
        self.cspansizer=cspansizer
        self.SetSizer(cspansizer)
        self.cbmp.Bind(wx.EVT_LEFT_DOWN, parent._OnClick, id=ID)
        self.add_selection.Bind(wx.EVT_BUTTON, parent._AddOrgSelection, id=ID + 1)
        self.del_selection.Bind(wx.EVT_BUTTON, parent._DelConSelection, id=ID + 2)

    # append and delete an item to get rid of
    # the ugly vertical scroll bar on the Listbox on Linux
    def RefreshMe(self):
        x = self.clb.Append(" ")
        app.win.conspanel.RefreshMe()
        self.clb.Delete(x)
        self.Layout()
        app.win.conspanel.Layout()


    def AddTypes(self, list):
        for i in list:
            self.clb.Append(i)
        self.RefreshMe()


    def GetTypes(self):
        alist = []
        for i in range(0, self.clb.GetCount()):
            alist.append(self.clb.GetString(i))
        return alist


    def GetBoxName(self):
        return self.box.GetLabel()


    def Replace(self, oldlabel, newlabel):
        index = self.clb.FindString(oldlabel)
        if index != wx.NOT_FOUND:
            self.clb.SetString(index, newlabel)


    def Delete(self, label):
        index = self.clb.FindString(label)
        if index != wx.NOT_FOUND:
            self.clb.Delete(index)


class myHelpPanel(wx.Panel):
    def __init__(self, parent, ID):
        wx.Panel.__init__(self, parent, -1)


class ezFrame(wx.Frame):

    ID_ABOUT  = 101
    ID_NEW    = 102
    ID_OPEN   = 103
    ID_SAVE   = 104
    ID_SAVEAS = 105
    ID_EXIT   = 106
    ID_HELP   = 107

    ID_ITRENAME = 111
    ID_ITADD    = 112
    ID_ITDEL    = 113

    ID_COLLAPSEALL = 121
    ID_EXPANDALL = 122
    ID_SORTALL = 123

    ID_TRANSLATE = 131

    ID_ORGEDT = 141
    ID_ORGADD = 142
    ID_ORGDEL = 143

    def __init__(self, parent, ID, title):
        global realm_bmp, workload_bmp, conflict_bmp

        wx.Frame.__init__(self, parent, ID, title,
                         wx.DefaultPosition,
                         wx.Size(700,450)
                          )

        realm_bmp = GetIconBitmap('Organization')
        workload_bmp = GetIconBitmap('Department')
        conflict_bmp = GetIconBitmap('Conflict')
        self.SetHelpText(GetHelp)
        self.orgfilename = None
        self.CreateStatusBar()
        self.SetStatusText("")
        self.bkg = wx.Panel(self)

        self.orgswin =  wx.SashLayoutWindow(
            self.bkg, -1, wx.DefaultPosition, (300, 150),wx.SW_3DSASH | wx.SW_BORDER)

        self.orgswin.SetDefaultSize((300,150))
        self.orgswin.SetOrientation(wx.LAYOUT_VERTICAL)
        self.orgswin.SetAlignment(wx.LAYOUT_LEFT)
        self.orgspanel = OrgsPanel(self.orgswin, -1)
        self.orgs = self.orgspanel.orgs

        self.realm_menu = wx.Menu()
        self.realm_menu.Append(self.ID_ORGADD, "Add Department\tctrl-a", "Add Department Workload")
        self.realm_menu.AppendSeparator()
        self.realm_menu.AppendSeparator()
        self.realm_menu.Append(self.ID_ORGEDT, "Rename Organization\tctrl-r", "Rename Organization Workload")
        self.realm_menu.Append(self.ID_ORGDEL, "Delete Organization\tctrl-d", "Delete Organization Workload")
        self.realm_menu.Bind(wx.EVT_MENU, self.orgs._OrgEdt, id= self.ID_ORGEDT)
        self.realm_menu.Bind(wx.EVT_MENU, self.orgs._OrgWAdd, id= self.ID_ORGADD)
        self.realm_menu.Bind(wx.EVT_MENU, self._ItemDel, id=self.ID_ORGDEL)

        self.workload_menu = wx.Menu()
        self.workload_menu.Append(self.ID_ORGEDT, "Rename Department\tctrl-r", "Rename Department Workload")
        self.workload_menu.Append(self.ID_ORGDEL, "Delete Department\tctrl-d", "Delete Department Workload")
        self.workload_menu.Bind(wx.EVT_MENU, self.orgs._OrgEdt, id= self.ID_ORGEDT)
        self.workload_menu.Bind(wx.EVT_MENU, self._ItemDel, id=self.ID_ORGDEL)

        self.orgs.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, self._OrgRightClick)
        self.orgs.Bind(wx.EVT_TREE_SEL_CHANGED, self._OrgSelectionChanged)

        self.conswin =  wx.SashLayoutWindow(
            self.bkg, -1, wx.DefaultPosition, (300, 150),
            #wx.NO_BORDER | wx.SW_3D
            wx.SW_3DSASH | wx.SW_BORDER
            )
        self.conswin.SetDefaultSize((300,150))
        self.conswin.SetOrientation(wx.LAYOUT_VERTICAL)
        self.conswin.SetAlignment(wx.LAYOUT_RIGHT)
        self.conswin.SetSashVisible(wx.SASH_LEFT, True)
        self.conswin.SetSashVisible(wx.SASH_RIGHT, False)

        #right tree control for non-concurrent workload execution
        self.conspanel = ConsPanel(self.conswin, -1)
        self.conspanel.RefreshMe()
        self.bkg.Bind(wx.EVT_SASH_DRAGGED_RANGE, self._OnSashDrag, id=self.conswin.GetId(),
                      id2=self.conswin.GetId())
        self.bkg.Bind(wx.EVT_SIZE, self._OnSize)

        # Main Menu
        #      -File
        fmenu = wx.Menu()
        fmenu.Append(self.ID_OPEN, "Open Workload Definition...\tctrl-o", "Open current workload definition")
        fmenu.Append(self.ID_SAVE, "Save Workload Definition\tctrl-s", "Save workload defintion")
        fmenu.Append(self.ID_SAVEAS, "Save Workload Defintion as...\talt-s", "Save into new file")
        fmenu.AppendSeparator()
        fmenu.Append(self.ID_TRANSLATE, "Save as Xen ACM Security Policy ...\talt-t", "Create Xen ACM security policy")
        fmenu.AppendSeparator()
        fmenu.Append(self.ID_NEW, "New\tctrl-n", "Create a new oganization definition")
        fmenu.AppendSeparator()
        fmenu.Append(self.ID_EXIT, "Exit\tctrl-x", "Terminate the program")
        self.fmenu = fmenu

        #      -Edit
        emenu = wx.Menu()
        emenu.Append(self.ID_ITRENAME, "Rename\tctrl-r", "Rename Selected Organization/Department")
        emenu.Append(self.ID_ITADD, "Add\tctrl-a", "Add Child to Selected Organization/Department")
        emenu.Append(self.ID_ITDEL, "Delete\tctrl-d", "Delete Selected Organization/Department")
        self.emenu = emenu
        #      -Help
        hmenu = wx.Menu()
        hmenu.Append(self.ID_HELP, "Step-By-Step Help\tctrl-h", "More information about this program")
        hmenu.Append(self.ID_ABOUT, "About", "More information about this program")
        self.hmenu = hmenu

        #      -View
        vmenu = wx.Menu()
        vmenu.Append(self.ID_SORTALL, "Sort All", "Sort Entries In All Trees")
        vmenu.Append(self.ID_COLLAPSEALL, "Collapse All\tctrl-c", "Collapse All Trees")
        vmenu.Append(self.ID_EXPANDALL, "Expand All\tctrl-e", "Expand All Trees")
        self.vmenu = vmenu

        menuBar = wx.MenuBar()
        menuBar.Append(fmenu, "&File");
        menuBar.Append(emenu, "&Edit");
        menuBar.Append(vmenu, "&View");
        menuBar.Append(hmenu, "&Help");

        self.SetMenuBar(menuBar)

        self.Bind(wx.EVT_MENU, self._OpenSpec,  id=self.ID_OPEN)
        self.Bind(wx.EVT_MENU, self._SaveSpec,  id=self.ID_SAVE)
        self.Bind(wx.EVT_MENU, self._SaveAsSpec,id=self.ID_SAVEAS)
        self.Bind(wx.EVT_MENU, self._NewSpec,   id=self.ID_NEW)
        self.Bind(wx.EVT_MENU, self._TimeToQuit,id=self.ID_EXIT)
        self.Bind(wx.EVT_MENU, self._TranslateSpec, id=self.ID_TRANSLATE)

        self.Bind(wx.EVT_MENU, self._ItemRename, id=self.ID_ITRENAME)
        self.Bind(wx.EVT_MENU, self._ItemAdd,    id=self.ID_ITADD)
        self.Bind(wx.EVT_MENU, self._ItemDel,    id=self.ID_ITDEL)

        self.Bind(wx.EVT_MENU, self._SortAll,    id=self.ID_SORTALL)
        self.Bind(wx.EVT_MENU, self._CollapseAll,id=self.ID_COLLAPSEALL)
        self.Bind(wx.EVT_MENU, self._ExpandAll,  id=self.ID_EXPANDALL)

        self.Bind(wx.EVT_MENU, self._Help, id=self.ID_HELP)
        self.Bind(wx.EVT_MENU, self._OnAbout, id=self.ID_ABOUT)
        self.Bind(wx.EVT_CLOSE, self._TimeToQuit)


    def RefreshMe(self):
        size=self.GetSize()
        self.Fit()
        self.SetSize(size)

    #helper methods
    def Load(self, file):
        self.orgfilename = file
        dictname = 'ezpolicy'
        d = {}
        # read in the config file
        globs = {}
        locs = {}
        execfile(file, globs, locs)
        for (k, v) in locs.items():
            if k == dictname:
                d = v
                break
        dict2org(d)
        self.orgspanel.orgs.UnselectAll()
        self.SetTitle("ezPolicy: " + self.orgfilename)
        self._ExpandAll(None)


    def Save(self, file):
        dictname = 'ezpolicy'
        d = org2dict()
        fd = open(file, "w")
        fd.write(dictname + " = ")
        fd.write(str(d))
        fd.close()


    def New(self):
        self.orgspanel.orgs.DeleteChildren(self.orgspanel.orgs.GetRootItem())
        self.conspanel.New()


    def LabelReplaceInConflictsets(self, item, oldlabel, newlabel):
        if isRealm(item):
            replace = [[ oldlabel, newlabel]]
            for i in iterchildren(item):
                replace.append([(oldlabel + "." + self.orgs.GetItemText(i)),
                                (newlabel + "." + self.orgs.GetItemText(i))])
        else:
            parent = self.orgs.GetItemParent(item)
            replace =   [
                            [(self.orgs.GetItemText(parent) + "." + oldlabel),
                             (self.orgs.GetItemText(parent) + "." + newlabel)]
                        ]
        for r in replace:
            for i in self.conspanel.conflictsets:
                if r[0] in i.GetTypes():
                    i.Replace(r[0], r[1])


    def OrgDelItem(self, item):
        label = self.orgs.GetItemText(item)
        if isRealm(item):
            delset = [label]
            for i in iterchildren(item):
                delset.append(label + "." + self.orgs.GetItemText(i))
        else:
            parent = self.orgs.GetItemParent(item)
            delset = [self.orgs.GetItemText(parent) + "." + label]
        for i in self.conspanel.conflictsets:
            for l in delset:
                i.Delete(l)
        #need to run in reverse order when deleting items
        rev = []
        for i in self.conspanel.conflictsets:
            rev.append(i)
        rev.reverse()
        for i in rev:
            if len(i.GetTypes()) < 1:
                self.conspanel.DelCSByItem(i)
        self.orgs.Delete(item)


    def _OnSashDrag(self, event):
        if event.GetDragStatus() == wx.SASH_STATUS_OUT_OF_RANGE:
            return
        w = event.GetEventObject()
        if w is self.conswin:
            self.conswin.SetDefaultSize((event.GetDragRect().width, 1000))
        wx.LayoutAlgorithm().LayoutWindow(self.bkg, self.orgswin)
        self.RefreshMe()


    def _OnSize(self, event):
        wx.LayoutAlgorithm().LayoutWindow(self.bkg, self.orgswin)


    def _OrgSelectionChanged(self, event):
        self.orgs.event = event
        item = self.orgs.event.GetItem()
        if not item.IsOk() or not self.orgs.IsSelected(item):
            self.emenu.Enable(self.ID_ITRENAME, False)
            self.emenu.Enable(self.ID_ITADD, False)
            self.emenu.Enable(self.ID_ITDEL, False)
            return
        self.SetStatusText("")
        #enable/disable edit menu functions
        if isRealm(item):
            self.emenu.Enable(self.ID_ITRENAME, True)
            self.emenu.Enable(self.ID_ITADD, True)
            self.emenu.Enable(self.ID_ITDEL, True)
        elif isWorkload(item):
            self.emenu.Enable(self.ID_ITRENAME, True)
            self.emenu.Enable(self.ID_ITADD, False)
            self.emenu.Enable(self.ID_ITDEL, True)
        if len(self.orgs.GetSelections()) > 1:
            self.emenu.Enable(self.ID_ITRENAME, False)
            self.emenu.Enable(self.ID_ITADD, False)


    def _OrgRightClick(self, event):
        self.SetStatusText("")
        self.orgs.event = event
        item = self.orgs.event.GetItem()
        #del not permitted on root items
        if isWorkload(item):
            self.workload_menu.Enable(self.ID_ORGDEL, True)
            self.workload_menu.Enable(self.ID_ORGEDT, True)
            if len(self.orgs.GetSelections()) > 1:
                self.workload_menu.Enable(self.ID_ORGEDT, False)
            self.PopupMenu(self.workload_menu)
        else:
            self.realm_menu.Enable(self.ID_ORGDEL, True)
            self.realm_menu.Enable(self.ID_ORGEDT, True)
            self.realm_menu.Enable(self.ID_ORGADD, True)
            if len(self.orgs.GetSelections()) > 1 or \
               ACM_LABEL_UNLABELED == self.orgs.GetItemText(item):
                self.realm_menu.Enable(self.ID_ORGEDT, False)
                self.realm_menu.Enable(self.ID_ORGADD, False)
            self.PopupMenu(self.realm_menu)


    def _OpenSpec(self, event):
        filediag = wx.FileDialog(self, defaultFile="myspec.wld",
                                wildcard="*.wld", style=wx.OPEN,
                                message="Select Workload Definition file name")
        ret = filediag.ShowModal()
        name = filediag.GetPath()
        filediag.Destroy()
        if ret not in [wx.ID_OK]:
            return
        self.orgfilename = name
        self.Load(self.orgfilename)
        self.SetTitle("ezPolicy: " + self.orgfilename)


    def _SaveSpec(self, event):
        if not self.orgfilename:
            filediag = wx.FileDialog(self, defaultFile="myspec.wld",
                                    wildcard="*.wld", style=wx.SAVE | wx.OVERWRITE_PROMPT,
                                    message="Select Workload Definition file name")
            ret = filediag.ShowModal()
            name = filediag.GetPath()
            filediag.Destroy()
            if ret not in [wx.ID_OK]:
                return
            self.orgfilename = name
        self.Save(self.orgfilename)
        self.SetTitle("ezPolicy: " + self.orgfilename)


    def _SaveAsSpec(self, event):
        if not self.orgfilename:
            self.orgfilename = "DEFAULT.wld"
        filediag = wx.FileDialog(self, defaultFile=self.orgfilename,
                                wildcard="*.wld", style=wx.SAVE | wx.OVERWRITE_PROMPT,
                                message="Select Workload Definition file name")
        ret = filediag.ShowModal()
        name = filediag.GetPath()
        filediag.Destroy()
        if ret not in [wx.ID_OK]:
            return
        self.orgfilename = name
        self.Save(self.orgfilename)
        self.SetTitle("ezPolicy: " + self.orgfilename)


    def _NewSpec(self, event):
        self.orgfilename = None
        #reset trees etc
        self.New()
        self.SetTitle("ezPolicy: *New File*")


    def _TranslateSpec(self, event):
        policyname = transInfo()
        if not policyname:
            return
        path="/etc/xen/acm-security/policies/"
        nameparts=string.split(policyname, ".")
        if len(nameparts) > 1:
            path = path + "/".join(nameparts[0:len(nameparts)-1])
        deffile = nameparts[len(nameparts) - 1] + "-security_policy.xml"
        filediag = wx.FileDialog(self, defaultDir=path, defaultFile=deffile,
                                wildcard="*.xml", message="Select Policy File Name",
                                style=wx.SAVE | wx.OVERWRITE_PROMPT)
        ret = filediag.ShowModal()
        filename = filediag.GetPath()
        filediag.Destroy()
        if ret not in [wx.ID_OK]:
            return
        #translate data into default policy
        timestamp = time.asctime()
        d = org2dict()
        types = []
        for i in d['orgs']:
            types.append(str(i[0]))
            for j in i[1]:
                types.append(str(i[0]) + "." + str(j))
        f = open(filename, "w")
        printPolicyHeader (f, policyname, timestamp)
        printPolicy(f, types, d['cons'])
        printLabels(f, d, types)#, d['cons'])
        printTrailer(f)
        f.close()


    def _ItemRename(self, event):
        #ensure only 1 item is selected
        sels = self.orgs.GetSelections()
        if len(sels) != 1:
            return
        self.orgs.OrgEdt(sels[0])


    def _ItemAdd(self, event):
        #ensure only 1 item is selected + add figure
        sels = self.orgs.GetSelections()
        if len(sels) != 1:
            return
        self.orgs.OrgWAdd(sels[0])


    def _ItemDel(self, event):
        sels = self.orgs.GetSelections()
        for i in sels:
            self.OrgDelItem(i)


    def _CollapseAll(self, event):
        for i in iterchildren(self.orgs.GetRootItem()):
            self.orgs.Collapse(i)


    def _ExpandAll(self, event):
        for i in iterchildren(self.orgs.GetRootItem()):
            self.orgs.Expand(i)


    def _SortAll(self, event):
        #would be nice to also sort the organizations
        for i in iterchildren(self.orgs.GetRootItem()):
            if self.orgs.GetChildrenCount(i) > 0:
                self.orgs.SortChildren(i)


    def _OnAbout(self, event):
        dlg = wx.MessageDialog(self,
                               "This program helps you to define the structure\n"
                               "of organizations and their departments.\n\n"
                               "It translates this \'Workload Definition\' into\n"
                               "a simple workload protection policy for the\n"
                               "Xen Access Control Module.\n\n\n"
                               "Copyright (c) 2006: IBM Corporation\n"
                               "Author:\nReiner Sailer <sailer@us.ibm.com>",
                              "About Me", wx.OK | wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()


    def _Help(self, event):
        hpopup = wx.Frame(self,-1, "HELP: Creating a Xen Security Policy in 3 Steps" )
        HelpHtmlWindow(hpopup, -1)
        hpopup.SetSize((650,650))
        hpopup.Show(True)


    def _TimeToQuit(self, event):
        self.Bind(wx.EVT_CLOSE, None)
        self.orgs.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, None)
        self.orgs.Bind(wx.EVT_TREE_SEL_CHANGED, None)
        self.Close(True)


class ezApp(wx.App):

    def OnInit(self):
        self.win = ezFrame(None, -1, title="EZ Workload Protection Policy Tool")
        self.win.Show(True)
        self.SetTopWindow(self.win)
        return True


    def Load(self, file):
        self.win.Load(file)


    def New(self):
        self.win.New()


def isRealm(it):
    if not it:
        return False
    return (app.win.orgspanel.orgs.GetItemParent(it) == app.win.orgspanel.orgs.GetRootItem())


def isWorkload(it):
    if not it or not app.win.orgs.GetItemParent(it):
        return False
    return (app.win.orgspanel.orgs.GetItemParent(app.win.orgspanel.orgs.GetItemParent(it))
            == app.win.orgspanel.orgs.GetRootItem())


def GetOrgsSelection():
        return (app.win.orgspanel.orgs, app.win.orgspanel.orgs.GetSelections())


def transInfo():
    info = wx.TextEntryDialog(app.win, message="POLICYNAME",
                              caption="Translate: Creating The Xen/ACM Policy")
    ret = info.ShowModal()
    name = info.GetValue()
    info.Destroy()
    if ret in [wx.ID_OK]:
        return name
    return None


def iterchildren(node):
    cid, citem = app.win.orgspanel.orgs.GetFirstChild(node)
    while cid.IsOk():
        yield cid
        cid, citem = app.win.orgspanel.orgs.GetNextChild(node, citem)


def dict2org(d):
    # release old structure
    app.New()
    # fill them with dict content
    for i in d['orgs']:
        orgnode = app.win.orgspanel.orgs.AppendItem(app.win.orgspanel.orgs.GetRootItem(), text=i[0])
        app.win.orgspanel.orgs.SetItemBold(orgnode, True)
        app.win.orgspanel.orgs.SetItemImage(orgnode, realm_icon, wx.TreeItemIcon_Normal)
        for j in i[1]:
            wlnode = app.win.orgspanel.orgs.AppendItem(orgnode, text=j)
            app.win.orgspanel.orgs.SetItemImage(wlnode, workload_icon, wx.TreeItemIcon_Normal)
    for i in d['cons']:
        app.win.conspanel.AddConflict(i[0], i[1])


def org2dict():
    global app
    dic = {}
    o= []
    for i in iterchildren(app.win.orgs.GetRootItem()):
        d = []
        for j in iterchildren(i):
            d.append(
                  str(app.win.orgspanel.orgs.GetItemText(j).encode("utf-8")))
        o.append([str(app.win.orgspanel.orgs.GetItemText(i).encode("utf-8")),
                 d])
    dic['orgs'] = o
    c=[]
    for i in app.win.conspanel.conflictsets:
        c.append([i.GetBoxName() , i.GetTypes()])
    dic['cons'] = c
    return dic


def dict_read(dictname, filename):
    """Loads <filename> and returns the dictionary named <dictname> from
       the file.
    """
    dic = {}

    # read in the config file
    globs = {}
    locs = {}
    execfile(filename, globs, locs)

    for (k, v) in locs.items():
        if k == dictname:
            dic = v
            break
    return dic

#==================== Policy Generation/Translation functions

def printPolicyHeader (fd, policyname, timestamp, version="1.0"):
    fd.write( """<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<!-- Auto-generated by ezPolicy        -->
<SecurityPolicyDefinition xmlns=\"http://www.ibm.com\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.ibm.com ../../security_policy.xsd \">
    <PolicyHeader>
        <PolicyName>%s</PolicyName>
        <Date>%s</Date>
        <Version>%s</Version>
    </PolicyHeader>
""" % (policyname, timestamp, version))



def printPolicy(fd, types, cons):
    fd.write("""
    <SimpleTypeEnforcement>
        <SimpleTypeEnforcementTypes>
            <Type>SystemManagement</Type>\n""")

    # add dynamically created type definitions org.dept
    for i in types:
        fd.write("""            <Type>%s</Type>\n""" % i)

    fd.write("""        </SimpleTypeEnforcementTypes>
    </SimpleTypeEnforcement>

    <ChineseWall priority="PrimaryPolicyComponent">
        <ChineseWallTypes>
            <Type>SystemManagement</Type>\n""")

    #add dinamically created cw types
    for i in types:
        fd.write("""            <Type>%s</Type>\n""" % i)

    fd.write("""        </ChineseWallTypes>\n\n""")

    if len(cons):
        fd.write("""        <ConflictSets>\n""")
        for i in cons:
            if len(i[1]) < 2:
                print "Ignoring Run-time exclusion set %s (less than 2 types}" % i[0]
                continue
            #name is optional but must be set
            if i[0]:
                rer_name = i[0]
            else:
                rer_name = "RER"
            fd.write("""            <Conflict name=\"""" +
                     rer_name.encode("utf-8") + """\">\n""")
            for j in i[1]:
                typ = j.encode("utf-8")
                fd.write("""                <Type>%s</Type>\n""" % typ)
            fd.write("""            </Conflict>\n""")
        fd.write("""       </ConflictSets>\n""")

    fd.write("""    </ChineseWall>\n\n""")



def printLabels(fd, d, types): #, cons):
    fd.write( """    <SecurityLabelTemplate>
        <SubjectLabels bootstrap=\"SystemManagement\">""")

    # create default boot label for dom0
    fd.write("""\n            <VirtualMachineLabel>
                <Name>SystemManagement</Name>
                <SimpleTypeEnforcementTypes>
                    <Type>SystemManagement</Type>\n""")
    # add dynamically created type definitions org.dept
    for i in types:
        fd.write("""                    <Type>%s</Type>\n""" % i)

    fd.write("""                </SimpleTypeEnforcementTypes>
                <ChineseWallTypes>
                    <Type>SystemManagement</Type>
                </ChineseWallTypes>
            </VirtualMachineLabel>\n""")

    # create one Udom label for each type ste type
    for i in d['orgs']:
        organization = i[0]
        fd.write("""\n            <VirtualMachineLabel>
                <Name>%s</Name>
                <SimpleTypeEnforcementTypes>
                    <Type>%s</Type>
                </SimpleTypeEnforcementTypes>
                <ChineseWallTypes>
                    <Type>%s</Type>
                </ChineseWallTypes>
            </VirtualMachineLabel>\n""" % (organization, organization, organization))
        for j in i[1]:
            workload = organization + "." + j
            fd.write("""\n            <VirtualMachineLabel>
                <Name>%s</Name>
                <SimpleTypeEnforcementTypes>
                    <Type>%s</Type>
                </SimpleTypeEnforcementTypes>
                <ChineseWallTypes>
                    <Type>%s</Type>
                    <Type>%s</Type>
                </ChineseWallTypes>
            </VirtualMachineLabel>\n""" % (workload, workload, organization , workload))

    fd.write("""        </SubjectLabels>\n\n""")

    #create resource labels for each type
    fd.write("""        <ObjectLabels>""")
    for i in ['SystemManagement'] + types:
        fd.write("""\n            <ResourceLabel>
                <Name>%s</Name>
                <SimpleTypeEnforcementTypes>
                    <Type>%s</Type>
                </SimpleTypeEnforcementTypes>
            </ResourceLabel>\n""" % (i, i))
    fd.write("""        </ObjectLabels>
    </SecurityLabelTemplate>\n""")

def printTrailer(fd):
    fd.write( """</SecurityPolicyDefinition>\n""")

#============== the icons/bitmaps ======================================
# to ensure the program runs anywhere, we include the buttons right here
# while this makes the file even bigger, it also makes it easier to use
import cStringIO

def GetIconBitmap(name):
    return wx.BitmapFromImage(GetIconImage(name))

def GetIconImage(name):
    if name == 'Organization':
        iostream = cStringIO.StringIO(GetOrganizationIconData())
    elif name == 'Department':
        iostream = cStringIO.StringIO(GetDepartmentIconData())
    elif name == 'Conflict':
        iostream = cStringIO.StringIO(GetConflictIconData())
    else:
        sys.exit("UNKNOWN ICON NAME")
    return wx.ImageFromStream(iostream)

def GetOrganizationIconData():
    return \
'\x89PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\
\x00\x00\x00\x10\x00\x00\x00\x11\x08\x02\x00\x00\x00\x5b\xcd\xbb\
\x93\x00\x00\x00\x03\x73\x42\x49\x54\x08\x08\x08\xdb\xe1\x4f\xe0\
\x00\x00\x02\x7b\x49\x44\x41\x54\x28\x91\x5d\xd1\xcb\x4f\x13\x51\
\x14\x06\xf0\x73\x1f\x74\x3a\x33\x9d\x96\x87\x0a\x14\x30\x3c\xd4\
\x60\x34\xf1\xb1\x70\xa5\x26\x2e\xfc\x87\x4d\xdc\x18\x17\x26\x08\
\x26\x44\x01\xc1\x07\x10\x52\x1e\x96\xb6\x94\x4a\x87\x0e\x33\x73\
\xef\xdc\x7b\xcf\x71\x01\x31\x81\x6f\x73\x36\xe7\xb7\xf8\xf2\x31\
\x22\x82\xab\x50\x51\x68\xa5\xd2\x6e\x77\xbf\xdd\xf8\x36\x52\x1b\
\x5f\x78\xfc\xc6\x0f\x6b\x70\x3d\xf2\xea\x97\x28\x8e\xbb\xfd\x7e\
\xd7\xb9\xb4\x3e\xe9\xe3\x99\x1d\x34\x3f\x34\xb9\xaa\x2f\xbe\x0d\
\x2a\xa3\x8c\xb1\xff\x80\x5f\x1e\x63\x4c\x9a\x1e\x23\xaa\x24\xd1\
\x8c\x91\xe0\xae\x04\xb1\xed\x7e\x6a\xff\x7e\x7f\x11\xb7\x01\xe8\
\x26\x90\x52\x02\x98\x30\xac\xf8\x7e\x95\x88\x13\x5a\x0e\x4e\xe0\
\xb9\xe9\x6f\xf5\xbb\x87\x5a\x17\x37\x01\xe7\x1c\x00\x38\x37\x9e\
\x87\x9c\x91\xb3\xce\x21\x2f\xc8\x4b\xac\xec\xf5\xf6\x76\xd7\xdf\
\xa9\x6c\x70\xad\x03\x00\x30\xc6\x6b\x35\x19\x86\x5c\x48\x42\x59\
\x71\xd1\x3d\x88\x26\x82\x68\x8a\xf4\xa0\x68\x7f\x69\xed\xc0\x9d\
\xb9\xd7\x41\xf5\xf6\x15\x50\x2a\x07\x60\xe5\xb2\x04\x00\x6b\x1d\
\x56\x67\x71\x68\xbc\x67\x43\xe3\xa2\x49\x8c\xcb\x10\xe7\xad\xa5\
\x53\x80\x5b\xb3\xaf\xa4\x52\x79\x9e\x0f\x8c\x4d\x01\xdc\x25\xb6\
\x08\x27\x38\xaa\xb9\x3b\x4a\xb4\x13\x30\x02\x69\xc0\x1c\xc7\x9e\
\xea\x2c\x1f\x1b\x23\x9b\xad\x46\xaa\xce\x53\x60\x7e\x09\xa7\x2e\
\x81\xc3\xf6\x05\x58\xc7\x12\x2c\x45\x1e\x17\x45\xce\x19\x32\x42\
\x61\xbb\x67\xad\x75\x79\xd0\x69\x9f\x23\x0e\xc0\x1f\x2e\xb3\x67\
\x00\x00\x80\x04\x85\x25\x72\x56\x7a\xa1\xc7\x32\x61\x33\xb8\x1a\
\x97\xca\xc1\xa8\x74\xa2\xd2\xd3\x8a\x0b\xc8\x0c\x68\xa5\x8c\xb1\
\x8e\x0d\x21\x22\x3a\xc7\x3c\xe9\x51\x21\x51\x01\x21\x00\x38\xe4\
\x95\xb1\xfb\x7c\xb8\x12\x0a\x00\xb2\x46\x19\x6c\xfd\x39\xdc\xda\
\xda\x56\xca\x5c\x6e\x6f\xb4\x4e\xe2\x93\xbf\x49\xac\x8d\x23\x00\
\xc7\x82\x70\x64\x5a\xd6\xc2\x00\x6d\x47\x08\x40\x12\x8d\x9d\x5f\
\x5f\x77\xe2\xdb\x33\x73\x51\x89\x98\x60\x71\xaf\xf9\xf3\x70\xa5\
\x99\x1c\x3c\x19\xe3\xf5\x9a\x57\x1d\x1e\xf5\x82\x31\x59\xe8\x84\
\x9b\x6c\x38\x08\x98\xc7\xb2\x76\x7a\xd2\xcf\x38\xc0\xf3\x49\xe6\
\x97\x82\xc1\xc9\xd2\x86\x5b\xdf\x3f\x75\x8d\x01\x3d\xb9\x55\x79\
\x51\xf2\x26\x84\x2f\x3f\xaf\x7d\x0c\xfd\xe0\xe9\xdd\xa7\xbe\x70\
\xdb\x1d\x1f\x31\x16\x9c\xcd\x4f\x8d\x29\xad\x3b\x71\x13\x88\x72\
\x8d\x22\xa2\x8d\x63\xdd\xef\x37\xa2\xf9\x16\xdf\x6d\x6f\x4a\x91\
\xf9\x43\xae\x1a\xf9\x82\x0b\x21\xf8\x45\x9a\x69\x5d\x74\xba\xa7\
\x44\x90\xb7\x1c\x9d\x1b\x8c\x2d\xa5\xf4\xeb\xa8\xb9\x77\xb4\x2f\
\x1f\xd5\x17\xbf\x6f\xad\x2d\xaf\xad\x3e\x9c\x78\x50\xaf\x08\xa5\
\xcc\xee\xee\xfe\x4e\x63\x73\xe5\xc7\xea\x41\xe3\xf8\x0e\x8a\x97\
\xf7\x66\x92\x3c\xa9\x4f\x4f\x64\xa5\xb9\x87\x0b\x8b\xff\x00\x63\
\xce\x84\xe6\xf7\x5b\x7e\xce\x00\x00\x00\x00\x49\x45\x4e\x44\xae\
\x42\x60\x82'

def GetDepartmentIconData():
    return \
'\x89PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\
\x00\x00\x00\x10\x00\x00\x00\x11\x08\x06\x00\x00\x00\xd4\xaf\x2c\
\xc4\x00\x00\x00\x04\x73\x42\x49\x54\x08\x08\x08\x08\x7c\x08\x64\
\x88\x00\x00\x01\x52\x49\x44\x41\x54\x38\x8d\xd5\x92\x3d\x4b\x42\
\x61\x18\x86\xaf\xf3\xfa\xfa\x81\xa9\x58\x48\x60\x08\x49\xd2\x26\
\xb4\x37\x4a\x14\x6d\x6d\x42\x42\x7f\x20\x68\xae\x31\x28\xff\x85\
\x83\xd0\x90\x05\x0d\x6d\x0d\xd2\x2a\x89\x24\x48\xb8\x85\x49\x1a\
\x48\x87\xd4\xca\x93\xbe\xd4\x69\x38\x39\x1c\xa8\x34\x1a\xa2\x7b\
\xbb\x79\xb8\xaf\x87\xe7\x43\x0b\x2f\x6c\xad\x05\x23\x4b\x39\x4d\
\x38\x5d\xe6\xdb\x80\x9b\xab\xd3\x7a\xaf\x96\x99\x65\x4c\xc9\xfb\
\x97\xd9\xdc\x43\xb3\xef\x82\x3e\xaf\xc6\x2d\x4a\x9b\x33\xc7\x0d\
\x03\x48\x25\xa3\x4e\x25\x86\x0d\x0d\xbc\x8e\x8e\xff\x28\x95\x3a\
\x70\x08\x21\x01\x0e\xcb\xe5\x5a\xb6\x52\xd9\xfe\x12\x60\x73\xa6\
\x62\x7f\xae\x3a\x15\xf5\xf8\x52\x00\x8d\x6e\x97\xc5\x40\xe0\x32\
\x0b\xdb\x00\x3e\x9f\xf0\xa4\xd3\x33\x9b\x5e\xaf\x70\x01\xe4\xf3\
\x9d\xb6\x1d\xf0\xd6\x67\x3d\xe4\x60\xfa\xc3\xb6\x0d\x03\xb7\x10\
\xc3\xaa\xd8\xd9\x99\x3c\x49\x24\x3c\xab\x00\xdd\xae\xc2\x30\x1e\
\xaf\xed\x80\xef\xe5\x4e\x26\xf5\x95\x58\x4c\x07\xa0\x50\x80\x60\
\x10\xc4\x88\xd0\x48\xfd\x1a\x30\x72\x84\x62\x24\x12\x9b\xdf\xdd\
\x3d\x33\x95\x12\x26\x7b\xda\x8f\x00\xe7\x42\x70\x1c\x8f\x07\x34\
\x29\x97\x91\x12\xd0\x00\xfb\x9b\x7c\x0b\xd0\xc3\x61\x5a\xa1\x90\
\x65\x06\x03\xcc\x4f\x5e\xec\xef\x97\xf8\xcf\x01\x4f\x4f\xd4\x25\
\xbd\xea\x05\x4a\xb7\xee\xdb\xab\x3e\x17\x5a\xad\x89\xa0\xdb\x0d\
\x40\x43\x08\x0d\xbf\xdf\xda\xbd\x52\x14\x8b\x26\x77\x4d\x2b\x5c\
\x2a\xa1\x67\x32\x6c\xbc\x03\x17\xdb\x6e\x97\x68\x69\xf7\x4f\x00\
\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82'

def GetConflictIconData():
    return \
'\x89PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\
\x00\x00\x00\x10\x00\x00\x00\x10\x08\x02\x00\x00\x00\x90\x91\x68\
\x36\x00\x00\x00\x03\x73\x42\x49\x54\x08\x08\x08\xdb\xe1\x4f\xe0\
\x00\x00\x02\x45\x49\x44\x41\x54\x28\x91\x6d\x92\x4f\x48\x9a\x71\
\x18\xc7\x7f\xbe\xef\xab\xcd\xed\x95\xcd\x8c\x25\x83\xc0\x24\xa9\
\xc3\x4a\x17\xce\xea\x96\x3b\xe4\x0e\x5d\xba\xce\xa8\x88\xe8\x20\
\x1a\x15\x1d\x3a\x78\x09\xf2\xed\xcf\xe8\x32\x68\x45\x56\x93\x66\
\x94\x78\x99\x53\x68\x4e\x1b\xe1\x61\x30\xc2\x19\x5b\x16\xac\x9c\
\x76\x19\x92\x2e\x35\xa6\x7b\xf7\xda\xfb\x3e\x3b\xd8\x9c\x9b\x7e\
\x8e\xdf\xdf\xf3\x81\xdf\xf3\x87\x07\x00\xe8\x0f\x99\xb3\xb3\xd0\
\xca\xca\x17\x97\x2b\x75\x7a\x8a\xf1\xf9\x77\xea\xeb\xe5\x3a\xdd\
\x83\xe1\xe1\x6a\x85\xa2\x58\xc3\x2b\x08\x5c\x3e\x1f\x98\x9a\xfa\
\xb0\xb0\x80\xf3\xf9\x72\x9d\xae\x56\xa5\xe2\x58\x36\x13\x8b\x9d\
\xb8\xdd\x3f\x2f\x2e\x1e\x8e\x8c\x3c\x9a\x9d\xc5\xab\xaa\x10\x42\
\x08\x00\x38\x96\x75\xf6\xf4\x58\x78\xbc\x37\x46\x23\x9d\x4e\x43\
\x09\x57\x34\xfd\x7e\x6e\x6e\x4e\x28\xb4\x6b\xb5\x2c\xc3\x00\x00\
\x02\x80\x77\x93\x93\xd3\x08\x51\x04\x71\xec\x74\x42\x25\xbe\xfa\
\x7c\xf3\x24\xb9\x63\x30\x00\x00\x4a\x45\x22\x33\x02\x81\xd7\x64\
\x5a\x69\x6e\x9e\xe1\xf3\x8f\x1c\x8e\x8a\xce\xc7\xe5\x65\x0b\x86\
\x7d\xdb\xdf\x47\xfe\x89\x89\xa7\x22\xd1\xaf\xcb\xcb\x6c\x22\x61\
\x55\x2a\x29\x82\x08\x6f\x6d\x95\x0b\x1c\xcb\x3e\x57\x28\x3c\x43\
\x43\x68\x5d\xa3\x71\x74\x77\x17\xd2\x5c\x32\x69\x55\xa9\x28\x82\
\x38\xdc\xdc\x2c\x77\xbc\x26\xd3\xb3\xba\x3a\xec\xfb\xf1\xb1\xb8\
\xa1\xa1\x30\x32\xa1\x44\xa2\xdf\xdd\xbd\xdb\xd2\xf2\xba\xbf\xff\
\xd0\x6e\x47\xff\x22\x69\x6a\xfa\x11\x8f\x63\x1c\xcb\xb2\x0c\x53\
\x4c\x85\xd5\xd5\x7a\xbf\xbf\x56\xa9\x74\x0f\x0c\x7c\xde\xd8\x28\
\x15\x80\xe3\x80\xe3\xb0\xdb\x32\x59\x26\x1a\x2d\x7d\xb8\x21\x16\
\x3f\xf1\xf9\xa4\xad\xad\x9e\xc1\xc1\x4f\x36\x5b\x31\x4f\x47\xa3\
\xa4\x54\x8a\x7c\xe3\xe3\xf3\x24\x99\x4b\x26\xff\xfb\x31\x9d\x4a\
\xad\x6b\x34\x14\x8e\x1f\xac\xad\x15\x9a\x5e\x6a\x6c\x74\xf5\xf5\
\xa1\x44\x38\x4c\xe1\xf8\xdb\xd1\xd1\xf2\x2e\xe9\x74\xfa\x45\x7b\
\xbb\x05\xc3\x42\x56\x6b\x70\x69\xc9\xc2\xe3\x9d\x05\x02\x08\x00\
\x76\x0c\x06\x8a\x20\xc2\xdb\xdb\x15\x9c\x4c\xc6\xd6\xd1\x61\xc1\
\xb0\x79\x92\x7c\xa5\xd7\x5f\x6f\x9a\x65\x98\x97\x9d\x9d\x14\x8e\
\xef\x99\xcd\x57\x34\x5d\x2a\xb0\x0c\xb3\x67\x36\x4f\x23\xb4\xae\
\x56\xe7\x73\x39\x00\xb8\x3e\xbe\x7c\x2e\xe7\x1b\x1b\x3b\x58\x5d\
\xbd\x59\x53\x23\xef\xea\x2a\x0c\x3a\x13\x8b\x45\xbc\xde\x6c\x3c\
\x7e\xbf\xb7\xf7\xf1\xe2\xa2\x40\x24\xfa\x7b\xad\x05\xe2\xc1\x60\
\xc8\x6a\x3d\xf1\x78\xb2\xe7\xe7\x88\xe3\x6e\x49\xa5\x32\xad\x56\
\x6d\x34\xde\x6b\x6b\x2b\xd6\xfc\x06\xb3\xcb\xb3\xdb\x2f\x3f\x31\
\xa9\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82'

#=============== help texts

NewRealmButtonHelp = \
    "Use this button to add a new top-level REALM type. \n\n\
You can refine an existing realm by right-clicking it \
and selecting \"Add workload\" from the pop-up menu.\n\n<Ctrl>-h for help"

RealmWorkloadPanelHelp = \
    "\
Use this panel to define names for  types of workloads that \
shall be confined against each other.\n\n<Ctrl>-h for help"

RunTimeExclusionPanelHelp = \
    "\
The run-time exclusion rules restrict which workload types \
can run simultaneously on the same platform. At most one \
type in an exclusion rule can run. If a domain starts, its \
workload type is looked up and if it is in any exclusion rule \
of which another type is already running, then it is denied \
to start.\n\n<Ctrl>-h for help"

CreateRunTimeButtonHelp = \
    "\
This button creates a new run-time exclusion rule using the \
selection from the left side workload definition panel.\n\n<Ctrl>-h for help"

AddToExclusionButtonHelp = \
    "\
This button adds the current selection in the left side \
workload definition panel to the associated exclusion rule.\n\n<Ctrl>-h for help"

DelFromExclusionButtonHelp = \
    "\
This button deletes the current selection of the associated \
exclusion rule from the associated exclusion rule.\n\n<Ctrl>-h for help"

ManageExclusionButtonHelp = \
    "\
This button allows to rename or delete the associated exclusion \
rule. Left-click the button for the menu.\n\n<Ctrl>-h for help"

ExclusionSetHelp = \
    "\
Of the workload types specified in an exclusion rule, \
only one can run at a time on the same platform.\n\n<Ctrl>-h for help"

GetHelp = \
    "\
Use <CTRL>-h to open the help window. Use the context help on buttons."

#================ html help page =================
# for ez use included in a single file, one could also
# optionally try to fetch the page from a public location
import wx.html as html

class HelpHtmlWindow(html.HtmlWindow):
    def __init__(self, parent, id):
        html.HtmlWindow.__init__(self, parent, id, style=wx.NO_FULL_REPAINT_ON_RESIZE)
        if "gtk2" in wx.PlatformInfo:
            self.SetStandardFonts()
        self.SetPage(helptext)

helptext = """
<HTML>
<HEAD>
<META http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<META name="GENERATOR" content="IBM WebSphere Studio Homepage Builder V6.0.2 for Windows">
<META http-equiv="Content-Style-Type" content="text/css">
<TITLE>Overview</TITLE>
</HEAD>
<BODY bgcolor="#dfdfdf" text="#000000">
<H3><FONT color="#000000" face="Palatino Linotype">Creating A Xen Workload-Protection Security Policy</FONT></H3>
<FONT face="Palatino Linotype">The purpose of this tool is to create a Xen security policy that understands
the workload types that you want to confine against each other. For this
purpose you enter the names of workload types that you want to assign to
domains and resources. You can also define groups of workload types that
should not run on the same system simultaneously for any reason; such groups
are called Runtime Exclusion Sets. Please refer to the Xen User Guide for
more information.<BR>
<BR>
This tool will create a unique security label for each workload type. Every
domain and resource must be labeled so that the hypervisor system can correctly
identify the associated workload type and control the sharing among domains
in a way that keeps different workload types confined from each other.
This tool ensures two things:<BR>
<BR>
1. The created security policy includes a distinctive label for each workload
type defined in step 1 below. These labels must later be assigned to Domains
and Resources to enable Xen to enforce the confinement.<BR>
<BR>
2. The created security policy includes access control rules that are enforced
by the Xen Hypervisor (independently of the guest Domains) and guarantee
that:</FONT>
<BLOCKQUOTE><FONT face="Palatino Linotype">(i) Domains that are assigned the same workload type label can
share (communicate,
use common resources) without restriction through the hypervisor. Their
interoperation can still be constraint by the domains (domain-internal
means).</FONT></BLOCKQUOTE>
<BLOCKQUOTE><FONT face="Palatino Linotype">(ii) Domains that are assigned different workload type labels cannot share,
i.e., cannot communicate or use common resources. Independently enforced
by the hypervisor, the domains cannot overrule this decision.</FONT></BLOCKQUOTE>
<BLOCKQUOTE><FONT face="Palatino Linotype">(iii) Once a Domain labeled with a workload type of a Runtime Exclusion
Rule is running, no other domain labeled with another workload type of
the same Runtime Exclusion Rule can start. This holds for all Runtime Exclusion
Rules.</FONT></BLOCKQUOTE>
<FONT face="Palatino Linotype">While all workloads share common hardware resources, the core hypervisor
isolation and virtualization in combination with the Xen access control
policy ensure that, e.g., viruses in one workload type cannot infect other
workload types and that secrets used within one workload type cannot leak
into another workload type. Currently the Xen access control enforcement
covers domains, local storage resources, and the local virtual network
interfaces. Protecting sharing through the open network is subject of ongoing
work; such protection must currently be setup manually using IP filtering
rules in Domain0.
<BR>
</FONT>
<H2><FONT color="#000000" face="Palatino Linotype">Step 1</FONT></H2>
<FONT face="Palatino Linotype">The first step of creating a workload protection policy is to determine
names for the different workload types. The left panel offers the means
to define and and manage workload type definitions.<BR>
<BR>
A workload can be an organization name (coarse-grained type), e.g. a corporate
realm such as IBM or PepsiCo. An organization can be refined to describe
independent functional groupings within the organization, such as IBM.Financing
or Pepsi.Payroll. Use the<B><I> &lt;New Org&gt;</I></B> button on the left panel
to create a new organization workload. To refine such a workload, right-click the
organization and chose <B><I>&lt;Add Department&gt;</I></B>. You can add multiple
departments to an organization but you do not have to add any.<BR>
<BR>
This tool will create a separate label name for each organization and for
each department workload. The policy will be computed so that there is
no sharing between organizations or departments by default. IBM, IBM.Financing,
Pepsi, and Pepsi.Payroll will by default not be able to share in this simple
policy example. You can introduce controlled sharing by refining the policy,
which is beyond the scope of this help.<BR>
<BR>
As an example, define the four organizations PepsiCo, CocaCola, Avis, Hertz.
Define department workloads Payroll, HumanResources and Financing for Avis
and CocaCola, and PepsiCo.<BR>
</FONT>
<H2><FONT color="#000000" face="Palatino Linotype">Step 2</FONT></H2>
<FONT face="Palatino Linotype">In this second step, we enter those workload types that should not run
simultaneously on the same hardware platform. There might be multiple reasons
for this, e.g., imperfect resource control.<BR>
<BR>
As an example, we will create a policy that guarantees that PepsiCo workloads
and CocaCola workloads never run simultaneously on the same platform: <BR>
<BR>
1. Select the PepsiCo organization on the left panel by left-clicking it..<BR>
<BR>
2. Press the &lt;Ctrl&gt;-Key and then select CocaCola organization by
left-clicking it while keeping the &lt;Ctrl&gt;-Key pressed..<BR>
<BR>
3. Click the <B><I>&lt;Create run-time exclusion rule from selection&gt;</I></B>
button and enter a name for this Run-time Exclusion rule (e.g., RER1). The name is
for your reference only. It has no impact on the policy. On the right panel, a run-time
exclusion rule with the chosen name appears. <BR>
<BR>
The interpretation of the rule is as follows: If a domain labeled PepsiCo
is running, then another domain labeled CocaCola cannot start on the same
system and the other way round. This also holds for departments of PepsiCo
and CocaCola (organizations dominate their departments). If PepsiCo or
PepsiCo.Payroll etc. are running, then a domain with label CocaCola or
CocaCola.Payroll etc. cannot start. If you want to restrict concurrency
between specific subtypes, then you must create a Run-time Exclusion rule
that specifies the department workload types. To exclude only CocaCola.Payroll
and PepsiCo.Payroll from running simultaneously the Run-time Exclusion
rule must be formed using Coca.Cola.Payroll and PepsiCo.Payroll, not their
organizations. Consequently it does not make sense to add both an organization
and any of its departments to the same Run-time Exclusion rule because
any department is already covered by its organization (this tool will not
allow it).<BR>
<BR>
You can create multiple Run-time Exclusion rules, all of which will be
enforced simultaneously by the hypervisor. You do not need to define any
Run-time Exclusion rule if you do not find it necessary. You can add or
delete workload types from Run-time Exclusion rules using the <B><I>&lt;Add&gt;</I></B>
and <I><B>&lt;Del&gt;</B></I> buttons associated with the rule. The <I><B>&lt;Add&gt;</B></I>
button adds the workload types selected in the left panel to the Run-time
Exclusion rule. The <I><B>&lt;Del&gt;</B></I> button deletes the workload types selected
in the associated Run-time Exclusion rule from the rule. <BR>
</FONT>
<H2><FONT color="#000000" face="Palatino Linotype">Step 3</FONT></H2>
<FONT face="Palatino Linotype">Now that we have defined the workloads and Run-time Exclusion rules, we
can save the workload definition for later reference or refinement. Select
the <I><B>File-&gt;Save Workload
Definition as..</B></I> menu entry and choose a file name.<BR>
<BR>
Please use the <B><I>File-&gt;Save as Xen ACM Security Policy..</I></B> menu entry and choose a policy
name to create a Xen Workload Protection
security policy from the current workload definition. To simplify the succeeding
steps, please use a name of the form &quot;example.chwall_ste.NAME&quot;
where you merely replace &quot;NAME&quot; with a policy name of your choice.
Save the policy under the name proposed by the tool in the proposed directory
if you are using this tool in your Xen environment. Otherwise, you need
to copy the resulting file into your Xen environment to the directory
&quot;/etc/xen/acm-security/policies/example/chwall_ste/&quot;.<BR>
<BR>
This tool creates policies for the Xen Chinese Wall and Simple Type Enforcement
policy. The Xen access control policy in general is more expressive and
this tool only uses a small subset of the possible configurations. <B><BR>
<BR>
Where to go from here.</B> <BR>
<BR>
Before the new policy can be activated, we need to translate the policy into a representation that
Xen and the Xen-tools can work with. To this end, in your Xen environment, please issue the command
<B><I>xm makepolicy example.chwall_ste.NAME</I></B> where NAME must be replaced by the name you chose
for your policy in step 3 above. Then, we need to make the policy available to the Xen hypervisor. In
your Xen environment, please issue the command <B><I>xm cfgbootpolicy example.chwall_ste.NAME</I></B>
to install the policy for the next reboot. If the command cannot find the correct boot title, then you
can manually install it as described in the xm man page.<BR>
<BR>
Finally, reboot your security-enabled Xen environment. Please refer to the xm man page for how to enable
Xen security. After reboot, you can use <I><B>xm labels type=any</B></I> to list all the created workload l
abels. Use the <I><B>xm addlabel</B></I> command to assign workload type labels to the associated domains
and resources.<BR>
<BR>
From here, please check the Xen user guide.<BR>
</FONT></BODY>
</HTML>
"""

#=============== main =====

def main():
    global app
    app = ezApp(0)
    if len(sys.argv) in [2]:
        app.Load(sys.argv[1])
    else:
        dict2org({'orgs' : [[ACM_LABEL_UNLABELED,[]]], 'cons': []})
    app.MainLoop()
    print "Goodbye"

if __name__ == '__main__':
    main()

#==== end of file
