aboutsummaryrefslogtreecommitdiffstats
path: root/ncomp-docker-adaptor/src/main/java/org/openecomp/ncomp/servers/docker/DockerDockerHostProvider.java
blob: 8ea1ba9c478d0831dd525b9ddd054dd37223581e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
/*-
 * ============LICENSE_START==========================================
 * OPENECOMP - DCAE
 * ===================================================================
 * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved.
 * ===================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0 
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END============================================
 */
	
package org.openecomp.ncomp.servers.docker;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.net.URLEncoder;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.io.UnsupportedEncodingException;

import org.openecomp.ncomp.sirius.manager.ISiriusServer;
import org.openecomp.ncomp.sirius.manager.ManagementServer;
import org.openecomp.ncomp.sirius.manager.ManagementServerUtils;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

import org.openecomp.ncomp.sirius.manager.BasicAdaptorProvider;
import org.openecomp.ncomp.docker.ContainerOptions;
import org.openecomp.ncomp.docker.ContainerCpuUsage;
import org.openecomp.ncomp.docker.ContainerCpuStats;
import org.openecomp.ncomp.docker.ContainerPortBindings;
import org.openecomp.ncomp.docker.ContainerNetworkStats;
import org.openecomp.ncomp.docker.ContainerMemoryStats;
import org.openecomp.ncomp.docker.ContainerMemoryUsage;
import org.openecomp.ncomp.docker.ContainerRestartPolicy;
import org.openecomp.ncomp.docker.DockerContainer;
import org.openecomp.ncomp.docker.DockerContainerStats;
import org.openecomp.ncomp.docker.DockerFactory;
import org.openecomp.ncomp.docker.DockerProcess;
import org.openecomp.ncomp.docker.DockerHost;
import org.openecomp.ncomp.docker.DockerImage;
import org.openecomp.ncomp.docker.DockerNetwork;
import org.openecomp.ncomp.docker.DockerPackage;


import org.eclipse.emf.common.util.EList;

class DockerDockerHostProvider extends BasicAdaptorProvider {
    
    private static final Logger logger = Logger.getLogger(DockerDockerHostProvider.class);
    
    DockerHost o;
    DockerHttpClient client;
    protected Date lastPoll;
    
    //
    // Docker endpoint types are --
    //  -> containers
    //  -> images
    //  -> networks
    //  -> misc 
    // 
    private static final String CONTAINERS = "/containers/";
    private static final String IMAGES = "/images/";
    private static final String NETWORKS = "/networks/";
    private static final String MISC = "/misc/";

    private static final String GET_METHOD = "GET";
    private static final String POST_METHOD = "POST";
    private static final String DELETE_METHOD = "DELETE";
    private static final int PRETTY_PRINT = 4;
    private static final int REPO = 0;
	private static final int PORT = 1;
	private static final int NAME = 2;
	private static final int VER = 3;
    
    private enum ContainerState { 
    	CREATED, STOPPED, RUNNING, PAUSED, DELETED
    }
    
    private enum ContainerEvents { 
    	CREATE, START, STOP, RESTART, PAUSE, UNPAUSE, KILL, DESTORY
    }
    
    public DockerDockerHostProvider(ISiriusServer controller, DockerHost o) {
        super(controller, o);
        this.o = o;
        this.client = new DockerHttpClient("docker.properties","dockerHost");
    }

    @Override
    public void start() {
        if (o.isRemote()) return;
    	Thread t = new Thread("docker poller: " + o.getName()) {
            @Override
            public void run() {
                while (true) {
                    try {
                        if (lastPoll == null
                                || lastPoll.getTime() + o.getPollingFrequency() < new Date()
                                        .getTime())
                            o.poll();
                        Thread.sleep(5000); // sleep 5 seconds
                    } catch (Exception e) {
                        ManagementServerUtils.printStackTrace(e);
                        logger.fatal("openstackPoller Thread DIED: " + e);
                        try {
                            Thread.sleep(30000);
                        } catch (InterruptedException e1) {
                        }
                    }
                }
            };
        };
        t.start();
    }

