예제 #1
0
def main(j, args, params, tags, tasklet):
    params.result = page = args.page
    machineId = int(args.getTag("machineId"))
    scl = j.clients.osis.getNamespace("cloudbroker")

    vmachine = scl.vmachine.get(machineId)
    cloudspace = scl.cloudspace.get(vmachine.cloudspaceId)
    accountId = cloudspace.accountId
    rescuedisks = scl.disk.search({
        "gid": cloudspace.gid,
        "type": "C",
        "status": "CREATED",
        "accountId": {
            "$in": [None, accountId]
        },
    })[1:]
    rescuedisks = [(disk["name"], disk["id"]) for disk in rescuedisks]

    popup = Popup(
        id="startmachine",
        header="Start Machine",
        submit_url="/restmachine/cloudbroker/machine/start",
        reload_on_success=False,
    )
    if rescuedisks:
        rescuedisks.insert(0, ("Normal boot", "null"))
        popup.addDropdown("Choose CD-ROM image", "diskId", rescuedisks)
    popup.addText("Reason", "reason")
    popup.addHiddenField("machineId", machineId)
    popup.write_html(page)

    return params
예제 #2
0
def main(j, args, params, tags, tasklet):
    params.result = page = args.page
    gid = int(args.getTag('gid'))
    actors = j.apps.cloudbroker.iaas.cb.actors.cloudapi

    images = actors.images.list(accountId=None, cloudspaceId=None)
    dropimages = list()

    def imageSorter(image):
        return image['type'] + image['name']

    for image in sorted(images, key=imageSorter):
        dropimages.append(("%(type)s: %(name)s" % image, image['id']))

    popup = Popup(id='createsystemspace', header='Create system space on the grid',
                  submit_url='/restmachine/cloudbroker/grid/createSystemSpace')
    popup.addText('Resource Name', 'name', required=True)
    popup.addDropdown('Choose Image', 'imageId', dropimages)
    popup.addNumber('Boot Disk Size in GiB', 'bootsize')
    popup.addNumber('Choose data Disk Size in GiB', 'dataDiskSize')
    popup.addNumber('Number of VCPUS', 'vcpus')
    popup.addNumber('Amount of memory in MiB', 'memory')
    popup.addTextArea('User data for cloud-init', 'userdata', required=False, rows=5)
    popup.addHiddenField('id', gid)
    popup.write_html(page)

    return params
예제 #3
0
def main(j, args, params, tags, tasklet):
    params.result = page = args.page
    machineId = int(args.getTag('machineId'))
    scl = j.clients.osis.getNamespace('cloudbroker')

    vmachine = scl.vmachine.get(machineId)
    cloudspace = scl.cloudspace.get(vmachine.cloudspaceId)
    accountId = cloudspace.accountId
    rescuedisks = scl.disk.search({
        'gid': cloudspace.gid,
        'type': 'C',
        'status': 'CREATED',
        'accountId': {
            '$in': [None, accountId]
        }
    })[1:]
    rescuedisks = [(disk['name'], disk['id']) for disk in rescuedisks]

    popup = Popup(id='startmachine',
                  header='Start Machine',
                  submit_url='/restmachine/cloudbroker/machine/start',
                  reload_on_success=False)
    if rescuedisks:
        rescuedisks.insert(0, ('Normal boot', 'null'))
        popup.addDropdown('Choose CD-ROM image', 'diskId', rescuedisks)
    popup.addText('Reason', 'reason')
    popup.addHiddenField('machineId', machineId)
    popup.write_html(page)

    return params
예제 #4
0
def main(j, args, params, tags, tasklet):

    params.result = page = args.page
    groupguid = args.getTag('guid')
    if groupguid is None:
        raise exceptions.BadRequest("BadRequest", "text/plain")
    scl = j.clients.osis.getNamespace('system')
    group = None
    guidExists = scl.group.search({'id': groupguid})[1:]
    if guidExists:
        group = scl.group.get(groupguid)
    if not group:
        return params
    popup = Popup(id='group_edit', header='Change Group', clearForm=False, submit_url='/restmachine/system/usermanager/editGroup')

    options = list()
    popup.addText('Enter domain', 'domain', value=group.domain)
    popup.addText('Enter description', 'description', value=group.description)
    for user in scl.user.search({})[1:]:
        available = user['id'] in group.users
        options.append((user['id'], user['id'], available))
    popup.addCheckboxes('Select Users', 'users', options)
    popup.addHiddenField('name', group.id)
    popup.write_html(page)

    return params
예제 #5
0
def main(j, args, params, tags, tasklet):

    params.result = page = args.page
    userguid = args.getTag('guid')
    if not userguid:
        raise exceptions.BadRequest("BadRequest", "text/plain")
    scl = j.clients.osis.getNamespace('system')
    user = scl.user.get(userguid)

    popup = Popup(id='user_edit', header='Update User',
                  submit_url='/restmachine/system/usermanager/editUser', clearForm=False)

    options = list()
    popup.addText('Enter Email Address', 'emails', value=', '.join(user.emails),
                  placeholder='If left empty, email address will not be changed')
    popup.addHiddenField('domain', user.domain)
    popup.addText('Enter Password', 'password', type='password',
                  placeholder='If left empty, password will not be changed')
    for group in scl.group.search({})[1:]:
        available = group['id'] in user.groups
        options.append((group['id'], group['id'], available))

    popup.addCheckboxes('Select Groups', 'groups', options)
    popup.addHiddenField('username', user.id)
    popup.write_html(page)

    return params
예제 #6
0
def main(j, args, params, tags, tasklet):
    params.result = page = args.page
    gid = int(args.getTag("gid"))
    actors = j.apps.cloudbroker.iaas.cb.actors.cloudapi

    images = actors.images.list(accountId=None, cloudspaceId=None)
    dropimages = list()

    def imageSorter(image):
        return image["type"] + image["name"]

    for image in sorted(images, key=imageSorter):
        dropimages.append(("%(type)s: %(name)s" % image, image["id"]))

    popup = Popup(
        id="createsystemspace",
        header="Create system space on the grid",
        submit_url="/restmachine/cloudbroker/grid/createSystemSpace",
    )
    popup.addText("Resource Name", "name", required=True)
    popup.addDropdown("Choose Image", "imageId", dropimages)
    popup.addNumber("Boot Disk Size in GiB", "bootsize")
    popup.addNumber("Choose data Disk Size in GiB", "dataDiskSize")
    popup.addNumber("Number of VCPUS", "vcpus")
    popup.addNumber("Amount of memory in MiB", "memory")
    popup.addTextArea("User data for cloud-init",
                      "userdata",
                      required=False,
                      rows=5)
    popup.addHiddenField("id", gid)
    popup.write_html(page)

    return params
예제 #7
0
def main(j, args, params, tags, tasklet):

    params.result = page = args.page
    userguid = args.getTag('guid')
    if not userguid:
        raise exceptions.BadRequest("BadRequest", "text/plain")
    scl = j.clients.osis.getNamespace('system')
    user = scl.user.get(userguid)

    popup = Popup(id='user_edit',
                  header='Update User',
                  submit_url='/restmachine/system/usermanager/editUser',
                  clearForm=False)

    options = list()
    popup.addText(
        'Enter Email Address',
        'emails',
        value=', '.join(user.emails),
        placeholder='If left empty, email address will not be changed')
    popup.addHiddenField('domain', user.domain)
    popup.addText('Enter Password',
                  'password',
                  type='password',
                  placeholder='If left empty, password will not be changed')
    for group in scl.group.search({})[1:]:
        available = group['id'] in user.groups
        options.append((group['id'], group['id'], available))

    popup.addCheckboxes('Select Groups', 'groups', options)
    popup.addHiddenField('username', user.id)
    popup.write_html(page)

    return params
