コード例 #1
0
def delete(args, appURL):
    tmp = appURL.split(":")
    appid = tmp[0]
    if len(tmp) > 1:
        appversion = tmp[1]
    else:
        appversion = 1  # default value

    if db.checkToken(args["x-token-id"]):
        if args["x-unpublish-on-delete"] == None:
            app = db.getLocalApplication(appid)
            if app == None:
                return "", 200  # Yes, it returns 200 even if the application doesn't exists
            if app["published"]:
                return """<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
                            <error>
                                <code>1303</code>
                                <description>App %s is in use: Unable to delete apps with name %s
                            As app with name %s and version%d is in published state</description>
                        </error>""" % (app["name"], app["name"], app["name"],
                                       app["name"]), 400, {
                                           "Content-Type": "application/xml"
                                       }  # TODO: customize returned error name
        db.deleteLocalApplication(appid)
        return "", 200
    else:
        return invalidToken()
コード例 #2
0
def post(args, data):
    if db.checkToken(args["x-token-id"]):
        try:
            appname = data["name"]
            sourceAppName = data["sourceAppName"]
            version = data["version"]
            appType = data["appSourceType"]
        except KeyError:
            return {
                    "code": 1001,
                    "description": "Given request is not valid: {0}"
                }, 400, {"Content-Type": "application/json"}
        if db.myAppExists(appname):
            return {
                    "code": 1304,
                    "description": "An app with name %s already exists." % appname # Cisco does not return the name but the identifier
                }, 409, {"content-type": "application/json"}
        if appType != "LOCAL_APPSTORE":
            {
                "code": -1,
                "description": "This simulator is not able to manage not LOCAL_APPSTORE applications"
            }, 400, {"Content-Type": "application/json"}
        if args["minjobs"] != None:
            minjob = int(args["minjobs"])
            myapp = db.createMyApp(appname, sourceAppName, version, appType, minjobs=minjob)
        else:
            myapp = db.createMyApp(appname, sourceAppName, version, appType)
        del myapp["_id"]
        return {"myappId": myapp["myappId"], "name": myapp["name"]}, 201, {"content-type": "application/json"}
    else:
        return invalidToken()
コード例 #3
0
def post(args, data, tagid):
    tag = db.getTag(tagid)
    if db.checkToken(args["x-token-id"]):
        try:
            deviceIds = data["devices"]
        except KeyError:
            deviceIds = []
        for deviceid in deviceIds:
            db.tagDevice(int(deviceid), tagid)
    else:
        return invalidToken()

    # You can destroy the server but the only information returned is the tag itself. Cisco, REALLY??
    return {
        "_links": {
            "device": {
                "href": "/api/v1/appmgr/tags/%s/devices" % tagid
            },
            "self": {
                "href": "/api/v1/appmgr/tags/%s" % tagid
            }
        },
        "tagId": tagid,
        "name": tag["name"],
        "description": tag["description"]
    }, 200, {
        "ContentType": "application/json"
    }
コード例 #4
0
def get(args):
    if db.checkToken(args["x-token-id"]):
        data = {"data": []}
        devices = db.getDevices(
            args["limit"] if args["limit"] != None else 1000,
            args["offset"] if args["offset"] != None else 0,
            args["searchByTags"], args["searchByAnyMatch"])

        for device in devices:
            del device[
                "password"]  # removing password from the returned HTTP API object
            del device["_id"]
            # formatting tags as API expects
            tags = []
            for tagid in device["tags"]:
                tag = db.getTag(tagid)
                tag["tagId"] = str(tag["_id"])
                del tag["_id"]
                if tag["description"] == "":
                    del tag["description"]
                tags.append(tag)
            device["tags"] = tags
            data["data"].append(formatDeviceOutput(device))
        return data, 200, {'ContentType': 'application/json'}
    else:
        return invalidToken()
コード例 #5
0
def delete(deviceid, args):
    if db.checkToken(args["x-token-id"]):
        dev = db.getDevice(deviceid)
        db.deleteDevice(deviceid)
        del dev["_id"]
        return dev, 200, [("content-type", "application/json")]
    else:
        return invalidToken()
コード例 #6
0
 def get(self, devid):
     parser = reqparse.RequestParser()
     parser.add_argument('x-token-id', location='headers')
     args = parser.parse_args()
     if db.checkToken(args["x-token-id"]):
         return "Not Implemented Yet"  # TODO Implement this
     else:
         return invalidToken()