    protected void poll() {
        logger.info("XXXX poll");
        lastPoll = new Date();
        JSONObject json = callRemoteApi("/images/json", GET_METHOD);
        logger.info("XXXX res:" + json.toString(2));
        updateImages(json);
        // containers
        // if you only want to see running containers, set "all" to false
        // this results in only running containers being shown
        //
        int ALL=1;
        json = callRemoteApi("/containers/json?all=" + ALL, GET_METHOD);
        logger.info("XXXX res:" + json.toString(2));
        updateContainers(json);
        // networks
        json = callRemoteApi("/networks", GET_METHOD);   
        logger.info("XXXX res:" + json.toString(2));
        updateNetworks(json);  
        updateContainerStats();

        logger.info("XXXX " + ManagementServer.ecore2json(o, 100, null, true).toString(2));
    }
    
    /*
     * json to provide with request to create a container from an image
     */
    private JSONObject mkContainerJson(String image) {
    	
            StringBuilder json = new StringBuilder();
            
                json.append("{");
                json.append("\"Hostname\":\"\",");
                json.append("\"User\":\"\",");
                json.append("\"Memory\":0,");
                json.append("\"MemorySwam\":0,");
                json.append("\"AttachStdin\":false,");
                json.append("\"AttachStdout\":true,");
                json.append("\"AttachStderr\":true,");
                json.append("\"PortSpecs\":null,");
                json.append("\"Privleged\":false,");
                json.append("\"Tty\":false,");
                json.append("\"OpenStdin\":false,");
                json.append("\"StdinOnce\":false,");
                json.append("\"Env\":null,");
                json.append("\"Dns\":null,");
                json.append("\"Image\":\"<image>\",");
                json.append("\"Volumes\":null,");
                json.append("\"VolumesFrom\":null,");
                json.append("\"WorkingDir\":\"\",");
                json.append("}");
                
                
                return new JSONObject(json.toString().replace("<image>", image));
    }
    
    /*
     * this is a composite of two separate API calls. the first call creates the
     * container. the second call starts the created container
     */ 
    public void dockerRun(String image) {
    	dockerRunWithName(image, null);
    }
    
    public void dockerRunWithName(String image, String name) {
         logger.debug("image <-" + image);
         boolean chkEnv = false;
         
         if (chkEnv) {
             Map<String,String> env = System.getenv();
             for(Map.Entry<String,String> entry : env.entrySet()) {
                 if (entry.getKey().toLowerCase().contains("proxy")) {
                     logger.debug(entry.getKey() + " = " + entry.getValue());
                 }
             }
         }
         
         String api = "/containers/create";
         if (name != null) {
        	 api += "?name=" + name;
         }
         
         JSONObject jobj = mkContainerJson(image);
         
         logger.info("container json <- " + jobj.toString(PRETTY_PRINT));
         
         JSONObject json = callRemoteApi(api, POST_METHOD, jobj);

        // 201 - no error
        // 404 - no such container
        // 406 - impossible to attach (container not running)
        // 500 - server error

         if (client.getResponseCode() == 201) {
        	 String shortId = json.getString("Id").substring(0,11);
        	 logger.info("Starting container <- " + shortId);
             startContainer(shortId);
         }
         
     }
    
