def update_instance_host(cluster_name, instance_id):
     cluster = ResourceManager.get_cluster(cluster_name)
     if not cluster:
         message = "ResourceManager--Update the instance to cluster failed. The cluster is not found. (cluster_name = %s)" % cluster_name
         # result = {"code": "1", "cluster_name":cluster_name, "message":message}
         result = Response(code="failed",
                           message=message,
                           data={"cluster_name": cluster_name})
         return result
     else:
         try:
             result = cluster.update_instance_host(instance_id)
             if result.code == 'failed':
                 return result
             ResourceManager.sync_to_database()
             #logging.info("ResourceManager--Update instance success , instance_id : %s , cluster_name : %s" % (instance_id, cluster_name))
             return result
         except Exception as e:
             message = "ResourceManager--Update the instacne fail.instance_id : %s , cluster_name : %s " % (
                 instance_id, cluster_name) + str(e)
             logging.error(message)
             # result = {"code": "1", "cluster_name": cluster_name, "message": message}
             result = Response(code="failed",
                               message=message,
                               data={"cluster_name": cluster_name})
             return result
 def _add_to_cluster_list(cluster_name, layers_string):
     try:
         cluster = Cluster(cluster_name, layers_string)
         ResourceManager._cluster_dict[cluster_name] = cluster
         message = "ResourceManager -sync to db -- create_cluster._add_to_cluster_list success, cluster_name : %s , protected_layers_string : %s" % (
             cluster_name, layers_string)
         logging.info(message)
         result = Response(code="succeed",
                           message=message,
                           data={
                               "cluster_name": cluster_name,
                               "protected_layers_string": layers_string
                           })
         return result
     except Exception as e:
         message = "ResourceManager - create_cluster._add_to_cluster_list fail,cluster_name : %s, protected_layers_string : %s" % (
             cluster_name, layers_string) + str(e)
         logging.error(message)
         # result = {"code": "1","cluster_name":cluster_name, "message": message}
         result = Response(code="failed",
                           message=message,
                           data={
                               "cluster_name": cluster_name,
                               "protected_layers_string": layers_string
                           })
         return result
 def delete_instance(cluster_name, instance_id):
     cluster = ResourceManager.get_cluster(cluster_name)
     if not cluster:
         message = "delete the instance to cluster failed. The cluster is not found. (cluster_name = %s)" % cluster_name
         # result = {"code": "1", "cluster_name": cluster_name, "instance id ": instance_id, "message": message}
         result = Response(code="failed",
                           message=message,
                           data={
                               "cluster_name": cluster_name,
                               "instance id": instance_id
                           })
         return result
     else:
         try:
             result = cluster.delete_instance(instance_id)
             ResourceManager.sync_to_database()
             #logging.info("ResourceManager--delete instance success")
             return result
         except Exception as e:
             message = "ResourceManager--delete instance failed. this instance is not being protected (instance_id = %s)" % instance_id + str(
                 e)
             logging.error(message)
             # result = {"code": "1", "cluster_name":cluster_name, "message":message}
             result = Response(code="failed",
                               message=message,
                               data={"cluster_name": cluster_name})
             return result
 def add_instance(cluster_name, instance_id):
     cluster = ResourceManager.get_cluster(cluster_name)
     message = ""
     if not cluster:
         message = "ResourceManager--Add the instance to cluster failed. The cluster is not found. (cluster_name = %s)" % cluster_name
         # result = {"code": "1", "cluster_name":cluster_name, "message":message}
         result = Response(code="failed",
                           message=message,
                           data={"cluster_name": cluster_name})
         return result
     else:
         try:
             if not ResourceManager._check_instance_not_overlapping_for_all_cluster(
                     instance_id):
                 return Response(
                     code="failed",
                     message="instance %s is already being protected" %
                     instance_id,
                     data={"instance": instance_id})
             result = cluster.add_instance(instance_id)
             if result.code == 'failed':
                 return result
             ResourceManager.sync_to_database()
             #logging.info("ResourceManager--Add instance success , instance_id : %s , cluster_name : %s" % (instance_id, cluster_name))
             return result
         except Exception as e:
             print str(e)
             message = "ResourceManager --add the instacne fail.instance_id : %s , cluster_name : %s " % (
                 instance_id, cluster_name) + str(e)
             logging.error(message)
             # result = {"code": "1", "cluster_name": cluster_name, "message": message}
             result = Response(code="failed",
                               message=message,
                               data={"cluster_name": cluster_name})
             return result
 def list_node(cluster_name):
     try:
         cluster = ResourceManager.get_cluster(cluster_name)
         if not cluster:
             message = "list the node failed. The cluster is not found. (cluster_name = %s)" % cluster_name
             # result = {"code": "1", "cluster_name":cluster_name, "message":message}
             result = Response(code="failed",
                               message=message,
                               data={"cluster_name": cluster_name})
             return result
         nodelist = cluster.get_all_node_info()
         message = "ResourceManager-list_node--get all node info finish"
         result = Response(code="succeed",
                           message=message,
                           data={
                               "cluster_name": cluster_name,
                               "nodeList": nodelist
                           })
         return result
     except Exception as e:
         message = "ResourceManager--list_node-- get all node info fail" + str(
             e)
         logging.error(message)
         result = Response(code="failed",
                           message=message,
                           data={"cluster_name": cluster_name})
         return result
Esempio n. 6
0
 def parse_rules(self, request):
     response = Response()
     response.type = ResponseType.ASK
     response.value = "Sorry, we cannot find your appointment. Could you repeat your full name?"
     response.state_change = False
     self.count = self.count + 1
     return response
def get(pageNumber):
    retList = []
    datasets = []

    user = AuthenticationService.verifySessionAndReturnUser(
        request.cookies["SID"])

    allDatasets = Dataset.objects.filter(Q(public=True) | Q(
        author=user)).order_by('-dateCreated')

    if pageNumber == "all":
        datasets = allDatasets
    elif pageNumber == "0":
        datasets = allDatasets[:16]
    else:
        datasetIndex = 16 + 12 * (int(pageNumber) - 1)
        datasets = allDatasets[datasetIndex:datasetIndex + 12]

    if len(datasets) == 0:
        return Response("No datasets matching the query were found",
                        status=400)

    for dataset in datasets:
        retList.append(DatasetService.createDatasetInfoObject(dataset))

    return Response(retList)
Esempio n. 8
0
 def addNode(cluster_id, node_name_list, write_DB=True):
     message = ""
     for node_name in node_name_list[:]:
         if not ClusterManager._checkNodeOverlappingForAllCluster(node_name):
             print "%s is already in a HA cluster. " % node_name
             message += "%s is overlapping node" % node_name
             node_name_list.remove(node_name)
     if node_name_list == []: raise Exception("all node in node list are(is) illegal")
     cluster = ClusterManager.getCluster(cluster_id)
     if not cluster:
         message += "ClusterManager--Add the node to cluster failed. The cluster is not found. (cluster_id = %s)" % cluster_id
         # result = {"code": "1", "clusterId":cluster_id, "message":message}
         result = Response(code="failed",
                           message=message,
                           data={"cluster_id": cluster_id})
         return result
     else:
         try:
             result = cluster.addNode(node_name_list)
             logging.info(
                 "ClusterManager--add node success.cluster id is %s ,node is %s " % (cluster_id, node_name_list))
             if result.code == "succeed" and write_DB:
                 ClusterManager.syncToDatabase()
             return result
         except:
             message += "add node fail. node not found. (node_name = %s)" % node_name_list
             logging.error(message)
             # result = {"code": "1", "clusterId": cluster_id, "message": message}
             result = Response(code="failed",
                               message=message,
                               data={"cluster_id": cluster_id})
             return result
	def send_message(self, message: str) -> tuple:
		try:
			self.client.sendall(bytearray([1, 125]) + bytes(message, 'utf-8'))
			return Response(ResponseType.CLIENT_MESSAGE_SENT).message()
		except BrokenPipeError:
			self.stop_client()
			return Response(ResponseType.CLIENT_CONNECTION_LOST).message()
