seunghwan пре 4 година
комит
0744ae3454

+ 8
- 0
.idea/.gitignore Прегледај датотеку

@@ -0,0 +1,8 @@
1
+# Default ignored files
2
+/shelf/
3
+/workspace.xml
4
+# Datasource local storage ignored files
5
+/dataSources/
6
+/dataSources.local.xml
7
+# Editor-based HTTP Client requests
8
+/httpRequests/

+ 9
- 0
.idea/TestClient.iml Прегледај датотеку

@@ -0,0 +1,9 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<module type="WEB_MODULE" version="4">
3
+  <component name="Go" enabled="true" />
4
+  <component name="NewModuleRootManager">
5
+    <content url="file://$MODULE_DIR$" />
6
+    <orderEntry type="inheritedJdk" />
7
+    <orderEntry type="sourceFolder" forTests="false" />
8
+  </component>
9
+</module>

+ 8
- 0
.idea/modules.xml Прегледај датотеку

@@ -0,0 +1,8 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<project version="4">
3
+  <component name="ProjectModuleManager">
4
+    <modules>
5
+      <module fileurl="file://$PROJECT_DIR$/.idea/TestClient.iml" filepath="$PROJECT_DIR$/.idea/TestClient.iml" />
6
+    </modules>
7
+  </component>
8
+</project>


+ 36
- 0
src/example.json Прегледај датотеку

@@ -0,0 +1,36 @@
1
+{
2
+  "||": [
3
+    {
4
+      "&&": [
5
+        {
6
+          "==": {
7
+            "attribute": "job",
8
+            "value": "doctor"
9
+          }
10
+        },
11
+        {
12
+          ">=": {
13
+            "attribute": "age",
14
+            "value": 40
15
+          }
16
+        }
17
+      ]
18
+    },
19
+    {
20
+      "&&" : [
21
+        {
22
+          "==": {
23
+          "attribute": "job",
24
+          "value": "programmer"
25
+          }
26
+        },
27
+        {
28
+          "<": {
29
+            "atrribute": "age",
30
+            "value": 30
31
+          }
32
+        }
33
+      ]
34
+    }
35
+  ]
36
+}

+ 29
- 0
src/getIpaddr.go Прегледај датотеку

@@ -0,0 +1,29 @@
1
+package main
2
+
3
+import (
4
+	"fmt"
5
+	"net"
6
+)
7
+
8
+func getCurrentIPAddr() string {
9
+	addrs, err := net.InterfaceAddrs()
10
+
11
+	if err != nil {
12
+		fmt.Println(err)
13
+	}
14
+
15
+	var currentIP string
16
+
17
+	for _, address := range addrs {
18
+
19
+		// check the address type and if it is not a loopback the display it
20
+		// = GET LOCAL IP ADDRESS
21
+		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
22
+			if ipnet.IP.To4() != nil {
23
+				//fmt.Println("Current IP address : ", ipnet.IP.String())
24
+				currentIP = ipnet.IP.String()
25
+			}
26
+		}
27
+	}
28
+	return currentIP
29
+}

+ 8
- 0
src/github.com/fatih/go.mod Прегледај датотеку

@@ -0,0 +1,8 @@
1
+module github.com/fatih/color
2
+
3
+go 1.13
4
+
5
+require (
6
+	github.com/mattn/go-colorable v0.1.8
7
+	github.com/mattn/go-isatty v0.0.13
8
+)

+ 8
- 0
src/github.com/fatih/go.sum Прегледај датотеку

@@ -0,0 +1,8 @@
1
+github.com/mattn/go-colorable v0.1.8 h1:c1ghPdyEDarC70ftn0y+A/Ee++9zz8ljHG1b13eJ0s8=
2
+github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
3
+github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
4
+github.com/mattn/go-isatty v0.0.13 h1:qdl+GuBjcsKKDco5BsxPJlId98mSWNKqYA+Co0SC1yA=
5
+github.com/mattn/go-isatty v0.0.13/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
6
+golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
7
+golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae h1:/WDfKMnPU+m5M4xB+6x4kaepxRw6jWvR5iDRdvjHgy8=
8
+golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=

+ 40
- 0
src/logConfig.go Прегледај датотеку

@@ -0,0 +1,40 @@
1
+package main
2
+
3
+import (
4
+	"go.uber.org/zap"
5
+	"go.uber.org/zap/zapcore"
6
+)
7
+
8
+func MyEncoderConfig() zapcore.EncoderConfig {
9
+	return zapcore.EncoderConfig{
10
+		// Keys can be anything except the empty string.
11
+		TimeKey:  "T",
12
+		LevelKey: "L",
13
+		NameKey:  "N",
14
+		//CallerKey:      "C",
15
+		FunctionKey: zapcore.OmitKey,
16
+		MessageKey:  "M",
17
+		//StacktraceKey:  "S",
18
+		LineEnding:     zapcore.DefaultLineEnding,
19
+		EncodeLevel:    zapcore.CapitalColorLevelEncoder,
20
+		EncodeTime:     zapcore.ISO8601TimeEncoder,
21
+		EncodeDuration: zapcore.StringDurationEncoder,
22
+		EncodeCaller:   zapcore.ShortCallerEncoder,
23
+	}
24
+}
25
+
26
+func NewMyLogger() *zap.Logger {
27
+	cfg := zap.Config{
28
+		Level:            zap.NewAtomicLevelAt(zap.DebugLevel),
29
+		Development:      true,
30
+		Encoding:         "console",
31
+		EncoderConfig:    MyEncoderConfig(),
32
+		OutputPaths:      []string{"stdout", "./test.log"},
33
+		ErrorOutputPaths: []string{"stderr"},
34
+	}
35
+	logger, err := cfg.Build()
36
+	if err != nil {
37
+		//panic(err)
38
+	}
39
+	return logger
40
+}

