Exemplo n.º 1
0
def delete_vm(profile, vm_id):
    gw = Gateway(**{'profile': profile})
    try:
        if vm_id in [vm['VmId'] for vm in gw.ReadVms()['Vms']]:
            gw.DeleteVms(VmIds=[vm_id])
        return True
    except:
        return False
Exemplo n.º 2
0
def create_vm(profile, vmtype, storage, omi):
    gw = Gateway(**{'profile': profile})
    
    with open('/Users/benjaminlaplane/.oapi_credentials') as creds:
        credentials = json.load(creds)
        region = credentials[profile]['region']
    with open('config/omi.json') as omis:
        omi_list = json.load(omis)
        image = omi_list[region][omi]
    try:
        if 'db_manager_key' not in [key['KeypairName'] for key in gw.ReadKeypairs()['Keypairs']] :
            new_keypair = gw.CreateKeypair(KeypairName='db_manager_key')
            with open('../db_manager_key.rsa', 'w') as newkey:
                newkey.write(new_keypair['Keypair']['PrivateKey'])

        new_vm = gw.CreateVms(ImageId=image, VmType=vmtype, KeypairName='db_manager_key')['Vms'][0]
        new_vol = gw.CreateVolume(Size=storage['size'], VolumeType=storage['type'], SubregionName=region + 'a')

        gw.LinkVolume(VmId=new_vm['VmId'], VolumeId=new_vol['Volume']['VolumeId'], DeviceName='/dev/xvdb')
    except Exception as errorExcept:
        return False, None, errorExcept

    new_vm = gw.ReadVms(Filters={'VmIds': [new_vm['VmId']]})['Vms'][0]

    if waitforit(gw=gw, vms=[new_vm], state='running'):
        return True, new_vm, None
    return False, new_vm, None
Exemplo n.º 3
0
 async def get_all_security_groups(session: Gateway):
     response = session.ReadSecurityGroups()
     security_groups = []
     if 'SecurityGroups' in response:
         for security_group in response['SecurityGroups']:
             security_groups.append(security_group)
     return security_groups
Exemplo n.º 4
0
 async def get_all_snapshots(session: Gateway):
     response = session.ReadSnapshots()
     snapshots = []
     if 'Snapshots' in response:
         for snapshot in response['Snapshots']:
             snapshots.append(snapshot)
     return snapshots
Exemplo n.º 5
0
 async def get_all_volumes(session: Gateway):
     response = session.ReadVolumes()
     volumes = []
     if 'Volumes' in response:
         for volume in response['Volumes']:
             volumes.append(volume)
     return volumes
Exemplo n.º 6
0
 def __call__(self):
     try:
         main.GATEWAY = Gateway(**{"profile": self.name})
         res = main.GATEWAY.ReadClientGateways()
         if "Errors" not in res:
             mainForm.MODE = 'INSTANCES'
             self.form.parentApp.addForm("Cockpit",
                                         mainForm.MainForm,
                                         name="osc-tui")
             self.form.parentApp.switchForm("Cockpit")
         else:
             should_destroy_profile = npyscreen.notify_yes_no(
                 "Credentials are not valids.\nDo you want do delete this profile?",
                 "ERROR",
             )
             if should_destroy_profile:
                 global OAPI_CREDENTIALS
                 del OAPI_CREDENTIALS[self.name]
                 save_credentials(self.form)
     except requests.ConnectionError:
         npyscreen.notify_confirm("Please check your internet connection.",
                                  "ERROR")
Exemplo n.º 7
0
 def authenticate(self, profile=None, access=None, **kwargs):
     if profile:
         try:
             session = Gateway(**{"profile": profile})
             session.ReadAccounts()
         except Exception as e:
             raise AuthenticationException(e)
     elif access:
         session = Gateway({
             "custom": {
                 "access_key": access[0],
                 "secret_key": access[1],
                 "region": "eu-west-2"
             }
         })
     else:
         try:
             session = Gateway()
         except Exception as e:
             raise AuthenticationException(e)
     return session
Exemplo n.º 8
0
import sys
sys.path.append("..")
from osc_sdk_python import Gateway
gw = Gateway()
res = gw.CreateNet(IpRange='142.42.42.42/32')
error = [error for error in res['Errors'] if error.get('Code') == '4014' and error.get('Details') == 'invalid-block-size']
assert len(error) == 1

Exemplo n.º 9
0
from osc_sdk_python import Gateway
import json
if __name__ == '__main__':
    gw = Gateway(**{'profile': 'default'})

    #for vm in gw.ReadVms()['Vms']:
    #   print(json.dumps(vm["SecurityGroups"]))
    vms = ((gw.ReadVms()['Vms']))
    VMs = dict()
    for vm in vms:
        VMs.update({vm['VmId']: vm})
    #print(json.dumps(VMs))
    #print  (VMs)
    #print(json.dumps(gw.ReadSecurityGroups()))

    #print("\nyour volumes:")
    #for volume in gw.ReadVolumes()["Volumes"]:
    #print(volume["VolumeId"])
    #ssgw1 = Gateway()
    #print(gw1.ReadSecurityGroups(  Filters = {    "SecurityGroupIds": [      "sg-c387f0b7"    ]})['SecurityGroups'][0]['InboundRules'])
    #imgs = gw.ReadImages()["Images"]
    #for img in imgs:
    #    account = img["AccountAlias"] if "AccountAlias" in img else "Unknow User"
    #    img_str = "creator: " + account + " id: " + img["ImageId"] + " name: " + img["ImageName"]
    #    print(img_str)
    #print(json.dumps(gw.ReadSecurityGroups(
    #            Filters={"SecurityGroupIds": ['sg-c387f0b7']}
    #        )["SecurityGroups"][0]["InboundRules"]))
    print(json.dumps(vms))
    from requests import get