Esempio n. 10
0
    def handle(self, request):
        response = Response()

        file_path = path.join(path.dirname(path.realpath(__file__)),
                              request.get_path())

        if not path.isfile(file_path):
            response.set_status("404 Not Found")
            return response

        chunk = 200
        f = open(file_path, "r")

        while True:
            data = f.read(chunk)
            if not data:
                break
            response.write_body(str.encode(data))

        size = path.getsize(file_path)
        f.close()

        response.set_header("Content-Length", str(size))
        response.set_status("200 OK")
        return response
Esempio n. 11
0
def getDatasetObjectsPrimary(dataset_id):

    user = AuthenticationService.verifySessionAndReturnUser(
        request.cookies["SID"])

    if (Dataset.objects.get(
            Q(id=dataset_id) & (Q(public=True) | Q(author=user))) != None):
        filename = dataset_id + ".csv"
        fileFromS3 = s3.get_object(Bucket="agriworks-user-datasets",
                                   Key=filename)
        dataset = pd.read_csv(fileFromS3["Body"], dtype=str)
    else:
        return Response("You do not have access to that dataset.", status=403)

    if (len(dataset) <= 1000):
        return Response({
            "datasetObjects":
            DatasetService.buildDatasetObjectsList(dataset)
        })
    else:
        cacheId = str(uuid4())
        DatasetCache[cacheId] = dataset[1000:]
        return Response({
            "datasetObjects":
            DatasetService.buildDatasetObjectsList(dataset[:1000]),
            "cacheId":
            cacheId
        })
Esempio n. 12
0
 def deleteInstance(self, instance_id, send_flag=True):
     result = None
     for instance in self.instance_list:
         host = instance.host
         if instance.id == instance_id:
             self.instance_list.remove(instance)
             if send_flag: self.sendUpdateInstance(host)
             message = "Cluster--delete instance success. this instance is deleted (instance_id = %s)" % instance_id
             logging.info(message)
             # result = {"code": "0", "clusterId": self.id, "instance id": instance_id, "message": message}
             result = Response(code="succeed",
                               message=message,
                               data={
                                   "cluster_id": self.id,
                                   "instance_id": instance_id
                               })
     # if instanceid not in self.instacne_list:
     if result == None:
         message = "Cluster--delete instance fail ,please check again! The instance id is %s." % instance_id
         logging.error(message)
         # result = {"code": "1", "cluster id": self.id, "instance id": instance_id, "message": message}
         result = Response(code="failed",
                           message=message,
                           data={
                               "cluster_id": self.id,
                               "instance_id": instance_id
                           })
     return result
 def addNode(self, node_name_list):
     # create node list
     message = ""
     try:
         if node_name_list == []: raise Exception
         for node_name in node_name_list:
             if self._isInComputePool(node_name):
                 # print node_name_list
                 node = Node(name=node_name, cluster_id=self.id)
                 self.node_list.append(node)
                 node.startDetectionThread()
                 message = "Cluster--The node %s is added to cluster." % self.getAllNodeStr(
                 )
                 logging.info(message)
                 # result = {"code": "0","clusterId": self.id,"node":node_name, "message": message}
                 result = Response(code="succeed",
                                   message=message,
                                   data={
                                       "cluster_id": self.id,
                                       "node": node_name
                                   })
             else:
                 message += "the node %s is illegal.  " % node_name
                 logging.error(message)
     except Exception as e:
         print str(e)
         message = "Cluster-- add node fail , some node maybe overlapping or not in compute pool please check again! The node list is %s." % (
             self.getAllNodeStr())
         logging.error(message)
         # result = {"code": "1", "clusterId": self.id, "message": message}
         result = Response(code="failed",
                           message=message,
                           data={"cluster_id": self.id})
     finally:
         return result
def logout():
    try:
        sessionId = request.form["sessionId"]
        AuthenticationService.logout(sessionId)
        return Response("Successfully logged out.", status=200)
    except:
        return Response("Unable to process request. Please reload and try again later.", status=400)
Esempio n. 15
0
 def addNode(cluster_id, node_name_list, write_DB=True):
     message = ""
     tmp = list(set(node_name_list)) # remove duplicate
     for node_name in tmp[:]:
         if not ClusterManager._checkNodeOverlappingForAllCluster(node_name):
             print "%s is already in a HA cluster. " % node_name
             message += "%s is overlapping node" % node_name
             tmp.remove(node_name)
     if tmp == []:
         return Response(code="failed",
                         message="node overlapping %s" % (str(node_name_list)),
                         data={"overlapping_node":node_name_list})
     cluster = ClusterManager.getCluster(cluster_id)
     if not cluster:
         message += "ClusterManager--Add the node to cluster failed. The cluster is not found. (cluster_id = %s)" % cluster_id
         # result = {"code": "1", "clusterId":cluster_id, "message":message}
         result = Response(code="failed",
                           message=message,
                           data={"clusterId": cluster_id})
         return result
     else:
         try:
             result = cluster.addNode(tmp)
             logging.info("ClusterManager--add node success.cluster id is %s ,node is %s " % (cluster_id, tmp))
             if result.code == "succeed" and write_DB:
                 ClusterManager.syncToDatabase()
             return result
         except Exception as e:
             message += "add node fail. node not found. (node_name = %s)"  % tmp +str(e)
             logging.error(message)
             # result = {"code": "1", "clusterId": cluster_id, "message": message}
             result = Response(code="failed",
                               message=message,
                               data={"clusterId": cluster_id})
             return result
 def deleteNode(self, node_name):
     try:
         node = self.getNodeByName(node_name)
         # stop Thread
         node.deleteDetectionThread()
         self.deleteInstanceByNode(node)
         self.node_list.remove(node)
         # ret = self.getAllNodeInfo()
         for node in self.node_list:
             if node.name == node_name:
                 raise Exception
         message = "Cluster delete node success! node is %s , node list is %s,cluster id is %s." % (
             node_name, self.getAllNodeStr(), self.id)
         logging.info(message)
         # result = {"code": "0","clusterId": self.id, "node":node_name, "message": message}
         result = Response(code="succeed",
                           message=message,
                           data={
                               "cluster_id": self.id,
                               "node": node_name
                           })
     except Exception as e:
         print str(e)
         message = "Cluster delete node fail , node maybe not in compute pool please check again! node is %s  The node list is %s." % (
             node_name, self.getAllNodeStr())
         logging.error(message)
         # result = {"code": "1", "node":node_name,"clusterId": self.id, "message": message}
         result = Response(code="failed",
                           message=message,
                           data={
                               "cluster_id": self.id,
                               "node": node_name
                           })
     finally:
         return result