예제 #8
0
def main(j, args, params, tags, tasklet):
    params.result = page = args.page
    ccl = j.clients.osis.getNamespace('cloudbroker')

    locations = [(loc['name'], loc['gid'])
                 for loc in ccl.location.search({})[1:]]
    popup = Popup(id='addpublicnetwork',
                  header='Add Public Network',
                  submit_url='/restmachine/cloudbroker/iaas/addPublicNetwork')
    popup.addDropdown('Choose Location', 'gid', locations)
    popup.addText('Network',
                  'network',
                  required=True,
                  placeholder='8.8.8.0/24')
    popup.addText('Gateway', 'gateway', required=True, placeholder='8.8.8.1')
    popup.addText('First Free Public IP Address',
                  'startip',
                  required=True,
                  placeholder='8.8.8.2')
    popup.addText('Last Free Public IP Address',
                  'endip',
                  required=True,
                  placeholder='8.8.8.254')
    popup.write_html(page)

    return params
예제 #9
0
def main(j, args, params, tags, tasklet):
    params.result = page = args.page
    ccl = j.clients.osis.getNamespace('cloudbroker')
    locations = list()
    for location in ccl.location.search({})[1:]:
        locations.append((location['name'], location['gid']))

    popup = Popup(id='createimage', header='Create Image',
                  submit_url='/restmachine/cloudbroker/image/createImage',
                  reload_on_success=False)
    popup.addText('Name', 'name', required=True)
    popup.addText('URL of image to import', 'url', required=True)
    popup.addDropdown('Choose Location', 'gid', locations)
    imagetypes = [
            ('Linux', 'Linux'),
            ('Windows', 'Windows'),
            ('Other', 'Other'),
    ]
    boottype = [
            ('BIOS', 'bios'),
            ('UEFI', 'uefi'),
    ]
    hotResize = [('Yes', True),
                 ('No', False)
    ]
    popup.addDropdown('Choose Type', 'imagetype', imagetypes)
    popup.addDropdown('Boot Type', 'boottype', boottype)
    popup.addDropdown('Hot Resize', 'hotresize', hotResize)
    popup.addText('Username for the image leave empty when the image is cloud-init enabled', 'username')
    popup.addText('Password for the image leave empty when the image is cloud-init enabled', 'password')
    popup.addText('AccountId optional if you want to make the image for this account only', 'accountId')
    popup.write_html(page)
    return params
예제 #10
0
def main(j, args, params, tags, tasklet):
    params.result = page = args.page
    ccl = j.clients.osis.getNamespace("cloudbroker")

    locations = [(loc["name"], loc["gid"])
                 for loc in ccl.location.search({})[1:]]
    popup = Popup(
        id="addpublicnetwork",
        header="Add Public Network",
        submit_url="/restmachine/cloudbroker/iaas/addPublicNetwork",
    )
    popup.addDropdown("Choose Location", "gid", locations)
    popup.addText("Network",
                  "network",
                  required=True,
                  placeholder="8.8.8.0/24")
    popup.addText("Gateway", "gateway", required=True, placeholder="8.8.8.1")
    popup.addText("First Free Public IP Address",
                  "startip",
                  required=True,
                  placeholder="8.8.8.2")
    popup.addText("Last Free Public IP Address",
                  "endip",
                  required=True,
                  placeholder="8.8.8.254")
    popup.write_html(page)

    return params
예제 #11
0
def main(j, args, params, tags, tasklet):
    params.result = page = args.page

    pars = args.expandParamsAsDict()

    page.addMessage('<a href="#{0}" role="button" class="btn" data-toggle="modal">Launch demo modal {0}</a>'.format(pars['id']))

    popup = Popup(id=pars['id'], header='Text popup', submit_url=pars['submit_url'])
    popup.addHiddenField('hidden_field', 'hidden_value')
    popup.addText('First name', 'firstname', required=True)
    popup.addNumber('Age', 'age')
    popup.addDropdown('Choose licence', 'license', [('MIT', 'mit'), ('BSD', 'bsd'), ('GPL version 3', 'gpl3')])
    popup.addRadio('Choose licence', 'license2', [('MIT', 'mit'), ('BSD', 'bsd'), ('GPL version 3', 'gpl3')])
    popup.addCheckboxes('Choose the software', 'software', [('MS Office', 'msoffice'), ('Photoshop', 'photoshop')])
    popup.write_html(page)

    return params
예제 #12
0
def main(j, args, params, tags, tasklet):
    params.result = page = args.page
    cloudspaceId = int(args.getTag("cloudspaceId"))
    scl = j.clients.osis.getNamespace("cloudbroker")
    actors = j.apps.cloudbroker.iaas.cb.actors.cloudapi

    cloudspace = scl.cloudspace.get(cloudspaceId)
    stacks = scl.stack.search({"gid": cloudspace.gid, "status": "ENABLED"})[1:]

    images = actors.images.list(
        accountId=cloudspace.accountId, cloudspaceId=cloudspace.id
    )
    dropimages = list()
    dropstacks = list()
    dropstacks.append(("Auto", 0))

    def imageSorter(image):
        return image["type"] + image["name"]

    def sortName(item):
        return item["name"]

    for image in sorted(images, key=imageSorter):
        dropimages.append(("%(type)s: %(name)s" % image, image["id"]))

    for stack in sorted(stacks, key=sortName):
        dropstacks.append((stack["name"], stack["id"]))

    popup = Popup(
        id="createmachine",
        header="Create Machine On CPU Node",
        submit_url="/restmachine/cloudbroker/machine/createOnStack",
    )
    popup.addText("Machine Name", "name", required=True)
    popup.addText("Machine Description", "description", required=True)
    popup.addDropdown("Choose CPU Node", "stackid", dropstacks)
    popup.addDropdown("Choose Image", "imageId", dropimages)
    popup.addNumber("Disk Size in GiB", "disksize")
    popup.addNumber("Number of VCPUS", "vcpus")
    popup.addNumber("Amount of memory in MiB", "memory")
    popup.addTextArea("User data for cloud-init", "userdata", required=False, rows=5)
    popup.addHiddenField("cloudspaceId", cloudspaceId)
    popup.write_html(page)

    return params
예제 #13
0
def main(j, args, params, tags, tasklet):
    # import ipdb; ipdb.set_trace()
    params.result = page = args.page
    reload = "noreload" not in args.tags.labels
    scl = j.clients.osis.getNamespace("system")

    popup = Popup(
        id="createuser",
        header="Create User",
        submit_url="/restmachine/cloudbroker/user/create",
        reload_on_success=reload,
    )

    options = list()
    popup.addText("Enter Username", "username")
    popup.addText("Enter Email Address", "emailaddress")
    popup.addHiddenField("domain", "")
    popup.addText(
        "Enter Password",
        "password",
        type="password",
        placeholder="If left empty, a random password will be generated",
    )
    for group in scl.group.search({})[1:]:
        options.append((group["id"], group["id"], False))

    popup.addCheckboxes("Select Groups", "groups", options)
    popup.write_html(page)

    return params
