├── Dockerfile ├── mysql ├── mysql_suite_test.go ├── mysql_test.go └── mysql.go ├── controller ├── controller_suite_test.go ├── controller.go └── controller_test.go ├── ci ├── tasks │ ├── build-candidate.sh │ ├── unit.sh │ ├── util.sh │ ├── integration.sh │ ├── run-integration.sh │ └── inventory-service-release.sh ├── integration │ └── docker-compose.yml └── pipeline.yml ├── .gitignore ├── glide.yaml ├── Makefile ├── README.md ├── glide.lock ├── main.go └── LICENSE /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:16.04 2 | 3 | ADD bin/voyager-inventory-service voyager-inventory-service 4 | 5 | CMD ./voyager-inventory-service 6 | -------------------------------------------------------------------------------- /mysql/mysql_suite_test.go: -------------------------------------------------------------------------------- 1 | package mysql_test 2 | 3 | import ( 4 | . "github.com/onsi/ginkgo" 5 | . "github.com/onsi/gomega" 6 | 7 | "testing" 8 | ) 9 | 10 | func TestMysql(t *testing.T) { 11 | RegisterFailHandler(Fail) 12 | RunSpecs(t, "mysql Suite") 13 | } 14 | -------------------------------------------------------------------------------- /controller/controller_suite_test.go: -------------------------------------------------------------------------------- 1 | package controller_test 2 | 3 | import ( 4 | . "github.com/onsi/ginkgo" 5 | . "github.com/onsi/gomega" 6 | 7 | "testing" 8 | ) 9 | 10 | func TestController(t *testing.T) { 11 | RegisterFailHandler(Fail) 12 | RunSpecs(t, "controller Suite") 13 | } 14 | -------------------------------------------------------------------------------- /ci/tasks/build-candidate.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e -x 4 | source voyager-inventory-service/ci/tasks/util.sh 5 | 6 | check_param GITHUB_EMAIL 7 | check_param GITHUB_USER 8 | check_param GITHUB_PASSWORD 9 | 10 | echo -e "machine github.com\n login $GITHUB_USER\n password $GITHUB_PASSWORD" >> ~/.netrc 11 | 12 | set_env 13 | build_binary "voyager-inventory-service" 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.dll 4 | *.so 5 | *.dylib 6 | 7 | # Test binary, build with `go test -c` 8 | *.test 9 | 10 | # Output of the go coverage tool, specifically when used with LiteIDE 11 | *.out 12 | 13 | # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 14 | .glide/ 15 | 16 | bin 17 | 18 | *.coverprofile 19 | -------------------------------------------------------------------------------- /ci/integration/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '2' 2 | services: 3 | rabbitmq: 4 | image: rabbitmq:3-management 5 | ports: 6 | - "5672:5672" 7 | container_name: "rabbitmq" 8 | hostname: "rabbitmq" 9 | 10 | 11 | mysql: 12 | image: mysql:8.0.0 13 | ports: 14 | - "3306:3306" 15 | container_name: "mysql" 16 | hostname: "mysql" 17 | environment: 18 | - MYSQL_ALLOW_EMPTY_PASSWORD=yes 19 | -------------------------------------------------------------------------------- /glide.yaml: -------------------------------------------------------------------------------- 1 | package: github.com/RackHD/voyager-inventory-service 2 | import: 3 | - package: github.com/go-sql-driver/mysql 4 | version: ~1.3.0 5 | - package: github.com/jinzhu/gorm 6 | version: ~1.0.0 7 | - package: github.com/RackHD/voyager-utilities 8 | subpackages: 9 | - amqp 10 | - models 11 | - package: github.com/streadway/amqp 12 | testImport: 13 | - package: github.com/onsi/ginkgo 14 | version: ~1.2.0 15 | - package: github.com/onsi/gomega 16 | version: ~1.0.0 17 | -------------------------------------------------------------------------------- /ci/tasks/unit.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e -x 4 | source voyager-inventory-service/ci/tasks/util.sh 5 | 6 | check_param GITHUB_USER 7 | check_param GITHUB_PASSWORD 8 | 9 | echo -e "machine github.com\n login $GITHUB_USER\n password $GITHUB_PASSWORD" >> ~/.netrc 10 | 11 | export GOPATH=$PWD 12 | export PATH=$PATH:$GOPATH/bin 13 | mkdir -p $GOPATH/src/github.com/RackHD/ 14 | cp -r voyager-inventory-service $GOPATH/src/github.com/RackHD/voyager-inventory-service 15 | 16 | pushd $GOPATH/src/github.com/RackHD/voyager-inventory-service 17 | make deps 18 | make build 19 | make unit-test 20 | echo "Unit test complete." 21 | popd 22 | -------------------------------------------------------------------------------- /ci/tasks/util.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e -x 3 | 4 | check_param() { 5 | local name=$1 6 | local value=$(eval echo '$'$name) 7 | if [ "$value" == 'replace-me' ]; then 8 | echo "environment variable $name must be set" 9 | exit 1 10 | fi 11 | } 12 | 13 | set_env() { 14 | WORK_DIR=${PWD} 15 | export GOPATH=${PWD} 16 | SOURCE_DIR=${GOPATH}/src/github.com/RackHD 17 | mkdir -p ${SOURCE_DIR} 18 | } 19 | 20 | build_binary() { 21 | cp -r $1 ${SOURCE_DIR}/$1 22 | pushd ${SOURCE_DIR}/$1 23 | make deps 24 | make build 25 | cp -r bin ${WORK_DIR}/build 26 | cp Dockerfile ${WORK_DIR}/build 27 | popd 28 | } 29 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | ORGANIZATION = RackHD 2 | PROJECT = voyager-inventory-service 3 | BINARYNAME = voyager-inventory-service 4 | GOOUT = ./bin 5 | export RABBITMQ_URL = amqp://guest:guest@localhost:5672 6 | 7 | default: deps build test 8 | 9 | deps: 10 | go get github.com/onsi/ginkgo/ginkgo 11 | go get github.com/onsi/gomega 12 | go get github.com/satori/go.uuid 13 | go get ./... 14 | 15 | integration-test: 16 | ginkgo -r -race -trace -cover -randomizeAllSpecs --slowSpecThreshold=30 --focus="\bINTEGRATION\b" 17 | 18 | unit-test: 19 | ginkgo -r -race -trace -cover -randomizeAllSpecs --slowSpecThreshold=30 --focus="\bUNIT\b" 20 | 21 | cover-cmd: test 22 | go tool cover -html=cmd/cmd.coverprofile 23 | 24 | build: 25 | go build -o $(GOOUT)/$(BINARYNAME) 26 | -------------------------------------------------------------------------------- /mysql/mysql_test.go: -------------------------------------------------------------------------------- 1 | package mysql_test 2 | 3 | import ( 4 | . "github.com/onsi/ginkgo" 5 | . "github.com/onsi/gomega" 6 | "github.com/RackHD/voyager-inventory-service/mysql" 7 | ) 8 | 9 | var _ = Describe("Mysql", func() { 10 | var dbUrl string 11 | 12 | BeforeEach(func() { 13 | 14 | dbUrl = "root@(localhost:3306)/mysql" 15 | }) 16 | 17 | Describe("Initilize", func() { 18 | Context("when the database url is valid", func() { 19 | It("INTEGRATION should connect without error", func() { 20 | db := mysql.DBconn{} 21 | err := db.Initialize(dbUrl) 22 | Expect(err).ToNot(HaveOccurred()) 23 | db.DB.DropTableIfExists("node_entities") 24 | db.DB.DropTableIfExists("ip_entities") 25 | db.DB.Close() 26 | }) 27 | }) 28 | }) 29 | }) 30 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # voyager-inventory-service 2 | Inventory Service stores information about nodes in the Voyager system 3 | 4 | Copyright © 2017 Dell Inc. or its subsidiaries. All Rights Reserved. 5 | 6 | ## Licensing 7 | 8 | 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 9 | 10 | 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. 11 | 12 | RackHD is a Trademark of Dell EMC 13 | -------------------------------------------------------------------------------- /ci/tasks/integration.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e -x 4 | source voyager-inventory-service/ci/tasks/util.sh 5 | 6 | 7 | # Get the env ip from locks input 8 | export INTEGRATION_VM_IP=$(cat $PWD/it-env/metadata) 9 | 10 | check_param INTEGRATION_VM_IP 11 | check_param INTEGRATION_VM_SSH_KEY 12 | check_param INTEGRATION_VM_USER 13 | 14 | echo "$INTEGRATION_VM_SSH_KEY" > ssh.key 15 | chmod 400 ssh.key 16 | 17 | project_path=/home/emc/.gvm/pkgsets/go1.7/global/src/github.com/RackHD 18 | ssh -i ssh.key -o "StrictHostKeyChecking no" ${INTEGRATION_VM_USER}@${INTEGRATION_VM_IP} "rm -rf $project_path && mkdir -p $project_path" 19 | scp -i ssh.key -o "StrictHostKeyChecking no" -r voyager-inventory-service ${INTEGRATION_VM_USER}@${INTEGRATION_VM_IP}:$project_path 20 | 21 | integration_file=$PWD/voyager-inventory-service/ci/tasks/run-integration.sh 22 | ssh -i ssh.key -o "StrictHostKeyChecking no" ${INTEGRATION_VM_USER}@${INTEGRATION_VM_IP} 'bash -s' < $integration_file 23 | -------------------------------------------------------------------------------- /ci/tasks/run-integration.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e -x 4 | 5 | [[ -s "/home/emc/.gvm/scripts/gvm" ]] >/dev/null 2>/dev/null 6 | source "/home/emc/.gvm/scripts/gvm" >/dev/null 2>/dev/null 7 | 8 | PROJECT_PATH=$GOPATH/src/github.com/RackHD 9 | COMPOSE_PATH=ci/integration/docker-compose.yml 10 | 11 | cleanUp() 12 | { 13 | # Don't exit on error here. All commands in this cleanUp must run, 14 | # even if some of them fail 15 | set +e 16 | 17 | # Delete all containers 18 | docker rm -f $(docker ps -a -q) 19 | 20 | # Delete all images 21 | docker rmi -f $(docker images -q) 22 | 23 | # Delete any dangling volumes 24 | docker volume rm $(docker volume ls -qf dangling=true) 25 | 26 | # Clean up all cloned repos 27 | cd $GOPATH 28 | rm -rf $GOPATH/src 29 | } 30 | 31 | trap cleanUp EXIT 32 | 33 | pushd $PROJECT_PATH/voyager-inventory-service 34 | echo "Testing Inventory Service" 35 | 36 | docker-compose -f ${COMPOSE_PATH} create 37 | docker-compose -f ${COMPOSE_PATH} start 38 | 39 | make deps 40 | make integration-test 41 | 42 | docker-compose -f ${COMPOSE_PATH} kill 43 | # Delete all containers 44 | docker rm -f $(docker ps -a -q) 45 | 46 | echo "Inventory Service PASS\n\n" 47 | popd 48 | 49 | exit 50 | -------------------------------------------------------------------------------- /ci/tasks/inventory-service-release.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e -x 4 | source voyager-inventory-service/ci/tasks/util.sh 5 | 6 | check_param GITHUB_EMAIL 7 | check_param GITHUB_USER 8 | check_param GITHUB_PASSWORD 9 | 10 | echo -e "machine github.com\n login $GITHUB_USER\n password $GITHUB_PASSWORD" >> ~/.netrc 11 | git config --global user.email ${GITHUB_EMAIL} 12 | git config --global user.name ${GITHUB_USER} 13 | git config --global push.default current 14 | 15 | export GOPATH=$PWD 16 | export PATH=$PATH:$GOPATH/bin 17 | mkdir -p $GOPATH/src/github.com/RackHD/ 18 | cp -r voyager-inventory-service $GOPATH/src/github.com/RackHD/voyager-inventory-service 19 | 20 | pushd $GOPATH/src/github.com/RackHD/voyager-inventory-service 21 | make deps 22 | make build 23 | make unit-test 24 | echo "Unit test complete." 25 | 26 | release_version=`cat version | tr -d '\n'` 27 | release_version=$((release_version+1)) 28 | printf ${release_version} > version 29 | 30 | git add version 31 | git commit -m ":airplane: New release v${release_version}" -m "[ci skip]" 32 | 33 | printf "voyager-inventory-service Release v${release_version}" > name 34 | printf "v${release_version}" > tag 35 | tar -czvf voyager-inventory-service-v${release_version}.tar.gz ./bin/* 36 | echo "New version released." 37 | 38 | printf "dev" > devtag 39 | 40 | popd 41 | 42 | cp -r $GOPATH/src/github.com/RackHD/voyager-inventory-service release 43 | -------------------------------------------------------------------------------- /mysql/mysql.go: -------------------------------------------------------------------------------- 1 | package mysql 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "time" 7 | 8 | _ "github.com/go-sql-driver/mysql" // Blank import because the library says to. 9 | "github.com/jinzhu/gorm" 10 | "github.com/RackHD/voyager-utilities/models" 11 | ) 12 | 13 | // DBconn is a struct for maintaining a connection to the MySQL Database 14 | type DBconn struct { 15 | DB *gorm.DB 16 | } 17 | 18 | // Initialize attempts to open and verify a connection to the DB 19 | func (d *DBconn) Initialize(address string) error { 20 | var err error 21 | 22 | for i := 0; i < 18; i++ { 23 | d.DB, err = gorm.Open("mysql", address) 24 | if err != nil { 25 | log.Printf("Could not connect. Sleeping for 10s %s\n", err) 26 | time.Sleep(10 * time.Second) 27 | continue 28 | } 29 | 30 | err = d.DB.DB().Ping() 31 | if err != nil { 32 | log.Printf("Could not Ping. Sleeping for 10s %s\n", err) 33 | time.Sleep(10 * time.Second) 34 | continue 35 | } 36 | 37 | d.createIfNotExist(&models.NodeEntity{}) 38 | d.createIfNotExist(&models.IPEntity{}) 39 | 40 | if err == nil { 41 | return nil 42 | } 43 | } 44 | return fmt.Errorf("Could not connect to database: %s\n", err) 45 | } 46 | 47 | func (d *DBconn) createIfNotExist(entity interface{}) { 48 | if hasTable := d.DB.HasTable(entity); !hasTable { 49 | if err := d.DB.CreateTable(entity).Error; err != nil { 50 | log.Printf("Error creating table: %s\n", err) 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /glide.lock: -------------------------------------------------------------------------------- 1 | hash: 07fc77d5262f061740bd4a4a79d18986e6905016892535b615deed4ea66c4313 2 | updated: 2017-01-05T13:52:11.724061339-05:00 3 | imports: 4 | - name: github.com/go-sql-driver/mysql 5 | version: a0583e0143b1624142adab07e0e97fe106d99561 6 | - name: github.com/jinzhu/gorm 7 | version: 5174cc5c242a728b435ea2be8a2f7f998e15429b 8 | - name: github.com/jinzhu/inflection 9 | version: 1c35d901db3da928c72a72d8458480cc9ade058f 10 | - name: github.com/RackHD/voyager-utilities 11 | version: 3d475365f014ecf9e2b75e80220ebc0ab61d05b3 12 | subpackages: 13 | - amqp 14 | - models 15 | - random 16 | - name: github.com/satori/go.uuid 17 | version: b061729afc07e77a8aa4fad0a2fd840958f1942a 18 | - name: github.com/sirupsen/logrus 19 | version: d26492970760ca5d33129d2d799e34be5c4782eb 20 | - name: github.com/streadway/amqp 21 | version: 63795daa9a446c920826655f26ba31c81c860fd6 22 | - name: golang.org/x/sys 23 | version: d75a52659825e75fff6158388dddc6a5b04f9ba5 24 | subpackages: 25 | - unix 26 | testImports: 27 | - name: github.com/onsi/ginkgo 28 | version: 462326b1628e124b23f42e87a8f2750e3c4e2d24 29 | subpackages: 30 | - config 31 | - internal/codelocation 32 | - internal/containernode 33 | - internal/failer 34 | - internal/leafnodes 35 | - internal/remote 36 | - internal/spec 37 | - internal/specrunner 38 | - internal/suite 39 | - internal/testingtproxy 40 | - internal/writer 41 | - reporters 42 | - reporters/stenographer 43 | - types 44 | - name: github.com/onsi/gomega 45 | version: a78ae492d53aad5a7a232d0d0462c14c400e3ee7 46 | subpackages: 47 | - format 48 | - internal/assertion 49 | - internal/asyncassertion 50 | - internal/testingtsupport 51 | - matchers 52 | - matchers/support/goraph/bipartitegraph 53 | - matchers/support/goraph/edge 54 | - matchers/support/goraph/node 55 | - matchers/support/goraph/util 56 | - types 57 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "log" 6 | 7 | "github.com/RackHD/voyager-inventory-service/controller" 8 | "github.com/RackHD/voyager-utilities/random" 9 | "github.com/streadway/amqp" 10 | ) 11 | 12 | var ( 13 | uri = flag.String("uri", "amqp://guest:guest@rabbitmq:5672/", "AMQP URI") 14 | exchange = flag.String("exchange", "voyager-inventory-service", "Durable, non-auto-deleted AMQP exchange name") 15 | exchangeType = flag.String("exchange-type", "topic", "Exchange type - direct|fanout|topic|x-custom") 16 | queue = flag.String("queue", "voyager-inventory-service-queue", "Ephemeral AMQP queue name") 17 | bindingKey = flag.String("key", "requests", "AMQP binding key") 18 | consumerTag = flag.String("consumer-tag", "simple-consumer", "AMQP consumer tag (should not be blank)") 19 | dbAddress = flag.String("db-address", "root@(mysql:3306)/mysql", "Address of the MySQL database") 20 | ) 21 | 22 | const ( 23 | onEvents = "on.events" 24 | onEventsBindingKey = "event.#" // no *s* 25 | ) 26 | 27 | func init() { 28 | flag.Parse() 29 | } 30 | 31 | func main() { 32 | inventory := controller.NewInventory(*uri, *dbAddress) 33 | defer inventory.MQ.Close() 34 | 35 | inventoryQueue := random.RandQueue() 36 | _, err := StartListening(*exchange, *exchangeType, inventoryQueue, *bindingKey, *consumerTag, inventory) 37 | if err != nil { 38 | log.Fatalf("Error Listening to RabbitMQ: %s\n", err) 39 | } 40 | 41 | onEventsQueue := random.RandQueue() 42 | _, err = StartListening(onEvents, *exchangeType, onEventsQueue, onEventsBindingKey, *consumerTag, inventory) 43 | if err != nil { 44 | log.Fatalf("Error Listening to RabbitMQ: %s\n", err) 45 | } 46 | 47 | select {} 48 | } 49 | 50 | // StartListening begins listening for AMQP messages in the background and kicks of a processor for each 51 | func StartListening(exchangeName, exchangeType, queueName, bindingKey, consumerTag string, inventory *controller.Inventory) (<-chan amqp.Delivery, error) { 52 | _, messageChannel, err := inventory.MQ.Listen(exchangeName, exchangeType, queueName, bindingKey, consumerTag) 53 | // Listen for messages in the background in infinite loop 54 | go func() { 55 | // Listen for messages in the background in infinite loop 56 | for m := range messageChannel { 57 | log.Printf( 58 | "got %dB delivery: [%v] %s", 59 | len(m.Body), 60 | m.DeliveryTag, 61 | m.Body, 62 | ) 63 | m.Ack(true) 64 | 65 | go inventory.ProcessMessage(&m) 66 | } 67 | }() 68 | 69 | return messageChannel, err 70 | } 71 | -------------------------------------------------------------------------------- /ci/pipeline.yml: -------------------------------------------------------------------------------- 1 | jobs: 2 | - name: unit 3 | plan: 4 | - aggregate: 5 | - get: voyager-inventory-service 6 | trigger: true 7 | - get: concourse-whale 8 | - task: unit 9 | image: concourse-whale 10 | config: 11 | platform: linux 12 | inputs: 13 | - name: voyager-inventory-service 14 | params: 15 | GITHUB_USER: {{github_username}} 16 | GITHUB_PASSWORD: {{github_password}} 17 | run: 18 | path: voyager-inventory-service/ci/tasks/unit.sh 19 | 20 | - name: integration 21 | plan: 22 | - aggregate: 23 | - put: it-env 24 | params: {acquire: true} 25 | - get: voyager-inventory-service 26 | trigger: true 27 | passed: [unit] 28 | - get: concourse-whale 29 | - task: integration 30 | image: concourse-whale 31 | config: 32 | platform: linux 33 | inputs: 34 | - name: voyager-inventory-service 35 | - name: it-env 36 | params: 37 | GITHUB_USER: {{github_username}} 38 | GITHUB_PASSWORD: {{github_password}} 39 | INTEGRATION_VM_USER: {{integration_vm_user}} 40 | INTEGRATION_VM_SSH_KEY: {{integration_vm_ssh_key}} 41 | run: 42 | path: voyager-inventory-service/ci/tasks/integration.sh 43 | ensure: 44 | put: it-env 45 | params: {release: it-env} 46 | 47 | - name: build-docker 48 | serial: true 49 | plan: 50 | - aggregate: 51 | - get: version 52 | params: {bump: patch} 53 | - get: concourse-whale 54 | - get: voyager-inventory-service 55 | trigger: true 56 | passed: [integration] 57 | - task: build 58 | image: concourse-whale 59 | config: 60 | platform: linux 61 | inputs: 62 | - name: voyager-inventory-service 63 | - name: version 64 | outputs: 65 | - name: build 66 | params: 67 | GITHUB_USER: {{github_username}} 68 | GITHUB_PASSWORD: {{github_password}} 69 | run: 70 | path: voyager-inventory-service/ci/tasks/build-candidate.sh 71 | - put: docker-voyager-inventory-service 72 | params: 73 | build: build 74 | tag: version/version 75 | - put: version 76 | params: {file: version/version} 77 | 78 | resources: 79 | - name: voyager-inventory-service 80 | type: git 81 | default-github: &github-secrets 82 | username: {{github_username}} 83 | password: {{github_password}} 84 | skip_ssl_verification: true 85 | source: 86 | uri: https://github.com/RackHD/voyager-inventory-service.git 87 | branch: master 88 | <<: *github-secrets 89 | 90 | - name: version 91 | type: semver 92 | source: 93 | driver: git 94 | uri: https://github.com/RackHD/voyager-inventory-service.git 95 | branch: version 96 | file: version 97 | <<: *github-secrets 98 | 99 | - name: it-env 100 | type: pool 101 | source: 102 | uri: https://github.com/RackHD/voyager-release.git 103 | branch: locks 104 | pool: integration 105 | <<: *github-secrets 106 | 107 | - name: concourse-whale 108 | type: docker-image 109 | source: 110 | repository: {{concourse_whale_repository}} 111 | insecure_registries: [{{docker_insecure_registries}}] 112 | 113 | - name: docker-voyager-inventory-service 114 | type: docker-image 115 | source: 116 | repository: {{docker_inventory_service_private_repository}} 117 | insecure_registries: [{{docker_insecure_registries}}] 118 | -------------------------------------------------------------------------------- /controller/controller.go: -------------------------------------------------------------------------------- 1 | package controller 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "log" 7 | 8 | "github.com/RackHD/voyager-inventory-service/mysql" 9 | "github.com/RackHD/voyager-utilities/amqp" 10 | "github.com/RackHD/voyager-utilities/models" 11 | 12 | samqp "github.com/streadway/amqp" 13 | ) 14 | 15 | // Inventory is a representation of Voyager's nodes and switches 16 | type Inventory struct { 17 | MQ *amqp.Client 18 | MySQL *mysql.DBconn 19 | } 20 | 21 | // NewInventory creates and initializes a new inventory 22 | func NewInventory(amqpAddress, dbAddress string) *Inventory { 23 | inventory := Inventory{} 24 | 25 | inventory.MQ = amqp.NewClient(amqpAddress) 26 | if inventory.MQ == nil { 27 | log.Fatalf("Could not connect to RabbitMQ: %s\n", amqpAddress) 28 | } 29 | 30 | inventory.MySQL = &mysql.DBconn{} 31 | err := inventory.MySQL.Initialize(dbAddress) 32 | if err != nil { 33 | log.Fatalf("Error connecting to DB: %s\n", err) 34 | } 35 | 36 | return &inventory 37 | } 38 | 39 | // ProcessMessage processes a message 40 | func (i *Inventory) ProcessMessage(m *samqp.Delivery) error { 41 | switch m.Exchange { 42 | 43 | case "voyager-inventory-service": 44 | return i.processInventoryService(m) 45 | 46 | case "on.events": 47 | return i.processOnEvents(m) 48 | 49 | default: 50 | err := fmt.Errorf("Unknown exchange name: %s\n", m.Exchange) 51 | log.Printf("Error: %s", err) 52 | return err 53 | 54 | } 55 | } 56 | 57 | // processInventoryService processes a message from the processInventoryService exchange 58 | func (i *Inventory) processInventoryService(d *samqp.Delivery) error { 59 | var cmd models.CmdMessage 60 | err := json.Unmarshal(d.Body, &cmd) 61 | if err != nil { 62 | log.Printf("Error: %s\n", err) 63 | return err 64 | } 65 | 66 | switch cmd.Command { 67 | 68 | case "get_nodes": 69 | // Process any Args 70 | // No args right Now 71 | 72 | // Call to DB for node_entities 73 | allNodes := make([]models.NodeEntity, 25) 74 | i.MySQL.DB.Find(&allNodes) 75 | 76 | // Marshal into json 77 | var responseBody []byte 78 | responseBody, err = json.Marshal(allNodes) 79 | if err != nil { 80 | log.Printf("Error: %s\n", err) 81 | return err 82 | } 83 | 84 | // amqp.send back to requestor 85 | return i.MQ.Send(d.Exchange, "topic", d.ReplyTo, string(responseBody), d.CorrelationId, d.RoutingKey) 86 | 87 | case "insert_ip_entry": 88 | var insertCmd models.CmdMessage 89 | insertCmd.Args = &models.IPEntity{} 90 | err = json.Unmarshal(d.Body, &insertCmd) 91 | if err != nil { 92 | log.Printf("Error: %s\n", err) 93 | return err 94 | } 95 | 96 | ipEntity := insertCmd.Args.(*models.IPEntity) 97 | if err = i.MySQL.DB.Create(&ipEntity).Error; err != nil { 98 | log.Printf("Error: %s\n", err) 99 | 100 | failure := fmt.Sprintf("ERROR: %s", err.Error()) 101 | i.MQ.Send(d.Exchange, "topic", d.ReplyTo, failure, d.CorrelationId, d.RoutingKey) 102 | 103 | return err 104 | } 105 | 106 | log.Printf("Node %s recorded with IP %s\n", ipEntity.NodeID, ipEntity.IPAddress) 107 | 108 | // amqp.send back to requestor 109 | return i.MQ.Send(d.Exchange, "topic", d.ReplyTo, "SUCCESS", d.CorrelationId, d.RoutingKey) 110 | 111 | case "update_node": 112 | nJSON, errMarshal := json.Marshal(cmd.Args) 113 | if errMarshal != nil { 114 | return errMarshal 115 | } 116 | var node models.NodeEntity 117 | err = json.Unmarshal(nJSON, &node) 118 | 119 | if err != nil { 120 | log.Printf("Error: %s\n", err) 121 | return err 122 | } 123 | 124 | log.Printf("Updating node to: %+v\n", node) 125 | if err = i.MySQL.DB.Model(&node).Update("status", node.Status).Error; err != nil { 126 | log.Printf("Error: %s\n", err) 127 | return err 128 | } 129 | 130 | // amqp.send back to requestor 131 | return i.MQ.Send(d.Exchange, "topic", d.ReplyTo, "SUCCESS", d.CorrelationId, d.RoutingKey) 132 | 133 | default: 134 | err = fmt.Errorf("Unknown command: %s\n", cmd.Command) 135 | log.Printf("Error: %s\n", err) 136 | return err 137 | 138 | } 139 | 140 | } 141 | 142 | // processOnEvents processes a message from the OnEvents exchange 143 | func (i *Inventory) processOnEvents(d *samqp.Delivery) error { 144 | log.Printf("Start to process rackhd on.events message") 145 | var node models.NodeMessage 146 | err := json.Unmarshal(d.Body, &node) 147 | if err != nil { 148 | log.Printf("Error: %s\n", err) 149 | return err 150 | } 151 | 152 | log.Printf("Node Message:\n %+v\n", node) 153 | 154 | switch node.Action { 155 | 156 | case "added": 157 | n := models.NodeEntity{ 158 | ID: node.NodeID, 159 | Type: node.NodeType, 160 | Status: models.StatusAdded, 161 | } 162 | log.Printf("Adding node to DB: %+v\n", n) 163 | 164 | if err = i.MySQL.DB.Create(&n).Error; err != nil { 165 | log.Printf("Error: %s\n", err) 166 | return err 167 | } 168 | return nil 169 | 170 | case "discovered": 171 | n := models.NodeEntity{ 172 | ID: node.NodeID, 173 | Type: node.NodeType, 174 | Status: models.StatusDiscovered, 175 | } 176 | var nJSON []byte 177 | nJSON, err = json.Marshal(models.NodeEntityJSON{ 178 | ID: node.NodeID, 179 | Type: node.NodeType, 180 | Status: models.StatusDiscovered, 181 | }) 182 | if err != nil { 183 | return err 184 | } 185 | 186 | log.Printf("Updating node to Discovered: %+v\n", n) 187 | if err = i.MySQL.DB.Model(&n).Update("status", "Discovered").Error; err != nil { 188 | log.Printf("Error: %s\n", err) 189 | return err 190 | } 191 | 192 | err = i.MQ.Send("voyager-inventory-service", "topic", "node.discovered.#", string(nJSON), "", "") 193 | if err != nil { 194 | log.Fatalf("Error sending to RabbitMQ: %s\n", err) 195 | } 196 | 197 | return nil 198 | 199 | default: 200 | err = fmt.Errorf("Unknown node action: %s\n", node.Action) 201 | log.Printf("Error: %s\n", err) 202 | return err 203 | } 204 | 205 | } 206 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /controller/controller_test.go: -------------------------------------------------------------------------------- 1 | package controller_test 2 | 3 | import ( 4 | "encoding/json" 5 | "os" 6 | 7 | "github.com/RackHD/voyager-inventory-service/controller" 8 | "github.com/RackHD/voyager-utilities/models" 9 | "github.com/RackHD/voyager-utilities/random" 10 | "github.com/streadway/amqp" 11 | 12 | . "github.com/onsi/ginkgo" 13 | . "github.com/onsi/gomega" 14 | ) 15 | 16 | var _ = Describe("Handler", func() { 17 | 18 | Describe("AMQP Message Handling", func() { 19 | var rabbitMQURL string 20 | var inventory *controller.Inventory 21 | var testExchange string 22 | var testExchangeType string 23 | var testQueueName string 24 | var testRoutingKey string 25 | var testConsumerTag string 26 | var testMessage string 27 | var testCorrelationID string 28 | var dbUrl string 29 | var err error 30 | 31 | BeforeEach(func() { 32 | rabbitMQURL = os.Getenv("RABBITMQ_URL") 33 | dbUrl = "root@(localhost:3306)/mysql" 34 | testExchange = "voyager-inventory-service" 35 | testExchangeType = "topic" 36 | testQueueName = random.RandQueue() 37 | testRoutingKey = "#" 38 | testConsumerTag = "testTag" 39 | testCorrelationID = "testID" 40 | 41 | inventory = controller.NewInventory(rabbitMQURL, dbUrl) 42 | Expect(inventory).ToNot(Equal(nil)) 43 | 44 | }) 45 | AfterEach(func() { 46 | inventory.MQ.Close() 47 | }) 48 | 49 | Context("When a message comes in to on.events", func() { 50 | 51 | var deliveries <-chan amqp.Delivery 52 | var err error 53 | 54 | BeforeEach(func() { 55 | testExchange = "on.events" 56 | _, deliveries, err = inventory.MQ.Listen(testExchange, testExchangeType, testQueueName, testRoutingKey, testConsumerTag) 57 | Expect(err).ToNot(HaveOccurred()) 58 | 59 | }) 60 | AfterEach(func() { 61 | inventory.MySQL.DB.DropTableIfExists("node_entities") 62 | inventory.MySQL.DB.Close() 63 | 64 | }) 65 | 66 | Context("When waiting on event.# binding key", func() { 67 | It("INTEGRATION receives event.# message from RackHD", func() { 68 | queueName := random.RandQueue() 69 | //We listen to match any binding key that have the word event. 70 | _, nodeMessages, err := inventory.MQ.Listen("on.events", testExchangeType, queueName, "event.#", testConsumerTag) 71 | Expect(err).ToNot(HaveOccurred()) 72 | 73 | // Pretend to be rackhd sending event.whatever message 74 | testMessage = `{"type":"node","action":"added","nodeId":"some_node_id","nodeType":"compute"}` 75 | err = inventory.MQ.Send("on.events", testExchangeType, "event.whatever", testMessage, "", "") 76 | Expect(err).ToNot(HaveOccurred()) 77 | 78 | d := <-nodeMessages 79 | d.Ack(false) 80 | Expect(string(d.Body)).To(Equal(testMessage)) 81 | }) 82 | }) 83 | 84 | It("INTEGRATION should add a new node to the DB if action is 'added'", func() { 85 | 86 | testMessage = `{"type":"node","action":"added","nodeId":"UNIQUE_ID","nodeType":"compute"}` 87 | err = inventory.MQ.Send(testExchange, testExchangeType, testRoutingKey, testMessage, testCorrelationID, "") 88 | Expect(err).ToNot(HaveOccurred()) 89 | 90 | d := <-deliveries 91 | d.Ack(false) 92 | 93 | err = inventory.ProcessMessage(&d) 94 | Expect(err).ToNot(HaveOccurred()) 95 | // Validate data is in DB 96 | out := models.NodeEntity{} 97 | inventory.MySQL.DB.Where("ID = ?", "UNIQUE_ID").Find(&out) 98 | Expect(out.ID).To(Equal("UNIQUE_ID")) 99 | Expect(out.Status).To(Equal("Added")) 100 | }) 101 | It("INTEGRATION should update a node's status if action is 'discovered'", func() { 102 | 103 | testMessage = `{"type":"node","action":"added","nodeId":"UNIQUE_ID","nodeType":"compute"}` 104 | err = inventory.MQ.Send(testExchange, testExchangeType, testRoutingKey, testMessage, testCorrelationID, "") 105 | Expect(err).ToNot(HaveOccurred()) 106 | d := <-deliveries 107 | d.Ack(false) 108 | err = inventory.ProcessMessage(&d) 109 | Expect(err).ToNot(HaveOccurred()) 110 | 111 | testMessage = `{"type":"node","action":"discovered","nodeId":"UNIQUE_ID","nodeType":"compute"}` 112 | err = inventory.MQ.Send(testExchange, testExchangeType, testRoutingKey, testMessage, testCorrelationID, "") 113 | Expect(err).ToNot(HaveOccurred()) 114 | 115 | d = <-deliveries 116 | d.Ack(false) 117 | 118 | err = inventory.ProcessMessage(&d) 119 | Expect(err).ToNot(HaveOccurred()) 120 | 121 | // Validate data is in DB 122 | out := models.NodeEntity{} 123 | err := inventory.MySQL.DB.Where("ID = ?", "UNIQUE_ID").Find(&out).Error 124 | 125 | Expect(err).ToNot(HaveOccurred()) 126 | Expect(out.ID).To(Equal("UNIQUE_ID")) 127 | Expect(out.Status).To(Equal("Discovered")) 128 | 129 | }) 130 | It("INTEGRATION should do nothing if action is unknown", func() { 131 | testMessage = `{"type":"node","action":"BAD_ACTION","nodeId":"UNIQUE_ID","nodeType":"compute"}` 132 | err = inventory.MQ.Send(testExchange, testExchangeType, testRoutingKey, testMessage, testCorrelationID, "") 133 | Expect(err).ToNot(HaveOccurred()) 134 | 135 | d := <-deliveries 136 | d.Ack(false) 137 | 138 | err = inventory.ProcessMessage(&d) 139 | Expect(err).To(HaveOccurred()) 140 | 141 | // Validate data is NOT in DB 142 | out := models.NodeEntity{} 143 | err = inventory.MySQL.DB.Where("ID = ?", "UNIQUE_ID").Find(&out).Error 144 | Expect(err).To(HaveOccurred()) 145 | Expect(out).To(Equal(models.NodeEntity{})) 146 | }) 147 | 148 | }) 149 | 150 | Context("When a message comes in to inventoryService exchange", func() { 151 | var inventoryServiceExchange, inventoryServiceExchangeType, inventoryServiceRoutingKey, inventoryServiceRecieveQueue, inventoryServiceConsumerTag, inventoryServiceCorrelationID string 152 | var requests <-chan amqp.Delivery 153 | var replies <-chan amqp.Delivery 154 | var nodeMessages <-chan amqp.Delivery 155 | var requestQueueName, repliesQueueName string 156 | BeforeEach(func() { 157 | 158 | inventoryServiceExchange = "voyager-inventory-service" 159 | inventoryServiceExchangeType = "topic" 160 | inventoryServiceRoutingKey = "request" 161 | inventoryServiceRecieveQueue = "reply" 162 | inventoryServiceCorrelationID = "test-id1" 163 | inventoryServiceConsumerTag = "consumer-tag1" 164 | 165 | requestQueueName = random.RandQueue() 166 | repliesQueueName = random.RandQueue() 167 | 168 | }) 169 | AfterEach(func() { 170 | inventory.MySQL.DB.DropTableIfExists("node_entities") 171 | inventory.MySQL.DB.DropTableIfExists("ip_entities") 172 | inventory.MySQL.DB.Close() 173 | 174 | }) 175 | 176 | Context("When we receive request with the command 'get_nodes'", func() { 177 | It("INTEGRATION should reply with a list of nodes in the DB", func() { 178 | // Setup for this Test 179 | _, requests, err = inventory.MQ.Listen(inventoryServiceExchange, inventoryServiceExchangeType, requestQueueName, inventoryServiceRoutingKey, inventoryServiceConsumerTag) 180 | Expect(err).ToNot(HaveOccurred()) 181 | 182 | _, replies, err = inventory.MQ.Listen(inventoryServiceExchange, inventoryServiceExchangeType, repliesQueueName, inventoryServiceRecieveQueue, inventoryServiceConsumerTag) 183 | Expect(err).ToNot(HaveOccurred()) 184 | 185 | _, nodeMessages, err = inventory.MQ.Listen("on.events", testExchangeType, testQueueName, testRoutingKey, testConsumerTag) 186 | Expect(err).ToNot(HaveOccurred()) 187 | 188 | testMessage = `{"type":"node","action":"added","nodeId":"UNIQUE_ID","nodeType":"compute"}` 189 | err = inventory.MQ.Send("on.events", testExchangeType, testRoutingKey, testMessage, testCorrelationID, "") 190 | Expect(err).ToNot(HaveOccurred()) 191 | testMessage = `{"type":"node","action":"added","nodeId":"UNIQUE_ID1","nodeType":"compute"}` 192 | err = inventory.MQ.Send("on.events", testExchangeType, testRoutingKey, testMessage, testCorrelationID, "") 193 | Expect(err).ToNot(HaveOccurred()) 194 | 195 | for i := 0; i < 2; i++ { 196 | nodeMsg := <-nodeMessages 197 | nodeMsg.Ack(false) 198 | err = inventory.ProcessMessage(&nodeMsg) 199 | Expect(err).ToNot(HaveOccurred()) 200 | } 201 | 202 | // The test itself 203 | requestMessage := `{"command": "get_nodes", "options":""}` 204 | expectedReply := `[{"ID":"UNIQUE_ID","Type":"compute","Status":"Added"},{"ID":"UNIQUE_ID1","Type":"compute","Status":"Added"}]` 205 | 206 | err := inventory.MQ.Send(inventoryServiceExchange, inventoryServiceExchangeType, inventoryServiceRoutingKey, requestMessage, inventoryServiceCorrelationID, inventoryServiceRecieveQueue) 207 | Expect(err).ToNot(HaveOccurred()) 208 | 209 | req := <-requests 210 | req.Ack(false) 211 | 212 | err = inventory.ProcessMessage(&req) 213 | Expect(err).ToNot(HaveOccurred()) 214 | Expect(req.CorrelationId).To(Equal(inventoryServiceCorrelationID)) 215 | 216 | reply := <-replies 217 | req.Ack(false) 218 | Expect(string(reply.Body)).To(Equal(expectedReply)) 219 | }) 220 | }) 221 | 222 | Context("When we receive request with the command 'insert_ip_entry'", func() { 223 | It("INTEGRATION should insert an IP object into the DB", func() { 224 | // Set up test 225 | _, requests, err = inventory.MQ.Listen(inventoryServiceExchange, inventoryServiceExchangeType, requestQueueName, inventoryServiceRoutingKey, inventoryServiceConsumerTag) 226 | Expect(err).ToNot(HaveOccurred()) 227 | 228 | _, replies, err = inventory.MQ.Listen(inventoryServiceExchange, inventoryServiceExchangeType, repliesQueueName, inventoryServiceRecieveQueue, inventoryServiceConsumerTag) 229 | Expect(err).ToNot(HaveOccurred()) 230 | 231 | testIPEntity := models.IPEntity{ 232 | IPID: "fake-ip-id", 233 | IPAddress: "10.10.10.10", 234 | NodeID: "fake-node-id", 235 | PoolID: "fake-pool-id", 236 | SubnetID: "fake-subnet-id", 237 | } 238 | testCmd := models.CmdMessage{ 239 | Command: "insert_ip_entry", 240 | Args: &testIPEntity, 241 | } 242 | testCmdMessage, err := json.Marshal(testCmd) 243 | Expect(err).ToNot(HaveOccurred()) 244 | 245 | // Send request message 246 | err = inventory.MQ.Send(inventoryServiceExchange, inventoryServiceExchangeType, inventoryServiceRoutingKey, string(testCmdMessage), inventoryServiceCorrelationID, inventoryServiceRecieveQueue) 247 | Expect(err).ToNot(HaveOccurred()) 248 | 249 | // Recieve and handle request 250 | req := <-requests 251 | req.Ack(false) 252 | err = inventory.ProcessMessage(&req) 253 | Expect(err).ToNot(HaveOccurred()) 254 | 255 | // Handle voyager-inventory-service's reply to requestor 256 | reply := <-replies 257 | reply.Ack(false) 258 | Expect(string(reply.Body)).To(Equal("SUCCESS")) 259 | 260 | allIPs := make([]models.IPEntity, 1) 261 | inventory.MySQL.DB.Find(&allIPs) 262 | Expect(allIPs[0].IPID).To(Equal("fake-ip-id")) 263 | Expect(allIPs[0].IPAddress).To(Equal("10.10.10.10")) 264 | Expect(allIPs[0].NodeID).To(Equal("fake-node-id")) 265 | Expect(allIPs[0].PoolID).To(Equal("fake-pool-id")) 266 | Expect(allIPs[0].SubnetID).To(Equal("fake-subnet-id")) 267 | 268 | }) 269 | 270 | It("INTEGRATION should fail gracefully on DB error", func() { 271 | // Set up test 272 | inventory.MySQL.DB.DropTableIfExists("ip_entities") 273 | _, requests, err = inventory.MQ.Listen(inventoryServiceExchange, inventoryServiceExchangeType, requestQueueName, inventoryServiceRoutingKey, inventoryServiceConsumerTag) 274 | Expect(err).ToNot(HaveOccurred()) 275 | 276 | _, replies, err = inventory.MQ.Listen(inventoryServiceExchange, inventoryServiceExchangeType, repliesQueueName, inventoryServiceRecieveQueue, inventoryServiceConsumerTag) 277 | Expect(err).ToNot(HaveOccurred()) 278 | 279 | testIPEntity := models.IPEntity{ 280 | IPID: "fake-ip-id", 281 | IPAddress: "10.10.10.10", 282 | NodeID: "fake-node-id", 283 | PoolID: "fake-pool-id", 284 | SubnetID: "fake-subnet-id", 285 | } 286 | testCmd := models.CmdMessage{ 287 | Command: "insert_ip_entry", 288 | Args: &testIPEntity, 289 | } 290 | testCmdMessage, err := json.Marshal(testCmd) 291 | Expect(err).ToNot(HaveOccurred()) 292 | 293 | // Send request message 294 | err = inventory.MQ.Send(inventoryServiceExchange, inventoryServiceExchangeType, inventoryServiceRoutingKey, string(testCmdMessage), inventoryServiceCorrelationID, inventoryServiceRecieveQueue) 295 | Expect(err).ToNot(HaveOccurred()) 296 | 297 | // Recieve and handle request 298 | req := <-requests 299 | req.Ack(false) 300 | err = inventory.ProcessMessage(&req) 301 | Expect(err).To(HaveOccurred()) 302 | 303 | // Handle voyager-inventory-service's reply to requestor 304 | reply := <-replies 305 | reply.Ack(false) 306 | Expect(string(reply.Body)).To(ContainSubstring("ERROR")) 307 | 308 | }) 309 | }) 310 | Context("When we receive request with the command 'update_node'", func() { 311 | It("INTEGRATION should Update the node with new info", func() { 312 | // Set up test 313 | // Setup for this Test 314 | _, requests, err = inventory.MQ.Listen(inventoryServiceExchange, inventoryServiceExchangeType, requestQueueName, inventoryServiceRoutingKey, inventoryServiceConsumerTag) 315 | Expect(err).ToNot(HaveOccurred()) 316 | 317 | _, replies, err = inventory.MQ.Listen(inventoryServiceExchange, inventoryServiceExchangeType, repliesQueueName, inventoryServiceRecieveQueue, inventoryServiceConsumerTag) 318 | Expect(err).ToNot(HaveOccurred()) 319 | 320 | _, nodeMessages, err = inventory.MQ.Listen("on.events", testExchangeType, testQueueName, testRoutingKey, testConsumerTag) 321 | Expect(err).ToNot(HaveOccurred()) 322 | 323 | testMessage = `{"type":"node","action":"added","nodeId":"UNIQUE_ID","nodeType":"switch"}` 324 | err = inventory.MQ.Send("on.events", testExchangeType, testRoutingKey, testMessage, testCorrelationID, "") 325 | Expect(err).ToNot(HaveOccurred()) 326 | nodeMsg := <-nodeMessages 327 | nodeMsg.Ack(false) 328 | err = inventory.ProcessMessage(&nodeMsg) 329 | Expect(err).ToNot(HaveOccurred()) 330 | 331 | testMessage = `{"type":"node","action":"discovered","nodeId":"UNIQUE_ID","nodeType":"switch"}` 332 | err = inventory.MQ.Send("on.events", testExchangeType, testRoutingKey, testMessage, testCorrelationID, "") 333 | Expect(err).ToNot(HaveOccurred()) 334 | nodeMsg = <-nodeMessages 335 | nodeMsg.Ack(false) 336 | err = inventory.ProcessMessage(&nodeMsg) 337 | Expect(err).ToNot(HaveOccurred()) 338 | 339 | testNodeEntity := models.NodeEntity{ 340 | ID: "UNIQUE_ID", 341 | Type: "switch", 342 | Status: "Available-Learning", 343 | } 344 | testCmd := models.CmdMessage{ 345 | Command: "update_node", 346 | Args: &testNodeEntity, 347 | } 348 | testCmdMessage, err := json.Marshal(testCmd) 349 | Expect(err).ToNot(HaveOccurred()) 350 | 351 | // Send request message 352 | err = inventory.MQ.Send(inventoryServiceExchange, inventoryServiceExchangeType, inventoryServiceRoutingKey, string(testCmdMessage), inventoryServiceCorrelationID, inventoryServiceRecieveQueue) 353 | Expect(err).ToNot(HaveOccurred()) 354 | 355 | // Recieve and handle request 356 | req := <-requests 357 | req.Ack(false) 358 | err = inventory.ProcessMessage(&req) 359 | Expect(err).ToNot(HaveOccurred()) 360 | Expect(req.CorrelationId).To(Equal(inventoryServiceCorrelationID)) 361 | 362 | // Handle voyager-inventory-service's reply to requestor 363 | reply := <-replies 364 | reply.Ack(false) 365 | Expect(string(reply.Body)).To(Equal("SUCCESS")) 366 | 367 | // Validate data is in DB 368 | out := models.NodeEntity{} 369 | err = inventory.MySQL.DB.Where("ID = ?", "UNIQUE_ID").Find(&out).Error 370 | 371 | Expect(err).ToNot(HaveOccurred()) 372 | Expect(out.ID).To(Equal("UNIQUE_ID")) 373 | Expect(out.Status).To(Equal("Available-Learning")) 374 | 375 | }) 376 | }) 377 | }) 378 | }) 379 | }) 380 | --------------------------------------------------------------------------------