Exemplo n.º 10
0
import json

from osc_sdk_python import Gateway

if __name__ == '__main__':
    gw = Gateway(**{'profile': 'open-source'})

    # for vm in gw.ReadVms()['Vms']:
    #   print(json.dumps(vm["SecurityGroups"]))
    vms = ((gw.ReadVms()['Vms']))
    VMs = dict()
    for vm in vms:
        VMs.update({vm['VmId']: vm})
    # print(json.dumps(VMs))
    #print  (VMs)
    # print(json.dumps(gw.ReadSecurityGroups()))

    #print("\nyour volumes:")
    # for volume in gw.ReadVolumes()["Volumes"]:
    # print(volume["VolumeId"])
    #ssgw1 = Gateway()
    #print(gw1.ReadSecurityGroups(  Filters = {    "SecurityGroupIds": [      "sg-c387f0b7"    ]})['SecurityGroups'][0]['InboundRules'])
    #imgs = gw.ReadImages()["Images"]
    # for img in imgs:
    #    account = img["AccountAlias"] if "AccountAlias" in img else "Unknow User"
    #    img_str = "creator: " + account + " id: " + img["ImageId"] + " name: " + img["ImageName"]
    #    print(img_str)
    # print(json.dumps(gw.ReadSecurityGroups(
    #            Filters={"SecurityGroupIds": ['sg-c387f0b7']}
    #        )["SecurityGroups"][0]["InboundRules"]))
    print(
Exemplo n.º 11
0
import sys
sys.path.append("..")
from osc_sdk_python import Gateway

gw = Gateway()

vms = gw.ReadVms()
assert isinstance(vms, dict)
assert isinstance(vms["Vms"], list)

vols = gw.ReadVolumes()
assert isinstance(vols, dict)
assert isinstance(vols["Volumes"], list)
Exemplo n.º 12
0
    def __call__(self):
        try:
            global res
            main.GATEWAY = Gateway(**{"profile": self.name})

            # The following code is a little bit completely tricky :)
            # Here is the idea:
            # I want to hook all calls to the main.GATEWAY modules to automatically display the pending animation.
            # (So it's a decorator)
            # However, for doing such things I need to add a form parameter.
            # However 2, when performing one call, it will do some "inner calls" so we must not trigger the animation all the time.
            # One way would be to decorate only the "main functions" but I wanna do it automatically!
            # Another one is the following one:
            # If we have the form parameter, we remove it form kwargs and start the pending animation.
            # So the pending animation won't be started again during "inner
            # calls".

            def decorator(func):
                def wrapped(*args, **kwargs):
                    form = kwargs.get('form')
                    global result
                    result = None
                    if form:
                        kwargs.pop('form')

                        def cb():
                            global result
                            result = func(*args, **kwargs)

                        popup.startLoading(form, cb)
                    else:
                        result = func(*args, **kwargs)
                    return result

                return wrapped

            # So now we iterate over all methods of the GATEWAY that are not prefixed by "__"
            # and basically we decorate them.
            for method_name in dir(main.GATEWAY):
                if not method_name.startswith("__"):
                    attr = getattr(main.GATEWAY, method_name)
                    if (callable(attr)):
                        wrapped = decorator(attr)
                        setattr(main.GATEWAY, method_name, wrapped)

            # now let's check if the profile worked:
            res = main.GATEWAY.ReadClientGateways(form=self.form)
            if "Errors" not in res:
                preloader.Preloader.load_async()
                mainForm.MODE = 'INSTANCES'
                self.form.parentApp.addForm("Cockpit",
                                            mainForm.MainForm,
                                            name="osc-tui")
                self.form.parentApp.switchForm("Cockpit")
            else:
                should_destroy_profile = npyscreen.notify_yes_no(
                    "Credentials are not valids.\nDo you want do delete this profile?",
                    "ERROR",
                )
                if should_destroy_profile:
                    global OAPI_CREDENTIALS
                    del OAPI_CREDENTIALS[self.name]
                    save_credentials(self.form)
        except requests.ConnectionError:
            npyscreen.notify_confirm("Please check your internet connection.",
                                     "ERROR")
Exemplo n.º 13
0
from osc_sdk_python import Gateway
import json
if __name__ == '__main__':
    gw = Gateway(**{'profile': 'fne'})

    def decorator(func):
        def wrapped(*args, **kwargs):
            print("TEST")
            return func(*args, **kwargs)

        return wrapped

    for method_name in dir(gw):
        if not method_name.startswith("__"):
            attr = getattr(gw, method_name)
            if (callable(attr)):
                wrapped = decorator(attr)
                setattr(gw, method_name, wrapped)
    # for vm in gw.ReadVms()['Vms']:
    #   print(json.dumps(vm["SecurityGroups"]))
    vms = ((gw.ReadVms()['Vms']))
    VMs = dict()
    for vm in vms:
        VMs.update({vm['VmId']: vm})
    # print(json.dumps(VMs))
    #print  (VMs)
    # print(json.dumps(gw.ReadSecurityGroups()))

    #print("\nyour volumes:")
    # for volume in gw.ReadVolumes()["Volumes"]:
    # print(volume["VolumeId"])