예제 #14
0
def main(j, args, params, tags, tasklet):
    #import ipdb; ipdb.set_trace()
    params.result = page = args.page
    reload = 'noreload' not in args.tags.labels
    scl = j.clients.osis.getNamespace('system')

    popup = Popup(id='createuser',
                  header='Create User',
                  submit_url='/restmachine/cloudbroker/user/create',
                  reload_on_success=reload)

    options = list()
    popup.addText('Enter Username', 'username')
    popup.addText('Enter Email Address', 'emailaddress')
    popup.addHiddenField('domain', '')
    popup.addText(
        'Enter Password',
        'password',
        type='password',
        placeholder='If left empty, a random password will be generated')
    for group in scl.group.search({})[1:]:
        options.append((group['id'], group['id'], False))

    popup.addCheckboxes('Select Groups', 'groups', options)
    popup.write_html(page)

    return params
예제 #15
0
def main(j, args, params, tags, tasklet):
    params.result = page = args.page
    cloudspaceId = int(args.getTag('cloudspaceId'))
    scl = j.clients.osis.getNamespace('cloudbroker')
    actors = j.apps.cloudbroker.iaas.cb.actors.cloudapi

    cloudspace = scl.cloudspace.get(cloudspaceId)
    stacks = scl.stack.search({'gid': cloudspace.gid, 'status': 'ENABLED'})[1:]

    images = actors.images.list(accountId=cloudspace.accountId, cloudspaceId=cloudspace.id)
    dropimages = list()
    dropstacks = list()
    dropstacks.append(('Auto', 0))
    def imageSorter(image):
        return image['type'] + image['name']

    def sortName(item):
        return item['name']

    for image in sorted(images, key=imageSorter):
        dropimages.append(("%(type)s: %(name)s" % image, image['id']))

    for stack in sorted(stacks, key=sortName):
        dropstacks.append((stack['name'], stack['id']))

    popup = Popup(id='createmachine', header='Create Machine On CPU Node',
                  submit_url='/restmachine/cloudbroker/machine/createOnStack')
    popup.addText('Machine Name', 'name', required=True)
    popup.addText('Machine Description', 'description', required=True)
    popup.addDropdown('Choose CPU Node', 'stackid', dropstacks)
    popup.addDropdown('Choose Image', 'imageId', dropimages)
    popup.addNumber('Disk Size in GiB', 'disksize')
    popup.addNumber('Number of VCPUS', 'vcpus')
    popup.addNumber('Amount of memory in MiB', 'memory')
    popup.addTextArea('User data for cloud-init', 'userdata', required=False, rows=5)
    popup.addHiddenField('cloudspaceId', cloudspaceId)
    popup.write_html(page)

    return params
예제 #16
0
def main(j, args, params, tags, tasklet):
    params.result = page = args.page
    machineId = int(args.getTag("machineId"))
    scl = j.clients.osis.getNamespace("cloudbroker")

    vmachine = scl.vmachine.get(machineId)
    cloudspace = scl.cloudspace.get(vmachine.cloudspaceId)
    stacks = scl.stack.search({
        "status": "ENABLED",
        "gid": cloudspace.gid,
        "images": vmachine.imageId
    })[1:]
    cpu_nodes = [(stack["name"], stack["id"]) for stack in stacks
                 if vmachine.stackId != stack["id"]]

    popup = Popup(
        id="movemachine",
        header="Move machine to another CPU node",
        submit_url=
        "/restmachine/cloudbroker/machine/moveToDifferentComputeNode",
        reload_on_success=False,
    )
    popup.addDropdown("Target CPU Node",
                      "targetStackId",
                      cpu_nodes,
                      required=True)
    popup.addDropdown(
        "Force (might require VM to restart)",
        "force",
        (("No", "false"), ("Yes", "true")),
        required=True,
    )
    popup.addText("Reason", "reason", required=True)
    popup.addHiddenField("machineId", machineId)
    popup.addHiddenField("async", "true")
    popup.write_html(page)

    return params
예제 #17
0
def main(j, args, params, tags, tasklet):
    params.result = page = args.page
    ccl = j.clients.osis.getNamespace("cloudbroker")
    locations = list()
    for location in ccl.location.search({})[1:]:
        locations.append((location["name"], location["gid"]))

    popup = Popup(
        id="createimage",
        header="Create Image",
        submit_url="/restmachine/cloudbroker/image/createImage",
        reload_on_success=False,
    )
    popup.addText("Name", "name", required=True)
    popup.addText("URL of image to import", "url", required=True)
    popup.addDropdown("Choose Location", "gid", locations)
    imagetypes = [("Linux", "Linux"), ("Windows", "Windows"),
                  ("Other", "Other")]
    boottype = [("BIOS", "bios"), ("UEFI", "uefi")]
    hotResize = [("Yes", True), ("No", False)]
    popup.addDropdown("Choose Type", "imagetype", imagetypes)
    popup.addDropdown("Boot Type", "boottype", boottype)
    popup.addDropdown("Hot Resize", "hotresize", hotResize)
    popup.addText(
        "Username for the image leave empty when the image is cloud-init enabled",
        "username",
    )
    popup.addText(
        "Password for the image leave empty when the image is cloud-init enabled",
        "password",
    )
    popup.addText(
        "AccountId optional if you want to make the image for this account only",
        "accountId",
    )
    popup.write_html(page)
    return params
예제 #18
0
def main(j, args, params, tags, tasklet):
    params.result = page = args.page
    machineId = int(args.getTag('machineId'))
    scl = j.clients.osis.getNamespace('cloudbroker')

    vmachine = scl.vmachine.get(machineId)
    cloudspace = scl.cloudspace.get(vmachine.cloudspaceId)
    stacks = scl.stack.search({
        'status': 'ENABLED',
        'gid': cloudspace.gid,
        'images': vmachine.imageId
    })[1:]
    cpu_nodes = [(stack['name'], stack['id']) for stack in stacks
                 if vmachine.stackId != stack['id']]

    popup = Popup(
        id='movemachine',
        header='Move machine to another CPU node',
        submit_url=
        '/restmachine/cloudbroker/machine/moveToDifferentComputeNode',
        reload_on_success=False)
    popup.addDropdown('Target CPU Node',
                      'targetStackId',
                      cpu_nodes,
                      required=True)
    popup.addDropdown('Force (might require VM to restart)',
                      'force', (
                          ('No', 'false'),
                          ('Yes', 'true'),
                      ),
                      required=True)
    popup.addText('Reason', 'reason', required=True)
    popup.addHiddenField('machineId', machineId)
    popup.addHiddenField('async', 'true')
    popup.write_html(page)

    return params
예제 #19
0
def main(j, args, params, tags, tasklet):

    params.result = page = args.page
    userid = args.getTag('id')
    user = j.data.models.system.User.get(userid)
    if not user:
        params.result = ('User with id %s not found' % userid, args.doc)
        return params

    popup = Popup(id='user_edit', header='Change User', submit_url='/restmachine/system/usermanager/editUser')

    options = list()
    popup.addText('Enter emails (comma seperated)', 'emails', value=', '.join(user.emails))
    popup.addHiddenField('domain', user.domain)
    popup.addText('Enter Password (leave empty to unchange)', 'password', type='password')
    for group in j.data.models.system.Group.find({}):
        available = group['name'] in user.groups
        options.append((group['name'], group['name'], available))

    popup.addCheckboxes('Select Groups', 'groups', options)
    popup.addHiddenField('username', user.name)
    popup.write_html(page)

    return params