Esempio n. 17
0
 def addInstance(cluster_id, instance_id, write_DB=True):
     cluster = ClusterManager.getCluster(cluster_id)
     message = ""
     if not cluster:
         message = "ClusterManager--Add the instance to cluster failed. The cluster is not found. (cluster_id = %s)" % cluster_id
         # result = {"code": "1", "clusterId":cluster_id, "message":message}
         result = Response(code="failed",
                           message=message,
                           data={"clusterId": cluster_id})
         return result
     else:
         try:
             if not ClusterManager._checkInstanceNOTOverlappingForAllCluster(instance_id):
                 return Response(code="failed",
                                 message="instance %s is already being protected" % instance_id,
                                 data={"instance": instance_id})
             result = cluster.addInstance(instance_id)
             if write_DB:
                 ClusterManager.syncToDatabase()
             logging.info(
                 "ClusterManager--Add instance success , instance_id : %s , cluster_id : %s" % (
                 instance_id, cluster_id))
             return result
         except Exception as e:
             print str(e)
             message = "ClusterManager --add the instacne fail.instance_id : %s , cluster_id : %s"  % (
                 instance_id, cluster_id) + str(e)
             logging.error(message)
             # result = {"code": "1", "clusterId": cluster_id, "message": message}
             result = Response(code="failed",
                               message=message,
                               data={"clusterId": cluster_id})
             return result
Esempio n. 18
0
 def deleteNode(cluster_id, node_name, write_DB=True):
     cluster = ClusterManager.getCluster(cluster_id)
     if not cluster:
         message = "delete the node failed. The cluster is not found. (cluster_id = %s)" % cluster_id
         # result = {"code": "1", "clusterId":cluster_id, "message":message}
         result = Response(code="failed",
                           message=message,
                           data={"clusterId": cluster_id})
         return result
     else:
         try:
             result = cluster.deleteNode(node_name)
             logging.info(
                 "ClusterManager-- delete node success ,cluster id is %s node is %s" % (cluster_id, node_name))
             if write_DB:
                 ClusterManager.syncToDatabase()
             return result
         except Exception as e:
             # code = "1"
             message = "delete node fail. node not found. (node_name = %s)" % node_name + str(e)
             logging.error(message)
             # result = {"code": "1", "clusterId":cluster_id, "message":message}
             result = Response(code="failed",
                               message=message,
                               data={"clusterId": cluster_id})
             return result
Esempio n. 19
0
 def deleteInstance(cluster_id, instance_id, send_flag=True, write_DB=True):
     cluster = ClusterManager.getCluster(cluster_id)
     if not cluster:
         message = "delete the instance to cluster failed. The cluster is not found. (cluster_id = %s)" % cluster_id
         # result = {"code": "1", "clusterId": cluster_id, "instance id ": instance_id, "message": message}
         result = Response(code="failed",
                           message=message,
                           data={"clusterId": cluster_id, "instance id": instance_id})
         return result
     else:
         try:
             result = cluster.deleteInstance(instance_id, send_flag)
             if write_DB:
                 ClusterManager.syncToDatabase()
             logging.info("ClusterManager--delete instance success")
             return result
         except Exception as e:
             #logging.error(str(e))
             print str(e)
             message = "ClusterManager--delete instance failed. this instance is not being protected (instance_id = %s)" % instance_id +str(e)
             logging.error(message)
             # result = {"code": "1", "clusterId":cluster_id, "message":message}
             result = Response(code="failed",
                               message=message,
                               data={"clusterId": cluster_id})
             return result
 def get(self, datasetId):
     try:
         return Response(Dataset.objects.get(id=datasetId)["filters"])
     except Dataset.DoesNotExist:
         return Response("Invalid dataset requested.", status=400)
     except Exception as e:
         return Response(e, status=500)
Esempio n. 21
0
def send_frame_to_neighbours(
    out_frame: Frame, timetables: dict, outstanding_frames: dict
) -> None:
    orig_src = out_frame.src
    for port, name in NEIGHBOURS.items():
        if out_frame.src == name or out_frame.origin == name:
            # Don't forward frames to senders
            print(f"{NAME} skipping sending a frame to {name}")
            continue
        try:
            neighbour_tt = timetables[name]
        except KeyError:
            print(
                f"Couldn't find {name} in neighbours,"
                f"skipping sending a frame to them"
            )
            continue
        out_frame.src = NAME
        out_frame.time = calc_arrival_time(neighbour_tt)
        UDP_SOCKET.sendto(out_frame.to_bytes(), (HOST, port))

    out_frame.src = orig_src
    if out_frame.origin not in outstanding_frames.keys():
        outstanding_frames[out_frame.origin] = []

    if out_frame.origin == NAME:
        # This is our request
        outstanding_frames[NAME].append(
            Response(len(NEIGHBOURS), out_frame, -1)
        )
    else:
        # We are forwarding a request
        outstanding_frames[out_frame.origin].append(
            Response(len(NEIGHBOURS) - 1, out_frame, -1)
        )
Esempio n. 22
0
 def _addToClusterList(cluster_name, cluster_id=None):
     try:
         # result = None
         if cluster_id:
             cluster = Cluster(id=cluster_id, name=cluster_name)
             ClusterManager._cluster_dict[cluster_id] = cluster
             message = "ClusterManager -syncofromDB-- createCluster._addToCluster success,cluster id = %s" % cluster_id
             logging.info(message)
             # result = {"code": "0", "clusterId":cluster_id,"message": message}
             result = Response(code="succeed",
                               message=message,
                               data={"clusterId": cluster_id})
             return result
         else:
             # start add to cluster list
             cluster_id = str(uuid.uuid4())
             cluster = Cluster(id=cluster_id, name=cluster_name)
             ClusterManager._cluster_dict[cluster_id] = cluster
             message = "ClusterManager - createCluster._addToClusterList success,cluster id = %s" % cluster_id
             logging.info(message)
             # result = {"code": "0","clusterId":cluster_id, "message":message}
             result = Response(code="succeed",
                               message=message,
                               data={"clusterId": cluster_id})
             return result
     except Exception as e:
         message = "ClusterManager - createCluster._addToCluster fail,cluster id : %s" % cluster_id + str(e)
         logging.error(message)
         # result = {"code": "1","clusterId":cluster_id, "message": message}
         result = Response(code="failed",
                           message=message,
                           data={"clusterId": cluster_id})
         return result
Esempio n. 23
0
    def speech_command_cb(self, command):
        '''Callback for when a speech command is received'''
        if command.command in self.responses.keys():
            rospy.loginfo('\033[32m Calling response for command ' +
                          command.command + '\033[0m')
            response = self.responses[command.command]

            if (not self.arms.is_executing() and not self._is_busy):
                response.respond()
            else:
                if command.command == Command.STOP_EXECUTION:
                    response.respond()
                else:
                    rospy.logwarn('Ignoring speech command during execution or busy: '
                                  + command.command)
        else:
            switch_command = 'SWITCH_TO_ACTION'
            if (switch_command in command.command):
                action_no = command.command[
                                len(switch_command):len(command.command)]
                action_no = int(action_no)
                if (self.session.n_actions() > 0):
                    self.session.switch_to_action(action_no,
                                                  self.world.get_frame_list())
                    response = Response(self.default_response,
                        [RobotSpeech.SWITCH_SKILL + str(action_no),
                         GazeGoal.NOD])
                else:
                    response = Response(self.default_response,
                        [RobotSpeech.ERROR_NO_SKILLS, GazeGoal.SHAKE])
                response.respond()
            else:
                rospy.logwarn('\033[32m This command (' + command.command
                              + ') is unknown. \033[0m')
Esempio n. 24
0
def publish_module(module_name,
                   stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr,
                   environ=os.environ, debug=0, request=None, response=None,
                   extra={}):
    must_die=0
    status=200
    after_list=[None]
    from Response import Response
    from Request import Request
    from Publish import publish
    try:
        try:
            if response is None:
                response=Response(stdout=stdout, stderr=stderr)
            else:
                stdout=response.stdout
            if request is None:
                request=Request(stdin, environ, response)
            for k, v in extra.items(): request[k]=v
            response = publish(request, module_name, after_list, debug=debug)
        except SystemExit, v:
            if hasattr(sys, 'exc_info'): must_die=sys.exc_info()
            else: must_die = SystemExit, v, sys.exc_info()[2]
            response.exception(must_die)
        except ImportError, v:
            if type(v) is type(()) and len(v)==3: must_die=v
            elif hasattr(sys, 'exc_info'): must_die=sys.exc_info()
            else: must_die = SystemExit, v, sys.exc_info()[2]
            response.exception(1, v)