    public void dockerRunWithOptions(String image, ContainerOptions opts) {
    	
          String api = "/containers/create";
          String name = opts.getName();
      
          if (name != null) {
         	 api += "?name=" + name;
          }
          
          JSONObject jobj = mkContainerJson(image);       
          JSONObject options = new JSONObject();
          JSONArray binds = new JSONArray();
                   
          for(String binding : opts.getVolumes()) {
        	  binds.put(binding);
          }
          
          if (binds.length() > 0) {
        	  options.put("Binds",binds);
          }
          
          JSONObject portBindings = new JSONObject();
          JSONObject exposedPorts = new JSONObject();
          
          for(ContainerPortBindings portMap : opts.getPortBindings()) {
        	  String tag = Integer.toString(portMap.getContainerPort()) + "/" + portMap.getProtocol();
        	  String val = Integer.toString(portMap.getVmPort());
        	  JSONObject pair = new JSONObject().put("HostIp", "").put("HostPort", val);
        	 
        	  if (portBindings.has(tag)) {
        		  portBindings.accumulate(tag,pair);
        	  } else {
        		  portBindings.put(tag, new JSONArray().put(pair));
        	  }
        	  exposedPorts.put(tag, new JSONObject());
          }
          
          if (portBindings.length() > 0) {
        	  options.put("PortBindings",portBindings);
          }
          
          // container links 
          if (!opts.getLinks().isEmpty()) {
        	  JSONArray links = new JSONArray();
        	  for(String fromLink : opts.getLinks()) {
        		  String linkAlias = "";
        		  String link = "";
        		  
        		  if (fromLink.contains(":")) {
        			  String[] ary = fromLink.split("\\:");
        			  if (ary.length > 1) {
        				  link = ary[0];
        				  linkAlias = ary[1];
        			  } 
        		  } else {
        			  link = fromLink;
        		  }
     
        		  String fqLink = link + ":" + name + "/" + linkAlias;
        		  links.put(fqLink);
        	  }
        	  options.put("Links", links);
          }
          
          // default behavior
          opts.setPublishAllPorts(true);
          
          if (opts.isPublishAllPorts()) {
        	  options.put("PublishAllPorts", true);
          }
          
          // restart policy defaults
          String policy = "always";
          int retries = 0;
                
          if (opts.getAutoRestart() != null && opts.getAutoRestart().getNm() != null) {
        	  policy = opts.getAutoRestart().getNm();
          }
          
          if ("on-failure".equals(policy)) {
        	  retries = opts.getAutoRestart().getMaxRetryCnt();
          }
          
          JSONObject restartPolicy = new JSONObject()
        	.put("Name", policy)
        	.put("MaximumRetryCount", retries);
        
          options.put("RestartPolicy", restartPolicy);
          
          if (options.length() > 0) {
        	  jobj.put("HostConfig",options);
          }
          
          if (exposedPorts.length() > 0) {
        	  jobj.put("ExposedPorts",exposedPorts);
          }
          
          JSONObject config = new JSONObject();  
           
          // add any runtime environment arguments
          if (!opts.getEnv().isEmpty()) {
        	  JSONArray rekv = new JSONArray();
        	  for(String kv : opts.getEnv()) {
        		  logger.debug("adding runtime argument " + kv);
        		  rekv.put(kv);
        	  }
              jobj.put("Env", rekv);
          }
       
          opts.setSetContainerName(true);
          
          if (opts.isSetContainerName()) {
        	  try { 
        		  jobj.put("Hostname", InetAddress.getLocalHost().getHostName());
        	  } catch(UnknownHostException e) {
        		  logger.error("Unable to determine local hostname", e);
        	  }
          }
          
          logger.info("container json <- " + jobj.toString(PRETTY_PRINT));
          
          JSONObject json = callRemoteApi(api, POST_METHOD, jobj);

         // 201 - no error
         // 404 - no such container
         // 406 - impossible to attach (container not running)
         // 500 - server error

          if (client.getResponseCode() == 201) {
         	 String shortId = json.getString("Id").substring(0,11);
         	 logger.info("Starting container <- " + shortId);
              startContainer(shortId);
          }
          
		
	}
    
    private void updateContainers(JSONObject json) {
        JSONArray a = json.getJSONArray("$list");
         o.getContainers().clear();
        for (int i = 0; i < a.length(); i++) {
            JSONObject j = a.getJSONObject(i);
            decapitalize(j);
            fixNull(j);
            rename(j, "created", "dockerCreated");
            fixMap(j, "hostConfig");
            fixMap(j, "labels");
            DockerContainer container = (DockerContainer) controller
                    .getServer().json2ecore(
                            DockerPackage.eINSTANCE.getDockerContainer(), j);
             if (container.getNames().size()>0)
                 container.setName(container.getNames().get(0).replace("/", ""));
             else container.setName(container.getId().substring(0, 10));
             
             // get container process info 
             //containerProcesses(container.getId());
//             String name = container.getId();
//             String api = CONTAINERS + name + "/top?ps_args=aux";   
//             JSONObject jo = callRemoteApi(api,GET_METHOD);
//             DockerProcess[] dp = setPtbl(jo);
             // so how do we actually update the DockerProcess processes 
             // member of the container class?
             // EList<DockerProcess> cp = container.getProcesses();
             // cp = (EList<DockerProcess>)Arrays.asList(dp);
             
//            System.err.println("XXXX "
//                    + ManagementServer.ecore2json(container, 100, null, true)
//                            .toString(2));
            o.getContainers().add(container);
        }
    }