예제 #20
0
def main(j, args, params, tags, tasklet):

    params.result = page = args.page
    groupid = args.getTag('id')
    group = j.data.models.system.Group.get(groupid)
    if not group:
        params.result = ('group with id %s not found' % groupid, args.doc)
        return params

    popup = Popup(id='group_edit', header='Change Group', clearForm=False,
                  submit_url='/restmachine/system/usermanager/editGroup')

    options = list()
    popup.addText('Enter domain', 'domain', value=group.domain)
    popup.addText('Enter description', 'description', value=group.description)
    for user in j.data.models.system.User.find({}):
        available = user['id'] in [u['id'] for u in j.data.models.system.User.find({'groups': group['name']})]
        options.append((user['name'], user['name'], available))

    popup.addCheckboxes('Select Users', 'users', options)
    popup.addHiddenField('name', group.name)
    popup.write_html(page)

    return params
예제 #21
0
def main(j, args, params, tags, tasklet):
    params.result = page = args.page
    ccl = j.clients.osis.getNamespace('cloudbroker')
    locations = list()
    for location in ccl.location.search({})[1:]:
        locations.append((location['name'], location['gid']))

    popup = Popup(id='createcdrom',
                  header='Create CD-ROM Image',
                  submit_url='/restmachine/cloudbroker/image/createCDROMImage',
                  reload_on_success=False)
    popup.addText('Name', 'name', required=True)
    popup.addText('URL of CD-ROM image to import', 'url', required=True)
    popup.addText(
        'AccountId optional if you want to make the image for this account only',
        'accountId')
    popup.addDropdown('Choose Location', 'gid', locations)
    popup.write_html(page)
    return params
예제 #22
0
def main(j, args, params, tags, tasklet):

    params.result = page = args.page
    reload = 'noreload' not in args.tags.labels
    scl = j.clients.osis.getNamespace('system')

    popup = Popup(id='user_create', header='Create User', submit_url='/restmachine/system/usermanager/create', reload_on_success=reload)

    options = list()
    popup.addText('Enter Username', 'username')
    popup.addText('Enter Email Address', 'emails')
    popup.addHiddenField('domain', '')
    popup.addText('Enter Password', 'password', type='password',
                  placeholder='If left empty, a random password will be generated')
    for group in scl.group.search({})[1:]:
        options.append((group['id'], group['id'], False))

    popup.addCheckboxes('Select Groups', 'groups', options)
    popup.write_html(page)

    return params
예제 #23
0
def main(j, args, params, tags, tasklet):
    params.result = page = args.page
    ccl = j.clients.osis.getNamespace("cloudbroker")
    locations = list()
    for location in ccl.location.search({})[1:]:
        locations.append((location["name"], location["gid"]))

    popup = Popup(
        id="createcdrom",
        header="Create CD-ROM Image",
        submit_url="/restmachine/cloudbroker/image/createCDROMImage",
        reload_on_success=False,
    )
    popup.addText("Name", "name", required=True)
    popup.addText("URL of CD-ROM image to import", "url", required=True)
    popup.addText(
        "AccountId optional if you want to make the image for this account only",
        "accountId",
    )
    popup.addDropdown("Choose Location", "gid", locations)
    popup.write_html(page)
    return params
예제 #24
0
def main(j, args, params, tags, tasklet):

    params.result = page = args.page
    reload = 'noreload' not in args.tags.labels

    popup = Popup(
        id='user_create',
        header='Create User',
        submit_url='/restmachine/system/usermanager/create',
        reload_on_success=reload)

    options = list()
    popup.addText('Enter Username', 'username')
    popup.addText('Enter Emails (comma seperated)', 'emails')
    popup.addHiddenField('domain', '')
    popup.addText('Enter Password', 'password', type='password')
    for group in j.data.models.system.Group.find({}):
        options.append((group['name'], group['name'], False))

    popup.addCheckboxes('Select Groups', 'groups', options)
    popup.write_html(page)

    return params
예제 #25
0
def main(j, args, params, tags, tasklet):
    page = args.page
    from JumpScale.portal.docgenerator.popup import Popup
    import yaml

    def _showexample():
        page.addMessage("""Actions must be in yaml form.
eg:
- display: Start
  action: /restmachine/cloudbroker/machine/start
  input:
  - reason
  - spacename
  - name: accesstype
    type: dropdown
    label: ACL
    values:
     - label: Admin
       value: ARCXDU
     - label: Write
       value: RCX
     - label: Read
       value: R

  data:
   machineId: $$id
   accountName: $$accountname

- display: Stop
  action: /restmachine/cloudbroker/machine/stop?machineId=$$id&reason=ops&accountName=$$accountname&spaceName=$$spacename
}}
""")
        params.result = page
        return params

    macrostr = args.macrostr.strip()
    content = "\n".join(macrostr.split("\n")[1:-1])

    if not content:
        return _showexample()

    actionoptions = [('Choose Action', '#')]
    actions = yaml.load(content)
    if actions == content:
        return _showexample()

    if not isinstance(actions, list):
        actions = [actions]

    for actiondata in actions:
        actionurl = actiondata['action']
        display = actiondata['display']
        inputs = actiondata.get('input', '')
        navigateback = actiondata.get('navigateback', False)
        reload = actiondata.get('reload', True)
        hide = actiondata.get('hide', False)
        data = actiondata.get('data', {})
        showresponse = actiondata.get('showresponse', False)
        hideon = actiondata.get('hideon', [])
        if hideon:
            hideon_input = actiondata.get('hideonInput', '')
            if hideon_input in hideon:
                continue

        if actionurl.startswith("#"):
            actionoptions.append((display, actionurl[1:]))
            continue
        else:
            actionid = "action-%s" % display.replace(' ', '')
            if not hide:
                actionoptions.append((display, actionid))

        popup = Popup(
            id=actionid,
            header="Confirm Action %s" %
            display,
            submit_url=actionurl,
            navigateback=navigateback,
            reload_on_success=reload,
            showresponse=showresponse)
        if inputs:
            for var in inputs:
                if isinstance(var, str):
                    popup.addText(var, var)
                else:
                    if var['type'] in ('dropdown', 'radio'):
                        label = var['label']
                        name = var['name']
                        options = list()
                        for value in var['values']:
                            options.append((value['label'], value['value']))
                        if var['type'] == 'dropdown':
                            popup.addDropdown(label, name, options)
                        elif var['type'] == 'radio':
                            popup.addRadio(label, name, options)
                    elif var['type'] in ('text', 'password', 'number'):
                        label = var['label']
                        name = var['name']
                        default = var.get('default', '')
                        required = var.get('required', False)
                        popup.addText(label, name, type=var['type'], value=default, required=required)
                    elif var['type'] == 'hidden':
                        popup.addHiddenField(var['name'], var['value'])

        for name, value in list(data.items()):
            popup.addHiddenField(name, value)

        popup.write_html(page)

    if len(actionoptions) > 1:
        id = page.addComboBox(actionoptions)
        page.addJS(None, """
            $(document).ready(function() {
                $("#%(id)s").change(function () {
                     var actionid = $("#%(id)s").val();
                     $("#%(id)s").val('#');
                     if (actionid != '#'){
                        $('#'+actionid).modal('show');
                     }
                });
            });
            """ % ({'id': id}))
    params.result = page

    return params