Esempio n. 25
0
    def delete_instance(self, instance_id):
        result = None
        for instance in self.instance_list:
            host = instance.host
            if instance.id == instance_id:
                self.instance_list.remove(instance)
                # send instance deletion information to node detection thread
                update_action = InstanceQueueConfig.REMOVE_INSTANCE
                instance_name = instance.get_name()
                host = self.get_node_by_name(host)
                host.send_update_instance(update_action, instance_name)

                message = "Cluster--delete instance success. this instance is deleted (instance_id = %s)" % instance_id
                logging.info(message)
                # result = {"code": "0", "cluster_name": self.name, "instance id": instance_id, "message": message}
                result = Response(code="succeed",
                                  message=message,
                                  data={
                                      "cluster_name": self.name,
                                      "instance_id": instance_id
                                  })
        # if instanceid not in self.instacne_list:
        if result == None:
            message = "Cluster--delete instance fail ,please check again! The instance id is %s." % instance_id
            logging.error(message)
            # result = {"code": "1", "cluster id": self.name, "instance id": instance_id, "message": message}
            result = Response(code="failed",
                              message=message,
                              data={
                                  "cluster_name": self.name,
                                  "instance_id": instance_id
                              })
        return result
    def test_GitHubApiDefault(self):
        top_level_type = 'application'
        sub_type = 'json'
        mime_type = '{top_level_type}/{sub_type}'.format(
            top_level_type=top_level_type, sub_type=sub_type)
        char_set = 'utf-8'
        content_type = '{mime_type}; charset={char_set}'.format(
            mime_type=mime_type, char_set=char_set)
        response = Response()
        #        c = Response.__Headers.__ContentType(content_type)

        res = requests.Response()
        res.headers = {}
        res.headers[
            'Content-Type'] = '{mime_type}; charset={char_set};'.format(
                mime_type=mime_type, char_set=char_set)
        h = response._Response__Headers(res)
        c = h._Headers__ContentType(content_type)
        self.assertEqual(content_type, c.String)
        print(c.String)
        print(c.MimeType.TopLevelType)
        print(c.MimeType.String)
        self.assertEqual(mime_type, c.MimeType.String)
        self.assertTrue('charset' in c.Parameters.keys())
        self.assertEqual(char_set, c.Parameters['charset'])
        self.assertEqual(top_level_type, c.MimeType.TopLevelType)
        self.assertEqual(sub_type, c.MimeType.SubType.String)
        self.assertEqual(None, c.MimeType.SubType.Facet)
        self.assertEqual(None, c.MimeType.SubType.Suffix)
        self.assertEqual(sub_type, c.MimeType.SubType.MediaType)
Esempio n. 27
0
 def listInstance(cluster_id, send_flag=True):
     cluster = ClusterManager.getCluster(cluster_id)
     try:
         if not cluster:
             raise Exception(
                 "ClusterManager--listInstance,get instance list fail , not find the cluster %s" % cluster_id)
         instance_list, illegal_instance = cluster.getAllInstanceInfo()
         # delete illegal instance
         if illegal_instance != []:
             for instance in illegal_instance:
                 ClusterManager.deleteInstance(cluster_id, instance[0], send_flag=False)
         # send upadte host of legal instacne and prev_host of illegal instance
         if send_flag == True:
             for instance in instance_list[:]:
                 cluster.sendUpdateInstance(instance[2])  # info[2]
             for instance in illegal_instance[:]:
                 cluster.sendUpdateInstance(instance[1])  # prev_host
         message = "ClusterManager--listInstance,getInstanceList success,instanceList is %s" % instance_list
         logging.info(message)
         # result = {"code": "0", "instanceList": instance_list}
         result = Response(code="succeed",
                           message=message,
                           data={"instance_list": instance_list})
         return result
     except Exception as e:
         # print str(e)
         # result = {"code": "1", "instanceList": []}
         message = "ClusterManager--listInstance,getInstanceList fail" + str(e)
         logging.error(message)
         result = Response(code="failed",
                           message=message,
                           data={"instance_list": []})
         return result
 def shutOffNode(self, node_name):
     message = ""
     # result =None
     if self._checkNodeIPMI(node_name) and self._checkNodeNotInCluster(
             node_name):
         try:
             ipmi_result = self.ipmi_module.shutOffNode(node_name)
             # check power status in IPMIModule
             if ipmi_result.code == "succeed":
                 message += "shut off node success.The node is %s." % node_name
                 logging.info(message)
                 # result = {"code": "0", "node_name": node_name, "message": message}
                 result = Response(code="succeed",
                                   message=message,
                                   data={"node_name": node_name})
             else:
                 raise Exception("IpmiModule shut off node fail")
         except Exception as e:
             # shut off fail
             message += "IPMIOperator--shut off node fail.The node is %s.%s" % (
                 node_name, e)
             logging.error(message)
             # result = {"code": "1", "node_name": node_name, "message": message}
             result = Response(code="failed",
                               message=message,
                               data={"node_name": node_name})
     else:
         message += " IPMIOperator--node is not in compute pool or is not a IPMI PC or is already be protected. The node is %s." % node_name
         logging.error(message)
         # result = {"code": "1", "node_name": node_name, "message": message}
         result = Response(code="failed",
                           message=message,
                           data={"node_name": node_name})
     return result
 def delete_node(cluster_name, node_name):
     cluster = ResourceManager.get_cluster(cluster_name)
     if not cluster:
         message = "delete the node failed. The cluster is not found. (cluster_name = %s)" % cluster_name
         # result = {"code": "1", "cluster_name":cluster_name, "message":message}
         result = Response(code="failed",
                           message=message,
                           data={"cluster_name": cluster_name})
         return result
     else:
         try:
             result = cluster.delete_node(node_name)
             #logging.info("ResourceManager-- delete node success ,cluster name is %s node is %s" % (cluster_name, node_name))
             ResourceManager.sync_to_database()
             return result
         except Exception as e:
             # code = "1"
             message = "delete node fail. node not found. (node_name = %s)" % node_name + str(
                 e)
             logging.error(message)
             # result = {"code": "1", "cluster_name":cluster_name, "message":message}
             result = Response(code="failed",
                               message=message,
                               data={"cluster_name": cluster_name})
             return result
Esempio n. 30
0
 def handleGet(self, request, transport):
     if self.checkVersion(request):
         fpath = self.getResource(request.resourceUrl)
         if fpath == '':
             blob = [ResponseCode.NotFound, '']
             resp = Response(blob, 0)
             transport.interface.reply(resp)
         else:
             tsz = os.path.getsize(fpath)
             step = transport.interface.datarate
             count = 0
             f = open(fpath, 'rb')
             while count < tsz:
                 count += step
                 buff = f.read(step)
                 if count < tsz:
                     blob = [ResponseCode.Continue, buff]
                     resp = Response(blob, tsz - count)
                     transport.interface.reply(resp)
                 else:
                     blob = [ResponseCode.OK, buff]
                     resp = Response(blob, 0)
                     transport.interface.reply(resp)
     else:
         blob = [ResponseCode.BadRequest, '']
         resp = Response(blob, 0)
         transport.interface.reply(resp)