    private void updateImages(JSONObject json) {
    	
    	
        JSONArray a = json.getJSONArray("$list");
        o.getImages().clear();
        for (int i = 0; i < a.length(); i++) {
            JSONObject j = a.getJSONObject(i);
            decapitalize(j);
            fixNull(j);
            rename(j, "created", "dockerCreated");
            if (j.has("labels")) j.remove("labels");
//            System.err.println("XXXX " + j.toString());
            DockerImage image = (DockerImage) controller.getServer()
                    .json2ecore(DockerPackage.eINSTANCE.getDockerImage(), j);
            // System.err.println("XXXX " + ManagementServer.ecore2json(image,
            // 100, null, true).toString(2));
            if (image.getRepoTags().size() > 0)
                image.setName(image.getRepoTags().get(0));
            image.setName(image.getName().replace("/", "_"));
            o.getImages().add(image);
        }
    }
    
   
    /*
     * should probably break this up into discrete pieces for 
     * cpu, memory, blkio, and network. but this is good enough for now.
     * blkio stats not modeled - since i'm not certain what is actually 
     * being reported
     */   
    private void updateContainerStats() {
    	
    	for(DockerContainer c : o.getContainers()) {
    		if (c.getStatus().equals("exited")) continue;
    		if (c.getStatus().startsWith("Exited")) continue;
    		if (c.getStatus().startsWith("Created")) continue;
    		String nm = c.getName();
    		JSONObject j = containerStats(nm,false);
    		logger.info("container stats json <- " + j.toString(4));
    		
    		DockerContainerStats cstats = DockerFactory.eINSTANCE.createDockerContainerStats();
    		
    		/*
    		 * network stats
    		 */
    		JSONObject netwks = j.getJSONObject("networks");
    		for(String net : JSONObject.getNames(netwks)) {
    			JSONObject intf = netwks.getJSONObject(net);
//    			System.err.println(net + " <- " + intf.toString(4));
    			ContainerNetworkStats cnet = DockerFactory.eINSTANCE.createContainerNetworkStats();
    			cnet.setIntf(net);
    			cnet.setRx_bytes(intf.getInt("rx_bytes"));
    			cnet.setRx_dropped(intf.getInt("rx_dropped"));
    			cnet.setRx_errors(intf.getInt("rx_errors"));
    			cnet.setRx_packets(intf.getInt("rx_packets"));
    			cnet.setTx_bytes(intf.getInt("tx_bytes"));
    			cnet.setTx_dropped(intf.getInt("tx_dropped"));
    			cnet.setTx_errors(intf.getInt("tx_errors"));
    			cnet.setTx_packets(intf.getInt("tx_packets"));
    			
    			cstats.getNetworks().add(cnet);
    		}
    		
    		/*
    		 * memory usage
    		 */
    		JSONObject mem = j.getJSONObject("memory_stats");
    		ContainerMemoryUsage memusg = DockerFactory.eINSTANCE.createContainerMemoryUsage();
    		
    		memusg.setUsage(mem.getInt("usage"));
    		memusg.setMax_usage(mem.getInt("max_usage"));
    		memusg.setLimit(mem.getInt("limit"));
			try {
				memusg.setFailcnt(mem.getInt("failcnt"));
			} catch (Exception e) {
			}
    		
    		/*
    		 * memory stats
    		 */
    		if (mem.has("stats") && isaJSONObject(mem.get("stats"))) {
    			JSONObject mstats = mem.getJSONObject("stats");
    		
    			if (mstats != null) {
    				ContainerMemoryStats memstats = DockerFactory.eINSTANCE.createContainerMemoryStats();		
    				memstats.setActive_anon(mstats.getInt("active_anon"));
    				memstats.setActive_file(mstats.getInt("active_file"));
    				memstats.setCache(mstats.getInt("cache"));
    				memstats.setHierarchical_memory_limit(mstats.getInt("hierarchical_memory_limit"));
    				memstats.setInactive_anon(mstats.getInt("inactive_anon"));
    				memstats.setInactive_file(mstats.getInt("inactive_file"));
    				memstats.setMapped_file(mstats.getInt("mapped_file"));
    				memstats.setPgfault(mstats.getInt("pgfault"));
    				memstats.setPgmajfault(mstats.getInt("pgmajfault"));
    				memstats.setPgpgin(mstats.getInt("pgpgin"));
    				memstats.setPgpgout(mstats.getInt("pgpgout"));
    				memstats.setRss(mstats.getInt("rss"));
    				memstats.setRss_huge(mstats.getInt("rss_huge"));
//    				memstats.setUnevictable(mstats.getInt("unevicatable"));
    				memstats.setTotal_active_anon(mstats.getInt("total_active_anon"));
    				memstats.setTotal_active_file(mstats.getInt("total_active_file"));
    				memstats.setTotal_cache(mstats.getInt("total_cache"));
    				memstats.setTotal_inactive_anon(mstats.getInt("total_inactive_anon"));
    				memstats.setTotal_inactive_file(mstats.getInt("total_inactive_file"));
    				memstats.setTotal_mapped_file(mstats.getInt("total_mapped_file"));
    				memstats.setTotal_pgfault(mstats.getInt("total_pgfault"));
    				memstats.setTotal_pgmajfault(mstats.getInt("total_pgmajfault"));
    				memstats.setTotal_pgpgin(mstats.getInt("total_pgpgin"));
    				memstats.setTotal_pgpgout(mstats.getInt("total_pgpgout"));
    				memstats.setTotal_rss(mstats.getInt("total_rss"));
    				memstats.setTotal_rss_huge(mstats.getInt("total_rss_huge"));
    				memstats.setTotal_unevictable(mstats.getInt("total_unevictable"));
    				memstats.setTotal_writeback(mstats.getInt("total_writeback"));
    			
    				memusg.setMemstats(memstats);
    			}
    		}	
    		
    		cstats.setMemory(memusg);
    		
    		/*
    		 * cpu stats
    		 */
    		ContainerCpuStats ccpustats = DockerFactory.eINSTANCE.createContainerCpuStats();
    		ContainerCpuUsage ccpuusage = DockerFactory.eINSTANCE.createContainerCpuUsage();
    
    		JSONObject jcpuusage = j.getJSONObject("cpu_stats").getJSONObject("cpu_usage");  		
    		
    		ccpuusage.setTotal_usage(jcpuusage.getLong("total_usage"));
    		ccpuusage.setUsage_in_usermode(jcpuusage.getLong("usage_in_kernelmode"));
    		ccpuusage.setUser_in_kernelmode(jcpuusage.getLong("usage_in_usermode"));
    		
    		JSONArray ccpupcpu = jcpuusage.getJSONArray("percpu_usage"); 
    		
    		for(int idx = 0; idx < ccpupcpu.length(); idx++) {
    			ccpuusage.getPercpu_usage().add(ccpupcpu.getLong(idx));	
    		}
    		
    		ccpustats.setCpu_usage(ccpuusage);
    		cstats.setCpu(ccpustats);
    		
    		c.setStats(cstats);
    		controller.getServer().save();
    	}
    	
    }