예제 #26
0
def main(j, args, params, tags, tasklet):
    import netaddr

    params.result = page = args.page
    accountId = args.getTag("accountId")
    ccl = j.clients.osis.getNamespace("cloudbroker")
    locations = list()
    for location in ccl.location.search({})[1:]:
        locations.append((location["name"], location["locationCode"]))
    externalnetworks = list()

    def network_sort(pool):
        return "%04d_%s" % (pool["vlan"], pool["name"])

    for pool in sorted(
            ccl.externalnetwork.search(
                {"accountId": {
                    "$in": [int(accountId), 0]
                }})[1:],
            key=network_sort,
    ):
        network = netaddr.IPNetwork("{network}/{subnetmask}".format(**pool))
        externalnetworks.append((
            "{name} - {network}".format(name=pool["name"], network=network),
            pool["id"],
        ))

    # Placeholder that -1 means no limits are set on the cloud unit
    culimitplaceholder = "leave empty if no limits should be set"
    popup = Popup(
        id="create_space",
        header="Create Cloud Space",
        submit_url="/restmachine/cloudbroker/cloudspace/create",
    )
    popup.addText("Name", "name", required=True)
    popup.addText(
        "Username to grant access (if empty will be currently logged in user)",
        "access",
        required=False,
    )
    popup.addDropdown("Choose Location", "location", locations)
    popup.addDropdown("Choose External Network", "externalnetworkId",
                      externalnetworks)
    popup.addText("Private Network",
                  "privatenetwork",
                  value="192.168.103.0/24")
    popup.addText(
        "Max Memory Capacity (GB)",
        "maxMemoryCapacity",
        placeholder=culimitplaceholder,
        type="float",
    )
    popup.addText(
        "Max VDisk Capacity (GB)",
        "maxVDiskCapacity",
        placeholder=culimitplaceholder,
        type="number",
    )
    popup.addText(
        "Max Number of CPU Cores",
        "maxCPUCapacity",
        placeholder=culimitplaceholder,
        type="number",
    )
    popup.addText(
        "Max External Network Transfer (GB)",
        "maxNetworkPeerTransfer",
        placeholder=culimitplaceholder,
        type="number",
    )
    popup.addText(
        "Max Number of Public IP Addresses",
        "maxNumPublicIP",
        placeholder=culimitplaceholder,
        type="number",
    )
    popup.addHiddenField("accountId", accountId)
    popup.write_html(page)
    return params
예제 #27
0
def main(j, args, params, tags, tasklet):
    params.result = page = args.page
    cloudspaceId = int(args.getTag("cloudspaceId"))
    scl = j.clients.osis.getNamespace("cloudbroker")

    cloudspace = scl.cloudspace.get(cloudspaceId)
    stacks = scl.stack.search({"gid": cloudspace.gid, "status": "ENABLED"})[1:]
    sizes = scl.size.search({})[1:]

    dropdisksizes = list()
    dropstacks = list()
    disksizes = set()

    def sizeSorter(size):
        return size["memory"]

    def sortName(item):
        return item["name"]

    for size in sorted(disksizes):
        dropdisksizes.append(("%s GB" % size, str(size)))

    for stack in sorted(stacks, key=sortName):
        dropstacks.append((stack["name"], stack["id"]))

    popup = Popup(
        id="importmachine",
        header="Import Machine",
        submit_url="/restmachine/cloudapi/machines/importOVF",
        reload_on_success=False,
    )
    popup.addText("Machine Name", "name", required=True)
    popup.addText("Machine Description", "desc", required=True)
    popup.addText("Import Link", "link", required=True)
    popup.addText("OVF path", "path")
    popup.addText("Username for Link", "username")
    popup.addText("Password for Link", "passwd", type="password")
    popup.addNumber("Number of VCPUS", "vcpus")
    popup.addNumber("Amount of memory", "memory")
    popup.addHiddenField("cloudspaceId", cloudspaceId)
    popup.write_html(page)

    return params
예제 #28
0
def main(j, args, params, tags, tasklet):
    page = args.page
    from JumpScale.portal.docgenerator.popup import Popup
    import yaml

    def _showexample():
        page.addMessage("""Actions must be in yaml form.
eg:
- display: Start       
  input:       
  - reason     
  - spacename      
  action: /restmachine/cloudbroker/machine/start       
  data:        
   machineId: $$id     
   accountName: $$accountname      
         
- display: Stop
  action: /restmachine/cloudbroker/machine/stop?machineId=$$id&reason=ops&accountName=$$accountname&spaceName=$$spacename
}}
""")
        params.result = page
        return params

    macrostr = args.macrostr.strip()
    content = "\n".join(macrostr.split("\n")[1:-1])

    if not content:
        return _showexample()

    actionoptions = [('Choose Action', '#')]
    actions = yaml.load(content)
    if actions == content:
        return _showexample()

    for actiondata in actions:
        actionurl = actiondata['action']
        display = actiondata['display']
        inputs = actiondata.get('input', '')
        data = actiondata.get('data', {})
        if actionurl.startswith("#"):
            actionoptions.append((display, actionurl[1:]))
            continue
        else:
            actionid = "action-%s" % display.replace(' ', '')
            actionoptions.append((display, actionid))

        popup = Popup(id=actionid,
                      header="Confirm Action %s" % display,
                      submit_url=actionurl)
        if inputs:
            for var in inputs:
                popup.addText(var, var)

        for name, value in data.iteritems():
            popup.addHiddenField(name, value)

        popup.write_html(page)

    id = page.addComboBox(actionoptions)
    page.addJS(
        None, """
        $(document).ready(function() {
            $("#%(id)s").change(function () {
                 var actionid = $("#%(id)s").val();
                 if (actionid != '#'){
                    $('#'+actionid).modal('show');
                 }
            });
        });
        """ % ({
            'id': id
        }))
    params.result = page

    return params
예제 #29
0
def main(j, args, params, tags, tasklet):
    import netaddr
    params.result = page = args.page
    accountId = args.getTag('accountId')
    ccl = j.clients.osis.getNamespace('cloudbroker')
    locations = list()
    for location in ccl.location.search({})[1:]:
        locations.append((location['name'], location['locationCode']))
    externalnetworks = list()

    def network_sort(pool):
        return '%04d_%s' % (pool['vlan'], pool['name'])

    for pool in sorted(ccl.externalnetwork.search(
        {'accountId': {
            '$in': [int(accountId), 0]
        }})[1:],
                       key=network_sort):
        network = netaddr.IPNetwork('{network}/{subnetmask}'.format(**pool))
        externalnetworks.append(
            ('{name} - {network}'.format(name=pool['name'],
                                         network=network), pool['id']))

    # Placeholder that -1 means no limits are set on the cloud unit
    culimitplaceholder = 'leave empty if no limits should be set'
    popup = Popup(id='create_space',
                  header='Create Cloud Space',
                  submit_url='/restmachine/cloudbroker/cloudspace/create')
    popup.addText('Name', 'name', required=True)
    popup.addText(
        'Username to grant access (if empty will be currently logged in user)',
        'access',
        required=False)
    popup.addDropdown('Choose Location', 'location', locations)
    popup.addDropdown('Choose External Network', 'externalnetworkId',
                      externalnetworks)
    popup.addText('Private Network',
                  'privatenetwork',
                  value='192.168.103.0/24')
    popup.addText('Max Memory Capacity (GB)',
                  'maxMemoryCapacity',
                  placeholder=culimitplaceholder,
                  type='float')
    popup.addText('Max VDisk Capacity (GB)',
                  'maxVDiskCapacity',
                  placeholder=culimitplaceholder,
                  type='number')
    popup.addText('Max Number of CPU Cores',
                  'maxCPUCapacity',
                  placeholder=culimitplaceholder,
                  type='number')
    popup.addText('Max External Network Transfer (GB)',
                  'maxNetworkPeerTransfer',
                  placeholder=culimitplaceholder,
                  type='number')
    popup.addText('Max Number of Public IP Addresses',
                  'maxNumPublicIP',
                  placeholder=culimitplaceholder,
                  type='number')
    popup.addHiddenField('accountId', accountId)
    popup.write_html(page)
    return params