+ 733
- 0
src/main.go Прегледај датотеку

@@ -0,0 +1,733 @@
1
+package main
2
+
3
+// TODO: 등록확인 되기 전에는 PM,SM 전송 불가하게 만들 것, 실행파일로 만든 후, AWS 이용해서 여러개 마이크로서비스 상태에서 테스트 해볼것
4
+
5
+import (
6
+	"bufio"
7
+	"encoding/json"
8
+	"errors"
9
+	"fmt"
10
+	"log"
11
+	"math/rand"
12
+	"net"
13
+	"net/rpc"
14
+	"os"
15
+	"os/signal"
16
+	"strconv"
17
+	"strings"
18
+	"syscall"
19
+	"time"
20
+	"unicode"
21
+)
22
+
23
+const (
24
+	KGM = 1 + iota
25
+	KSM
26
+	PM
27
+	SM
28
+	RM
29
+	WM
30
+)
31
+
32
+type Message struct {
33
+	From    string //ip 주소
34
+	Version string
35
+	Time    string
36
+	Kind    int //종류
37
+}
38
+
39
+type MsgUnit interface {
40
+	// ConvertToJson - send 전 json 형식으로 바꾸는 함수
41
+	ConvertToJson() ([]byte, error)
42
+	// CheckType - Message 의 타입을 알려줌
43
+	CheckType() int
44
+}
45
+
46
+type RegisterImgMsg struct {
47
+	Message
48
+	PrivateKey float64
49
+}
50
+
51
+type RegisterMsg struct {
52
+	Message
53
+	PrivateKey int64
54
+}
55
+
56
+type SubscriptionImage struct {
57
+	Message
58
+	Topic []float64 //
59
+}
60
+
61
+type SubscriptionMsg struct {
62
+	Message
63
+	Topic    []int64  //대주제
64
+	Value    []int64  //피연산자
65
+	Operator []string //연산자
66
+	IsAlpha  bool     //value가 숫자인지 문자열인지
67
+}
68
+
69
+type PublishImage struct {
70
+	Message
71
+	Topic []float64 // 이미지 vector
72
+}
73
+type PublishMsg struct {
74
+	Message
75
+	Topic   []int64 //대주제
76
+	Value   []int64 //Topic 의 세부적인 내용
77
+	Content []int64 // 내용
78
+}
79
+
80
+type WithdrawMsg struct {
81
+	Message
82
+}
83
+
84
+//type ImgReceiver struct {
85
+//	thisNodeAddr string
86
+//	microService MicroImgService
87
+//}
88
+
89
+type Receiver struct {
90
+	thisNodeAddr string
91
+	microService MicroService
92
+}
93
+
94
+//type MicroImgService struct {
95
+//	ClientAddr string
96
+//	PrivateKey float64
97
+//	ShareKey   float64
98
+//	// 메세지 미들웨어에 연결되어 있는가
99
+//	IsConnected chan bool
100
+//	MMAddress   string
101
+//}
102
+
103
+type MicroService struct {
104
+	ClientAddr string
105
+	PrivateKey float64
106
+	ShareKey   float64
107
+	// 메세지 미들웨어에 연결되어 있는가
108
+	IsConnected chan bool
109
+	MMAddress   string
110
+}
111
+
112
+func (receiver Receiver) Receive(args Args, reply *Reply) error {
113
+	switch args.Kind {
114
+
115
+	case KSM:
116
+		//var msg KeyShareMsg
117
+		//err := json.Unmarshal(args.JsonMsg, &msg)
118
+		//if err != nil {
119
+		//	return err
120
+		//}
121
+		//go func() {
122
+		//	_, err := receiver.moscato.Receive(msg)
123
+		//	if err != nil {
124
+		//
125
+		//	}
126
+		//}()
127
+		//reply.CompleteLog = "received completely"
128
+	case PM:
129
+		var msg PublishImage
130
+		err := json.Unmarshal(args.JsonMsg, &msg)
131
+		if err != nil {
132
+			return err
133
+		}
134
+		go func() {
135
+			receiver.microService.Receive(msg)
136
+		}()
137
+		reply.CompleteLog = "[" + receiver.thisNodeAddr + "] : pubMsg received"
138
+		//var msg PublishMsg
139
+		//err := json.Unmarshal(args.JsonMsg, &msg)
140
+		//if err != nil {
141
+		//	return err
142
+		//}
143
+		//
144
+		//go func() {
145
+		//	_, err := receiver.moscato.Receive(msg)
146
+		//	if err != nil {
147
+		//
148
+		//	}
149
+		//}()
150
+		//reply.CompleteLog = "PM received completely"
151
+	case SM:
152
+		//var msg SubscriptionMsg
153
+		//err := json.Unmarshal(args.JsonMsg, &msg)
154
+		//if err != nil {
155
+		//	return err
156
+		//}
157
+		//go func() {
158
+		//	_, err := receiver.moscato.Receive(msg)
159
+		//	if err != nil {
160
+		//
161
+		//	}
162
+		//}()
163
+		//reply.CompleteLog = "received completely"
164
+	case RM:
165
+		var msg RegisterMsg
166
+		err := json.Unmarshal(args.JsonMsg, &msg)
167
+		if err != nil {
168
+			return err
169
+		}
170
+		go func() {
171
+			receiver.microService.Receive(msg)
172
+		}()
173
+		reply.CompleteLog = "[" + receiver.thisNodeAddr + "] : ackRM received"
174
+	case WM:
175
+		//var msg WithdrawMsg
176
+		//err := json.Unmarshal(args.JsonMsg, &msg)
177
+		//if err != nil {
178
+		//	return err
179
+		//}
180
+		//go func() {
181
+		//	_, err := receiver.moscato.Receive(msg)
182
+		//	if err != nil {
183
+		//
184
+		//	}
185
+		//}()
186
+		//reply.CompleteLog = "received completely"
187
+	default:
188
+		return errors.New("message type Error: Not registered message type")
189
+	}
190
+	//reply.CompleteLog = "received completely"
191
+	return nil
192
+}
193
+
194
+func (microService MicroService) Receive(msg MsgUnit) {
195
+	logger := NewMyLogger()
196
+	logger.Sync()
197
+
198
+	var msg_type = msg.CheckType()
199
+	//메세지 타입에 따라 다르게 처리
200
+	switch msg_type {
201
+
202
+	case KSM: //Key share msg
203
+
204
+	case PM: //Publish msg
205
+		fmt.Println("----- received PM ------")
206
+		DecryptionImg(msg.(PublishImage), microService.ShareKey, microService.PrivateKey)
207
+		fmt.Println("Topic is", FloatSlice2String(msg.(PublishImage).Topic))
208
+		fmt.Println("------------------------")
209
+
210
+	case SM: //Subscription msg
211
+
212
+	case RM: //Register msg
213
+
214
+		microService.IsConnected <- true
215
+		logger.Info("MM Registered this node Complete!")
216
+
217
+	case WM: //Withdraw msg
218
+		//moscato.MicroServiceManager.RemoveMicroservice(msg.(*WithdrawMsg).From)
219
+
220
+	default:
221
+		errors.New("message type Error: Not registered message type")
222
+	}
223
+
224
+	return
225
+}
226
+
227
+func (msg RegisterImgMsg) ConvertToJson() ([]byte, error) {
228
+	js := msg
229
+	jsonBytes, err := json.Marshal(js)
230
+	return jsonBytes, err
231
+}
232
+
233
+func (msg SubscriptionImage) ConvertToJson() ([]byte, error) {
234
+	js := msg
235
+	jsonBytes, err := json.Marshal(js)
236
+	return jsonBytes, err
237
+}
238
+
239
+func (msg SubscriptionMsg) ConvertToJson() ([]byte, error) {
240
+	js := msg
241
+	jsonBytes, err := json.Marshal(js)
242
+	return jsonBytes, err
243
+}
244
+
245
+func (msg PublishImage) ConvertToJson() ([]byte, error) {
246
+	js := msg
247
+	jsonBytes, err := json.Marshal(js)
248
+	return jsonBytes, err
249
+}
250
+
251
+func (msg PublishMsg) ConvertToJson() ([]byte, error) {
252
+	js := msg
253
+	jsonBytes, err := json.Marshal(js)
254
+	return jsonBytes, err
255
+}
256
+
257
+func (msg RegisterMsg) ConvertToJson() ([]byte, error) {
258
+	js := msg
259
+	jsonBytes, err := json.Marshal(js)
260
+	return jsonBytes, err
261
+}
262
+
263
+func (msg WithdrawMsg) ConvertToJson() ([]byte, error) {
264
+	js := msg
265
+	jsonBytes, err := json.Marshal(js)
266
+	return jsonBytes, err
267
+}
268
+
269
+func (msg Message) CheckType() int {
270
+	return msg.Kind
271
+}
272
+
273
+func CreatePubImage(msg Message, topic string) PublishImage {
274
+
275
+	publishTextSlice := strings.Split(topic, " ")
276
+	var topicFloat []float64
277
+	for index := 0; index < len(publishTextSlice); index++ {
278
+		float, _ := strconv.ParseFloat(publishTextSlice[index], 8)
279
+		topicFloat = append(topicFloat, float)
280
+	}
281
+	return PublishImage{msg, topicFloat}
282
+}
283
+func CreatePubMsg(msg Message, topic string, value string, content string) PublishMsg {
284
+	//toPubMsg := new(PublishMsg)
285
+	//toPubMsg.Message = msg
286
+
287
+	intArr := []rune(topic)
288
+	//fmt.Print("Topic length ")
289
+	//fmt.Println(len(intArr))
290
+	//fmt.Println(len(toPubMsg.Topic))
291
+	var topicInt []int64
292
+	for index := 0; index < len(intArr); index++ {
293
+		//toPubMsg.Topic = append(toPubMsg.Topic, int64(intArr[index]))
294
+		topicInt = append(topicInt, int64(intArr[index]))
295
+	}
296
+	//fmt.Println(len(toPubMsg.Topic))
297
+
298
+	intArr = []rune(value)
299
+	var valueInt []int64
300
+	strInt64, _ := strconv.ParseInt(value, 10, 64)
301
+	if unicode.IsDigit(intArr[0]) {
302
+		valueInt = append(valueInt, strInt64)
303
+	} else {
304
+		for index := 0; index < len(intArr); index++ {
305
+			//toPubMsg.Value = append(toPubMsg.Value, int64(intArr[index]))
306
+			valueInt = append(valueInt, int64(intArr[index]))
307
+		}
308
+	}
309
+
310
+	intArr = []rune(content)
311
+	var contentInt []int64
312
+	for index := 0; index < len(intArr); index++ {
313
+		//toPubMsg.content = append(toPubMsg.content, int64(intArr[index]))
314
+		contentInt = append(contentInt, int64(intArr[index]))
315
+	}
316
+
317
+	return PublishMsg{msg, topicInt, valueInt, contentInt}
318
+}
319
+func CreateSubImage(msg Message, topic string) SubscriptionImage {
320
+
321
+	publishTextSlice := strings.Split(topic, " ")
322
+	var topicFloat []float64
323
+	for index := 0; index < len(publishTextSlice); index++ {
324
+		float, _ := strconv.ParseFloat(publishTextSlice[index], 8)
325
+		topicFloat = append(topicFloat, float)
326
+	}
327
+	return SubscriptionImage{msg, topicFloat}
328
+}
329
+
330
+func CreateSubMsg(msg Message, topic string, value string, operator string, isAlpha bool) SubscriptionMsg {
331
+	//toPubMsg := new(PublishMsg)
332
+	//toPubMsg.Message = msg
333
+
334
+	intArr := []rune(topic)
335
+	//fmt.Print("Topic length ")
336
+	//fmt.Println(len(intArr))
337
+	//fmt.Println(len(toPubMsg.Topic))
338
+	var topicInt []int64
339
+	for index := 0; index < len(intArr); index++ {
340
+		//toPubMsg.Topic = append(toPubMsg.Topic, int64(intArr[index]))
341
+		topicInt = append(topicInt, int64(intArr[index]))
342
+	}
343
+	//fmt.Println(len(toPubMsg.Topic))
344
+	var valueInt []int64
345
+	if isAlpha {
346
+		intArr = []rune(value)
347
+
348
+		for index := 0; index < len(intArr); index++ {
349
+			//toPubMsg.Value = append(toPubMsg.Value, int64(intArr[index]))
350
+			valueInt = append(valueInt, int64(intArr[index]))
351
+		}
352
+	} else {
353
+		stringSlice := strings.Split(value, " ")
354
+		for index := 0; index < len(stringSlice); index++ {
355
+			strInt64, _ := strconv.ParseInt(stringSlice[index], 10, 64)
356
+			valueInt = append(valueInt, strInt64)
357
+		}
358
+	}
359
+	var operatorSlice []string
360
+	operatorSlice = strings.Split(operator, " ")
361
+
362
+	//intArr = []rune(content)
363
+	//var contentInt [] int64
364
+	//for index := 0; index < len(intArr); index++ {
365
+	//	//toPubMsg.content = append(toPubMsg.content, int64(intArr[index]))
366
+	//	contentInt = append(contentInt, int64(intArr[index]))
367
+	//}
368
+
369
+	return SubscriptionMsg{msg, topicInt, valueInt, operatorSlice, isAlpha}
370
+}
371
+
372
+type Args struct { // 매개변수
373
+	JsonMsg []byte
374
+	Kind    int
375
+}
376
+
377
+type Reply struct { // 리턴값
378
+	CompleteLog string
379
+}
380
+
381
+func generateRanUint64() uint64 {
382
+	rand.Seed(time.Now().UnixNano())
383
+	//return uint64(rand.Uint32())<<32 + uint64(rand.Uint32())
384
+	return uint64(0 + uint64(rand.Uint32()))
385
+}
386
+
387
+func main() {
388
+	logger := NewMyLogger()
389
+	logger.Sync()
390
+
391
+	var argu string
392
+	for _, v := range os.Args {
393
+		if strings.Index(v, "-mma") == 0 {
394
+			argu = strings.Replace(v, "-mma=", "", -1)
395
+			break
396
+		}
397
+	}
398
+	MMAddress := argu
399
+	if argu == "" {
400
+		logger.Fatal("there is no Message Middleware address")
401
+		return
402
+	}
403
+
404
+	args := new(Args)
405
+	reply := new(Reply)
406
+
407
+	currentIP := getCurrentIPAddr()
408
+
409
+	const debugPK = 12345
410
+	privateKey := float64(generateRanUint64())
411
+	//privateKey := int64(generateRanUint64())
412
+	shareKey := float64(9999)
413
+	//shareKey := int64(9999)
414
+
415
+	microService := MicroService{currentIP, privateKey, shareKey, make(chan bool), MMAddress}
416
+	//microService := MicroService{currentIP, privateKey, shareKey, make(chan bool), MMAddress}
417
+	receiver := Receiver{thisNodeAddr: currentIP, microService: microService}
418
+
419
+	logger.Info("current machine address : " + currentIP + " / MM address : " + MMAddress)
420
+	logger.Debug("private key : " + strconv.FormatUint(uint64(privateKey), 10))
421
+
422
+	errReg := rpc.Register(receiver)
423
+	if errReg != nil {
424
+		log.Println(errReg)
425
+		return
426
+	}
427
+
428
+	client, err := rpc.Dial("tcp", microService.MMAddress+":8160") // RPC 서버에 연결
429
+	if err != nil {
430
+		logger.Fatal(err.Error())
431
+		return
432
+	}
433
+	defer client.Close() // main 함수가 끝나기 직전에 RPC 연결을 닫음
434
+
435
+	go Listen()
436
+
437
+	// Register 메세지 생성
438
+	message := Message{From: microService.ClientAddr, Version: "1", Time: "1", Kind: RM}
439
+	regMsg := RegisterImgMsg{message, microService.PrivateKey}
440
+	RJsonMsg, _ := regMsg.ConvertToJson()
441
+	args.JsonMsg = RJsonMsg
442
+	args.Kind = RM
443
+	// arguments로 MMReceive호출해서 MM으로 보냄
444
+	err = client.Call("Receiver.MmReceive", args, reply)
445
+	logger.Info("RM sent")
446
+	if err != nil {
447
+		fmt.Println(err)
448
+		return
449
+	}
450
+	logger.Debug("[MM] " + reply.CompleteLog)
451
+
452
+	sigs := make(chan os.Signal, 1)
453
+	done := make(chan bool, 1)
454
+
455
+	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
456
+
457
+	go func() {
458
+		sig := <-sigs
459
+		withDraw(message, client)
460
+		//fmt.Println(sig)
461
+		_ = sig
462
+		done <- true
463
+		fmt.Println("\nquit Moscato Successful and terminate microservice")
464
+		os.Exit(0)
465
+	}()
466
+
467
+	// 연결 되면 채널로 연결 확인이 되어야 다음 단계로 넘어감
468
+	checkConnect := <-microService.IsConnected
469
+	_ = checkConnect
470
+	// 엔터쳐야 다음으로 진행
471
+	fmt.Scanln()
472
+	logger.Info("sending Subscription messages")
473
+
474
+	/*
475
+		파일에서 subscription 읽어서 subscription 보내기
476
+		 **/
477
+	subFile, err := os.Open("subscription.txt")
478
+	if err != nil {
479
+		fmt.Println("sub")
480
+		log.Fatalf("Error when opening file: %s", err)
481
+	}
482
+	defer subFile.Close()
483
+	fileScanner := bufio.NewScanner(subFile)
484
+	var subscriptionText string
485
+	numSub := 0
486
+	file1, _ := os.Create("./subTimeLog.log")
487
+	defer file1.Close()
488
+	for fileScanner.Scan() {
489
+		subscriptionText = fileScanner.Text()
490
+		//subscriptionTextSlice := strings.Split(subscriptionText, "/")
491
+		//subTopic := subscriptionTextSlice[0]
492
+		//subValue := subscriptionTextSlice[1]
493
+		//subOperator := subscriptionTextSlice[2]
494
+		//var subIsAlpha bool
495
+		//if subscriptionTextSlice[3] == "true" {
496
+		//	subIsAlpha = true
497
+		//} else if subscriptionTextSlice[3] == "false" {
498
+		//	subIsAlpha = false
499
+		//} else {
500
+		//	println(numSub, "subscription isAlpha type error.")
501
+		//}
502
+		fmt.Println(subscriptionText)
503
+		numSub++
504
+		message = Message{From: microService.ClientAddr, Version: "1", Time: "1", Kind: SM}
505
+
506
+		// 메세지 생성시간 측정
507
+		subMakingStartTime := time.Now()
508
+
509
+		subMsg := CreateSubImage(message, subscriptionText)
510
+		//logger.Debug("subMsg #" + strconv.Itoa(numSub) + " topic: " + subTopic + " / value: " + subValue + " / operator: " + subOperator)
511
+		logger.Debug("before enc subMsg #" + strconv.Itoa(numSub) + " topic: " + FloatSlice2String(subMsg.Topic))
512
+
513
+		//subMsg := CreateSubMsg(message, "soccer", "player", "==", true)
514
+		//fmt.Println(pubMsg)
515
+
516
+		// enc 필요없으므로 일단 주석
517
+		subMsg = EncryptionSubImage(subMsg, microService.ShareKey, microService.PrivateKey)
518
+		//fmt.Println(subMsg)
519
+		logger.Debug("after enc subMsg #" + strconv.Itoa(numSub) + " topic: " + FloatSlice2String(subMsg.Topic))
520
+		jsonMsg, _ := subMsg.ConvertToJson()
521
+		args.JsonMsg = jsonMsg
522
+		args.Kind = subMsg.Kind
523
+		//fmt.Println(subMsg)
524
+
525
+		//fmt.Println(string(args.JsonMsg))
526
+		subMakingElapsedTime := time.Since(subMakingStartTime)
527
+
528
+		// 메세지 생성 완료시간 측정
529
+		fmt.Printf("sub 생성시간: %d\n", subMakingElapsedTime.Nanoseconds())
530
+
531
+		fmt.Fprintln(file1, subMakingElapsedTime.Nanoseconds())
532
+
533
+		err = client.Call("Receiver.MmReceive", args, reply)
534
+		logger.Info("SM sent! #" + strconv.Itoa(numSub))
535
+
536
+		if err != nil {
537
+			fmt.Println(err)
538
+			return
539
+		}
540
+		//log.Println(reply.CompleteLog)
541
+		logger.Debug("[MM] " + reply.CompleteLog)
542
+
543
+	}
544
+
545
+	fmt.Scanln()
546
+	logger.Info("sending Publish messages")
547
+
548
+	pubFile, err := os.Open("publish.txt")
549
+	if err != nil {
550
+		log.Fatalf("Error when opening file: %s", err)
551
+	}
552
+	defer pubFile.Close()
553
+	fileScanner2 := bufio.NewScanner(pubFile)
554
+	var publishText string
555
+	numPub := 0
556
+	file2, _ := os.Create("./pubTimeLog.log")
557
+	defer file2.Close()
558
+
559
+	for fileScanner2.Scan() {
560
+		publishText = fileScanner2.Text()
561
+		//publishTextSlice := strings.Split(publishText, " ")
562
+		//fmt.Println(publishTextSlice)
563
+		pubTopic := publishText
564
+		//pubValue := publishTextSlice[1]
565
+		//pubContent := publishTextSlice[2]
566
+
567
+		numPub++
568
+		message = Message{From: microService.ClientAddr, Version: "1", Time: "1", Kind: PM}
569
+		pubMakingStartTime := time.Now()
570
+
571
+		pubMsg := CreatePubImage(message, pubTopic)
572
+		logger.Debug("pubMsg #" + strconv.Itoa(numPub) + " topic: " + pubTopic)
573
+		logger.Debug("before enc pubMsg #" + strconv.Itoa(numPub) + " topic: " + FloatSlice2String(pubMsg.Topic))
574
+
575
+		// pubMsg Encryption
576
+		fmt.Println("Publisher Private Key :", strconv.FormatUint(uint64(microService.PrivateKey), 10))
577
+		pubMsg = EncryptionPubImage(pubMsg, microService.ShareKey, microService.PrivateKey)
578
+		logger.Debug("after enc pubMsg #" + strconv.Itoa(numPub) + " topic: " + FloatSlice2String(pubMsg.Topic))
579
+
580
+		jsonMsg, _ := pubMsg.ConvertToJson()
581
+		fmt.Println(jsonMsg)
582
+		args.JsonMsg = jsonMsg
583
+		args.Kind = pubMsg.Kind
584
+
585
+		pubMakingElapsedTime := time.Since(pubMakingStartTime)
586
+
587
+		fmt.Printf("pub 생성시간: %d\n\n", pubMakingElapsedTime.Nanoseconds())
588
+		fmt.Fprintln(file2, pubMakingElapsedTime.Nanoseconds())
589
+
590
+		err = client.Call("Receiver.MmReceive", args, reply)
591
+		logger.Info("PM sent! #" + strconv.Itoa(numPub))
592
+		if err != nil {
593
+			fmt.Println(err)
594
+			return
595
+		}
596
+
597
+		logger.Debug("[MM]: " + reply.CompleteLog)
598
+
599
+	}
600
+
601
+	<-done
602
+	return
603
+}
604
+
605
+func withDraw(msg Message, client *rpc.Client) {
606
+	msg.Kind = WM
607
+	wdMsg := WithdrawMsg{msg}
608
+	var args Args
609
+	args.JsonMsg, _ = wdMsg.ConvertToJson()
610
+	args.Kind = WM
611
+	var reply Reply
612
+	client.Call("Receiver.MmReceive", args, reply)
613
+}
614
+
615
+func EncryptionPubImage(msg PublishImage, gyKey float64, privateKey float64) PublishImage {
616
+	for index := range msg.Topic {
617
+		msg.Topic[index] = msg.Topic[index] + gyKey + privateKey
618
+	}
619
+	return msg
620
+}
621
+
622
+func EncryptionPubMsg(msg PublishMsg, gyKey int64, privateKey int64) PublishMsg {
623
+	for index := range msg.Topic {
624
+		msg.Topic[index] = msg.Topic[index] + gyKey + privateKey
625
+	}
626
+	for index := range msg.Value {
627
+		msg.Value[index] = msg.Value[index] + gyKey + privateKey
628
+	}
629
+	for index := range msg.Content {
630
+		msg.Content[index] = msg.Content[index] + gyKey + privateKey
631
+	}
632
+
633
+	return msg
634
+}
635
+
636
+func EncryptionSubImage(msg SubscriptionImage, gyKey float64, privateKey float64) SubscriptionImage {
637
+	for index := range msg.Topic {
638
+		msg.Topic[index] = msg.Topic[index] + gyKey + privateKey
639
+	}
640
+	return msg
641
+}
642
+
643
+func EncryptionSubMsg(msg SubscriptionMsg, gyKey int64, privateKey int64) SubscriptionMsg {
644
+	for index := range msg.Topic {
645
+		msg.Topic[index] = msg.Topic[index] + gyKey + privateKey
646
+	}
647
+	for index := range msg.Value {
648
+		msg.Value[index] = msg.Value[index] + gyKey + privateKey
649
+	}
650
+	return msg
651
+}
652
+
653
+func DecryptionImg(msg PublishImage, gyKey float64, privateKey float64) {
654
+	for index := range msg.Topic {
655
+		msg.Topic[index] = msg.Topic[index] - gyKey - privateKey
656
+	}
657
+
658
+	var runeArr []rune
659
+	for index := range msg.Topic {
660
+		runeArr = append(runeArr, rune(int(msg.Topic[index])))
661
+	}
662
+	//fmt.Println("Topic is: " + string(runeArr))
663
+	runeArr = nil
664
+
665
+}
666
+
667
+func DecryptionMsg(msg PublishMsg, gyKey int64, privateKey int64) {
668
+	for index := range msg.Topic {
669
+		msg.Topic[index] = msg.Topic[index] - gyKey - privateKey
670
+	}
671
+	for index := range msg.Value {
672
+		msg.Value[index] = msg.Value[index] - gyKey - privateKey
673
+	}
674
+	for index := range msg.Content {
675
+		msg.Content[index] = msg.Content[index] - gyKey - privateKey
676
+	}
677
+
678
+	var runeArr []rune
679
+	for index := range msg.Topic {
680
+		runeArr = append(runeArr, rune(int(msg.Topic[index])))
681
+	}
682
+	fmt.Println("Topic is: " + string(runeArr))
683
+	runeArr = nil
684
+
685
+	for index := range msg.Value {
686
+		runeArr = append(runeArr, rune(int(msg.Value[index])))
687
+	}
688
+
689
+	if len(runeArr) == 1 {
690
+		fmt.Println("Value is: ", runeArr)
691
+	} else {
692
+		fmt.Println("Value is:", string(runeArr))
693
+	}
694
+
695
+	runeArr = nil
696
+
697
+	for index := range msg.Content {
698
+		runeArr = append(runeArr, rune(int(msg.Content[index])))
699
+	}
700
+	fmt.Println("Content is: " + string(runeArr))
701
+	runeArr = nil
702
+
703
+}
704
+
705
+func Listen() {
706
+	l, err1 := net.Listen("tcp", ":8150") //MM로 부터 받는거
707
+	if err1 != nil {
708
+		log.Fatal(fmt.Sprintf("Unable to listen on given port: %s", err1))
709
+	}
710
+	defer l.Close()
711
+
712
+	for {
713
+		conn, _ := l.Accept()
714
+		go rpc.ServeConn(conn)
715
+	}
716
+}
717
+func FloatSlice2String(target []float64) string {
718
+	var targetString string
719
+	targetString = ""
720
+	for _, value := range target {
721
+		targetString += strconv.FormatFloat(float64(value), 'f', -1, 64) + " "
722
+	}
723
+	return targetString
724
+}
725
+
726
+func IntSlice2String(target []int64) string {
727
+	var targetString string
728
+	targetString = ""
729
+	for _, value := range target {
730
+		targetString += strconv.FormatInt(int64(value), 10) + " "
731
+	}
732
+	return targetString
733
+}