    private static final boolean isaJSONObject(Object v) {
        if (v.getClass().equals(JSONObject.class)) {
            return true;
        }
        return false;
    }
    
    private void updateNetworks(JSONObject json) {
        JSONArray a = json.getJSONArray("$list");
        o.getNetworks().clear();
        for (int i = 0; i < a.length(); i++) {
            JSONObject j = a.getJSONObject(i);
            decapitalize(j);
            fixNull(j);
            rename(j, "created", "dockerCreated");
            fixMap(j, "containers", "id");
            fixMap(j, "options");
            DockerNetwork network = (DockerNetwork) controller.getServer()
                    .json2ecore(DockerPackage.eINSTANCE.getDockerNetwork(), j);
            // System.err.println("XXXX " + ManagementServer.ecore2json(network,
            // 100, null, true).toString(2));
            o.getNetworks().add(network);
        }
    }

    // change JSONObject to a JSONArray with name,value objects
    private void fixMap(JSONObject j, String key) {
        JSONArray a = new JSONArray();
        if (!j.has(key)) return;
        JSONObject jjj = j.getJSONObject(key);
        for (Iterator<String> i = jjj.keys(); i.hasNext();) {
            String k = i.next();
            Object v = jjj.get(k);
            JSONObject jj = new JSONObject();
            jj.put("name", k);
            jj.put("value", v);
            a.put(jj);
        }
        j.put(key, a);
    }