Esempio n. 31
0
def getMeeting(meetingID):
    dict = getMeetingDict(meetingID)
    if (meeting == None):
        return Response("No meeting", status=400)
    print(dict)
    print("Id: " + dict["meetingID"])
    return Response(dict, status=200)
Esempio n. 32
0
def closeMeeting(meetingID):
    print("Hello2")
    active = MeetingService.closeMeeting(meetingID)
    if (not active):
        return Response({"active": active}, status=200)
    else:
        return Response("Meeting not found", status=400)
Esempio n. 33
0
 def __init__(self,respId,respName,respType,mitDesc,mitCost,mitRoles,mitProps,detPt,detMech,mitRisks,mitTargets):
   Response.__init__(self,respId,respName,mitRisks,mitCost,mitRoles)
   PropertyHolder.__init__(self,mitProps)
   self.theDescription = mitDesc
   self.theDetectionPoint = detPt
   self.theDetectionMechanism = detMech
   self.theTargets = mitTargets
   self.theMitigationType = respType
Esempio n. 34
0
 def stop_execution(self, dummy=None):
     '''Stops ongoing execution'''
     if (self._demo_state == DemoState.PLAYING_DEMO and
         self.arms.is_executing()):
         self.arms.stop_execution()
         
         Respoonse.say(RobotSpeech.STOPPING_EXECUTION)
         Response.perform_gaze_action(GazeGoal.NOD)
     else:
         Response.perform_gaze_action(GazeGoal.SHAKE)
         Respoonse.say(RobotSpeech.ERROR_IS_NOT_PLAYING)
Esempio n. 35
0
	def __init__(self, transaction, strmOut, headers=None):
		"""Initialize the request."""

		Response.__init__(self, transaction, strmOut)

		self._committed = False

		if headers is None:
			self._headers = {}
			self.setHeader('Content-type', 'text/html')
		else:
			self._headers = headers

		self._cookies = {}
Esempio n. 36
0
    def take_tool(self, arm_index):
        '''Robot's response to TAKE_TOOL'''
        self._is_busy = True
        if self._demo_state == DemoState.READY_TO_TAKE:
            ## Robot closes the hand
            Arms.set_gripper_state(arm_index, GripperState.CLOSED, wait=True)
            
            ## Robot moves the hand near the camera to take a look at the tool
            self._move_to_arm_pose('look', arm_index, wait=True)
            self.tool_id = self.world.get_tool_id()

            if self.tool_id is None:
                ## Robot moves the arm back to the person can take the tool
                self._move_to_arm_pose('take', 0, wait=True)
                Response.say(RobotSpeech.ERROR_TOOL_NOT_RECOGNIZED)
                Response.perform_gaze_action(GazeGoal.SHAKE)
                self._demo_state = DemoState.NO_TOOL_NO_SURFACE
            else:
                self.session.new_action(self.tool_id)
                Response.say(RobotSpeech.RECOGNIZED_TOOL + str(self.tool_id))

                self._demo_state = DemoState.HAS_TOOL_NO_SURFACE
                self.detect_surface()
        else:
            Response.say(RobotSpeech.ERROR_NOT_IN_TAKE_STATE)

        rospy.loginfo('Current state: ' + self._demo_state)
        self._is_busy = False
Esempio n. 37
0
    def setupTransfer(self, f):
        self.setFile(f)
        if not self.checkFileExists(self.config.get("data_stream.directory") + "/" + f):
            rc = ResponseCode(False)
            grv = Response(rc, "Not attempting file transfer")
            return grv
        file_name = (TransferUtils.getPlainFileName(self.config.get(
            "data_stream.directory"), f, self.config.get("outgoing.dir_size_limit")))
        if not file_name:
            (TransferUtils.quarantine(f, self.config.get("data_stream.directory"),
                 self.config.get("outgoing.quarantine_dir")))
            grv = Response.failure("Did not attempt transfer of %s" % f)
            self.info("Did not attempt transfer of %s" % f)
            return grv
        else:
            self.setFile(os.path.basename(file_name))

        fn = os.path.join(self.config.get("data_stream.directory"), file_name)
        filesize = os.path.getsize(fn)

        try:
            self.checkVars()
        except Exception, ex:
            rc = ResponseCode(False)
            r = Response(rc, "not all required variables in GridFTPTransfer are set : ", str(ex))
            self.info("not all required variables in GridFTPTransfer are set : %s " % str(ex))
            return r
Esempio n. 38
0
def publish_module(
    module_name,
    stdin=sys.stdin,
    stdout=sys.stdout,
    stderr=sys.stderr,
    environ=os.environ,
    debug=0,
    request=None,
    response=None,
    extra={},
):
    must_die = 0
    status = 200
    after_list = [None]
    from Response import Response
    from Request import Request
    from Publish import publish

    try:
        try:
            if response is None:
                response = Response(stdout=stdout, stderr=stderr)
            else:
                stdout = response.stdout
            if request is None:
                request = Request(stdin, environ, response)
                # make sure that the request we hand over has the
                # default layer/skin set on it; subsequent code that
                # wants to look up views will likely depend on it
                from zope.app.publication.browser import setDefaultSkin

                setDefaultSkin(request)

            for k, v in extra.items():
                request[k] = v
            response = publish(request, module_name, after_list, debug=debug)
        except SystemExit, v:
            must_die = sys.exc_info()
            response.exception(must_die)
        except ImportError, v:
            if isinstance(v, TupleType) and len(v) == 3:
                must_die = v
            else:
                must_die = sys.exc_info()
            response.exception(1, v)
Esempio n. 39
0
    def generateResponse(self, module, operation):
        response = Response()
        if module == 'google':
            response.texts.append(Google.getResult(operation))
        if module == 'wikipedia':
            response.texts.append(Wikipedia.getSummary(operation))
        if module == 'imdb':
            response.texts = IMDB.getMovieInfo(operation)
        if module == 'releases':
            response.texts.append(Releases.getReleaseDate(operation))
        if module == 'lyrics':
            response.texts.append(Lyrics.getLyrics(operation))
        if module == 'reddit':
            response.texts = self.handleReddit(operation)
        if module == 'wolfram':
            response.images = Wolfram.getImages(operation)
        if module == 'network':
            response.text = network.scan()
        if module == 'hltb':
            response.text = (hltb.getTimes(opertaion))
        if module == 'hltr':
            response.texts.append(hltr.getInfo(operation))
        if module == 'espeak':
            espeak.speak(operation)
            response.texts.append('Done, sir')

        if not response.texts and not response.images and not response.audios:
            response.texts = ['I\'m sorry dave, I\'m afraid I can\'t do that']
        return response
Esempio n. 40
0
    def stop_recording(self, dummy=None):
        '''Stops recording continuous motion'''
        self.busy = True

        if (self._demo_state == DemoState.RECORDING_DEMO):
            
            traj_step = ActionStep()
            traj_step.type = ActionStep.ARM_TRAJECTORY

            waited_time = Interaction._arm_trajectory.timing[0]

            for i in range(len(Interaction._arm_trajectory.timing)):
                Interaction._arm_trajectory.timing[i] -= waited_time
                Interaction._arm_trajectory.timing[i] += rospy.Duration(0.1)
            
            '''If motion was relative, record transformed pose'''
            traj_step.armTrajectory = ArmTrajectory(
                Interaction._arm_trajectory.rArm[:],
                Interaction._arm_trajectory.lArm[:],
                Interaction._arm_trajectory.timing[:],
                Interaction._arm_trajectory.rRefFrame,
                Interaction._arm_trajectory.lRefFrame,
                Interaction._arm_trajectory.rRefFrameObject,
                Interaction._arm_trajectory.lRefFrameObject)
            
            traj_step.gripperAction = GripperAction(
                                        self.arms.get_gripper_state(0),
                                        self.arms.get_gripper_state(1))
                                        
            self.session.add_step_to_action(traj_step,
                                        self.world.get_frame_list())
            

            Interaction._arm_trajectory = None
            Interaction._trajectory_start_time = None
            self.session.save_current_action()
            self.freeze_arm(0)

            self._demo_state = DemoState.HAS_RECORDED_DEMO

            Response.say(RobotSpeech.STOPPED_RECORDING)
            Response.perform_gaze_action(GazeGoal.NOD)

        else:

            Response.say(RobotSpeech.ERROR_NOT_RECORDING)
            Response.perform_gaze_action(GazeGoal.SHAKE)

        rospy.loginfo('Current state: ' + self._demo_state)
        self.busy = False