+ 50
- 0
src/parseJson_test.go Прегледај датотеку

@@ -0,0 +1,50 @@
1
+package main
2
+
3
+import (
4
+	"encoding/json"
5
+	"fmt"
6
+	"io/ioutil"
7
+	"testing"
8
+)
9
+
10
+func parseJson(dat []byte) {
11
+	data := make(map[string]interface{})
12
+	err := json.Unmarshal([]byte(dat), &data)
13
+	if err != nil {
14
+		fmt.Println(err)
15
+	}
16
+	traverseCheck(data)
17
+}
18
+
19
+
20
+func traverseCheck(el map[string]interface{}) {
21
+	for key, val := range el{
22
+		_ = val
23
+		if key == "==" || key == ">=" || key == "<=" || key == "<" || key == ">"{
24
+			//fmt.Println("****************")
25
+			tmpMap := el[key].(map[string]interface{})
26
+			fmt.Println(key)
27
+			for k, v := range tmpMap{
28
+				fmt.Println(k, v)
29
+			}
30
+			//fmt.Println("****************")
31
+
32
+		} else if key == "||" || key == "&&"{
33
+			tmpSlice := el[key].([]interface{})
34
+			fmt.Println(key)
35
+			for _, obj := range tmpSlice{
36
+				data := obj.(map[string]interface{})
37
+				traverseCheck(data)
38
+			}
39
+		}
40
+	}
41
+}
42
+
43
+func TestParseJson(t *testing.T) {
44
+
45
+	dat, err := ioutil.ReadFile("./example.json")
46
+	if err != nil {
47
+		fmt.Println(err)
48
+	}
49
+	parseJson(dat)
50
+}