    // change JSONObject to a JSONArray with name,value objects
    private void fixMap(JSONObject j, String key, String nameKey) {
        JSONArray a = new JSONArray();
        JSONObject jjj = j.getJSONObject(key);
        for (Iterator<String> i = jjj.keys(); i.hasNext();) {
            String k = i.next();
            JSONObject v = jjj.getJSONObject(k);
            v.put(nameKey, k);
            a.put(v);
        }
        j.put(key, a);
    }

    private void fixNull(JSONObject j) {
        for (Iterator<String> i = j.keys(); i.hasNext();) {
            String k = i.next();
            Object v = j.get(k);
            // System.err.println("XXXX " + v.getClass().getName());
            if (v.getClass().getName().equals("org.json.JSONObject$Null")) {
                j.put(k, new JSONArray());
//                System.err.println("XXXX change null to empty array " + k);
            }
        }
    }

    private void decapitalize(JSONObject j) {
        ArrayList<String> l = new ArrayList<String>();
        for (Iterator<String> i = j.keys(); i.hasNext();) {
            l.add(i.next());
        }
        for (String k : l) {
            Object v = j.get(k);
            if (v instanceof JSONObject) {
                JSONObject jj = (JSONObject) v;
                decapitalize(jj);
            }
            if (v instanceof JSONArray) {
				JSONArray a = (JSONArray) v;
		        for (int i = 0; i < a.length(); i++) {
		        	Object v1 = a.get(i);
		            if (v1 instanceof JSONObject) {
		                JSONObject jj = (JSONObject) v1;
		                decapitalize(jj);
		            }
		        }		        	
			}
            rename(j, k, k.substring(0, 1).toLowerCase() + k.substring(1));
        }

    }

    private void rename(JSONObject j, String k1, String k2) {
        if (k1.equals(k2))
            return;
        if (j.has(k1)) {
            j.put(k2, j.get(k1));
            j.remove(k1);
        }
    }

	// run through json.get("Processes") arrays 
	// and generate a DockerProcess object
    // "USER","PID","%CPU","%MEM","VSZ","RSS","TTY","STAT","START","TIME","COMMAND" 
    private DockerProcess[] setPtbl(JSONObject json) {
    	
    	if (!json.has("Proccesses")) {
    		return null;
    	}
    	JSONArray processes = json.getJSONArray("Processes");
    	int sz = processes.length();
    	
    	DockerProcess[] dprocs = new DockerProcess[sz];
    
    	for (int i=0; i < processes.length(); i++) {
    		JSONArray proc = processes.getJSONArray(i);
    		logger.debug("proc <- " + proc.toString(PRETTY_PRINT));
    		
    		DateFormat df = new SimpleDateFormat();
    
    		DockerProcess dp = DockerFactory.eINSTANCE.createDockerProcess();
    			dp.setUser(proc.getString(0));
    			dp.setPid(proc.getLong(1));
    			dp.setCpu(proc.getDouble(2));
    			dp.setMem(proc.getDouble(3));
    			dp.setVsz(proc.getLong(4));
    			dp.setRss(proc.getLong(5));
    			dp.setTty(proc.getString(6));
    			dp.setStat(proc.getString(7));
    			dp.setCommand(proc.getString(10));
    			// 9th field is a duration indicator. FIXME
    			dp.setTimeElapsed(0);
    			
    			try { 
    				dp.setStart(df.parse(proc.getString(8)));
    			} 
    			catch(ParseException ep) {
    				logger.warn("Could not parse " + proc.getString(8) + " into a Date");
    				dp.setStart(null);
    			}
    			catch(NullPointerException e){
    				logger.warn("Could not parse " + proc.getString(8) + " into a Date");
    				dp.setStart(null);
    			}
    			
    			dprocs[i] = dp;
    	}
    	
    	return dprocs;
    }
    