Esempio n. 41
0
 def gui_command_cb(self, command):
     '''Callback for when a GUI command is received'''
     if (not self.arms.is_executing()):
         if (self.session.n_actions() > 0):
             if (command.command == GuiCommand.SWITCH_TO_ACTION):
                 action_no = command.param
                 self.session.switch_to_action(action_no,
                                               self.world.get_frame_list())
                 response = Response(Interaction.empty_response,
                     [RobotSpeech.SWITCH_SKILL + str(action_no),
                      GazeGoal.NOD])
                 response.respond()
             elif (command.command == GuiCommand.SELECT_ACTION_STEP):
                 step_no = command.param
                 self.session.select_action_step(step_no)
                 rospy.loginfo('Selected action step ' + str(step_no))
             else:
                 rospy.logwarn('\033[32m This command (' + command.command
                               + ') is unknown. \033[0m')
         else:
             response = Response(Interaction.empty_response,
                 [RobotSpeech.ERROR_NO_SKILLS, GazeGoal.SHAKE])
             response.respond()
     else:
         rospy.logwarn('Ignoring GUI command during execution: ' +
                             command.command)
Esempio n. 42
0
def item2():
    # print 'this is a post item'
    # initialize in case no answer

    response = Response()

    response.order = app.order[app.num - 1]
    response.recog = request.form["recog"]
    response.comp = request.form["comp"]
    response.comp_conf = request.form["comp_conf"]
    response.piece = request.form["piece"]
    response.piece_conf = request.form["piece_conf"]
    response.name = app.progvars["name"]
    response.age = app.progvars["age"]

    db.saveResponse(response)

    return redirect(url_for("main"))
Esempio n. 43
0
    def __init__(self):
        self.arms = Arms()
        self.world = World()
        self.session = Session(object_list=self.world.get_frame_list(),
                               is_debug=True)
        self._viz_publisher = rospy.Publisher('visualization_marker_array', MarkerArray)
        self._demo_state = None
        self._is_busy = True

        rospy.Subscriber('recognized_command', Command, self.speech_command_cb)
        rospy.Subscriber('gui_command', GuiCommand, self.gui_command_cb)

        self.responses = {
            Command.TEST_MICROPHONE: Response(self.default_response,
                                [RobotSpeech.TEST_RESPONSE, GazeGoal.NOD]),
            Command.TAKE_TOOL: Response(self.take_tool, 0),
            Command.RELEASE_TOOL: Response(self.release_tool, 0),
            Command.START_RECORDING: Response(self.start_recording, None),
            Command.STOP_RECORDING: Response(self.stop_recording, None),
            Command.REPLAY_DEMONSTRATION: Response(self.replay_demonstration, None)
            Command.DETECT_SURFACE: Response(self.detect_surface, None)
        }

        rospy.loginfo('Will wait until arms ready to respond.')
        while ((self.arms.get_ee_state(0) is None) or
            (self.arms.get_ee_state(1) is None)):
            time.sleep(0.1)

        rospy.loginfo('Starting to move to the initial pose.')
        # TODO: Make it possible to take with either hand
        self._move_to_arm_pose('take', 0)
        self._move_to_arm_pose('away', 1)
        self._wait_for_arms()
        self._demo_state = DemoState.READY_TO_TAKE
        Response.say(RobotSpeech.HAND_TOOL_REQUEST)
        Response.perform_gaze_action(GazeGoal.GLANCE_RIGHT_EE)
        self._is_busy = False
        rospy.loginfo('Interaction initialized.')
Esempio n. 44
0
    def release_tool(self, arm_index):
        self.busy = True
        if (self._demo_state != DemoState.READY_TO_TAKE and 
            self._demo_state != DemoState.PLAYING_DEMO and
            self._demo_state != DemoState.RECORDING_DEMO):
            self._move_to_arm_pose('take', 0, wait=True)
            self.arms.set_gripper_state(arm_index, GripperState.OPEN, wait=True)
            Response.say(RobotSpeech.TOOL_RELEASED)
            Response.perform_gaze_action(GazeGoal.GLANCE_RIGHT_EE)
            self._demo_state = DemoState.READY_TO_TAKE
        else:
            Response.perform_gaze_action(GazeGoal.SHAKE)
            Response.say(RobotSpeech.ERROR_NOT_IN_RELEASE_STATE)

        rospy.loginfo('Current state: ' + self._demo_state)
        self.busy = False
Esempio n. 45
0
  def test_insertsResponseIntoTable(self):
    oldCount = self.db.countResponses()

    resp = Response()
    resp.recog = "True"
    resp.comp = "Composer"
    resp.comp_conf = "5"
    resp.piece = "Piece"
    resp.piece_conf = "3"
    resp.name = "Name"
    resp.age = "23"

    self.db.saveResponse(resp)

    newCount = self.db.countResponses()
    newResponses = newCount - oldCount

    self.assertEquals(newResponses, 1)
Esempio n. 46
0
    def detect_surface(self):
        self._is_busy = True

        if self._demo_state == DemoState.HAS_TOOL_NO_SURFACE:
            ## Robot moves the arm away and looks at the surface
            self._move_to_arm_pose('away', 0, wait=True)
            self.surface = self.world.get_surface()

            if self.surface is None:
                Response.say(RobotSpeech.ERROR_NO_SURFACE)
                Response.perform_gaze_action(GazeGoal.SHAKE)
            else:
                Response.say(RobotSpeech.SURFACE_DETECTED)
                self._move_to_arm_pose('ready', arm_index, wait=True)
                Response.say(RobotSpeech.READY_FOR_DEMO)
                self._demo_state = DemoState.READY_FOR_DEMO

        self._is_busy = False
Esempio n. 47
0
    def move_to_joints(self, r_arm, l_arm):
        '''Makes the arms move to indicated joint poses'''

        time_to_r_pose = Arms._get_time_to_pose(r_arm, 0)
        time_to_l_pose = Arms._get_time_to_pose(l_arm, 1)

        #  If both arms are moving adjust velocities and find most moving arm
        is_r_moving = (time_to_r_pose != None)
        is_l_moving = (time_to_l_pose != None)
        if (not is_r_moving):
            Response.look_at_point(l_arm.ee_pose.position)
        elif (not is_l_moving):
            Response.look_at_point(r_arm.ee_pose.position)
        else:
            if (time_to_r_pose > time_to_l_pose):
                time_to_l_pose = time_to_r_pose
                Response.look_at_point(r_arm.ee_pose.position)
            else:
                time_to_r_pose = time_to_l_pose
                Response.look_at_point(l_arm.ee_pose.position)

        #  Move arms to target
        if (is_r_moving):
            Arms.arms[0].move_to_joints(r_arm.joint_pose, time_to_r_pose)
        if (is_l_moving):
            Arms.arms[1].move_to_joints(l_arm.joint_pose, time_to_l_pose)

        # Wait until both arms complete the trajectory
        while((Arms.arms[0].is_executing() or
               Arms.arms[1].is_executing()) and not self.preempt):
            time.sleep(0.01)
        rospy.loginfo('Arms reached target.')

        # Verify that both arms succeeded
        if ((not Arms.arms[0].is_successful() and is_r_moving) or
            (not Arms.arms[1].is_successful() and is_l_moving)):
            rospy.logwarn('Aborting because arms failed to move to pose.')
            return False
        else:
            return True