コード例 #7
0
def get(args):
    if db.checkToken(args["x-token-id"]):
        data = {"data": []}
        apps = db.getLocalApplications()
        for app in apps:
            del app[
                "_id"]  # removing internal ID, not JSON serializable object
            data["data"].append(app)
        return data, 200, {"Content-Type": "application/json"}
    else:
        return invalidToken()
コード例 #8
0
ファイル: Alerts.py プロジェクト: di-unipi-socc/FogDirSim
def get(args):
    if db.checkToken(args["x-token-id"]):
        alerts = db.getAlerts()
        data = []
        for alert in alerts:
            data.append(alert)
        data.sort(key=cmp_to_key(lambda x, y: -1 if x["time"] < y["time"] else
                                 (0 if x["time"] == y["time"] else 1)))
        return {"data": data}, 200, {"content-type": "application/json"}
    else:
        return invalidToken()
コード例 #9
0
ファイル: Jobs.py プロジェクト: di-unipi-socc/FogDirSim
def get(args):
    if db.checkToken(args["x-token-id"]):
        jobs = db.getJobs()
        data = []
        for job in jobs:
            job["id"] = str(job["_id"])
            del job["_id"]
            data.append(job)
        return {"data": data}, 200, {"content-type": "application/json"}
    else:
        return invalidToken()
コード例 #10
0
def get(args):
    if db.checkToken(args["x-token-id"]):
        data = {"data": []}
        myapps = db.getMyApps(args["searchByName"])
        for myapp in myapps:
            del myapp["_id"]
            data["data"].append(myapp)
            if args["searchByName"] != None:
                return myapp, 200, {'ContentType':'application/json'} 
        return data, 200, {'ContentType':'application/json'} 
    else:
        return invalidToken()
コード例 #11
0
def delete(args, myappId):
    if db.checkToken(args["x-token-id"]):
        try:
            app = db.deleteMyApp(myappId)

            del app["_id"]
            return app
        except MyAppInstalledOnDeviceError as e:
            return {"Error": str(e)}, 400, {"Content-type": "application/json"} # TODO: this response is not compared with FogDirector
        return {"Simulation Internal Server Error in MyApps_executor delete", 500}
    else:
        return invalidToken()
コード例 #12
0
ファイル: Tags.py プロジェクト: di-unipi-socc/FogDirSim
def post(args, data):
    if db.checkToken(args["x-token-id"]):
        try:
            tagname = data["name"]
        except KeyError:
            return {
                "code":
                1000,
                "description":
                "An unexpected error happened. Validation failed for classes [com.cisco.eng.ccm.model.device.Tag] during persist time for groups [javax.validation.groups.Default, ]\nList of constraint violations:[\n\tConstraintViolationImpl{interpolatedMessage='may not be null', propertyPath=name, rootBeanClass=class com.cisco.eng.ccm.model.device.Tag, messageTemplate='{javax.validation.constraints.NotNull.message}'}\n]"
            }, 500, {
                "ContentType": "application/json"
            }
        try:
            tagdescription = data["description"]
        except KeyError:
            tagdescription = ""

        if db.tagExists(tagname):
            return {
                "code": 1402,
                "description": "Tag with name new_tag, already exist."
            }, 409, {
                "ContentType": "application/json"
            }

        tagid = str(db.addTag(tagname, tagdescription))
        return {
            "_links": {
                "device": {
                    "href": "/api/v1/appmgr/tags/%s/devices" % tagid
                },
                "self": {
                    "href": "/api/v1/appmgr/tags/%s" % tagid
                }
            },
            "tagId": tagid,
            "name": "newtag"
        }, 201, {
            'ContentType': 'application/json'
        }
    else:
        return invalidToken()
コード例 #13
0
def post(args, data, devices=None):
    if db.checkToken(args["x-token-id"]):
        if data == None or\
            data["ipAddress"] == None or\
            data["port"] == None or\
            data["username"] == None or\
            data["password"] == None:
            return {
                "description":
                "ipAddress, port, username or password not defined"
            }, 401, {
                "ContentType": "application/json"
            }

        if db.deviceExists(data["ipAddress"], data["port"]):
            return {
                "code":
                1101,
                "description":
                "A device with IP address, %s, already exists in the inventory."
                % data["ipAddress"]
            }, 409, {
                "ContentType": "application/json"
            }

        try:
            devSpecs = db.addDevice(data["ipAddress"], data["port"],
                                    data["username"], data["password"])
        except LookupError:
            return {
                "error":
                "LookupError: The device you are adding is not present in the RealDatabase"
            }, 400, {
                'ContentType': 'application/json'
            }
        del devSpecs["_id"]
        return formatDeviceOutput(devSpecs), 201, {
            'ContentType': 'application/json'
        }
    else:
        return invalidToken()
