Stop installing librairies during tests
[parser.git] / verigraph / src / main / java / it / polito / grpc / Client.java
1 /*******************************************************************************
2  * Copyright (c) 2017 Politecnico di Torino and others.
3  *
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Apache License, Version 2.0
6  * which accompanies this distribution, and is available at
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *******************************************************************************/
9
10 package it.polito.grpc;
11
12 import java.util.ArrayList;
13 import java.util.Iterator;
14 import java.util.List;
15 import java.util.Map;
16 import java.util.concurrent.TimeUnit;
17
18 import com.google.protobuf.Message;
19
20 import io.grpc.ManagedChannel;
21 import io.grpc.ManagedChannelBuilder;
22 import io.grpc.StatusRuntimeException;
23 import io.grpc.verigraph.ConfigurationGrpc;
24 import io.grpc.verigraph.GetRequest;
25 import io.grpc.verigraph.GraphGrpc;
26 import io.grpc.verigraph.NeighbourGrpc;
27 import io.grpc.verigraph.NewGraph;
28 import io.grpc.verigraph.NewNeighbour;
29 import io.grpc.verigraph.NewNode;
30 import io.grpc.verigraph.NodeGrpc;
31 import io.grpc.verigraph.NodeGrpc.FunctionalType;
32 import io.grpc.verigraph.Policy;
33 import io.grpc.verigraph.Policy.PolicyType;
34 import io.grpc.verigraph.RequestID;
35 import io.grpc.verigraph.Status;
36 import io.grpc.verigraph.TestGrpc;
37 import io.grpc.verigraph.VerificationGrpc;
38 import io.grpc.verigraph.VerigraphGrpc;
39
40 public class Client {
41
42         private final ManagedChannel channel;
43         private final VerigraphGrpc.VerigraphBlockingStub blockingStub;
44
45         public Client(String host, int port) {
46                 this(ManagedChannelBuilder.forAddress(host, port).usePlaintext(true));
47         }
48
49         /** Construct client for accessing RouteGuide server using the existing channel. */
50         public Client(ManagedChannelBuilder<?> channelBuilder) {
51                 channel = channelBuilder.build();
52                 blockingStub = VerigraphGrpc.newBlockingStub(channel);
53         }
54
55         /** Get array of graphs */
56         public List<GraphGrpc> getGraphs() {
57                 List<GraphGrpc> graphsRecveived = new ArrayList<GraphGrpc>();
58                 GetRequest request = GetRequest.newBuilder().build();
59                 Iterator<GraphGrpc> graphs;
60                 try {
61                         graphs = blockingStub.getGraphs(request);
62                         while (graphs.hasNext()) {
63                                 GraphGrpc graph = graphs.next();
64                                 System.out.println("Graph id : "+graph.getId());
65                                 if(graph.getErrorMessage().equals("")){
66                                         System.out.println("Node id : "+graph.getId());
67                                         graphsRecveived.add(graph);
68                                 }else{
69                                         System.out.println("Error : " + graph.getErrorMessage());
70                                         return graphsRecveived;
71                                 }
72                         }
73                 } catch (StatusRuntimeException ex) {
74                         System.err.println("RPC failed: " + ex.getStatus());
75                 }
76                 return graphsRecveived;
77         }
78
79         /** Create new Graph */
80         public NewGraph createGraph(GraphGrpc gr) {
81                 NewGraph response;
82                 try {
83                         response = blockingStub.createGraph(gr);
84                         if(response.getSuccess()){
85                                 System.out.println("Successful operation ");
86                         }else{
87                                 System.out.println("Unsuccessful operation: " + response.getErrorMessage());
88                         }
89                 } catch (StatusRuntimeException e) {
90                         System.err.println("RPC failed: " + e.getStatus());
91                         return NewGraph.newBuilder().setSuccess(false).build();
92                 }
93                 return response;
94         }
95
96         /** Delete a Graph */
97         public boolean deleteGraph(long idGraph) {
98
99                 RequestID id = RequestID.newBuilder().setIdGraph(idGraph).build();
100                 Status response;
101                 try {
102                         response = blockingStub.deleteGraph(id);
103                         if(response.getSuccess()){
104                                 System.out.println("Successful operation ");
105                                 return true;
106                         }else{
107                                 System.out.println("Unsuccessful operation: " + response.getErrorMessage());
108                         }
109                 } catch (StatusRuntimeException e) {
110                         System.err.println("RPC failed: " + e.getStatus());
111                 }
112                 return false;
113         }
114
115         /** Edits a single graph */
116         public NewGraph updateGraph(long idGraph, GraphGrpc newGraph) {
117
118                 GraphGrpc gr = GraphGrpc.newBuilder(newGraph).setId(idGraph).build();
119                 NewGraph response;
120                 try {
121                         response = blockingStub.updateGraph(gr);
122                         if(response.getSuccess()){
123                                 System.out.println("Successful operation ");
124                         }else{
125                                 System.out.println("Unsuccessful operation: " + response.getErrorMessage());
126                         }
127                 } catch (StatusRuntimeException e) {
128                         System.err.println("RPC failed: " + e.getStatus());
129                         return NewGraph.newBuilder().setSuccess(false).build();
130                 }
131                 return response;
132         }
133
134         /** Get a single graph*/
135         public GraphGrpc getGraph(long idGraph) {
136
137                 RequestID request = RequestID.newBuilder().setIdGraph(idGraph).build() ;
138                 try {
139                         GraphGrpc graph = blockingStub.getGraph(request);
140                         if(!graph.getErrorMessage().equals("")){
141                                 System.out.println("Error in operation: " + graph.getErrorMessage());
142                         }
143                         return graph;
144                 } catch (StatusRuntimeException ex) {
145                         System.err.println("RPC failed: " + ex.getStatus());
146                         return null;
147                 }
148         }
149
150         /** Verify a given policy*/
151         public VerificationGrpc verify(Policy policy) {
152
153                 VerificationGrpc response;
154                 try {
155                         response = blockingStub.verifyPolicy(policy);
156                         if(!response.getErrorMessage().equals("")){
157                                 System.out.println("Error in operation: " + response.getErrorMessage());
158                         }
159                         System.out.println("Result : "+response.getResult());
160                         System.out.println("Comment : "+response.getComment());
161                         //uncomment if you want to print the paths
162                         /*for(TestGrpc test:response.getTestList()){
163                                 System.out.println("Test : "+test.getResult()+". Traversed nodes:");
164                                 for(NodeGrpc node:test.getNodeList()){
165                                         //prints only the name
166                                         System.out.println("Node "+node.getName());
167                                 }
168                         }*/
169                         return response;
170                 } catch (StatusRuntimeException e) {
171                         System.err.println("RPC failed: " + e.getStatus());
172                         return null;
173                 }
174         }
175
176         /*Node part*/
177
178         /** Get array of nodes */
179         public List<NodeGrpc> getNodes(long idGraph) {
180                 List<NodeGrpc> nodesReceived = new ArrayList<NodeGrpc>();
181                 RequestID request = RequestID.newBuilder().setIdGraph(idGraph).build() ;
182                 Iterator<NodeGrpc> nodes;
183                 try {
184                         nodes = blockingStub.getNodes(request);
185                         while (nodes.hasNext()) {
186                                 NodeGrpc node = nodes.next();
187                                 if(node.getErrorMessage().equals("")){
188                                         System.out.println("Node id : "+node.getId());
189                                         nodesReceived.add(node);
190                                 }else{
191                                         System.out.println("Error : " + node.getErrorMessage());
192                                         return nodesReceived;
193                                 }
194                         }
195                 } catch (StatusRuntimeException ex) {
196                         System.err.println("RPC failed: " + ex.getStatus());
197                 }
198                 return nodesReceived;
199         }
200
201         /** Create new Node */
202         public NewNode createNode(NodeGrpc node, long idGraph) {
203
204                 NewNode response;
205                 try {
206                         NodeGrpc n = NodeGrpc.newBuilder(node).setIdGraph(idGraph).build();
207                         response = blockingStub.createNode(n);
208                         if(response.getSuccess()){
209                                 System.out.println("Successful operation ");
210                         }else{
211                                 System.out.println("Unsuccessful operation: " + response.getErrorMessage());
212                         }
213                 } catch (StatusRuntimeException e) {
214                         System.err.println("RPC failed: " + e.getStatus());
215                         return NewNode.newBuilder().setSuccess(false).build();
216                 }
217                 return response;
218         }
219
220         /** Delete a Node */
221         public boolean deleteNode(long idGraph, long idNode) {
222
223                 RequestID id = RequestID.newBuilder().setIdGraph(idGraph).setIdNode(idNode).build();
224                 Status response;
225                 try {
226                         response = blockingStub.deleteNode(id);
227                         if(response.getSuccess()){
228                                 System.out.println("Successful operation ");
229                                 return true;
230                         }else{
231                                 System.out.println("Unsuccessful operation: " + response.getErrorMessage());
232                         }
233                 } catch (StatusRuntimeException e) {
234                         System.err.println("RPC failed: " + e.getStatus());
235                 }
236                 return false;
237         }
238
239         /** Edits a single Node */
240         public NewNode updateNode(long idGraph, long idNode, NodeGrpc node) {
241
242                 NodeGrpc nu = NodeGrpc.newBuilder(node).setIdGraph(idGraph).setId(idNode).build();
243                 NewNode response;
244                 try {
245                         response = blockingStub.updateNode(nu);
246                         if(response.getSuccess()){
247                                 System.out.println("Successful operation ");
248                         }else{
249                                 System.out.println("Unsuccessful operation: " + response.getErrorMessage());
250                         }
251                 } catch (StatusRuntimeException e) {
252                         System.err.println("RPC failed: " + e.getStatus());
253                         return NewNode.newBuilder().setSuccess(false).build();
254                 }
255                 return response;
256         }
257
258         /** Get a single Node*/
259         public NodeGrpc getNode(long idGraph, long idNode) {
260
261                 RequestID request = RequestID.newBuilder().setIdGraph(idGraph).setIdNode(idNode).build() ;
262                 try {
263                         NodeGrpc node = blockingStub.getNode(request);
264                         if(!node.getErrorMessage().equals("")){
265                                 System.out.println("Error in operation: " + node.getErrorMessage());
266                         }
267                         return  node;
268                 } catch (StatusRuntimeException ex) {
269                         System.err.println("RPC failed: " + ex.getStatus());
270                         return null;
271                 }
272         }
273
274         /** Configure a single Node*/
275         public boolean configureNode(long idGraph, long idNode, ConfigurationGrpc configuration) {
276
277                 try {
278                         ConfigurationGrpc request = ConfigurationGrpc.newBuilder(configuration)
279                                         .setIdGraph(idGraph).setIdNode(idNode).build() ;
280
281                         Status response = blockingStub.configureNode(request);
282                         if(response.getSuccess()){
283                                 System.out.println("Successful operation ");
284                                 return true;
285                         }else{
286                                 System.out.println("Unsuccessful operation: " + response.getErrorMessage());
287                         }
288                 } catch (StatusRuntimeException e) {
289                         System.err.println("RPC failed: " + e.getStatus());
290                 }
291                 return false;
292         }
293
294         /*Neighbour part*/
295
296         /** Get array of neighbours */
297         public List<NeighbourGrpc> getNeighbours(long idGraph, long idNode) {
298
299                 List<NeighbourGrpc> neighboursReceived = new ArrayList<NeighbourGrpc>();
300                 RequestID request = RequestID.newBuilder().setIdGraph(idGraph).setIdNode(idNode).build() ;
301                 Iterator<NeighbourGrpc> neighbours;
302                 try {
303                         neighbours = blockingStub.getNeighbours(request);
304                         while (neighbours.hasNext()) {
305                                 NeighbourGrpc neighbour = neighbours.next();
306                                 if(neighbour.getErrorMessage().equals("")){
307                                         System.out.println("Neighbour id : "+neighbour.getId());
308                                         neighboursReceived.add(neighbour);
309                                 }else{
310                                         System.out.println("Error : " + neighbour.getErrorMessage());
311                                         return neighboursReceived;
312                                 }
313                         }
314                 } catch (StatusRuntimeException ex) {
315                         System.err.println("RPC failed: " + ex.getStatus());
316                 }
317                 return neighboursReceived;
318         }
319
320         /** Create new Neighbour */
321         public NewNeighbour createNeighbour(NeighbourGrpc neighbour, long idGraph, long idNode) {
322
323                 NewNeighbour response;
324                 try {
325                         NeighbourGrpc n = NeighbourGrpc.newBuilder(neighbour).setIdGraph(idGraph)
326                                         .setIdNode(idNode).build();
327                         response = blockingStub.createNeighbour(n);
328                         if(response.getSuccess()){
329                                 System.out.println("Successful operation ");
330                         }else{
331                                 System.out.println("Unsuccessful operation: " + response.getErrorMessage());
332                         }
333                 } catch (StatusRuntimeException e) {
334                         System.err.println("RPC failed: " + e.getStatus());
335                         return NewNeighbour.newBuilder().setSuccess(false).build();
336                 }
337                 return response;
338         }
339
340         /** Delete a Neighbour */
341         public boolean deleteNeighbour(long idGraph, long idNode, long idNeighbour) {
342
343                 RequestID id = RequestID.newBuilder().setIdGraph(idGraph).setIdNode(idNode).setIdNeighbour(idNeighbour).build();
344                 Status response;
345                 try {
346                         response = blockingStub.deleteNeighbour(id);
347                         if(response.getSuccess()){
348                                 System.out.println("Successful operation ");
349                                 return true;
350                         }else{
351                                 System.out.println("Unsuccesful operation: " + response.getErrorMessage());
352                         }
353                 } catch (StatusRuntimeException e) {
354                         System.err.println("RPC failed: " + e.getStatus());
355                 }
356                 return false;
357         }
358
359         /** Edits a single Neighbour */
360         public NewNeighbour updateNeighbour(long idGraph, long idNode, long idNeighbour, NeighbourGrpc neighbour) {
361
362                 NeighbourGrpc nu = NeighbourGrpc.newBuilder(neighbour).setIdGraph(idGraph).setIdNode(idNode)
363                                                                                 .setId(idNeighbour).build();
364                 NewNeighbour response;
365                 try {
366                         response = blockingStub.updateNeighbour(nu);
367                         if(response.getSuccess()){
368                                 System.out.println("Successful operation ");
369                         }else{
370                                 System.out.println("Unsuccessful operation: " + response.getErrorMessage());
371                         }
372                 } catch (StatusRuntimeException e) {
373                         System.err.println("RPC failed: " + e.getStatus());
374                         return NewNeighbour.newBuilder().setSuccess(false).build();
375                 }
376                 return response;
377         }
378
379         /** Get a single Neighbour*/
380         public NeighbourGrpc getNeighbour(long idGraph, long idNode, long idNeighbour) {
381
382                 RequestID request = RequestID.newBuilder().setIdGraph(idGraph).setIdNode(idNode).setIdNeighbour(idNeighbour).build() ;
383                 try {
384                         NeighbourGrpc neighbour = blockingStub.getNeighbour(request);
385                         if(!neighbour.getErrorMessage().equals("")){
386                                 System.out.println("Error in operation: " + neighbour.getErrorMessage());
387                         }
388                         return neighbour;
389                 } catch (StatusRuntimeException ex) {
390                         System.err.println("RPC failed: " + ex.getStatus());
391                         return null;
392                 }
393         }
394
395         public void shutdown() throws InterruptedException {
396                 channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
397         }
398
399         /** Test on the Server. */
400         public static void main(String[] args) throws Exception {
401
402                 List<Long> listGraph = new ArrayList<Long>();   //list of ID
403
404                 Client client = new Client("localhost" , 50051);
405                 try {
406                         NodeGrpc node1 = createNodeGrpc("Node1", "endhost", null, null);
407                         List<NeighbourGrpc> neighbours = new ArrayList<NeighbourGrpc>();
408                         NeighbourGrpc nb = createNeighbourGrpc("Node1");
409                         neighbours.add(nb);
410                         NodeGrpc node2 = createNodeGrpc("Node2", "endpoint", neighbours, null);
411                         List<NodeGrpc> nodes = new ArrayList<NodeGrpc>();
412                         nodes.add(node1);
413                         nodes.add(node2);
414
415                         GraphGrpc graph = createGraphGrpc(nodes);
416
417                         NewGraph createdGraph = client.createGraph(graph);
418                         if(createdGraph.getSuccess() == true){
419                                 listGraph.add(createdGraph.getGraph().getId());
420                                 System.out.println("Created graph with id :"+ createdGraph.getGraph().getId());
421                         }
422
423                         client.getGraphs();
424                 } catch(Exception ex){
425                         System.out.println("Error: " + ex.getMessage());
426                         ex.printStackTrace();
427                 }finally {
428                         client.shutdown();
429                 }
430         }
431
432         public static NeighbourGrpc createNeighbourGrpc(String name){
433                 return NeighbourGrpc.newBuilder().setName(name).build();
434         }
435
436         public static NodeGrpc createNodeGrpc(String name, String functionalType, List<NeighbourGrpc> neighbours, ConfigurationGrpc conf) throws Exception{
437                 NodeGrpc.Builder nb = NodeGrpc.newBuilder();
438
439                 if(name != null)
440                         nb.setName(name);
441                 else
442                         throw new Exception("Node must have a name");
443
444                 if(functionalType != null)
445                         nb.setFunctionalType(FunctionalType.valueOf(functionalType));
446                 else
447                         throw new Exception("Node must have a functional type");
448
449                 if( neighbours!= null){
450                         for(NeighbourGrpc value:neighbours)
451                                 nb.addNeighbour(value);
452                 }
453                 if(conf == null){
454                         try{
455                                 conf = createConfigurationGrpc(null, null, null, null);
456                         }catch(Exception e){
457                                 throw new Exception(e.getMessage());
458                         }
459                 }
460                 nb.setConfiguration(conf);
461                 return nb.build();
462         }
463
464         public static GraphGrpc createGraphGrpc(List<NodeGrpc> nodes){
465                 GraphGrpc.Builder gb = GraphGrpc.newBuilder();
466                 if(nodes != null){
467                         for(NodeGrpc value:nodes)
468                                 gb.addNode(value);
469                 }
470                 return gb.build();
471         }
472
473         public static Policy createPolicy(String src, String dst, String type, String middlebox, long idGraph) throws IllegalArgumentException{
474                 if(!validMiddlebox(type, middlebox))
475                         throw new IllegalArgumentException("Not valid middlebox valid with this type");
476                 Policy.Builder policy = Policy.newBuilder();
477                 policy.setIdGraph(idGraph);
478                 if(src != null)
479                         policy.setSource(src);
480                 else{
481                         throw new IllegalArgumentException("Please insert source field");
482                 }
483                 if(dst != null)
484                         policy.setDestination(dst);
485                 else{
486                         throw new IllegalArgumentException("Please insert destination field");
487                 }
488                 if(type != null)
489                         policy.setType(PolicyType.valueOf(type));
490                 if(middlebox != null)
491                         policy.setMiddlebox(middlebox);
492                 return policy.build();
493         }
494
495         public static ConfigurationGrpc createConfigurationGrpc(Map<String,String> parameters, List<String> lists, String id, String description) throws Exception{
496                 ConfigurationGrpc.Builder cb = ConfigurationGrpc.newBuilder();
497                 StringBuilder sb = new StringBuilder("[");
498                 if(parameters != null && lists == null){
499                         int i = 0;
500                         sb.append("{");
501                         for (String key: parameters.keySet()) {
502                                 sb.append("\"");
503                                 sb.append(key);
504                                 sb.append("\":\"");
505                                 sb.append(parameters.get(key));
506                                 sb.append("\"");
507                                 if((i+1)<parameters.keySet().size()){
508                                         sb.append(", ");
509                                 }
510                                 i++;
511                         }
512                         sb.append("}");
513                 }
514                 else if(parameters == null && lists != null){
515                         int i = 0;
516                         for (String value: lists) {
517                                 sb.append("\"");
518                                 sb.append(value);
519                                 sb.append("\"");
520                                 if((i+1)<lists.size()){
521                                         sb.append(", ");
522                                 }
523                                 i++;
524                         }
525                 }
526                 else if(parameters != null && lists != null){
527                         throw new Exception("Error, configuration must contains or a sequence name:value or sequence"
528                                         + "of string, but not both");
529                 }
530                 sb.append("]");
531                 cb.setConfiguration(sb.toString());
532                 if(id != null)
533                         cb.setId(id);
534                 if(description != null)
535                         cb.setDescription(description);
536                 return cb.build();
537         }
538
539         private static boolean validMiddlebox(String type, String middlebox) {
540                 if(type == null)
541                         return false;
542                 if(type.equals("reachability") && (middlebox == null || middlebox.equals("")))
543                         return true;
544                 if(type.equals("isolation") && !(middlebox == null || middlebox.equals("")))
545                         return true;
546                 if(type.equals("traversal") && !(middlebox == null || middlebox.equals("")))
547                         return true;
548                 return false;
549         }
550 }