Esempio n. 48
0
    def update(self):
        '''Periodic update for the two arms'''
        Arms.arms[0].update(self.is_executing())
        Arms.arms[1].update(self.is_executing())

        moving_arm = Arms._get_most_moving_arm()
        if (moving_arm != self.attended_arm and not self.is_executing()):
            if (moving_arm == -1):
                Response.perform_gaze_action(GazeGoal.LOOK_FORWARD)
            elif (moving_arm == 0):
                Response.perform_gaze_action(GazeGoal.FOLLOW_RIGHT_EE)
            else:
                Response.perform_gaze_action(GazeGoal.FOLLOW_LEFT_EE)
            self.attended_arm = moving_arm
Esempio n. 49
0
    def replay_demonstration(self, dummy=None):
        '''Starts the execution of the current demonstration'''
        self.busy = True
        execution_z_offset = 0.00
        if (self._demo_state == DemoState.HAS_RECORDED_DEMO):
            self.session.save_current_action()
            action = self.session.get_current_action()
            self.arms.start_execution(action, execution_z_offset)
            Response.say(RobotSpeech.STARTED_REPLAY)
            self._demo_state = DemoState.PLAYING_DEMO
        else:
            Response.say(RobotSpeech.ERROR_CANNOT_REPLAY)
            Response.perform_gaze_action(GazeGoal.SHAKE)

        rospy.loginfo('Current state: ' + self._demo_state)
        self.busy = False
Esempio n. 50
0
    def default_response(self, responses):
        '''Default response to speech commands'''
        self.busy = True
        speech_resp = responses[0]
        gaze_resp = responses[1]

        # Speech response
        if (speech_resp != None):
            Response.say(speech_resp)
            Response.respond_with_sound(speech_resp)
        
        # Gaze response
        if (gaze_resp != None):
            Response.perform_gaze_action(gaze_resp)

        rospy.loginfo('Current state: ' + self._demo_state)
        self.busy = False
Esempio n. 51
0
    def setupTransfer(self, f):
        self.setFile(f)
        if not self.checkFileExists(self.config.get("data_stream.directory") + "/" + f):
            rc = ResponseCode(False)
            grv = Response(rc, "Not attempting file transfer")
            return grv
        # if we are mirroring - then do not zip directories - (we pass False
        # to getPlainFileName)
        if self.config.get("rsync_native.transfer_mode") == "mirror":
            self.mirror = True
            file_name = (TransferUtils.getPlainFileName(self.config.get(
                "data_stream.directory"), f, self.config.get(
                "outgoing.dir_size_limit"), False))
        else:
            file_name = (TransferUtils.getPlainFileName(self.config.get(
                "data_stream.directory"), f, self.config.get(
                "outgoing.dir_size_limit")))
        if not file_name:
            (TransferUtils.quarantine(f, self.config.get(
                "data_stream.directory"), self.config.get(
                "outgoing.quarantine_dir")))
            grv = Response.failure("Did not attempt transfer of %s" % f)
            self.info("Did not attempt transfer of %s" % f)
            return grv
        else:
            self.setFile(os.path.basename(file_name))

        fn = os.path.join(self.config.get("data_stream.directory"), file_name)
        filesize = os.path.getsize(fn)

        try:
            self.checkVars()
        except Exception, ex:
            rc = ResponseCode(False)
            r = (Response(rc, "not all variables in RsyncNativeTransfer ",
                str(ex)))
            self.info("not all variables in RsyncNativeTransfer %s " % str(ex))
            return r
Esempio n. 52
0
    def start_recording(self, dummy=None):
        '''Starts recording continuous motion'''
        self.busy = True
        if (self._demo_state == DemoState.READY_FOR_DEMO or
            self._demo_state == DemoState.HAS_RECORDED_DEMO):

            Interaction._arm_trajectory = ArmTrajectory()
            Interaction._trajectory_start_time = rospy.Time.now()

            if self.session.n_frames() > 0:
                self.session.clear_current_action()

            self.relax_arm(0)
            self._demo_state = DemoState.RECORDING_DEMO
            Response.say(RobotSpeech.STARTED_RECORDING)
            Response.perform_gaze_action(GazeGoal.NOD)
        elif (self._demo_state == DemoState.RECORDING_DEMO):
            Response.perform_gaze_action(GazeGoal.SHAKE)
            Response.say(RobotSpeech.ERROR_ALREADY_RECORDING)
        else:
            Response.perform_gaze_action(GazeGoal.SHAKE)
            Response.say(RobotSpeech.ERROR_NOT_READY_TO_RECORD)

        rospy.loginfo('Current state: ' + self._demo_state)
        self.busy = False
Esempio n. 53
0
    def _execute_action_step(self, action_step):
        '''Executes the motion part of an action step'''
        # For each step check step type
        # If arm target action
        if (action_step.type == ActionStep.ARM_TARGET):
            rospy.loginfo('Will perform arm target action step.')

            if (not self.move_to_joints(action_step.armTarget.rArm,
                                        action_step.armTarget.lArm)):
                self.status = ExecutionStatus.OBSTRUCTED
                return False

        # If arm trajectory action
        elif (action_step.type == ActionStep.ARM_TRAJECTORY):

            rospy.loginfo('Will perform arm trajectory action step.')

            # First move to the start frame
            if (not self.move_to_joints(action_step.armTrajectory.rArm[0],
                                        action_step.armTrajectory.lArm[0])):
                self.status = ExecutionStatus.OBSTRUCTED
                return False

            #  Then execute the trajectory
            Arms.arms[0].exectute_joint_traj(action_step.armTrajectory.rArm,
                                             action_step.armTrajectory.timing)
            Arms.arms[1].exectute_joint_traj(action_step.armTrajectory.lArm,
                                             action_step.armTrajectory.timing)

            # Wait until both arms complete the trajectory
            while((Arms.arms[0].is_executing() or Arms.arms[1].is_executing())
                  and not self.preempt):
                time.sleep(0.01)
            rospy.loginfo('Trajectory complete.')

            # Verify that both arms succeeded
            if ((not Arms.arms[0].is_successful()) or
                (not Arms.arms[1].is_successful())):
                rospy.logwarn('Aborting execution; ' +
                              'arms failed to follow trajectory.')
                self.status = ExecutionStatus.OBSTRUCTED
                return False

        # If hand action do it for both sides
        if (action_step.gripperAction.rGripper !=
                            Arms.arms[0].get_gripper_state()):
            rospy.loginfo('Will perform right gripper action ' +
                          str(action_step.gripperAction.rGripper))
            Arms.arms[0].set_gripper(action_step.gripperAction.rGripper)
            Response.perform_gaze_action(GazeGoal.FOLLOW_RIGHT_EE)

        if (action_step.gripperAction.lGripper !=
                            Arms.arms[1].get_gripper_state()):
            rospy.loginfo('Will perform LEFT gripper action ' +
                          str(action_step.gripperAction.lGripper))
            Arms.arms[1].set_gripper(action_step.gripperAction.lGripper)
            Response.perform_gaze_action(GazeGoal.FOLLOW_LEFT_EE)

        # Wait for grippers to be done
        while(Arms.arms[0].is_gripper_moving() or
              Arms.arms[1].is_gripper_moving()):
            time.sleep(0.01)
        rospy.loginfo('Hands done moving.')

        # Verify that both grippers succeeded
        if ((not Arms.arms[0].is_gripper_at_goal()) or
            (not Arms.arms[1].is_gripper_at_goal())):
            rospy.logwarn('Hand(s) did not fully close or open!')

        return True