+ 1
- 0
src/pubTimeLog.log Прегледај датотеку

@@ -0,0 +1 @@
1
+198000

+ 1
- 0
src/publish.txt Прегледај датотеку

@@ -0,0 +1 @@
1
+10.123123 30.3214135 20.2541531 40.523412 12.542321 43.532123 51.31242 32.25234132413

+ 1
- 0
src/subTimeLog.log Прегледај датотеку

@@ -0,0 +1 @@
1
+1033875

+ 1
- 0
src/subscription.txt Прегледај датотеку

@@ -0,0 +1 @@
1
+1.0 2.0 3.0 4.0 5.0 6.0

+ 340837
- 0
src/test.log
Разлика између датотеке није приказан због своје велике величине
Прегледај датотеку


+ 41
- 0
test.log Прегледај датотеку

@@ -0,0 +1,41 @@
1
+2022-01-02T15:43:21.444+0900	INFO	current machine address : 192.168.0.77 / MM address : 127.0.0.1
2
+2022-01-02T15:43:21.445+0900	DEBUG	private key : 3547138460
3
+2022-01-02T15:43:21.447+0900	INFO	RM sent
4
+2022-01-02T15:43:21.447+0900	DEBUG	[MM] RM received
5
+2022-01-02T15:43:21.453+0900	INFO	MM Registered this node Complete!
6
+2022-01-02T15:46:14.173+0900	INFO	current machine address : 192.168.0.77 / MM address : 127.0.0.1
7
+2022-01-02T15:46:14.174+0900	DEBUG	private key : 1652718355
8
+2022-01-02T15:46:14.175+0900	INFO	RM sent
9
+2022-01-02T15:46:14.175+0900	DEBUG	[MM] RM received
10
+2022-01-02T15:46:14.181+0900	INFO	MM Registered this node Complete!
11
+2022-01-02T15:46:25.988+0900	INFO	sending Subscription messages
12
+2022-01-02T15:48:06.443+0900	INFO	current machine address : 192.168.0.77 / MM address : 127.0.0.1
13
+2022-01-02T15:48:06.443+0900	DEBUG	private key : 2580440694
14
+2022-01-02T15:48:06.445+0900	INFO	RM sent
15
+2022-01-02T15:48:06.445+0900	DEBUG	[MM] RM received
16
+2022-01-02T15:48:19.445+0900	INFO	current machine address : 192.168.0.77 / MM address : 127.0.0.1
17
+2022-01-02T15:48:19.445+0900	DEBUG	private key : 2861559125
18
+2022-01-02T15:48:19.448+0900	INFO	RM sent
19
+2022-01-02T15:48:19.452+0900	DEBUG	[MM] RM received
20
+2022-01-02T15:48:19.458+0900	INFO	MM Registered this node Complete!
21
+2022-01-02T15:48:22.290+0900	INFO	sending Subscription messages
22
+2022-01-02T15:59:46.422+0900	INFO	current machine address : 192.168.0.77 / MM address : 127.0.0.1
23
+2022-01-02T15:59:46.422+0900	DEBUG	private key : 1320653589
24
+2022-01-02T15:59:46.424+0900	INFO	RM sent
25
+2022-01-02T15:59:46.424+0900	DEBUG	[MM] RM received
26
+2022-01-02T15:59:46.437+0900	INFO	MM Registered this node Complete!
27
+2022-01-02T15:59:49.270+0900	INFO	sending Subscription messages
28
+2022-01-02T16:00:17.004+0900	INFO	current machine address : 192.168.0.77 / MM address : 127.0.0.1
29
+2022-01-02T16:00:17.005+0900	DEBUG	private key : 560452067
30
+2022-01-02T16:00:17.006+0900	INFO	RM sent
31
+2022-01-02T16:00:17.006+0900	DEBUG	[MM] RM received
32
+2022-01-02T16:00:29.424+0900	INFO	current machine address : 192.168.0.77 / MM address : 127.0.0.1
33
+2022-01-02T16:00:29.424+0900	DEBUG	private key : 213155866
34
+2022-01-02T16:00:29.426+0900	INFO	RM sent
35
+2022-01-02T16:00:29.426+0900	DEBUG	[MM] RM received
36
+2022-01-02T16:00:29.440+0900	INFO	MM Registered this node Complete!
37
+2022-01-02T16:00:32.131+0900	INFO	sending Subscription messages
38
+2022-01-02T16:08:17.494+0900	INFO	current machine address : 192.168.0.77 / MM address : 127.0.0.1
39
+2022-01-02T16:08:17.496+0900	INFO	RM sent
40
+2022-01-02T16:08:17.503+0900	INFO	MM Registered this node Complete!
41
+2022-01-02T16:08:20.647+0900	INFO	sending Subscription messages

Loading…
Откажи
Сачувај