コード例 #14
0
ファイル: Tags.py プロジェクト: di-unipi-socc/FogDirSim
def get(args):
    if db.checkToken(args["x-token-id"]):
        tags = db.getTags()
        data = []
        for tag in tags:
            data.append({
                "_links": {
                    "device": {
                        "href":
                        "/api/v1/appmgr/tags/%s/devices" % str(tag["_id"])
                    },
                    "self": {
                        "href": "/api/v1/appmgr/%s/2714" % str(tag["_id"])
                    }
                },
                "tagId": str(tag["_id"]),
                "name": tag["name"],
                "description": tag["description"]
            })
        return {"data": data}, 200, {'ContentType': 'application/json'}
    else:
        return invalidToken()
コード例 #15
0
def put(args, data, appURL):
    if db.checkToken(args["x-token-id"]):
        tmp = appURL.split(":")
        appid = tmp[0]
        if len(tmp) > 1:
            appversion = tmp[1]
        else:
            appversion = 1  # default value
        if (not db.localApplicationExists(appid, appversion)):
            return notFoundApp(appid)
        if (appversion == None):
            return notFoundApp(
                appid
            )  # this error is returned even if the application exists, but no version is specified
        db.updateLocalApplication(appid, data)
        # Another error should be returned if the data passed is not completed as stored in DB. All the field
        # have to be passed, also the unchanged ones. I ignore this error.
        app = db.getLocalApplication(appid)
        del app["_id"]
        return app, 200, {"Content-Type": "application/json"}
    else:
        return invalidToken()
コード例 #16
0
def post(args, request, uploadDir, filename):
    if db.checkToken(args["x-token-id"]):
        # Extracting file
        os.chdir(uploadDir)

        tmpDir = str(hash(filename))
        if not os.path.exists(tmpDir):
            os.makedirs(tmpDir)

        if (filename.endswith("tar.gz")):
            tar = tarfile.open(filename, "r:gz")
            os.chdir(tmpDir)
            tar.extractall()
            tar.close()

        elif (filename.endswith("tar")):
            tar = tarfile.open(filename, "r:")
            os.chdir(tmpDir)
            tar.extractall()
            tar.close()

        # Opening YAML Description of the application
        try:
            with open("package.yaml", 'r') as stream:
                app_data = yaml.load(stream)
        except IOError:
            return file_error_string, 400, {"Content-Type": "application/xml"}
        os.chdir("../")

        if db.getMyApps(searchByName=app_data["info"]["name"]).count() != 0:
            return '''<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
                    <error>
                        <code>1316</code>
                        <description>An app with the same deployId already exists. Please make sure that the characters of the app do not match with any of the existing apps.</description>
                    </error>''', 409, {
                "Content-Type": "application/xml"
            }

        appJson = createApplicationJSON(
            creationDate=int(time.time()),
            lastupdateTime=int(time.time()),
            descriptorSchemaVersion=app_data["descriptor-schema-version"],
            info=app_data["info"],
            app=app_data["app"],
            signed=False,
            appid=-1,
            version=app_data["info"]["version"],
            name=app_data["info"]["name"],
            description=app_data["info"]["description"],
            apptype=app_data["app"]["type"],
            published=False,
            resources=app_data["app"]["resources"],
            cpuUsage=0,
            memoryUsage=0)
        if (args["x-publish-on-upload"] == "true"
                or args["x-publish-on-upload"] == "True"
                or args["x-publish-on-upload"] == True):
            appJson["published"] = True
        appID = str(db.addLocalApplication(appJson))
        appJson["localAppId"] = appID
        appJson["sourceAppName"] = str(appID) + ":1"
        os.rename(tmpDir, appID)

        os.chdir("../")
        appReturn = db.getLocalApplication(appID)
        del appReturn["_id"]
        response = Response(json.dumps(appReturn),
                            201,
                            mimetype="application/json;charset=UTF-8")
        return response  # and finally yes, it returns also the charset here!
    else:
        return invalidToken()