예제 #30
0
def main(j, args, params, tags, tasklet):
    params.result = page = args.page
    cloudspaceId = int(args.getTag('cloudspaceId'))
    scl = j.clients.osis.getNamespace('cloudbroker')

    cloudspace = scl.cloudspace.get(cloudspaceId)
    stacks = scl.stack.search({'gid': cloudspace.gid, 'status': 'ENABLED'})[1:]
    sizes = scl.size.search({})[1:]

    dropdisksizes = list()
    dropstacks = list()
    disksizes = set()

    def sizeSorter(size):
        return size['memory']

    def sortName(item):
        return item['name']

    for size in sorted(disksizes):
        dropdisksizes.append(("%s GB" % size, str(size)))

    for stack in sorted(stacks, key=sortName):
        dropstacks.append((stack['name'], stack['id']))

    popup = Popup(id='importmachine',
                  header='Import Machine',
                  submit_url='/restmachine/cloudapi/machines/importOVF',
                  reload_on_success=False)
    popup.addText('Machine Name', 'name', required=True)
    popup.addText('Machine Description', 'desc', required=True)
    popup.addText('Import Link', 'link', required=True)
    popup.addText('OVF path', 'path')
    popup.addText('Username for Link', 'username')
    popup.addText('Password for Link', 'passwd', type='password')
    popup.addNumber('Number of VCPUS', 'vcpus')
    popup.addNumber('Amount of memory', 'memory')
    popup.addHiddenField('cloudspaceId', cloudspaceId)
    popup.write_html(page)

    return params
예제 #31
0
def main(j, args, params, tags, tasklet):
    page = args.page
    from JumpScale.portal.docgenerator.popup import Popup
    import yaml

    def _showexample():
        page.addMessage("""Actions must be in yaml form.
eg:
- display: Start
  action: /restmachine/cloudbroker/machine/start
  input:
  - reason
  - spacename
  - name: accesstype
    type: dropdown
    label: ACL
    values:
     - label: Admin
       value: ARCXDU
     - label: Write
       value: RCX
     - label: Read
       value: R

  data:
   machineId: $$id
   accountName: $$accountname

- display: Stop
  action: /restmachine/cloudbroker/machine/stop?machineId=$$id&reason=ops&accountName=$$accountname&spaceName=$$spacename
}}
""")
        params.result = page
        return params

    macrostr = args.macrostr.strip()
    title = args.getTag('title', 'Action')
    gridbinding = args.getTag('gridbinding', '').split()
    content = "\n".join(macrostr.split("\n")[1:-1])

    if not content:
        return _showexample()

    actionoptions = []
    actions = yaml.load(content)
    if actions == content:
        return _showexample()

    if not isinstance(actions, list):
      actions = [actions]

    for actiondata in actions:
        actionurl = actiondata['action']
        display = actiondata['display']
        inputs = actiondata.get('input', '')
        navigateback = actiondata.get('navigateback', False)
        reload = actiondata.get('reload', True)
        clearForm = actiondata.get('clearform', True)
        hide = actiondata.get('hide', False)
        data = actiondata.get('data', {})
        showresponse = actiondata.get('showresponse', False)
        hideon = actiondata.get('hideon', [])
        if hideon:
            hideon_input = actiondata.get('hideonInput', '')
            if hideon_input in hideon:
                continue

        action = "$('%s').modal('show');"

        if actionurl.startswith("#"):
            actionoptions.append((display, action % actionurl))
            continue
        else:
            actionid = "action-%s" % display.replace(' ', '')
            if not hide:
                actionoptions.append((display, action % ('#' + actionid)))

        popup = Popup(id=actionid, header="Confirm Action %s" % display, submit_url=actionurl,
                      navigateback=navigateback, reload_on_success=reload,
                      showresponse=showresponse, clearForm=clearForm, gridbinding=gridbinding)
        if inputs:
            for var in inputs:
                if isinstance(var, basestring):
                    popup.addText(var, var)
                else:
                    if var['type'] in ('dropdown', 'radio'):
                        label = var['label']
                        name = var['name']
                        options = list()
                        for value in var['values']:
                            options.append((value['label'], value['value']))
                        if var['type'] == 'dropdown':
                            popup.addDropdown(label, name, options)
                        elif var['type'] == 'checkboxes':
                            popup.addCheckboxes(label, name, options)
                        elif var['type'] == 'radio':
                            popup.addRadio(label, name, options)
                    elif var['type'] in ('text', 'password', 'number', 'float'):
                        label = var['label']
                        name = var['name']
                        default = var.get('default', '')
                        required = var.get('required', False)
                        placeholder = var.get('placeholder', '')
                        if var['type'] == 'float':
                            popup.addText(label, name, required, type='number', value=default, placeholder=placeholder, step="0.1")
                        else:
                            popup.addText(label, name, required, type=var['type'], value=default, placeholder=placeholder)
                    elif var['type'] == 'hidden':
                        popup.addHiddenField(var['name'], var['value'])
                    elif var['type'] == 'message':
                        popup.addMessage(var['message'], var['messagetype'])

        for name, value in data.items():
            popup.addHiddenField(name, value)

        popup.write_html(page)

    if len(actionoptions) >= 1:
        actionsid = None
        if gridbinding:
            actionsid = "actions_%s" % gridbinding[0]
            jscontent = """
    $(document).on('init.dt', function(e, settings) {
        var actionid = '#actions_' + settings.sTableId;
        var action = $(actionid);
        if (action) {
            var button = action.find('button');
            action.css('margin', '10px');
            var container = '#' + settings.sTableId + '_length';
            $(container).append(action);
            var tableid = '#' + settings.sTableId;
            var table = $(tableid);
            if (table.dataTable().fnSettings().oInit.select) {
                button.prop('disabled', true);
                var linka = $('<a href="#">Select All</a>');
                var linkn = $('<a href="#">Clear Selection</a>');
                linkn.hide();
                linka.click(function (e) {
                    e.preventDefault();
                    var rows = table.DataTable().rows();
                    rows.select();
                });
                linkn.click(function (e) {
                    e.preventDefault();
                    var rows = table.DataTable().rows();
                    rows.deselect();
                });
                $(container).append(linka);
                $(container).append('&nbsp;');
                $(container).append(linkn);
                var onselect = function (e, dt, type, indexes) {
                    var count = dt.rows({'selected': true}).count()
                    var totalcount = dt.rows().count()
                    if (count == 0){
                        linkn.hide();
                        button.prop('disabled', true);
                    } else {
                        linkn.show();
                        button.prop('disabled', false);
                    }
                    if (totalcount == count) {
                        linka.hide();
                    } else {
                        linka.show();
                    }
                };
                table.DataTable().on('select', onselect);
                table.DataTable().on('deselect', onselect);
            }
        }
    });
"""
            page.addDocumentReadyJSfunction(jscontent)
        page.addBootstrapCombo(title, actionoptions, actionsid)
    params.result = page

    return params