    /*
     * many remote docker api calls do not return a json message
     * your only indication of operational success will be in the 
     * http client response code. the json object will be null in 
     * those cases
     */
    private JSONObject callRemoteApi(String api, String method) {
    	return callRemoteApi(api,method,null);
    }
    
    private JSONObject callRemoteApi(String api, String method, JSONObject context) {
    	
    	 HashMap<String, String> headers = new HashMap<String, String>();
    	 JSONObject json = null;
    	 
    	 // this will be prepended to the api string passed into the method
         String url = client.getBaseAddress();
         
         logger.info("api <- " + method + " " + url + api);
         
         switch(method) {
         case GET_METHOD : 
        	 json = client.httpJsonTransaction(api, method, headers, null, 5000L);
        	 break;
         case POST_METHOD :
        	 if (context == null) {
        		 client.httpBinaryTransaction(api, method, headers, context, 5000L);
        	 } else {
        		 json = client.httpJsonTransaction(api,method, headers, context, 5000L);
        	 }
        	 break;
         case DELETE_METHOD :
        	 json = client.httpJsonTransaction(api, method, headers, null, 5000L);
        	 break;
         }
         
         logger.info("http response <- " + client.getResponseCode());
         
         if (json != null) {
        	 logger.debug("json <- " + json.toString(PRETTY_PRINT));
         } 
         
         return json;
    }
    
    private JSONArray callRemoteApiStream(String api, String method, JSONObject aContext) {
  
     	 HashMap<String, String> headers = new HashMap<String, String>();
     	 byte[] bytes;
     	 JSONObject context = aContext;
     	 String func = "callRemoteApiStream";
    	 
    	 // this will be prepended to the api string passed into the method
         String url = client.getBaseAddress();
         
         logger.info("api <- " + method + " " + url + api);
        
         bytes = client.httpBinaryTransaction(api, method, headers, context, 5000L);
         logger.info("http response <- " + client.getResponseCode());
         
         JSONObject json = new JSONObject(bytes.toString());
         JSONArray a = json.getJSONArray("$list");
         
    	return a;
    }
    
    //
    // GET /containers/(id)/json
    // 
    // return low level information about a container
    //
    // should it be void? this is returns  
    public void inspectContainer(String name) {
    	
        int size = 0; // 1 - true, 0 - false
        String url = CONTAINERS + name + "/json?size=" + size;
        
        JSONObject json = callRemoteApi(url,GET_METHOD);
        logger.info("container " + name + " <- " + json.toString(PRETTY_PRINT));
        
        // status codes: 
        //    200 - no error
        //    404 - no such container
        //    500 - server error
        // process JSON
    }

    // GET /containers/(id)/top
    // List processes running in a container
    public void containerProcesses(String name) {
    	
        String api = CONTAINERS + name + "/top?ps_args=aux";   
        JSONObject json = callRemoteApi(api,GET_METHOD);
        logger.info("container " + name + " <- " + json.toString(PRETTY_PRINT));     
        setPtbl(json);
    }
    
    // POST /containers/(id)/kill 
    public void killContainer(String name,String sigint) {
    	
        String url = CONTAINERS + name + "/kill?signal=" + sigint;    
        JSONObject json = callRemoteApi(url,POST_METHOD);
        
        // status codes: 
        //    204 - no error
        //    404 - no such container
        //    500 - server err
        // process JSON
    }
    
    // POST /containers/(id)/restart?t=seconds
    public void restartContainer(String name, int seconds) {
    	
        String url = CONTAINERS + name + "/restart?seconds=" + seconds;       
        JSONObject json = callRemoteApi(url,POST_METHOD);
        // status codes: 
        //    204 - no error
        //    404 - no such container
        //    500 - server err
        // process JSON
    }
    