コード例 #17
0
def post(args, data, myappId):
    if db.checkToken(args["x-token-id"]):
        try:
            myapp = db.getMyApp(myappId)
            if "deploy" in data.keys():
                action = "deploy"
                data = data["deploy"]
                devices = data["devices"]  
                app = db.getLocalApplicationBySourceName(myapp["sourceAppName"])
                if not app["published"]: # This is not checked in FogDirector, but in unpublished app it crash
                    return {"error": "the app have to be published"}, 400, {"content-type": "application/json"}
                deviceSuccessful = []
                profile = constants.MYAPP_PROFILE_NORMAL
                for device in devices:
                    devid = device["deviceId"]
                    resourceAsked = device["resourceAsk"]["resources"]
                    if args["profile"] in [constants.MYAPP_PROFILE_LOW, constants.MYAPP_PROFILE_NORMAL, constants.MYAPP_PROFILE_HIGH]:
                        profile = args["profile"]
                    else:
                        profile = constants.MYAPP_PROFILE_NORMAL
                    try:
                        if not db.deviceIsAlive(devid):
                            return {"Error": "Device does not reachable"}, 400, {"content-type": "application/json"}
                        try:
                            db.checkAndAllocateResource(devid, resourceAsked["cpu"], resourceAsked["memory"])
                        except TypeError:
                            return {"Error": "Device does not exist"}, 400, {"content-type": "application/json"}
                        db.addMyAppToDevice(myappId, devid, profile)
                        db.addMyAppLog({
                            "time": int(time.time()),
                            "action": action,
                            "deviceSerialNo": devid,
                            "appName": myapp["name"],
                            "appVersion": "1",
                            "severity": "info",
                            "profile": profile,
                            "user": "******",
                            "message": action+" operation succeeded"
                        })
                        deviceSuccessful.append(device)
                    except NoResourceError as e:
                        db.addMyAppLog({
                            "time": int(time.time()),
                            "action": action,
                            "deviceSerialNo": devid,
                            "appName": myapp["name"],
                            "appVersion": "1",
                            "severity": "info",
                            "user": "******",
                            "message": action+" operation failed, no sufficient resources"
                        })
                        return {
                            "code": 1000,
                            "description": str(e)
                        }, 400, {"content-type": "application/json"}
                # TODO: if la myapp è già sul device: ritorna errore  
                jobid = db.addJobs(myappId, deviceSuccessful, profile=profile, payload=data)
                
            elif "start" in data.keys() or "stop" in data.keys(): 
                action = "start" if "start" in data.keys() else "stop"
                db.addMyAppLog({
                    "time": int(time.time()),
                    "action": action,
                    "appName": myapp["name"],
                    "appVersion": "1",
                    "severity": "info",
                    "user": "******",
                    "message": action+" operation succeeded"
                })
                jobid = db.updateJobsStatus(myappId, action)
                
            elif "undeploy" in data.keys(): 
                action = "undeploy"
                data = data[action]
                devices_payload = data["devices"]
                myapp = db.getMyApp(myappId) # Taken for Name only
                myapp_jobs = db.getJobs(myappId)
                if myapp_jobs == 0:
                    return {"Error": "no jobs are running"}, 400, {"content-type": "application/json"}
                for job in myapp_jobs:
                    try:
                        jobDescr = job["payload"]
                        resourcesDevs = jobDescr["devices"]
                        for device in resourcesDevs:
                            if device["deviceId"] in devices_payload:
                                cpu = 0
                                mem = 0
                                resourceAsked = device["resourceAsk"]["resources"]
                                if device["deviceId"] in devices_payload:
                                    cpu = device["resourceAsk"]["resources"]["cpu"]
                                    mem = device["resourceAsk"]["resources"]["memory"]
                                    db.deallocateResource(device["deviceId"],cpu, mem)
                                    db.removeMyAppsFromDevice(myappId, device["deviceId"])
                                    db.uninstallJob(myappId, device["deviceId"])

                                    db.addMyAppLog({
                                        "time": int(time.time()),
                                        "action": action,
                                        "deviceSerialNo": device["deviceId"],
                                        "appName": myapp["name"],
                                        "appVersion": "1",
                                        "severity": "info",
                                        "user": "******",
                                        "message": action+" operation succeeded"
                                    })
                    except TypeError:
                        return {"Error": "Internal Error TypeError"}, 500, {"content-type": "application/json"}
            try:
                return {
                    "jobId": str(jobid)
                }, 200, {"content-type": "application/json"}   
            except UnboundLocalError:
                return {}, 200, {"content-type": "application/json"}
        except KeyError as e:
            traceback.print_exc()
            return {
                    "code": 1001,
                    "description": "Given request is not valid: "+str(e)
                }, 400, {"content-type": "application/json"}
        return {
                "code": 500,
                "description": "An unexpected error happened. {0}"
            }, 500, {"content-type": "application/json"} 
    else:
        return invalidToken()