예제 #32
0
def main(j, args, params, tags, tasklet):

    params.result = page = args.page
    diskid = args.getTag("diskid")

    osiscl = j.clients.osis.getByInstance("main")
    cbosis = j.clients.osis.getNamespace("cloudbroker", osiscl)

    disk = cbosis.disk.get(int(diskid))
    iotune = disk.iotune

    popup = Popup(
        id="disk_limitio_%s" % disk.id,
        header="Limit disk io",
        submit_url="/restmachine/cloudbroker/qos/limitIO",
        clearForm=False,
    )

    popup.addMessage(
        "Value won't be updated if field is empty. Enter 0 to remove IO limitation."
    )
    popup.addText(
        "Total iops per sec",
        "total_iops_sec",
        type="number",
        value=iotune.get("total_iops_sec", ""),
    )
    popup.addText(
        "Read iops per sec",
        "read_iops_sec",
        type="number",
        value=iotune.get("read_iops_sec", ""),
    )
    popup.addText(
        "Write iops per sec",
        "write_iops_sec",
        type="number",
        value=iotune.get("write_iops_sec", ""),
    )
    popup.addText(
        "Total bytes per sec",
        "total_bytes_sec",
        type="number",
        value=iotune.get("total_bytes_sec", ""),
    )
    popup.addText(
        "Total read bytes per sec",
        "read_bytes_sec",
        type="number",
        value=iotune.get("read_bytes_sec", ""),
    )
    popup.addText(
        "Total write bytes per sec",
        "write_bytes_sec",
        type="number",
        value=iotune.get("write_bytes_sec", ""),
    )
    popup.addText(
        "Maximum total bytes per sec",
        "total_bytes_sec_max",
        type="number",
        value=iotune.get("total_bytes_sec_max", ""),
    )
    popup.addText(
        "Maximum read bytes per sec",
        "read_bytes_sec_max",
        type="number",
        value=iotune.get("read_bytes_sec_max", ""),
    )
    popup.addText(
        "Maximum write bytes per sec",
        "write_bytes_sec_max",
        type="number",
        value=iotune.get("write_bytes_sec_max", ""),
    )
    popup.addText(
        "Maximum total iops per sec",
        "total_iops_sec_max",
        type="number",
        value=iotune.get("total_iops_sec_max", ""),
    )
    popup.addText(
        "Maximum read iops per sec",
        "read_iops_sec_max",
        type="number",
        value=iotune.get("read_iops_sec_max", ""),
    )
    popup.addText(
        "Maximum write iops per sec",
        "write_iops_sec_max",
        type="number",
        value=iotune.get("write_iops_sec_max", ""),
    )
    popup.addText(
        "Iops size per sec",
        "size_iops_sec",
        type="number",
        value=iotune.get("size_iops_sec", ""),
    )

    popup.addHiddenField("diskId", disk.id)
    popup.write_html(page)

    return params
예제 #33
0
def main(j, args, params, tags, tasklet):
    params.result = page = args.page

    # Placeholder that -1 means no limits are set on the cloud unit
    culimitplaceholder = 'leave empty if no limits should be set'
    options = OrderedDict({'Yes': 1, 'No': 0})
    popup = Popup(id='createaccount',
                  header='Create Account',
                  submit_url='/restmachine/cloudbroker/account/create')
    popup.addText('Name', 'name', required=True, placeholder='Account Name')
    popup.addText(
        'Username',
        'username',
        required=True,
        placeholder='Owner of account, will be created if does not exist')
    popup.addText(
        'Email Address',
        'emailaddress',
        required=False,
        placeholder='User email, only required if username does not exist')
    popup.addText('Max Memory Capacity (GB)',
                  'maxMemoryCapacity',
                  placeholder=culimitplaceholder,
                  type='float')
    popup.addText('Max VDisk Capacity (GB)',
                  'maxVDiskCapacity',
                  placeholder=culimitplaceholder,
                  type='number')
    popup.addText('Max Number of CPU Cores',
                  'maxCPUCapacity',
                  placeholder=culimitplaceholder,
                  type='number')
    popup.addText('Max External Network Transfer (GB)',
                  'maxNetworkPeerTransfer',
                  placeholder=culimitplaceholder,
                  type='number')
    popup.addText('Max Number of Public IP Addresses',
                  'maxNumPublicIP',
                  placeholder=culimitplaceholder,
                  type='number')
    popup.addDropdown(
        'Email is sent when a user is granted access to a resource',
        'sendAccessEmails', options.iteritems())
    popup.write_html(page)
    return params
예제 #34
0
def main(j, args, params, tags, tasklet):
    params.result = page = args.page
    ccl = j.clients.osis.getNamespace("cloudbroker")
    locations = ccl.location.search({})[1:]

    popup = Popup(
        id="addexternalnetwork",
        header="Add External Network",
        submit_url="/restmachine/cloudbroker/iaas/addExternalNetwork",
    )
    popup.addText("Name", "name", required=True)
    popup.addText("Subnet CIDR", "subnet", required=True)
    popup.addText("Gateway IP Address", "gateway", required=True)
    popup.addText("Start IP Address", "startip", required=True)
    popup.addText("End IP Address", "endip", required=True)
    popup.addNumber(
        "VLAN Tag (leave empty if its the standard public bridge)",
        "vlan",
        required=False,
    )
    popup.addNumber(
        "AccountId (make external network exclusive to this accountId otherwise leave empty)",
        "accountId",
        required=False,
    )
    popup.addDropdown(
        "Choose Location",
        "gid",
        [(location["name"], location["gid"]) for location in locations],
    )
    popup.addText(
        " Enter list of ips(seperated by commas), eg 8.8.8.8,10.10.10.10. If you want to disable the health check, enter 127.0.0.1",
        "pingips",
        placeholder="If left empty default will be 8.8.8.8",
    )
    popup.write_html(page)

    return params