    // remove - remove volumes, force - kill & remove
    public void removeContainer(String name, boolean remove, boolean force) {
    	
    	int rm = (force) ? 1 : 0;
    	int vol = (remove) ? 1 : 0;
    	
    	String url = CONTAINERS + name + "?force=" + rm + "&v=" + vol;
    	
        JSONObject json = callRemoteApi(url,DELETE_METHOD);
        
        // status codes: 
        //  204 - no error
        //  400 - bad parameter
        //  404 - no such container
        //  500 - server error
        // process JSON
    }
    
    // POST /containers/(id)/pause
    public void pauseContainer(String name) {
    	
        String url = CONTAINERS + name + "/pause";      
        JSONObject json = callRemoteApi(url,POST_METHOD);
        
        // status codes: 
        //    204 - no error
        //    404 - no such container
        //    500 - server err
        // process JSON
    }
    
    // POST /containers/(id)/unpause
    public void unpauseContainer(String name) {
  
        String url = CONTAINERS + name + "/unpause";
        JSONObject json = callRemoteApi(url,POST_METHOD);
        
        // status codes: 
        //    204 - no error
        //    404 - no such container
        //    500 - server err
        // process JSON
    }
    
    // GET /containers/(id)/stats?stream
    // stream - true or false, if false, poll once and exit
    public JSONObject containerStats(String  name, boolean stream) {
    	
    	String url = CONTAINERS + name + "/stats?stream=" + stream;
    	JSONObject json = callRemoteApi(url,GET_METHOD);
    	
    	return json;   
    }
    
    // POST /containers/(id)/start
    public void startContainer(String name) {
    	
        String url = CONTAINERS + name + "/start";
        JSONObject json = callRemoteApi(url,POST_METHOD);
        // status codes: 
        //    200 - no error
        //    304 - container already started
        //    404 - no such container
        //    500 - server err
    }
    
    // POST /containers/(id)/stop?t=seconds
    // t = seconds to wait before killing the container
    public void stopContainer(String name, int seconds) {
    	
        String url = CONTAINERS + name + "/stop?t=" + seconds;
        JSONObject json = callRemoteApi(url,POST_METHOD);    
        // status codes: 
        //    204 - no error
        //    304 - container already stopped
        //    404 - no such container
        //    500 - server err
    }

    private List<String> getImageNameElements(String image) {
    	
    	 List<String> a = new ArrayList<>();
         for(String z : image.split("\\/")) {
         	String[] iz = z.split(":");
         	for(int i = 0; i < iz.length; i++) {
         		a.add(iz[i]);
         	}
         }
    	return a;
    }
    
    /*
     * return the latest version nbr of a package
     */
    private String getLatest(String image) {
 
    	List<String> vers = new ArrayList<>();
    	
    	for(DockerImage im : o.getImages()) {
    		List<String> elms = getImageNameElements(im.getName()); 
    		
    		if (image.contains(elms.get(NAME))) {
    			EList<String> tags = im.getRepoTags();
    			for(int i = 0; i < tags.size(); i++) {
    				List<String> repoElm = getImageNameElements(tags.get(i));
    				vers.add(repoElm.get(VER));
    			}
    		}	
    	}
    	Collections.sort(vers);
		
    	return vers.get(vers.size()-1);
    }
    
   /*
    * Tag the most current version of an image as latest 
    */
    public void tagImage(String image, String ver, boolean force) {
    	
    	 int f = (force) ? 1 : 0;
    	 
    	 if (ver.isEmpty()) {
    		 ver = "latest";
    	 }
    	 
    	 List<String> elms = getImageNameElements(image);
    	 String repo = elms.get(REPO);
    	 
    	 String url = IMAGES + "/" + image + "/tag" + "?repo=" + repo + "&tag=" + ver + "&force=" + f;
    	 
         JSONObject json = callRemoteApi(url,POST_METHOD);    
         // status codes: 
         //    201 - no error
         //    400 - bad parameter
         //    404 - no such image
         //    500 - server err
     }
}