Esempio n. 54
0
    def _end_execution(self):
        '''Responses for when the action execution ends'''
        if (self.arms.status == ExecutionStatus.SUCCEEDED):
            Response.say(RobotSpeech.EXECUTION_ENDED)
            Response.perform_gaze_action(GazeGoal.NOD)
        elif (self.arms.status == ExecutionStatus.PREEMPTED):
            Response.say(RobotSpeech.EXECUTION_PREEMPTED)
            Response.perform_gaze_action(GazeGoal.SHAKE)
        else:
            Response.say(RobotSpeech.EXECUTION_ERROR_NOIK)
            Response.perform_gaze_action(GazeGoal.SHAKE)

        self.arms.status = ExecutionStatus.NOT_EXECUTING
Esempio n. 55
0
    def update_object_pose(self):
        ''' Function to externally update an object pose'''
        Response.perform_gaze_action(GazeGoal.LOOK_DOWN)
        while (Response.gaze_client.get_state() == GoalStatus.PENDING or
               Response.gaze_client.get_state() == GoalStatus.ACTIVE):
            time.sleep(0.1)

        if (Response.gaze_client.get_state() != GoalStatus.SUCCEEDED):
            rospy.logerr('Could not look down to take table snapshot')
            return False

        rospy.loginfo('Looking at table now.')
        goal = UserCommandGoal(UserCommandGoal.RESET, False)
        self._object_action_client.send_goal(goal)
        while (self._object_action_client.get_state() == GoalStatus.ACTIVE or
               self._object_action_client.get_state() == GoalStatus.PENDING):
            time.sleep(0.1)
        rospy.loginfo('Object recognition has been reset.')
        rospy.loginfo('STATUS: ' +
                      self._object_action_client.get_goal_status_text())
        self._reset_objects()

        if (self._object_action_client.get_state() != GoalStatus.SUCCEEDED):
            rospy.logerr('Could not reset recognition.')
            return False

        # Do segmentation
        goal = UserCommandGoal(UserCommandGoal.SEGMENT, False)
        self._object_action_client.send_goal(goal)
        while (self._object_action_client.get_state() == GoalStatus.ACTIVE or
               self._object_action_client.get_state() == GoalStatus.PENDING):
            time.sleep(0.1)
        rospy.loginfo('Table segmentation is complete.')
        rospy.loginfo('STATUS: ' +
                      self._object_action_client.get_goal_status_text())

        if (self._object_action_client.get_state() != GoalStatus.SUCCEEDED):
            rospy.logerr('Could not segment.')
            return False

        # Do recognition
        goal = UserCommandGoal(UserCommandGoal.RECOGNIZE, False)
        self._object_action_client.send_goal(goal)
        while (self._object_action_client.get_state() == GoalStatus.ACTIVE or
               self._object_action_client.get_state() == GoalStatus.PENDING):
            time.sleep(0.1)
        rospy.loginfo('Objects on the table have been recognized.')
        rospy.loginfo('STATUS: ' +
                      self._object_action_client.get_goal_status_text())

        # Record the result
        if (self._object_action_client.get_state() == GoalStatus.SUCCEEDED):
            wait_time = 0
            total_wait_time = 5
            while (not World.has_objects() and wait_time < total_wait_time):
                time.sleep(0.1)
                wait_time += 0.1

            if (not World.has_objects()):
                rospy.logerr('Timeout waiting for a recognition result.')
                return False
            else:
                rospy.loginfo('Got the object list.')
                return True
        else:
            rospy.logerr('Could not recognize.')
            return False
Esempio n. 56
0
def publish_module(module_name,
                   stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr,
                   environ=os.environ, debug=0, request=None, response=None,
                   extra={}):
    must_die=0
    status=200
    after_list=[None]
    from Response import Response
    from Request import Request
    from Publish import publish
    from zope.publisher.interfaces import ISkinnable
    from zope.publisher.skinnable import setDefaultSkin
    try:
        try:
            if response is None:
                response=Response(stdout=stdout, stderr=stderr)
            else:
                stdout=response.stdout

            # debug is just used by tests (has nothing to do with debug_mode!)
            response.handle_errors = not debug

            if request is None:
                request=Request(stdin, environ, response)

            # make sure that the request we hand over has the
            # default layer/skin set on it; subsequent code that
            # wants to look up views will likely depend on it
            if ISkinnable.providedBy(request):
                setDefaultSkin(request)

            for k, v in extra.items(): request[k]=v
            response = publish(request, module_name, after_list, debug=debug)
        except (SystemExit, ImportError):
            # XXX: Rendered ImportErrors were never caught here because they
            # were re-raised as string exceptions. Maybe we should handle
            # ImportErrors like all other exceptions. Currently they are not
            # re-raised at all, so they don't show up here.
            must_die = sys.exc_info()
            request.response.exception(1)
        except:
            # debug is just used by tests (has nothing to do with debug_mode!)
            if debug:
                raise
            request.response.exception()
            status = response.getStatus()

        if response:
            outputBody=getattr(response, 'outputBody', None)
            if outputBody is not None:
                outputBody()
            else:
                response=str(response)
                if response: stdout.write(response)

        # The module defined a post-access function, call it
        if after_list[0] is not None: after_list[0]()

    finally:
        if request is not None: request.close()

    if must_die:
        # Try to turn exception value into an exit code.
        try:
            if hasattr(must_die[1], 'code'):
                code = must_die[1].code
            else: code = int(must_die[1])
        except:
            code = must_die[1] and 1 or 0
        if hasattr(request.response, '_requestShutdown'):
            request.response._requestShutdown(code)

        try: raise must_die[0], must_die[1], must_die[2]
        finally: must_die=None

    return status
Esempio n. 57
0
    def _end_replay(self):
        '''Responses for when the action execution ends'''
        if (self.arms.status == ExecutionStatus.SUCCEEDED):
            if self._demo_state == DemoState.PLAYING_DEMO:
                Response.say(RobotSpeech.ENDED_REPLAY)
                Response.perform_gaze_action(GazeGoal.NOD)
                self._demo_state = DemoState.HAS_RECORDED_DEMO
            else:
                rospy.loginfo('Non-replay motion successful.')
        elif (self.arms.status == ExecutionStatus.PREEMPTED):
            if self._demo_state == DemoState.PLAYING_DEMO:
                Response.say(RobotSpeech.ERROR_PREEMPTED_REPLAY)
                Response.perform_gaze_action(GazeGoal.SHAKE)
                self._demo_state = DemoState.HAS_RECORDED_DEMO
            else:
                rospy.loginfo('Non-replay motion pre-empted.')
        else:
            if self._demo_state == DemoState.PLAYING_DEMO:
                Response.say(RobotSpeech.ERROR_REPLAY_NOT_POSSIBLE)
                Response.perform_gaze_action(GazeGoal.SHAKE)
                self._demo_state = DemoState.HAS_RECORDED_DEMO
            else:
                rospy.loginfo('Non-replay motion has no IK.')

        self.arms.status = ExecutionStatus.NOT_EXECUTING