예제 #35
0
def main(j, args, params, tags, tasklet):
    page = args.page
    from JumpScale.portal.docgenerator.popup import Popup
    import yaml

    def _showexample():
        page.addMessage("""Actions must be in yaml form.
eg:
- display: Start
  action: /restmachine/cloudbroker/machine/start
  input:
  - reason
  - spacename
  - name: accesstype
    type: dropdown
    label: ACL
    values:
     - label: Admin
       value: ARCXDU
     - label: Write
       value: RCX
     - label: Read
       value: R

  data:
   machineId: $$id
   accountName: $$accountname

- display: Stop
  action: /restmachine/cloudbroker/machine/stop?machineId=$$id&reason=ops&accountName=$$accountname&spaceName=$$spacename
}}
""")
        params.result = page
        return params

    macrostr = args.macrostr.strip()
    title = args.getTag('title', 'Action')
    gridbinding = args.getTag('gridbinding', '').split()
    content = "\n".join(macrostr.split("\n")[1:-1])

    if not content:
        return _showexample()

    actionoptions = []
    actions = yaml.load(content)
    if actions == content:
        return _showexample()

    if not isinstance(actions, list):
        actions = [actions]

    for actiondata in actions:
        actionurl = actiondata['action']
        display = actiondata['display']
        inputs = actiondata.get('input', '')
        navigateback = actiondata.get('navigateback', False)
        reload = actiondata.get('reload', True)
        clearForm = actiondata.get('clearform', True)
        hide = actiondata.get('hide', False)
        data = actiondata.get('data', {})
        showresponse = actiondata.get('showresponse', False)
        hideon = actiondata.get('hideon', [])
        if hideon:
            hideon_input = actiondata.get('hideonInput', '')
            if hideon_input in hideon:
                continue

        action = "$('%s').modal('show');"

        if actionurl.startswith("#"):
            actionoptions.append((display, action % actionurl))
            continue
        else:
            actionid = "action-%s" % display.replace(' ', '')
            if not hide:
                actionoptions.append((display, action % ('#' + actionid)))

        popup = Popup(id=actionid,
                      header="Confirm Action %s" % display,
                      submit_url=actionurl,
                      navigateback=navigateback,
                      reload_on_success=reload,
                      showresponse=showresponse,
                      clearForm=clearForm,
                      gridbinding=gridbinding)
        if inputs:
            for var in inputs:
                if isinstance(var, basestring):
                    popup.addText(var, var)
                else:
                    if var['type'] in ('dropdown', 'radio'):
                        label = var['label']
                        name = var['name']
                        options = list()
                        for value in var['values']:
                            options.append((value['label'], value['value']))
                        if var['type'] == 'dropdown':
                            popup.addDropdown(label, name, options)
                        elif var['type'] == 'checkboxes':
                            popup.addCheckboxes(label, name, options)
                        elif var['type'] == 'radio':
                            popup.addRadio(label, name, options)
                    elif var['type'] in ('text', 'password', 'number',
                                         'float'):
                        label = var['label']
                        name = var['name']
                        default = var.get('default', '')
                        placeholder = var.get('placeholder', '')
                        if var['type'] == 'float':
                            popup.addText(label,
                                          name,
                                          type='number',
                                          value=default,
                                          placeholder=placeholder,
                                          step="0.1")
                        else:
                            popup.addText(label,
                                          name,
                                          type=var['type'],
                                          value=default,
                                          placeholder=placeholder)
                    elif var['type'] == 'hidden':
                        popup.addHiddenField(var['name'], var['value'])
                    elif var['type'] == 'message':
                        popup.addMessage(var['message'], var['messagetype'])

        for name, value in data.items():
            popup.addHiddenField(name, value)

        popup.write_html(page)

    if len(actionoptions) >= 1:
        actionsid = None
        if gridbinding:
            actionsid = "actions_%s" % gridbinding[0]
            jscontent = """
    $(document).on('init.dt', function(e, settings) {
        var actionid = '#actions_' + settings.sTableId;
        var action = $(actionid);
        if (action) {
            action.css('margin', '10px');
            var container = '#' + settings.sTableId + '_length';
            $(container).append(action);
            var tableid = '#' + settings.sTableId;
            var table = $(tableid);
            if (table.dataTable().fnSettings().oInit.select) {
                var link = $('<a href="#">Select All</a>');
                var selected = false;
                link.click(function (e) {
                    e.preventDefault();
                    var rows = table.DataTable().rows();
                    if (!selected) {
                        rows.select();
                        $(this).text('Clear Selection');
                    } else {
                        rows.deselect();
                        $(this).text('Select All');
                    }
                    selected = !selected;
                });
                $(container).append(link);
            }
        }
    });
"""
            page.addDocumentReadyJSfunction(jscontent)
        page.addBootstrapCombo(title, actionoptions, actionsid)
    params.result = page

    return params
예제 #36
0
def main(j, args, params, tags, tasklet):
    page = args.page
    from JumpScale.portal.docgenerator.popup import Popup
    import yaml


    def _showexample():
        page.addMessage("""Actions must be in yaml form.
eg:
- display: Start       
  input:       
  - reason     
  - spacename      
  action: /restmachine/cloudbroker/machine/start       
  data:        
   machineId: $$id     
   accountName: $$accountname      
         
- display: Stop
  action: /restmachine/cloudbroker/machine/stop?machineId=$$id&reason=ops&accountName=$$accountname&spaceName=$$spacename
}}
""")
        params.result = page
        return params

    macrostr = args.macrostr.strip()
    content = "\n".join(macrostr.split("\n")[1:-1])

    if not content:
        return _showexample()

    actionoptions = [('Choose Action', '#')]
    actions = yaml.load(content)
    if actions == content:
        return _showexample()

    for actiondata in actions:
        actionurl = actiondata['action']
        display = actiondata['display']
        inputs = actiondata.get('input', '')
        data = actiondata.get('data', {})
        if actionurl.startswith("#"):
            actionoptions.append((display, actionurl[1:]))
            continue
        else:
            actionid = "action-%s" % display.replace(' ', '')
            actionoptions.append((display, actionid))

        popup = Popup(id=actionid, header="Confirm Action %s" % display, submit_url=actionurl)
        if inputs:
            for var in inputs:
                popup.addText(var, var)

        for name, value in data.iteritems():
            popup.addHiddenField(name, value)

        popup.write_html(page)

    id = page.addComboBox(actionoptions)
    page.addJS(None, """
        $(document).ready(function() {
            $("#%(id)s").change(function () {
                 var actionid = $("#%(id)s").val();
                 if (actionid != '#'){
                    $('#'+actionid).modal('show');
                 }
            });
        });
        """ % ({'id':id}))
    params.result = page

    return params
예제 #37
0
def main(j, args, params, tags, tasklet):
    params.result = page = args.page
    ccl = j.clients.osis.getNamespace('cloudbroker')
    locations = ccl.location.search({})[1:]

    popup = Popup(id='addexternalnetwork', header='Add External Network',
                  submit_url='/restmachine/cloudbroker/iaas/addExternalNetwork')
    popup.addText('Name', 'name', required=True)
    popup.addText('Subnet CIDR', 'subnet', required=True)
    popup.addText('Gateway IP Address', 'gateway', required=True)
    popup.addText('Start IP Address', 'startip', required=True)
    popup.addText('End IP Address', 'endip', required=True)
    popup.addNumber('VLAN Tag (leave empty if its the standard public bridge)', 'vlan', required=False)
    popup.addNumber('AccountId (make external network exclusive to this accountId otherwise leave empty)', 'accountId', required=False)
    popup.addDropdown('Choose Location', 'gid', [(location['name'], location['gid']) for location in locations])
    popup.addNumber("DHCP server ID (leave empty if no DHCP server for this network)", "dhcpServerId", required=False)
    popup.addText(' Enter list of ips(seperated by commas), eg 8.8.8.8,10.10.10.10. If you want to disable the health check, enter 127.0.0.1', 'pingips', placeholder='If left empty default will be 8.8.8.8')
    popup.write_html(page)

    return params
예제 #38
0
def main(j, args, params, tags, tasklet):
    params.result = page = args.page

    # Placeholder that -1 means no limits are set on the cloud unit
    culimitplaceholder = "leave empty if no limits should be set"
    options = OrderedDict({"Yes": 1, "No": 0})
    popup = Popup(
        id="createaccount",
        header="Create Account",
        submit_url="/restmachine/cloudbroker/account/create",
    )
    popup.addText("Name", "name", required=True, placeholder="Account Name")
    popup.addText(
        "Username",
        "username",
        required=True,
        placeholder="Owner of account, will be created if does not exist",
    )
    popup.addText(
        "Email Address",
        "emailaddress",
        required=False,
        placeholder="User email, only required if username does not exist",
    )
    popup.addText(
        "Max Memory Capacity (GB)",
        "maxMemoryCapacity",
        placeholder=culimitplaceholder,
        type="float",
    )
    popup.addText(
        "Max VDisk Capacity (GB)",
        "maxVDiskCapacity",
        placeholder=culimitplaceholder,
        type="number",
    )
    popup.addText(
        "Max Number of CPU Cores",
        "maxCPUCapacity",
        placeholder=culimitplaceholder,
        type="number",
    )
    popup.addText(
        "Max External Network Transfer (GB)",
        "maxNetworkPeerTransfer",
        placeholder=culimitplaceholder,
        type="number",
    )
    popup.addText(
        "Max Number of Public IP Addresses",
        "maxNumPublicIP",
        placeholder=culimitplaceholder,
        type="number",
    )
    popup.addDropdown(
        "Email is sent when a user is granted access to a resource",
        "sendAccessEmails",
        options.iteritems(),
    )
    popup.write_html(page)
    return params