branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/main
<repo_name>skaiterskull/api-admin-cms<file_sep>/src/routers/tokenRouter.js import express from 'express' const Router = express.Router() import { verifyRefreshJWT, createAccessJWT } from '../helpers/jwt.helper.js' import { getUser, getUserByEMail } from '../models/user/User.model.js' import { createPasswordResetOTP } from '../models/reset-pin/ResetPin.model.js' import { passwordResetOTPNotification } from '../helpers/mail.helper.js' Router.get('/', async (req, res) => { try { const { authorization } = req.headers if (authorization) { const decoded = verifyRefreshJWT(authorization) if (decoded?.email) { const filter = { email: decoded.email, refreshJWT: authorization, } const user = await getUser(filter) if (user?._id) { const accessJWT = await createAccessJWT({ _id: user._id, email: user.email, }) return res.json({ status: 'Success', message: 'New access token has been generated', accessJWT, }) } } } res.status(401).json({ status: 'Error', message: 'Invalid token', }) } catch (error) { console.log(error) res.status(500).json({ status: 'Error', message: 'Internal server error', }) } }) Router.post('/request-otp', async (req, res) => { try { const { email } = req.body if (email) { //check email in database const user = await getUserByEMail(email) if (user?.id && user?.role === 'admin') { // create unique OTP and store in database const result = await createPasswordResetOTP(email) // email that otp to the user email if (result?._id) { passwordResetOTPNotification({ email, otp: result.otp }) } } } res.json({ status: 'Success', message: 'If email exist in our system, we will send you an OTP, please check your email and use OTP to reset the password. The OTP will expired in 15 minutes.', }) } catch (error) { console.log(error) res.status(500).json({ status: 'Error', message: 'Internal server error', }) } }) export default Router <file_sep>/server.js import dotenv from 'dotenv' dotenv.config() import express from 'express' import helmet from 'helmet' import cors from 'cors' import morgan from 'morgan' import mongoClient from './src/config/db.js' const app = express() import path from 'path' const PORT = process.env.PORT || 8000 //Middlewares app.use(helmet()) app.use(cors()) app.use(morgan('tiny')) app.use(express.urlencoded()) app.use(express.json()) //Connect MongoDB mongoClient() //Serve static files from public dir const __dirname = path.resolve() app.use(express.static(path.join(__dirname, 'public'))) //Routers import userRouter from './src/routers/userRouter.js' import categoryUser from './src/routers/categoryRouter.js' import tokenRouter from './src/routers/tokenRouter.js' import productRouter from './src/routers/productRouter.js' import { isAdminAuth } from './src/middlewares/auth.middleware.js' app.use('/api/v1/user', userRouter) app.use('/api/v1/category', isAdminAuth, categoryUser) app.use('/api/v1/token', tokenRouter) app.use('/api/v1/product', isAdminAuth, productRouter) app.use('/', (req, res) => { res.send('You have reached the end of the router list') }) app.listen(PORT, (error) => { if (error) { return console.log(error) } console.log(`Server is running at http://localhost:${PORT}`) }) <file_sep>/src/helpers/mail.helper.js import nodemailer from 'nodemailer' const send = async (mailInfo) => { const transporter = nodemailer.createTransport({ host: process.env.EMAIL_SMTP, port: 587, auth: { user: process.env.EMAIL_USER, pass: process.env.EMAIL_PASS, }, }) const info = await transporter.sendMail(mailInfo) // Preview only available when sending through an Ethereal account console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info)) } export const emailProcesser = ({ email, otp }) => { const link = `${process.env.CLIENT_ROOT_URL}/email-verification?otp=${otp}&email=${email}` const mailObj = { from: `E-shop 👻 <${process.env.EMAIL_USER}>`, // sender address to: email, // list of receivers subject: 'User Email Verification', // Subject line text: `Hi there Please follow the link to verify your email ${link}`, // plain text body html: ` Hello there, <br/> <p>Thank you for register with us. Please verify your email</p> <p><a href=${link}>${link}</a></p> <br/> <p>Kind regards</p> <br/> <p>--Some company info</p> `, // html body } send(mailObj) } export const emailVerificationWelcome = (email) => { const mailObj = { from: `E-shop 👻 <${process.env.EMAIL_USER}>`, // sender address to: email, // list of receivers subject: 'Welcome, your email has been verified', // Subject line text: `Hi there, your email has been verified, you can sign in now`, // plain text body html: ` Hello there, <br/> <p>Thank you for register with us. Your email has been verified</p> <p>Kind regards</p> <br/> <p>--Some company info</p> `, // html body } send(mailObj) } export const userProfileUpdateNotification = (email) => { const mailObj = { from: `E-shop 👻 <${process.env.EMAIL_USER}>`, // sender address to: email, // list of receivers subject: 'Profile update', // Subject line text: `Hi there, your profile has been updated. If you did not make this change, please contact us immediately.`, // plain text body html: ` Hello there, <br/> <p>Hi there, your profile has been updated. If you did not make this change, please contact us immediately.</p> <p>Kind regards</p> <br/> <p>--Some company info</p> `, // html body } send(mailObj) } export const userPasswordUpdateNotification = (email) => { const mailObj = { from: `E-shop 👻 <${process.env.EMAIL_USER}>`, // sender address to: email, // list of receivers subject: 'Password update', // Subject line text: `Hi there, your password has been updated. If you did not make this change, please contact us immediately.`, // plain text body html: ` Hello there, <br/> <p>Hi there, your password has been updated. If you did not make this change, please contact us immediately.</p> <p>Kind regards</p> <br/> <p>--Some company info</p> `, // html body } send(mailObj) } export const passwordResetOTPNotification = ({ email, otp }) => { const mailObj = { from: `E-shop 👻 <${process.env.EMAIL_USER}>`, // sender address to: email, // list of receivers subject: 'OTP for password reset', // Subject line text: `Hi there, use the otp ${otp} to reset the password. The password will expire in x amount`, // plain text body html: ` Hello there, <br/> <p>Hi there, use the otp ${otp} to reset the password. The password will expire in x amount</p> <p>Kind regards</p> <br/> <p>--Some company info</p> `, // html body } send(mailObj) } <file_sep>/src/middlewares/auth.middleware.js import { verifyAccessJWT } from '../helpers/jwt.helper.js' import { getSession } from '../models/session/Session.model.js' import { getUserById } from '../models/user/User.model.js' export const isAdminAuth = async (req, res, next) => { try { const { authorization } = req.headers if (authorization) { const decoded = verifyAccessJWT(authorization) if (decoded === 'jwt expired') { console.log(decoded) return res.json({ status: 'error', message: 'JWT expired', }) } if (decoded?.email) { const session = await getSession({ token: authorization }) if (session?._id) { const user = await getUserById(session.userId) if (user?.role === 'admin') { req.user = user return next() } } } } return res.status(401).json({ status: 'error', message: 'Unauthenticated', }) } catch (error) { console.log(error) return res.status(500).json({ status: 'error', message: 'Internal server error', }) } } <file_sep>/src/middlewares/validation.middleware.js import Joi from 'joi' const str = Joi.string().max(30) const shortStr = Joi.string().alphanum().max(30).required() const email = Joi.string().email({ minDomainSegments: 2 }) const password = Joi.string().min(6).max(50).required() const otp = Joi.string().min(6).max(6).required() export const newUserformValidaton = (req, res, next) => { const schema = Joi.object({ fname: shortStr, lname: shortStr, dob: Joi.date().allow('').allow(null), email, password, phone: Joi.string().allow('').max(15), address: Joi.string().allow('').max(50), gender: Joi.string().allow('').max(6), }) const result = schema.validate(req.body) if (result.error) { return res.json({ status: 'Error', message: result.error.message, }) } next() } export const emailVerificationValidation = (req, res, next) => { const schema = Joi.object({ otp: shortStr, email: email.required(), }) const result = schema.validate(req.body) if (result.error) { console.log(result.error.message) } next() } export const newCategoryValidation = (req, res, next) => { const schema = Joi.object({ name: str.required(), parentCat: str.allow('').allow(null), }) const result = schema.validate(req.body) if (result.error) { return res.json({ status: 'Error', message: result.error.message, }) } next() } export const updateCategoryValidation = (req, res, next) => { const schema = Joi.object({ _id: shortStr, name: str.required(), parentCat: str.allow('').allow(null), }) const result = schema.validate(req.body) if (result.error) { return res.json({ status: 'Error', message: result.error.message, }) } next() } export const adminLoginValidation = (req, res, next) => { const schema = Joi.object({ email, password: Joi.string().min(6).max(50).required(), }) const result = schema.validate(req.body) if (result.error) { return res.json({ status: 'Error', message: result.error.message, }) } next() } export const updateUserformValidaton = (req, res, next) => { const schema = Joi.object({ fname: shortStr, lname: shortStr, dob: Joi.date().allow('').allow(null), phone: Joi.string().allow('').max(15), address: Joi.string().allow('').max(50), gender: Joi.string().allow('').max(6), }) const result = schema.validate(req.body) if (result.error) { return res.json({ status: 'Error', message: result.error.message, }) } next() } export const updatePasswordformValidaton = (req, res, next) => { const schema = Joi.object({ password, currentPassword: <PASSWORD>, }) const result = schema.validate(req.body) if (result.error) { return res.json({ status: 'Error', message: result.error.message, }) } next() } export const resetPasswordformValidaton = (req, res, next) => { const schema = Joi.object({ otp, password, email, }) const result = schema.validate(req.body) if (result.error) { return res.json({ status: 'Error', message: result.error.message, }) } next() } <file_sep>/README.MD # API-ADMIN-ESHOP This is part of eshop system. This project is the backend api for admin cms. ## HOW TO RUN - Clone the project - Run `npm install` - Run `npm i nodemon` if you dont have nodemon installed in your system - Run `npm run dev` ## APIS All the api will follow the following path `${rootUrl/api/v1}` ie. http://localhost All the private apis endpoint only be accessible if authorization header is included. ### User API All user api will follow the following endpoint `${rootUrl/api/v1/user}`. | # | API | METHOD | DESCRIPTION | isPrivate | | --- | --------------------- | ------ | --------------------------------------------------------------------------- | --------- | | 1 | `/` | POST | Expect the user info object and create user in DB and return status message | Yes | | 2 | `/email-verification` | POST | Expect the user info object and check if the link valid | No | | 3 | `/login` | POST | Expect an user info {email, password} and proceed to private route | No | | 4 | `/` | PUT | Expect an user info object and then update it on database | Yes | | 5 | `/` | PATCH | Expect an current password and new password to update the password | Yes | | 6 | `/reset-password` | PATCH | Expect otp, new password, and email to reset password | No | ### Category API All user api will follow the following endpoint `${rootUrl/api/v1/category}` | # | API | METHOD | DESCRIPTION | isPrivate | | --- | --------- | ------ | -------------------------------------------------------------------------------------------------- | --------- | | 1 | `/` | POST | Expects the category info object and creates category in DB and return stat message | Yes | | 2 | `/` | GET | Fetching all the data from category table | Yes | | 3 | `/` | PATCH | Expect the category info object {\_id, name, parentCat} and based on that will update the database | Yes | | 4 | `/params` | DELETE | Require the category info object {\_id} and pass it as params for deleting the data | Yes | ### Token API All token api will follow the following endpoint `${rootUrl/api/v1/token}` | # | API | METHOD | DESCRIPTION | isPrivate | | --- | --- | ------ | ------------------------------------------------------------------------------------ | --------- | | 1 | `/` | GET | Expect the Authorization data as headers from frontend for authorization of the user | No | | 2 | `/` | POST | Expect an email and OTP will be sent to the email | No | ### Product API All token api will follow the following endpoint `${rootUrl/api/v1/product}` | # | API | METHOD | DESCRIPTION | | --- | --------- | ------ | ------------------------------------------------------------------------------- | | 1 | `/:slug?` | GET | Fetch data, if slug provided will fetch data by slug, otherwise fetch all datas | | 2 | `/` | POST | Expect an object and save in database | | 3 | `/params` | DELETE | Expect an id as params and delete the product by id | <file_sep>/src/routers/categoryRouter.js import express from 'express' const Router = express.Router() import slugify from 'slugify' import { createCategory, deleteCategory, getCategory, updateCategory, } from '../models/category/Category.model.js' import { newCategoryValidation, updateCategoryValidation, } from '../middlewares/validation.middleware.js' Router.all('/', (req, res, next) => { next() }) //Create Category Router.post('/', newCategoryValidation, async (req, res) => { try { console.log(req.body) const { name, parentCat } = req.body // slugify const slug = slugify(name, { lower: true }) const newCat = { name, slug, parentCat: parentCat ? parentCat : null, } //insert into database const result = await createCategory(newCat) //response to frontend if (result?._id) { return res.json({ status: 'Success', message: 'New category has been added', }) } res.json({ status: 'Error', message: 'Unable to add category, please try again later', }) } catch (error) { console.log(error) let msg = 'Unable to process your request' if (error.message.includes('E11000')) { msg = 'Category is already exist' } res.json({ status: 'Error', message: msg, }) } }) //Delete Category Router.delete('/:_id?', async (req, res) => { try { const { _id } = req.params if (_id) { const result = await deleteCategory(_id) if (result?._id) { return res.json({ status: 'Success', message: 'Category has been deleted', }) } } res.json({ status: 'Error', message: 'Unable to delete category, please try again later', }) } catch (error) { console.log(error) res.status(500).json({ status: 'Error', message: "Unable to process your request'", }) } }) Router.patch('/', updateCategoryValidation, async (req, res) => { try { const { parentCat } = req.body req.body.parentCat = parentCat ? parentCat : null const result = await updateCategory(req.body) if (result?._id) { return res.json({ status: 'Success', message: 'Category has been updated', }) } res.json({ status: 'Error', message: 'Unable to update category, please try again later', }) } catch (error) { console.log(error) res.json({ status: 'Error', message: "Unable to process your request'", }) } }) //Fetch Category Router.get('/', async (req, res) => { try { const result = await getCategory() res.json({ status: 'Success', message: 'Request success', result, }) } catch (error) { console.log(error) res.status(500).json({ status: 'Error', message: 'Unable to process your request', }) } }) export default Router
e80ab56cdf9c7acfd2c1790c29ddb16cd822d5bb
[ "JavaScript", "Markdown" ]
7
JavaScript
skaiterskull/api-admin-cms
5fe4258c971cc8c85877b095fc56a20a6b41414d
ad0e6e248379169d70b03c6fa1e423ecd96d9823
refs/heads/main
<repo_name>faraz176/Connect_4_Ai<file_sep>/Code.py class Board(): def __init__(self): self.board_game = [] self.board_dict = {} def board(self): row_wise = ['A', 'B', 'C', 'D', 'E', 'F', 'G'] column_wise = [1,2,3,4,5,6] for i,k in enumerate(row_wise): for z in column_wise: coordinate = (i,z) self.board_game.append(coordinate) for i in range(len(self.board_game)): self.board_dict[self.board_game[i]] = '' def piece_drop(self, board_column, row_location, color): coord = (board_column,row_location) if coord in self.board_dict.keys(): if self.board_dict[coord] != '': print(self.board_dict) else: self.board_dict[coord] = color print(self.board_dict) def win_checker(self): #Vertical Logic coords_to_iterate = list(self.board_dict.keys()) count_red = 0 count_yellow = 0 for i in range(len(self.board_game)): if self.board_dict[coords_to_iterate[i]] == 'red': count_red += 1 if count_red == 4: red_won = 'Red Wins!' return red_won else: count_red = 0 for i in range(len(self.board_game)): if self.board_dict[coords_to_iterate[i]] == 'yellow': count_yellow += 1 if count_yellow == 4: yellow_won = 'Yellow Wins!' return yellow_won else: count_yellow = 0 #Horizonatal Logic for i in range(0,7): for z in range(1,6,5): coords_to_check = (i,z) if self.board_dict[coords_to_check] == 'red': count_red += 1 if count_red == 4: red_won = 'Red Wins!' return red_won else: count_red = 0 for i in range(0,7): for z in range(1,6,5): coords_to_check = (i,z) if self.board_dict[coords_to_check] == 'yellow': count_yellow += 1 if count_yellow == 4: yellow_won = 'Yellow Wins!' return yellow_won else: yellow_red = 0 #45 degree logic new_game = Board() new_game.board() x = None while x != 'done': # x = input("Please type 'done' to end game ") board_column = int(input('Please input a column number from (0-6) ')) row_location = int(input('Please input a row number (1-6) ')) color = input('please input a color red or yellow ') new_game.piece_drop(board_column, row_location, color) vz = new_game.win_checker() if vz != None: print(vz) x = 'done' <file_sep>/test.py colors = ['yellow', 'red', 'blue'] for i in colors: if i == 'yellow': print<file_sep>/yu.py import random as r class Board(): def __init__(self, color1,): cock = [] for i in range(1,7): for z in range(0,7): cock.append([]) self.color_player_1 = color1 self.color_player_2 = '' self.turn = 0 self.board_game = [] self.moves_ready = [] self.board_dict = {} self.last_dropped = '' self.count_red_variable = 1 self.count_yellow_variable = 1 self.looking_board = cock self.game_turn = 0 def board(self): row_wise = ['A', 'B', 'C', 'D', 'E', 'F', 'G'] column_wise = [1,2,3,4,5,6] for i,k in enumerate(row_wise): for z in column_wise: coordinate = (i,z) self.board_game.append(coordinate) for i in range(len(self.board_game)): self.board_dict[self.board_game[i]] = '' def weird_board(self): for i in range(1,7): for z in range(0,7): self.looking_board.append([]) for i in range(len(self.board_game)): self.looking_board[i] = self.board_game[i] def board_look(self): #Mapping for i in range(len(self.board_game)): if self.looking_board[i] == self.last_dropped: self.looking_board[i] = self.color_player_2 num_to_iterate = 0 num_to_end = 6 for i in range(1,8): print(self.looking_board[num_to_iterate:num_to_end]) num_to_iterate += 6 num_to_end += 6 def piece_drop(self, board_column): #coord = (board_column,row_location) for i in (range(1,7)): if self.turn == 0: if self.board_dict[(board_column, i)] == '': self.board_dict[(board_column, i)] = self.color_player_1 self.color_player_2 = self.color_player_1 self.last_dropped = (board_column, i) #print(self.board_dict) self.turn +=1 break else: if self.color_player_1 == 'red': color_2 = 'yellow' if self.board_dict[(board_column, i)] == '': self.board_dict[(board_column, i)] = color_2 self.color_player_2 = color_2 self.last_dropped = (board_column, i) #print(self.board_dict) self.turn = 0 break def availiable_moves(self): self.moves_ready = [] for i in range(0,7): for z in range(1,7): if self.board_dict[(i,z)] == '': space = (i,z) self.moves_ready.append(space) break return self.moves_ready def win_checker(self): #Vertical Logic coords_to_iterate = list(self.board_dict.keys()) count_red = 0 count_yellow = 0 for i in range(len(self.board_game)): if coords_to_iterate[i-1][0] < coords_to_iterate[i][0]: count_red = 0 if self.board_dict[coords_to_iterate[i]] == 'red': count_red += 1 if count_red == 4: red_won = 'red' return red_won else: count_red = 0 for i in range(len(self.board_game)): if coords_to_iterate[i-1][0] < coords_to_iterate[i][0]: count_yellow = 0 if self.board_dict[coords_to_iterate[i]] == 'yellow': count_yellow += 1 if count_yellow == 4: yellow_won = 'yellow' return yellow_won else: count_yellow = 0 #Horizonatal Logic for i in range(0,7): for z in range(1,6,5): coords_to_check = (i,z) if self.board_dict[coords_to_check] == 'red': count_red += 1 if count_red == 4: red_won = 'red' return red_won else: count_red = 0 for i in range(0,7): for z in range(1,6,5): coords_to_check = (i,z) if self.board_dict[coords_to_check] == 'yellow': count_yellow += 1 if count_yellow == 4: yellow_won = 'yellow' return yellow_won else: count_yellow = 0 #45 degree logic piece_dropped = self.last_dropped try: if self.board_dict[(piece_dropped[0]-1, piece_dropped[1]-1)] == 'red': self.count_red_variable += 1 print("red: " + str(self.count_red_variable)) if self.count_red_variable == 4: red_won = 'red' return red_won except KeyError: None piece_dropped = self.last_dropped try: if self.board_dict[(piece_dropped[0]-1, piece_dropped[1]-1)] == 'yellow': self.count_yellow_variable += 1 print("yellow: "+ str(self.count_yellow_variable)) if self.count_yellow_variable == 4: yellow_won = 'yellow' return yellow_won except KeyError: None # def minimax(self): # if self.turn == 0: # maximizingPlayer = self.color_player_1 # if self.turn == 1: # maximizingPlayer = 'yellow' # other_player = 'yellow' # if self.win_checker() == other_player: # return {'position': None, 'score': 1 * (len(self.availiable_moves) + 1) if other_player == maximizingPlayer else -1 * ( # len(self.availiable_moves()) + 1)} # elif not self.availiable_moves(): # return{'position': None, 'score':0} # if self.color_player_1 == maximizingPlayer: # best = {'position': None, 'score': -math.inf} # else: # best = {'position': None, 'score': math.inf} # for possible_move in self.availiable_moves(): # self.piece_drop(possible_move) # sim_score = self.minimax(self, other_player) # self.piece_drop[possible_move] = ' ' # sim_score['position'] = possible_move # if self.color_player_1 == maximizingPlayer: # if sim_score['score'] > best['score']: # best = sim_score # else: # if sim_score['score'] < best['score']: # best = sim_score # return best def AI(self): if self.turn == 1: if self.game_turn == 0: num_choose = r.randint(0,6) best_move = num_choose self.game_turn += 1 return best_move moves_to_consider = [] for i in self.moves_ready: try: if self.board_dict[i[0], i[1] - 1] == 'yellow': move_possible_1 = 0.8 moves_to_consider.append((i, move_possible_1)) elif self.board_dict[i[0] - 1, i[1]] == 'yellow': move_possible_2 = 0.8 moves_to_consider.append((i, move_possible_2)) elif self.board_dict[i[0] -1, i[1] -1] == 'yellow': move_possible_3 = 0.8 moves_to_consider.append((i, move_possible_3)) elif self.board_dict[i[0], i[1] - 1] == 'red': move_possible_4 = 0.8 moves_to_consider.append((i, move_possible_4)) elif self.board_dict[i[0] - 1, i[1]] == 'red': move_possible_5 = 0.6 moves_to_consider.append((i, move_possible_5)) elif self.board_dict[i[0] -1, i[1] -1] == 'red': move_possible_6 = 0.3 moves_to_consider.append((i, move_possible_6)) except KeyError: None # best_move = '' # biggest_move = moves_to_consider[0][1] # for i in range(len(moves_to_consider)): # if moves_to_consider[i][1] > biggest_move: # biggest_move = moves_to_consider[i][1] # best_move = moves_to_consider[i][0] best_move = moves_to_consider return best_move new_game = Board('red') new_game.board() new_game.weird_board() turn = 0 x = None while x != 'done': if turn == 0: board_column = int(input('Please input a column number from (0-6) ')) new_game.piece_drop(board_column) new_game.board_look() print(new_game.availiable_moves()) turn += 1 else: #print(new_game.availiable_moves()) # print(new_game.turn) print(new_game.AI()) # board_column = int(input('Please input a column number from (0-6) ')) # AI_move = new_game.AI() # column_AI = AI_move[0] # new_game.piece_drop(board_column) # new_game.board_look() # print(new_game.availiable_moves()) turn = 0 vz = new_game.win_checker() if vz != None: print(vz) x = 'done'
9a6235c0a5fc8d276e6011b1304da6487438f7d1
[ "Python" ]
3
Python
faraz176/Connect_4_Ai
b7a77e45df36fcfec981162c4f7cb5bfdf7a07ea
ef480e8d6c3bcc9b668a725866270d8a56d91a33
refs/heads/master
<file_sep>''' AUTHOR: principio LAST EDITED: 2015-06-04 22:34:31 DESCRIPTION: Circle item class. KNOWN ISSUES: *> Will crash if anything on OpenGL side fails (which, mind you, was barely tested). ''' from helpers import getRandomColor, load_GLshaders import constants as const import geometry import pyglet from shape import Shape class Circle(Shape, geometry.Circle): def __init__(self, center, radius): Shape.__init__(self, center-radius, radius*2, radius*2) geometry.Circle.__init__(self, center, radius) # Normalization needed for OpenGL color model (vec4([0...1])) self.color = getRandomColor() #Load static shaders. Since we have no fallback option if this fails, ignore all exceptions. shaders=load_GLshaders() def render(self): self.set_colliding_flag() self.shaders.bind() scalex = 2/self.SCENE_WIDTH # Set scale factors to width/height reciprocals: this will map pixels to OpenGL coordinates scaley = 2/self.SCENE_HEIGHT relative_scalex = scalex*(self.radius + const.SMOOTH_WIDTH) # Determine relative scale factors: scale with respect to radius relative_scaley = scaley*(self.radius + const.SMOOTH_WIDTH) # We add smooth_width here because the transition ring is also part of the circle self.shaders.uniformi(b'paintBorder', self.colliding) # Whether the border should be painted # Center is mapped to correct offset (coords start from center, so -1+coord is its translation to lower left corner, where Pyglet coords start) # We divide center coords by relative scale factors, because they are NOT to be scaled with respect to radius, only distances are. self.shaders.uniformf(b'center', (-1+self.x*scalex)/relative_scalex, (-1+self.y*scaley)/relative_scaley) self.shaders.uniformf(b'smoothWidth', const.SMOOTH_WIDTH) self.shaders.uniformf(b'borderWidth', const.BORDER_WIDTH) self.shaders.uniformf(b'circleColor', *self.color) if(self.colliding): self.shaders.uniformf(b'borderColor', *const.COLOR_COLLIDING[self.colliding]) # Now, all distances will be scaled with respect to the radius of the circle. self.shaders.uniform_matrixf(b'scaleMatrix', [relative_scalex, 0, 0, 0,\ 0, relative_scaley, 0, 0,\ 0, 0, 1, 0,\ 0, 0, 0, 1]) # Create a texture, that, when translated to (-1,-1), the Pyglet coord origin, will cover the entire scene (we will scale it later in shaders). tex=pyglet.image.Texture.create(2, 2) # ...and translate it as needed. tex.blit(-1, -1) self.shaders.unbind() def updateBounds(self): self.bounds.x, self.bounds.y = self-self.radius self.bounds.width = self.bounds.height = self.radius * 2 def collidingWith(self, item): # Item is a circle if(type(self) is type(item)): return const.COLLISION_CIRCLE if geometry.check_collide_circles(self, item) else const.COLLISION_NONE # Item is a polygon elif(issubclass(type(item), geometry.Polygon)): return const.COLLISION_SAT if geometry.check_collide_polygon_circle(item.dots, self, item.normals) else const.COLLISION_NONE else: raise TypeError("Only shapes can be checked for collisions") <file_sep>''' AUTHOR: principio LAST EDITED: 2015-06-04 22:41:28 DESCRIPTION: Polygon item class. Since rects use a different algorithm, they do not belong. KNOWN ISSUES: *> Polygon antialiasing unavailable without hacking pyglet code or writing custom shaders. Sad, sad. ''' from helpers import getRandomColor import constants as const import geometry import pyglet.gl as gl from pyglet.graphics import draw from shape import Shape class Polygon(Shape, geometry.Polygon): # The respresentation of a polygon is a list of dots (vertices) def __init__(self, dots): # Calculate bounds as minimum/maximum values of x and y for all dots max_x = max(x for x, y in dots) min_x = min(x for x, y in dots) max_y = max(y for x, y in dots) min_y = min(y for x, y in dots) # This will be the bounding box. Shape.__init__(self, geometry.Point(min_x, min_y), max_x-min_x, max_y-min_y) geometry.Polygon.__init__(self, dots) self.gl_vertices = self.get_gl_vertices() self.color=getRandomColor() def render(self): self.set_colliding_flag() self.gl_vertices = self.get_gl_vertices() # Without this, number of points in polygon is undefined to pyglet. gl.glEnable(gl.GL_PRIMITIVE_RESTART) gl.glPrimitiveRestartIndex(-1) gl.glEnable(gl.GL_LINE_SMOOTH) vertices = round(len(self.gl_vertices)/2) gl.glColor4f(*self.color) draw(vertices, gl.GL_POLYGON, ('v2f', self.gl_vertices)) if(self.colliding): gl.glLineWidth(const.BORDER_WIDTH) gl.glColor4f(*const.COLOR_COLLIDING[self.colliding]) draw(vertices-1, gl.GL_LINE_LOOP, ('v2f', self.gl_vertices[:-2])) # Exclude last vertex (the primitive restart) gl.glDisable(gl.GL_LINE_SMOOTH) def updateBounds(self): # Find maxima of x and y coordinates max_x = max(x for x, y in self.dots) min_x = min(x for x, y in self.dots) max_y = max(y for x, y in self.dots) min_y = min(y for x, y in self.dots) self.bounds.x, self.bounds.y = min_x, min_y self.bounds.width = max_x-min_x self.bounds.height = max_y-min_y def collidingWith(self, item): # First, check if bounding rects collide. If not, there is no collision. if(not geometry.check_collide_rectangles(self.bounds, item.bounds)): return const.COLLISION_NONE # Item is a polygon if(type(self) is type(item)): # If both are rectangles, use rectangle-specific algo if(hasattr(self, 'rectangle') and hasattr(item, 'rectangle')): # Rectangle collision is equivalent to bounds collision, and we've already checked that return True else: return const.COLLISION_SAT if\ geometry.check_collide_polygons(self.dots, item.dots, self.normals, item.normals) else const.COLLISION_NONE # Item is a circle elif(issubclass(type(item), geometry.Circle)): return const.COLLISION_SAT if geometry.check_collide_polygon_circle(self.dots, item, self.normals) else const.COLLISION_NONE else: raise TypeError("Only shapes can be checked for collisions") <file_sep># Original copyright <NAME> 2008. # Modified by <NAME> 2015. # # Distributed under the Boost Software License, Version 1.0 # (see http://www.boost.org/LICENSE_1_0.txt) ''' AUTHOR: principio LAST EDITED: 2015-06-04 22:44:50 DESCRIPTION: OpenGL shader program convenience class. KNOWN ISSUES: *> VERY liberal in terms of error-checking; better pray that nothing fails. *> Barely tested ''' import pyglet.gl as gl from ctypes import * class Shader: # We can theoretically have more that one source string per shader. # They will be concatenated later. def __init__(self, vert = [], frag = []): self.handle = gl.glCreateProgram() self.linked = False self.createShader(vert, gl.GL_VERTEX_SHADER) self.createShader(frag, gl.GL_FRAGMENT_SHADER) self.link() def createShader(self, strings, type): count = len(strings) #If no code if count < 1: return shader = gl.glCreateShader(type) # ctypes magic: convert python [strings] to C (char**). src = (c_char_p * count)(*strings) gl.glShaderSource(shader, count, cast(pointer(src), POINTER(POINTER(c_char))), None) gl.glCompileShader(shader) # Retrieve the compile status status = c_int(0) gl.glGetShaderiv(shader, gl.GL_COMPILE_STATUS, byref(status)) # If compilation failed, get log and abort. if not status: gl.glGetShaderiv(shader, gl.GL_INFO_LOG_LENGTH, byref(status)) log = create_string_buffer(status.value) gl.glGetShaderInfoLog(shader, status, None, log) raise Exception("Compiling shaders failed: {0}".format(log.value)) else: # If all is well, attach the shader to the program gl.glAttachShader(self.handle, shader); def link(self): gl.glLinkProgram(self.handle) # Retrieve the link status status = c_int(0) gl.glGetProgramiv(self.handle, gl.GL_LINK_STATUS, byref(status)) # If linking failed, get log and abort. if not status: #Retrieve the log and pass it up with an exception. gl.glGetProgramiv(self.handle, gl.GL_INFO_LOG_LENGTH, byref(status)) log = create_string_buffer(status.value) gl.glGetProgramInfoLog(self.handle, status, None, log) raise Exception("Linking shaders failed {0}".format(log.value)) else: self.linked = True def bind(self): gl.glUseProgram(self.handle) # Since we don't really care which program is bound when we unbind it, # this doesn't require an instance to be called on. @classmethod def unbind(self): gl.glUseProgram(0) # Upload an integer or a vector of integers as a uniform def uniformi(self, name, *vals): if len(vals) in range(1, 5): # Select the correct function { 1 : gl.glUniform1i, 2 : gl.glUniform2i, 3 : gl.glUniform3i, 4 : gl.glUniform4i # Retrieve the uniform location, and set }[len(vals)](gl.glGetUniformLocation(self.handle, name), *vals) # Upload a float or a vector of floats as a uniform def uniformf(self, name, *vals): if len(vals) in range(1, 5): # Select the correct function { 1 : gl.glUniform1f, 2 : gl.glUniform2f, 3 : gl.glUniform3f, 4 : gl.glUniform4f # Retrieve the uniform location, and set }[len(vals)](gl.glGetUniformLocation(self.handle, name), *vals) # Upload a uniform matrix def uniform_matrixf(self, name, mat): # Obtian the uniform location loc = gl.glGetUniformLocation(self.handle, name) # Uplaod the 4x4 floating point matrix gl.glUniformMatrix4fv(loc, 1, False, (c_float * 16)(*mat)) <file_sep>''' AUTHOR: principio LAST EDITED: 2015-06-04 21:33:47 DESCRIPTION: Shape parentclass. All shapes should subclass this. KNOWN ISSUES: ''' import constants as const import geometry class Shape: # This implements general collision-related abstractions and 'declares' # methods that will be invoked from the main module and, therefore, have to be implemented. #These are specific to a particular shape and are implemeted in subclasses. ''' def contains(self, point) #[V] Will be pulled in from geometry.* def render(self) def collidingWith(self, item) ''' # Every item is defined by at least a pair of coords. # These coords and width and height, as far as this class is concerned, # delimit a bounding rect for this shape. # Generally, all shape-independent stuff goes here. def __init__(self, origin, width, height): self.bounds = geometry.Rectangle(origin, width, height) self.collisions=[] self.colliding = 0 @classmethod def tellScreenBounds(this, width, height): this.SCENE_START_HEIGHT = height*const.BUTTON_HEIGHT_FACTOR this.SCENE_WIDTH=width this.SCENE_HEIGHT=height # For an arbitrary 2D shape, parallel translation by a vector is well-defined. # moveTo(point), however, is not (what is the anchor point of a pentagon, for instance?) # Therefore, external code can only use this subroutine for shape translation. def moveBy(self, trans_vector): # If the item cannot fit in given bounds, restrict movement. if(self.bounds.width > self.SCENE_WIDTH or self.bounds.height > self.SCENE_HEIGHT): return False self += trans_vector # Move the item itself self.bounds += trans_vector # Move bounding rect accordingly self.adjustBounds() # Make sure the shape stays in current window # Returns whether def adjustBounds(self): adjust_vector = geometry.Vector(0, 0) # Lower/left edges if(self.bounds.x<0): adjust_vector.x = -self.bounds.x if(self.bounds.y<self.SCENE_START_HEIGHT): adjust_vector.y = self.SCENE_START_HEIGHT-self.bounds.y # Upper/right edges x_overflow = self.bounds.x+self.bounds.width - self.SCENE_WIDTH y_overflow = self.bounds.y+self.bounds.height - self.SCENE_HEIGHT if(x_overflow>0): adjust_vector.x = -x_overflow if(y_overflow>0): adjust_vector.y = -y_overflow if(not adjust_vector.isNullVector()): self.moveBy(adjust_vector) return True def getCollidingItems(self, items): collisions = [] for item in items: if item is not self: collision_type = self.collidingWith(item) if(collision_type != const.COLLISION_NONE): collisions.append((item, collision_type)) return collisions # item informs us that it is colliding with self. Record that. def adviseCollision(self, item, coltype): if (item, coltype) not in self.collisions: self.collisions.append((item, coltype)) # Ditto, but this tells us that item is no longer colliding with self. def adviseNoCollision(self, item): # By iterating through all collision records, for collision in self.collisions: # Find the one where the items matches the advice sender if(collision[0] is item): self.collisions.remove(collision) # Get items currently colliding with self; update local item list accordingly; # inform other items about the collision state. def updateCollisions(self, items): new_collisions=self.getCollidingItems(items) for collision in self.collisions: if collision not in new_collisions: collision[0].adviseNoCollision(self) self.collisions.remove(collision) for collision in new_collisions: if collision not in self.collisions: collision[0].adviseCollision(self, collision[1]) self.collisions.append(collision) # Before actually rendering anything, set the colliding flag appropriately. def set_colliding_flag(self): self.colliding = const.COLLISION_NONE for item, coltype in self.collisions: self.colliding = coltype if coltype > self.colliding else self.colliding<file_sep>''' AUTHOR: principio LAST EDITED: 2015-06-04 22:30:18 DESCRIPTION: This is the main class of a simple collision detection demo written in Python (Pyglet framework). KNOWN ISSUES: *> Segfaults on the only Windows machine I have at my disposal. Appears to be a Python issue. *> On Linux/X11, going fullscreen will sometimes mess up the picture. Dragging any item helps. ''' import pyglet import pyglet.gl as gl from pyglet.window import key, mouse import constants as const import helpers import geometry from shape import Shape from circle import Circle from polygon import Polygon from button import Button class MainWindow(pyglet.window.Window): def __init__(self): super().__init__(resizable=True) # Seemingly no way to toggle resizability # without passing the flag to parent constructor self.maximize() # Start maximized self.set_minimum_size(*const.MAIN_MIN_SIZE) self.set_caption(const.MAIN_TITLE) # Blend alpha so that the more shapes overlap, the less transparent the intersection area. gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) pyglet.clock.set_fps_limit(const.FPS) self.items = [] # All items rendered within this window self.dragged_items = [] # Items being dragged at the moment self.move_vectors = {} # Vectors for random movement self.fullscreen_flag = False self.multidrag_flag = True # Whether all overlapping items or only the uppermost one should be dragged. self.random_move_flag = False # Whether shapes should be automatically moved self.creation_flags = const.CREATE_NONE # This will be popped off when needed self.push_handlers(on_mouse_press = self.select_items, on_mouse_drag = self.drag_items, on_mouse_release = self.release_items) self.push_handlers(on_mouse_press = self.check_buttons) self.update_buttons() def add_item(self, item): if(issubclass(type(item), Shape)): self.items.append(item) self.check_collisions([item]) else: raise NotImplementedError("Only Shape subclasses can be added to this scene.") def update_buttons(self): width = self.width*const.BUTTON_WIDTH_FACTOR height = self.height*const.BUTTON_HEIGHT_FACTOR self.buttons=[Button('Add rectangles', 0, 0, width, height, self.begin_creation, [const.CREATE_RECT], self.end_creation), Button('Add circles', width, 0, width, height, self.begin_creation, [const.CREATE_CIRCLE], self.end_creation), Button('Add polygons', 2*width, 0, width, height, self.begin_creation, [const.CREATE_POLY], self.end_creation), Button('Enable random motion', 3*width, 0, width, height, self.toggle_random, [], self.toggle_random, []), Button('Enable multidrag', 4*width, 0, width, height, self. toggle_multidrag, [], self.toggle_multidrag, [], True)] def check_collisions(self, items): for item in items: item.updateCollisions(self.items) def toggle_random(self): self.random_move_flag = not self.random_move_flag if(self.random_move_flag): pyglet.clock.schedule(self.random_move) else: pyglet.clock.unschedule(self.random_move) def toggle_multidrag(self): self.multidrag_flag = not self.multidrag_flag # Move items randomly by pre-generated vectors. def random_move(self, dt): for item in self.items: try: vector = self.move_vectors[id(item)] except: # If the vector does not exist yet, create it vector = geometry.Vector.fromTuple(helpers.getRandomTranslation()) self.move_vectors[id(item)] = vector # IF the vector has been shortened by too much, make a new one if(vector.length < const.AUTO_SPEED): vector = geometry.Vector.fromTuple(helpers.getRandomTranslation()) self.move_vectors[id(item)] = vector # Current transition vector is computed from the direction of the # principal transition vector and predefined speed current_trans = vector.normalized() * const.AUTO_SPEED item.moveBy(current_trans) # We decrement the translation vector by current vector vector.shortenBy(current_trans) self.check_collisions(self.items) def on_draw(self): self.clear() for button in self.buttons: button.render() for item in self.items: item.render() def on_resize(self, width, height): # Resize GL viewport gl.glViewport(0, 0, width, height) gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() gl.glOrtho(0, width, 0, height, -1, 1) gl.glMatrixMode(gl.GL_MODELVIEW) # Inform all items of the new dimensions and adjust their positions accordingly Shape.tellScreenBounds(width, height) for item in self.items: item.adjustBounds() # Update button positions: they are supposed to be dynamically sized self.update_buttons() def check_buttons(self, x, y, button, modifiers): status = False if(button == mouse.LEFT): for button in self.buttons: status |= button.tellClicked(x, y) if(status): return True # Don't let anyone else handle this event # Builds a list of items that could be dragged after this mouse_press. # Caveat: only these items are deemed to be "selected", i.e. deletion etc # can only be invoked on them while they are being dragged. def select_items(self, x, y, button, modifiers): for item in self.items[::-1]: #Start with the uppermost item if(item.contains(geometry.Point(x, y))): self.dragged_items.append(item) if(not self.multidrag_flag): # If no multidrag, return when found the uppermost selected item return True # Moves selected items with the cursor. Performance would benefit from, moving the # collision detection to on_draw(), since no one cares about collisions unless # they are indicated during rendering, but there is a _miniscule_ chance # that the button will be realeased in between two on_draw()'s. Better play it safe. def drag_items(self, x, y, dx, dy, buttons, modifiers): for item in self.dragged_items: item.moveBy(geometry.Vector(dx, dy)) self.check_collisions(self.dragged_items) # Clears the list of items def release_items(self, x, y, button, modifiers): if(button == mouse.LEFT): self.dragged_items.clear() # Handle key presses. def on_key_press(self, symbol, modifiers): if(modifiers and key.MOD_CTRL): # On CTRL+F, toggle fullscreen if(symbol == key.F): self.fullscreen_flag = not self.fullscreen_flag self.set_fullscreen(self.fullscreen_flag) # On CTRL+Q, exit if(symbol == key.Q): window.dispatch_event('on_close') # On Delete, remove all items that are currently being dragged if(symbol == key.DELETE): for item in self.dragged_items: self.items.remove(item) self.check_collisions(self.items) # Dispatch default closing event on Escape. if(symbol == key.ESCAPE): window.dispatch_event('on_close') def begin_creation(self, shape): # Pop all handlers off and delete previous item reference try: while 1: self.pop_handlers() except: pass try: del self.temp_item except: pass # Set the flag and push appropriate handlers self.creation_flags = shape if(self.creation_flags == const.CREATE_RECT): self.push_handlers(on_mouse_press = self.rect_on_click, on_mouse_drag = self.rect_on_drag, on_mouse_release = self.rect_on_release) elif(self.creation_flags == const.CREATE_CIRCLE): self.push_handlers(on_mouse_press = self.circle_on_click, on_mouse_drag = self.circle_on_drag, on_mouse_release = self.circle_on_release) elif(self.creation_flags == const.CREATE_POLY): self.push_handlers(on_mouse_press = self.polygon_on_click) # Push UI handlers on the top self.push_handlers(on_mouse_press = self.check_buttons) def end_creation(self): # Complete the polygon if(self.creation_flags == const.CREATE_POLY): if(len(self.temp_item.dots) <= 3): self.items.remove(self.temp_item) del self.temp_item # Pop all handlers try: while 1: self.pop_handlers() except: pass # Push itemdrag handlers self.push_handlers(on_mouse_press = self.select_items, on_mouse_drag = self.drag_items, on_mouse_release = self.release_items) # Push UI handler self.push_handlers(on_mouse_press = self.check_buttons) self.creation_flag = const.CREATE_NONE # ~~~~~~~~~~ CIRCLE creation subroutines ~~~~~~~~~~ def circle_on_click(self, x, y, button, modifiers): if(button == mouse.LEFT): self.temp_item = Circle(geometry.Point(x, y), 0) self.add_item(self.temp_item) def circle_on_drag(self, x, y, dx, dy, buttons, modifiers): try: # Radius is the distance between the starting point and current point self.temp_item.radius = geometry.Vector(x-self.temp_item.x, y-self.temp_item.y).length self.temp_item.updateBounds() self.check_collisions([self.temp_item]) except AttributeError: pass def circle_on_release(self, x, y, button, modifiers): try: if(button == mouse.LEFT): # Don't store zero-width circles if (self.temp_item.radius == 0): self.items.remove(self.temp_item) del self.temp_item except AttributeError: pass # ~~~~~~~~~~ RECTANGLE creation subroutines ~~~~~~~~~~ def rect_on_click(self, x, y, button, modifiers): if(button == mouse.LEFT): self.temp_item = Polygon.fromRectangle(geometry.Point(x, y), 0, 0) self.add_item(self.temp_item) def rect_on_drag(self, x, y, dx, dy, buttons, modifiers): try: self.temp_item.width += dx self.temp_item.height += dy self.temp_item.updateFromRectangle() self.temp_item.updateBounds() self.check_collisions([self.temp_item]) except AttributeError: pass def rect_on_release(self, x, y, button, modifiers): try: if(button == mouse.LEFT): # Don't store zero-width/height rectangles if (self.temp_item.width == 0 or self.temp_item.height == 0): self.items.remove(self.temp_item) del self.temp_item return True except AttributeError: pass # ~~~~~~~~~~ POLYGON creation subroutines ~~~~~~~~~~ def polygon_on_click(self, x, y, button, modifiers): if(button == mouse.LEFT): if(not hasattr(self, 'temp_item')): self.temp_item = Polygon([geometry.Point(x, y)]) self.add_item(self.temp_item) else: self.temp_item.add_point(geometry.Point(x, y)) self.check_collisions([self.temp_item]) if (__name__=="__main__"): window = MainWindow() pyglet.app.run() <file_sep>''' AUTHOR: principio LAST EDITED: 2015-06-04 22:24:24 DESCRIPTION: Geometrical classes and algorithms KNOWN ISSUES: Names will collide, import by name only. ''' import math from copy import copy # Get normals to a polygon's sides def get_polygon_normals(polygon): normals = [] prevertex=polygon[0] for vertex in polygon[1:]: normal = Vector.fromTuple(prevertex-vertex).normal() normal.normalize() normals.append(normal) prevertex=vertex return normals # Get the only normal for circle-polygon collision (from centre to the nearest point) def _get_circle_to_polygon_normal(polygon, circle): min_dist = polygon[0].dist(circle) closest = polygon[0] for dot in polygon[1:]: dist = dot.dist(circle) if(dist<min_dist): closest=dot min_dist=dist normal = Vector.fromTuple(circle-closest) normal.normalize() return [normal] # Dot product of two 2D vectors def dot(vector, other): return (vector.x*other.x+vector.y*other.y) # Vector product (multiplied as 2x1 matrices) def vec(vector, other): return Vector(vector.x*other.x, vector.y*other.y) # Cross product of vectors OA and OB. def cross(o, a, b): return (a.x-o.x)*(b.y-o.y) - (a.y-o.y)*(b.x-o.x) # Project a polygon onto an axis def _project_polygon(polygon, axis): min_point = dot(polygon[0], axis) max_point = min_point for vertex in polygon: current_point = dot(vertex, axis) min_point = min(min_point, current_point) max_point = max(max_point, current_point) return (min_point, max_point) def _project_circle(circle, axis): center_point = dot(circle, axis) min_point = center_point-circle.radius max_point = center_point+circle.radius return (min_point, max_point) # Check if two projections overlap def _overlap(proj1, proj2): # ...1[0]....2[0]....1[1].....2[1] is when polygons overlap. # Then, the signs of difference between each .[0] and .[1] are the same d1 = proj1[0]-proj2[1] d2 = proj2[0]-proj1[1] return (d1*d2>0) def check_collide_polygons(first, second, first_normals, second_normals): normals = first_normals + second_normals for normal in normals: first_p = _project_polygon(first, normal) second_p = _project_polygon(second, normal) if(not _overlap(first_p, second_p)): return False return True def check_collide_polygon_circle(polygon, circle, polygon_normals): normals = polygon_normals + _get_circle_to_polygon_normal(polygon, circle) for normal in normals: polygon_p = _project_polygon(polygon, normal) circle_p = _project_circle(circle, normal) if(not _overlap(polygon_p, circle_p)): return False return True # Non-SAT stuff starts here # Convex hull of a set of points, stolen from Wikibooks ftw def convex_hull(dots): # Do nothing for non-polygons if(len(dots)<3): return dots # Remove duplicates and sort as tuples dots = sorted(set(dots), key=lambda a: (a.x, a.y)) upper_hull = [] lower_hull=[] for dot in dots: # If the angle is counter-clockwise, pop the outliers off while(len(upper_hull) >=2 and cross(upper_hull[-2], upper_hull[-1], dot) <= 0): upper_hull.pop() upper_hull.append(dot) for dot in reversed(dots): # Ditto, but in opposite direction while(len(lower_hull) >=2 and cross(lower_hull[-2], lower_hull[-1], dot) <= 0): lower_hull.pop() lower_hull.append(dot) return lower_hull[:-1] + upper_hull[:-1] def check_collide_rectangles(first, second): return (((first.x>=second.x and first.x<=second.x+second.width) or #X1...x3...X2 (second.x>=first.x and second.x<=first.x+first.width)) and #x3...X1...x4 ((first.y>=second.y and first.y<=second.y+second.height) or #Y1...y3...Y2 (second.y>=first.y and second.y<=first.y+first.height))) #y3...Y1...y4 def check_collide_circles(first, second): return first.dist(second) <= first.radius+second.radius #O1O2 <= R1+R2 class Point: def __init__(self, x, y): super().__init__() # Needed for cooperative inheritance self.x=x self.y=y @classmethod def fromTuple(cls, coord_tuple): return cls(*coord_tuple) def dist(self, other): return math.sqrt((self.x-other.x)*(self.x-other.x)+(self.y-other.y)*(self.y-other.y)) def __add__(self, other): try: return Point(self.x+other.x, self.y+other.y) except: # If other has no (x,y), assume it's scalar return Point(self.x+other, self.y+other) def __iadd__(self, other): try: self.x += other.x self.y += other.y except AttributeError: self.x += other self.y += other return self def __sub__(self, other): try: return Point(self.x-other.x, self.y-other.y) except AttributeError: # If other has no (x,y), assume it's scalar return Point(self.x-other, self.y-other) def __isub__(self, other): try: self.x -= other.x self.y -= other.y except: self.x -= other self.y -= other return self def __mul__(self, other): try: # If this type is a container, do matrix multiplication return vec(self, other) except AttributeError: # Else, assume that other is scalar return Point(self.x*other, self.y*other) def __imul__(self, other): self = self*other return self def __truediv__(self, other): return Point(self.x/other, self.y/other) def __itruediv__(self, other): self.x/=other self.y/=other return self def __iter__(self): self.index=-1 return self def __next__(self): if(self.index<1): self.index+=1 return self[self.index] else: raise StopIteration def __getitem__(self, index): if(index==0): return self.x elif(index==1): return self.y def __len__(self): return 2 def __repr__(self): return '({0},{1})'.format(self.x, self.y) # Vector are the same as points, for the purposes of this class Vector(Point): def __init__(self, x, y): super().__init__(x, y) self._updateLength() def __iadd__(self, other): self=super().__iadd__(other) self._updateLength() return self def __isub__(self, other): self=super().__isub__(other) self._updateLength() return self def __imul__(self, other): self=super().__imul__(other) self._updateLength() return self def __itruediv__(self, other): self=super().__itruediv__(other) self._updateLength() return self def _updateLength(self): self.length = math.sqrt(self.x*self.x + self.y*self.y) def isNullVector(self): return self.x==0 and self.y==0 def shortenBy(self, vector): self.x -= -vector.x if (self.x>0) != (vector.x>0) else vector.x self.y -= -vector.y if (self.y>0) != (vector.y>0) else vector.y self._updateLength() def normal(self): return Vector(self.y, -self.x) def normalize(self): if(self.length>0): self /= self.length self.length = 1 def normalized(self): proxy=copy(self) proxy.normalize() return proxy # Shapes will inherit from point, as they necessarily have a point-of-origin class Rectangle(Point): def __init__(self, origin, width, height): super().__init__(*origin) self.width=width self.height=height setTo = __init__ def contains(self, point): return (self.x<=point.x) and (self.x+self.width>=point.x)\ and (self.y<=point.y) and (self.y+self.height>=point.y) #If X1...x...X2 and Y1...y...Y2. def __repr__(self): return 'Bottom-left @ {0} width={1} height={2}\n'.format(super().__repr__(), self.width, self.height) class Circle(Point): def __init__(self, origin, radius): super().__init__(*origin) self.radius = radius def contains(self, point): return (point.x-self.x)*(point.x-self.x)+(point.y-self.y)*(point.y-self.y) <= self.radius*self.radius # (x-m)^2+(y-n)^2 <= R^2 def __repr__(self): return 'Center @ {0} radius={1}\n'.format(super().__repr__(), self.radius) # Polygon will _not_ inherit from point: polygons have no origin class Polygon: def __init__(self, dots): if(dots[0] != dots[-1]): dots.append(copy(dots[0])) # Append first vertex to the end, making the polygon enclosed self.dots = dots self.normals = get_polygon_normals(self.dots) # Determine if the point tested lies within the polygon. # The algorithm is simple: for each two consecutive vertices of the polygon, we obtain # the equation for the line that contains the segment delimited by these two points: # (y-y1) (x-x1) (y-y1) # ------- = -------; Then X = ------- * (x2-x1) + x1 is the equation for when X lies on the line. # (y2-y1) (x2-x1) (y2-y1) # # Therefore, X <> ... signifies cases when the point lies off on the side with respect to the line. # We consider all segments that have the examined point in their y-range. If the number of segments # for which the point lies on the same side is even, the point lies within the polygon. def contains(self, point): # But first, check if bounding rect contains the point. if(not self.bounds.contains(point)): return False prevertex = self.dots[-1] inside = False for vertex in self.dots: if(((vertex.y>point.y) != (prevertex.y>point.y)) # Y1...y...Y2 and (point.x < (prevertex.x-vertex.x)*(point.y-vertex.y)/(prevertex.y-vertex.y) + vertex.x)): inside = not inside prevertex=vertex return inside @classmethod def fromRectangle(cls, origin, width, height): instance = cls([Point(origin.x, origin.y), Point(origin.x, origin.y+height), Point(origin.x+width, origin.y+height), Point(origin.x+width, origin.y)]) instance.rectangle = True instance.width = width instance.height = height instance.x, instance.y = instance.dots[0] return instance def updateFromRectangle(self): try: Polygon.__init__(self, [Point(self.x, self.y), Point(self.x, self.y+self.height), Point(self.x+self.width, self.y+self.height), Point(self.x+self.width, self.y)]) except: pass @classmethod def fromList(cls, lst): return cls(list(map(Point.fromTuple, lst))) def add_point(self, point): self.dots.insert(len(self.dots)-1, point) self.dots = convex_hull(self.dots) self.dots.append(copy(self.dots[0])) self.updateBounds() self.normals = get_polygon_normals(self.dots) def get_gl_vertices(self): vertices = [coord for dot in self.dots for coord in dot] # Transform list of tuples into a flat list vertices += [-1, -1] # Restart trigger for OpenGL. Repeated twice because vertex data has to be 2-aligned return vertices # We shift a polygon by translating each point thereof by the translation vector def __iadd__(self, point): for dot in self.dots: dot += point return self def __isub__(self, point): for dot in self.dots: dot -= point return self def __repr__(self): representation = '\n' for dot in self.dots: representation += dot.__repr__()+'\n' return representation <file_sep>''' AUTHOR: principio LAST EDITED: 2015-06-04 22:37:34 DESCRIPTION: This holds the constants that pertain to this program KNOWN ISSUES: ''' FPS = 40 #Smooth enough on my machine, subject to decrement if drawing code becomes too bloated. VERTEX_SHADER_SRC = "vertex.vert" FRAGMENT_SHADER_SRC = "fragment.frag" MAIN_TITLE = "Collision detector" #Width could be larger, depending on the window dectorations. Let the WM handle that. MAIN_MIN_SIZE = (100, 100) BORDER_WIDTH = 2.0 #Outline width for colliding shapes SMOOTH_WIDTH = 2.0 #Transition span for circles BUTTON_WIDTH_FACTOR = 1/5 BUTTON_HEIGHT_FACTOR = 1/10 AUTO_TRANS_MAX = 300 # Maximum length of a random translation vector AUTO_SPEED = 200/FPS # Yes, this is ugly. No going to change anytime soon. #The higher the number, the higher the priority when displaying COLLISION_NONE, COLLISION_RECT, COLLISION_CIRCLE, COLLISION_SAT = 0, 1, 2, 3 CREATE_NONE, CREATE_RECT, CREATE_CIRCLE, CREATE_POLY = 0, 1, 2, 3 COLOR_WHITE = (1.0, 1.0, 1.0, 1.0) COLOR_BLACK = (0, 0, 0, 1.0) COLOR_RED = (1.0, 0, 0, 1.0) COLOR_GREEN = (0, 1.0, 0, 1.0) COLOR_BLUE = (0, 0, 1.0, 1.0) COLOR_LOWEST = 100/255 #Lower and upper limits for color generation COLOR_HIGHEST = 200/255 COLOR_ALPHA = 150/255 #Let alpha be uniform for all shapes COLOR_COLLIDING = {COLLISION_RECT: COLOR_RED, COLLISION_CIRCLE: COLOR_BLUE, COLLISION_SAT: COLOR_GREEN} COLOR_BUTTON = (0.0, 0.55, 0.45, COLOR_ALPHA) COLOR_BUTTON_TOGGLED = (0.0, 0.35, 0.25, COLOR_ALPHA*1.2) COLOR_BUTTON_BORDER = (0.0, 0.65, 0.55, COLOR_ALPHA) # Pyglet.text.Label uses byte values instead of floats COLOR_BUTTON_TEXT = (255, 255, 255, 255) <file_sep>''' AUTHOR: principio LAST EDITED: 2015-06-04 22:26:08 DESCRIPTION: Helper functions KNOWN ISSUES: *> Probably too small for a separate module ''' import constants as const from random import uniform, seed from glhelper import Shader # Get a random RGBA vector. Alpha is constant and defined in constants.py, as well as generation bounds. def getRandomColor(): seed() return tuple([round(uniform (const.COLOR_LOWEST, const.COLOR_HIGHEST)) for i in range(3)])+ (const.COLOR_ALPHA,) def getRandomTranslation(): dx = uniform(-const.AUTO_TRANS_MAX, const.AUTO_TRANS_MAX) dy = uniform(-const.AUTO_TRANS_MAX, const.AUTO_TRANS_MAX) return (dx, dy) # Set up vertex and geometry shaders from source files. def load_GLshaders(vertex_src=const.VERTEX_SHADER_SRC, fragment_src=const.FRAGMENT_SHADER_SRC): vertex_f=open(vertex_src, 'rb') vertex_code=vertex_f.read() vertex_f.close() fragment_f=open(fragment_src, 'rb') fragment_code=fragment_f.read() fragment_f.close() return Shader([vertex_code], [fragment_code]) <file_sep>''' AUTHOR: principio LAST EDITED: 2015-06-04 22:23:32 DESCRIPTION: Button class for UI KNOWN ISSUES: *> Barely tested ''' import constants as const import pyglet from pyglet.graphics import draw from pyglet.gl import GL_QUADS, GL_LINE_LOOP, glColor4f class Button: ''' Params: text - the text to display x, y - lower bottom point width, height - dimensions of the button oncallback, offcallback - callback functions to be called when the button is toggled on/off *_params - params to pass to the respective functions ''' def __init__(self, text, x, y, width, height, oncallback=lambda:None, oncallback_param=[], offcallback=lambda:None, offcallback_param=[], toggled=False): self.text = text self.setCoords(x, y, width, height) self.toggled = toggled self.oncallback = oncallback self.oncallback_param = oncallback_param self.offcallback = offcallback self.offcallback_param = offcallback_param # Tell that a click was performed. The button will claim it (returning True) or reject it (False) def tellClicked(self, x, y): # IF bound containt the point if (self.x<=x) and (self.x+self.width>=x)\ and (self.y<=y) and (self.y+self.height>=y): self.toggled = not self.toggled if(self.toggled): self.oncallback(*self.oncallback_param) else: self.offcallback(*self.offcallback_param) return True return False def setCoords(self, x, y, width, height): self.x, self.y = x,y self.height, self.width = height, width # The label is centered self.label = pyglet.text.Label(self.text, color=const.COLOR_BUTTON_TEXT, x=x+width/2, y=y+height/2, anchor_x='center', anchor_y='center') self.gl_vertices = [self.x, self.y, self.x+width, self.y, self.x+width, self.y+height, self.x, self.y+height] def render(self): if(self.toggled): glColor4f(*const.COLOR_BUTTON_TOGGLED) else: glColor4f(*const.COLOR_BUTTON) draw(4, GL_QUADS, ('v2f', self.gl_vertices)) glColor4f(*const.COLOR_BUTTON_BORDER) draw(4, GL_LINE_LOOP, ('v2f', self.gl_vertices)) self.label.draw()
b1e19026f689405218464cb3a5138806e7dc8d72
[ "Python" ]
9
Python
principio/Final
578b179f84946e3b8f18c0905f5ff46b63126175
997631d2cdc003ea5f200dfc01208a2f229b280f
refs/heads/master
<file_sep>class ContactForm < ApplicationRecord validates :name, presence: true validates :email, presence: true, email: true validates :message, presence: true #honeypot attr_accessor :telephone validates :telephone, inclusion: { in: [''] } end
df004bec64902d5d2e42490272e2bce0bd89fd4f
[ "Ruby" ]
1
Ruby
Capt-Obviouse/portfolio-series
020c5f183c54c0336c7caf95ce949754d72b1f4b
0ddd99fcf5e925014f1fc1217c711dc2121ccfab
refs/heads/master
<repo_name>qyjandroid/h5-logutils<file_sep>/test.ts // import LogUtils from "./build/es6" // ES6 const LogUtils = require("./build/cmjs").default; // commonjs // console.log("LogUtils==", LogUtils, "===hhh==", LogLevel) //import LogUtils from "./build/es6/index"; const logLevelEnum = LogUtils.getAllLogLevel(); //2.设置筛选的log等级 LogUtils.setLogLevel(logLevelEnum.INFO); LogUtils.enable("app*"); //创建app1 log对象 const app1 = LogUtils.create("app:1"); //3.打印 log 等级日志 app1.log("log"); app1.debug("debug"); app1.info("info"); app1.warn("warn"); app1.error("error"); const app2 = LogUtils.create("app:2"); //3.打印 log 等级日志 app2.log("log"); app2.debug("debug"); app2.info("info"); app2.warn("warn"); app2.error("error"); const aa2 = LogUtils.create("aa"); aa2.log("log"); aa2.debug("debug"); aa2.info("info"); aa2.warn("warn"); aa2.error("error");<file_sep>/build/es6/index.js var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; import Log from "./Log"; import LogLevel, { LogLeve_ENUM } from "./LogLevel"; var LogUtil = (function () { function LogUtil() { var _this = this; this.instances = {}; this.defaultLogOption = { enabled: true, useColors: false, isNodeEnv: false, names: [], skips: [] }; this.setLogLevel = function (logLevel) { LogLevel.setLogLevel(logLevel); }; this.getAllLogLevel = function () { return LogLeve_ENUM; }; this.checkIsNode = function () { return false; }; this.useColors = function () { if (_this.checkIsNode()) return false; if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { return true; } if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { return false; } return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); }; this.create = function (namespaces, LogOptions) { if (LogOptions === void 0) { LogOptions = {}; } if (!namespaces) { return null; } var instance = _this.instances[namespaces]; if (instance) { return instance; } instance = new Log(namespaces, __assign(__assign(__assign({}, _this.defaultLogOption), LogOptions), { names: _this.names, skips: _this.skips })); _this.instances[namespaces] = instance; return instance; }; this.enable = function (namespaces) { var i; var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); var len = split.length; var skips = []; var names = []; for (i = 0; i < len; i += 1) { if (!split[i]) { continue; } var newNamespaces = split[i].replace(/\*/g, '.*?'); if (newNamespaces[0] === '-') { skips.push(new RegExp("^" + newNamespaces.substr(1) + "$")); } else { names.push(new RegExp("^" + newNamespaces + "$")); } } var keys = Object.keys(_this.instances); for (i = 0; i < keys.length; i += 1) { var namespacesItem = keys[i]; var instance = _this.instances[namespacesItem]; instance.setEnabled(skips, names); } _this.names = names; _this.skips = skips; }; this.destroy = function (namespaces) { var instance = _this.instances[namespaces]; if (instance) { delete _this.instances[namespaces]; } }; LogLevel.setLogLevel(LogLeve_ENUM.LOG); this.defaultLogOption.useColors = this.useColors(); this.defaultLogOption.isNodeEnv = this.checkIsNode(); this.names = []; this.skips = []; } return LogUtil; }()); var LogUtils = new LogUtil(); export default LogUtils; <file_sep>/src/custom.d.ts declare const LOG_LEVEL; <file_sep>/src/Log.ts import LogLevel, { LogLeve_ENUM } from "./LogLevel"; /* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable no-undef */ /* eslint-disable no-param-reassign */ /* eslint-disable no-bitwise */ /* * @Author: quanyj * @Date: 2020-01-07 17:38:14 * @Last Modified by: quanyj * @Last Modified time: 2020-01-14 17:43:58 */ export interface LogOptions { /** * * 开启 * @type {boolean} * @memberof LogOptions */ enabled: boolean; /** * * 是否可以使用颜色 * @type {boolean} * @memberof LogOptions */ useColors: boolean; /** * * 是否node环境 * @type {boolean} * @memberof LogOptions */ isNodeEnv: boolean; /** * * 显示日志条件 * @type {string[]} * @memberof LogOptions */ names: RegExp[]; /** * * 过滤日志条件 * @type {string[]} * @memberof LogOptions */ skips: RegExp[]; } const colors = { 1: "#00CCB1", 2: "#0099FF", 3: "#0092CC", 4: "#4EF564", 5: "#E71710" }; export default class Log { private name: string; private enabled: boolean; private useColors: boolean; private isNodeEnv: boolean; constructor(name, options: LogOptions) { this.name = name; this.enabled = options.enabled || true; this.useColors = options.useColors; this.isNodeEnv = options.isNodeEnv; this.setEnabled(options.skips, options.names); } /** * * * 获取log实例的名称 * @memberof Log */ getName = () => this.name; /** * * 设置是否开启,私有方法 * @memberof Log */ setEnabled = (skips: RegExp[], names: RegExp[]) => { if (this.name[this.name.length - 1] === '*') { this.enabled = true; return; } let i; let len; for (i = 0, len = skips.length; i < len; i += 1) { if (skips[i].test(this.name)) { this.enabled = false; return; } } //没有被规则禁用 if (names.length > 0) { for (i = 0, len = names.length; i < len; i += 1) { if (names[i].test(this.name)) { //规则中包含的显示。 this.enabled = true; return; } } //规则中不包含的隐藏 this.enabled = false; } else { //空数组显示 this.enabled = true; } } log = (...args: any[]) => { const flag = this.checkOutLog(LogLeve_ENUM.LOG); if (flag) { this.formatArgs(LogLeve_ENUM.LOG, args); console.log(...args); } } debug = (...args: any[]) => { const flag = this.checkOutLog(LogLeve_ENUM.DEBUG); if (flag) { this.formatArgs(LogLeve_ENUM.DEBUG, args); console.debug(...args); } } info = (...args: any[]) => { const flag = this.checkOutLog(LogLeve_ENUM.INFO); if (flag) { this.formatArgs(LogLeve_ENUM.INFO, args); console.info(...args); } } warn = (...args: any[]) => { const flag = this.checkOutLog(LogLeve_ENUM.WARN); if (flag) { this.formatArgs(LogLeve_ENUM.WARN, args); console.warn(...args); } } error = (...args: any[]) => { const flag = this.checkOutLog(LogLeve_ENUM.ERROR); if (flag) { this.formatArgs(LogLeve_ENUM.ERROR, args); console.error(...args); } } checkOutLog = (logLevel: any) => { const curGlobalLevel = LogLevel.getLogLevel(); if (logLevel >= curGlobalLevel && this.enabled) { return true; } return false; } formatArgs = (logType: LogLeve_ENUM, args: any[]) => { args[0] = this.coerce(args[0]); if (typeof args[0] !== 'string') { // Anything else let's inspect with %O args.unshift('%O'); } args[0] = `${(this.useColors ? '%c' : '') + this.name + (this.useColors ? ' %c' : ' ') + args[0]}`; if (!this.useColors) { return; } const c = `color: ${colors[logType]}`; args.splice(1, 0, c, 'color: inherit'); } coerce = (val: Error | string) => { if (val instanceof Error) { return val.stack || val.message; } return val; } } <file_sep>/src/LogLevel.ts /* * @Author: quanyj * @Date: 2020-01-14 17:30:19 * @Last Modified by: quanyj * @Last Modified time: 2020-01-14 17:43:44 */ export enum LogLeve_ENUM { LOG = 1, DEBUG = 2, INFO = 3, WARN = 4, ERROR = 5 } let curLevel = LogLeve_ENUM.LOG; /** * * 全局日志等级 * @export * @class LogLevel */ export default class LogLevel { static setLogLevel = (level: LogLeve_ENUM) => { curLevel = level; } static getLogLevel = () => { return curLevel; } } <file_sep>/build/cmjs/LogLevel.js "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LogLeve_ENUM; (function (LogLeve_ENUM) { LogLeve_ENUM[LogLeve_ENUM["LOG"] = 1] = "LOG"; LogLeve_ENUM[LogLeve_ENUM["DEBUG"] = 2] = "DEBUG"; LogLeve_ENUM[LogLeve_ENUM["INFO"] = 3] = "INFO"; LogLeve_ENUM[LogLeve_ENUM["WARN"] = 4] = "WARN"; LogLeve_ENUM[LogLeve_ENUM["ERROR"] = 5] = "ERROR"; })(LogLeve_ENUM = exports.LogLeve_ENUM || (exports.LogLeve_ENUM = {})); var curLevel = LogLeve_ENUM.LOG; var LogLevel = (function () { function LogLevel() { } LogLevel.setLogLevel = function (level) { curLevel = level; }; LogLevel.getLogLevel = function () { return curLevel; }; return LogLevel; }()); exports.default = LogLevel; <file_sep>/README.md # 欢迎使用 h5-logutils **h5 日志工具类,可以控制日志输出以及方便的筛选日志,不同的等级使用不同的颜色值来区分,日志更加清晰** ## 安装 ```bash $ npm install h5-logutils -S ``` ## 引用示例 #### 直接引用 build/web/h5LogUtils.js 压缩文件 ```html <body> <div>web测试日志</div> <script src="./build/web/h5LogUtils.js"></script> <script> //1.获取Log等级枚举对象。 var logLevelEnum = window.LogUtils.getAllLogLevel(); console.log(logLevelEnum); //2.设置筛选的log等级 window.LogUtils.setLogLevel(logLevelEnum.WARN); //创建app1 log对象 var app1 = window.LogUtils.create("app:1"); //3.打印 log 等级日志 app1.log("log"); app1.debug("debug"); app1.info("info"); app1.warn("warn"); app1.error("error"); </script> </body> ``` #### require 方式引入 ```js const LogUtils = require("h5-logutils").default; // commonjs //1.获取Log等级枚举对象。 const logLevelEnum = LogUtils.getAllLogLevel(); //2.设置筛选的log等级 LogUtils.setLogLevel(logLevelEnum.WARN); //创建app1 log对象 const app1 = LogUtils.create("app:1"); //3.打印 log 等级日志 app1.log("log"); app1.debug("debug"); app1.info("info"); app1.warn("warn"); app1.error("error"); ``` #### import 方式引入 ```js import LogUtils from "h5-logutils"; // ES6 //1.获取Log等级枚举对象。 const logLevelEnum = LogUtils.getAllLogLevel(); //2.设置筛选的log等级 LogUtils.setLogLevel(logLevelEnum.WARN); //创建app1 log对象 const app1 = LogUtils.create("app:1"); //3.打印 log 等级日志 app1.log("log"); app1.debug("debug"); app1.info("info"); app1.warn("warn"); app1.error("error"); ``` ## 用法 #### LogUtils 是一个日志模块工厂,允许您传入模块名称为不同的模块调试日志。 Example app.js: ```js import LogUtils from "h5-logutils"; // ES6 //1.获取全部log等级 const logLevelEnum = LogUtils.getAllLogLevel(); console.log(logLevelEnum); //2.可以根据开发模式和生产模式,设置全局显示的log等级 LogUtils.setLogLevel(logLevelEnum.WARN); ``` a.js: ```js import LogUtils from "h5-logutils"; // ES6 const logA = LogUtils.create("a"); logA.log("log"); logA.debug("debug"); logA.info("info"); logA.warn("warn"); logA.error("error"); ``` b.js: ```js import LogUtils from "h5-logutils"; // ES6 const logB = LogUtils.create("b"); logB.log("log"); logB.debug("debug"); logB.info("info"); logB.warn("warn"); logB.error("error"); ``` #### LogUtils 允许您过滤日志 #### 规则 ( "_" 显示全部, "-_" 隐藏全部, "-a" 隐藏 a, "a,b", 显示 a 和 b, "a,-b",显示 a 隐藏 b)。 Example a.js: ```js import LogUtils from "h5-logutils"; // ES6 var logA = LogUtils.create("worker:a"); logA.log("log"); logA.debug("debug"); logA.info("info"); logA.warn("warn"); logA.error("error"); ``` b.js: ```js import LogUtils from "h5-logutils"; // ES6 var logA = LogUtils.create("worker:b"); logA.log("log"); logA.debug("debug"); logA.info("info"); logA.warn("warn"); logA.error("error"); ``` c.js: ```js import LogUtils from "h5-logutils"; // ES6 var logB = LogUtils.create("c"); logB.log("log"); logB.debug("debug"); logB.info("info"); logB.warn("warn"); logB.error("error"); ``` app.js: ```js import LogUtils from "h5-logutils"; // ES6 //1:根据业务名称 worker 过滤日志 LogUtils.enable("worker:*"); //2:显示某些文件日志 "c,worker:a" 过滤日志(模块名称用逗号隔开) LogUtils.enable("c,worker:a"); //2:排除筛选出来的某一模块的日志 "worker:*,-worker:b" 过滤日志,用逗号隔开( - 用来排除日志) LogUtils.enable("worker:*,-worker:b"); ``` #### LogUtils 允许您根据业务需求打印不同的等级日志。 Example a.js: ```js import LogUtils from "h5-logutils"; // ES6 var logA = LogUtils.create("worker:a"); // 打印 LOG 日志 logA.log("log"); // 打印 DEBUG 日志 logA.debug("debug"); //打印 INFO 日志 logA.info("info"); //打印 WARN 日志 logA.warn("warn"); //打印 ERROR 日志 logA.error("error"); ``` ## Authors - quanyj <file_sep>/build/cmjs/Log.d.ts import { LogLeve_ENUM } from "./LogLevel"; export interface LogOptions { enabled: boolean; useColors: boolean; isNodeEnv: boolean; names: RegExp[]; skips: RegExp[]; } export default class Log { private name; private enabled; private useColors; private isNodeEnv; constructor(name: any, options: LogOptions); getName: () => string; setEnabled: (skips: RegExp[], names: RegExp[]) => void; log: (...args: any[]) => void; debug: (...args: any[]) => void; info: (...args: any[]) => void; warn: (...args: any[]) => void; error: (...args: any[]) => void; checkOutLog: (logLevel: any) => boolean; formatArgs: (logType: LogLeve_ENUM, args: any[]) => void; coerce: (val: string | Error) => string; } <file_sep>/build/es6/index.d.ts import Log from "./Log"; import { LogLeve_ENUM } from "./LogLevel"; declare class LogUtil { private instances; private defaultLogOption; private logLevelInstance; private names; private skips; constructor(); setLogLevel: (logLevel: LogLeve_ENUM) => void; getAllLogLevel: () => typeof LogLeve_ENUM; checkIsNode: () => boolean; useColors: () => any; create: (namespaces: string, LogOptions?: {}) => Log; enable: (namespaces: string) => void; destroy: (namespaces: string) => void; } declare const LogUtils: LogUtil; export default LogUtils; <file_sep>/build/es6/LogLevel.d.ts export declare enum LogLeve_ENUM { LOG = 1, DEBUG = 2, INFO = 3, WARN = 4, ERROR = 5 } export default class LogLevel { static setLogLevel: (level: LogLeve_ENUM) => void; static getLogLevel: () => LogLeve_ENUM; } <file_sep>/build/es6/Log.js import LogLevel, { LogLeve_ENUM } from "./LogLevel"; var colors = { 1: "#00CCB1", 2: "#0099FF", 3: "#0092CC", 4: "#4EF564", 5: "#E71710" }; var Log = (function () { function Log(name, options) { var _this = this; this.getName = function () { return _this.name; }; this.setEnabled = function (skips, names) { if (_this.name[_this.name.length - 1] === '*') { _this.enabled = true; return; } var i; var len; for (i = 0, len = skips.length; i < len; i += 1) { if (skips[i].test(_this.name)) { _this.enabled = false; return; } } if (names.length > 0) { for (i = 0, len = names.length; i < len; i += 1) { if (names[i].test(_this.name)) { _this.enabled = true; return; } } _this.enabled = false; } else { _this.enabled = true; } }; this.log = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var flag = _this.checkOutLog(LogLeve_ENUM.LOG); if (flag) { _this.formatArgs(LogLeve_ENUM.LOG, args); console.log.apply(console, args); } }; this.debug = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var flag = _this.checkOutLog(LogLeve_ENUM.DEBUG); if (flag) { _this.formatArgs(LogLeve_ENUM.DEBUG, args); console.debug.apply(console, args); } }; this.info = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var flag = _this.checkOutLog(LogLeve_ENUM.INFO); if (flag) { _this.formatArgs(LogLeve_ENUM.INFO, args); console.info.apply(console, args); } }; this.warn = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var flag = _this.checkOutLog(LogLeve_ENUM.WARN); if (flag) { _this.formatArgs(LogLeve_ENUM.WARN, args); console.warn.apply(console, args); } }; this.error = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var flag = _this.checkOutLog(LogLeve_ENUM.ERROR); if (flag) { _this.formatArgs(LogLeve_ENUM.ERROR, args); console.error.apply(console, args); } }; this.checkOutLog = function (logLevel) { var curGlobalLevel = LogLevel.getLogLevel(); if (logLevel >= curGlobalLevel && _this.enabled) { return true; } return false; }; this.formatArgs = function (logType, args) { args[0] = _this.coerce(args[0]); if (typeof args[0] !== 'string') { args.unshift('%O'); } args[0] = "" + ((_this.useColors ? '%c' : '') + _this.name + (_this.useColors ? ' %c' : ' ') + args[0]); if (!_this.useColors) { return; } var c = "color: " + colors[logType]; args.splice(1, 0, c, 'color: inherit'); }; this.coerce = function (val) { if (val instanceof Error) { return val.stack || val.message; } return val; }; this.name = name; this.enabled = options.enabled || true; this.useColors = options.useColors; this.isNodeEnv = options.isNodeEnv; this.setEnabled(options.skips, options.names); } return Log; }()); export default Log; <file_sep>/build/es6/LogLevel.js export var LogLeve_ENUM; (function (LogLeve_ENUM) { LogLeve_ENUM[LogLeve_ENUM["LOG"] = 1] = "LOG"; LogLeve_ENUM[LogLeve_ENUM["DEBUG"] = 2] = "DEBUG"; LogLeve_ENUM[LogLeve_ENUM["INFO"] = 3] = "INFO"; LogLeve_ENUM[LogLeve_ENUM["WARN"] = 4] = "WARN"; LogLeve_ENUM[LogLeve_ENUM["ERROR"] = 5] = "ERROR"; })(LogLeve_ENUM || (LogLeve_ENUM = {})); var curLevel = LogLeve_ENUM.LOG; var LogLevel = (function () { function LogLevel() { } LogLevel.setLogLevel = function (level) { curLevel = level; }; LogLevel.getLogLevel = function () { return curLevel; }; return LogLevel; }()); export default LogLevel; <file_sep>/src/index.ts import Log from "./Log"; import LogLevel, { LogLeve_ENUM } from "./LogLevel"; /* * @Author: quanyj * @Date: 2020-01-07 17:32:37 * @Last Modified by: quanyj * @Last Modified time: 2020-01-14 18:16:09 */ class LogUtil { private instances: { [key: string]: Log } = {}; private defaultLogOption = { enabled: true, useColors: false, isNodeEnv: false, names: [], skips: [] }; private logLevelInstance; /** * * 需要显示的 * @private * @memberof LogUtil */ private names: RegExp[]; /** * * 需要排除的 * @private * @memberof LogUtil */ private skips: RegExp[]; constructor() { LogLevel.setLogLevel(LogLeve_ENUM.LOG); // 初始化是否可以使用颜色 this.defaultLogOption.useColors = this.useColors(); // 初始化是否node环境 this.defaultLogOption.isNodeEnv = this.checkIsNode(); this.names = []; this.skips = []; } /** * * 设置全局日志过滤等级 * @memberof LogUtil */ setLogLevel = (logLevel: LogLeve_ENUM) => { LogLevel.setLogLevel(logLevel); } /** * * 获取所有的日志等级 * @memberof LogUtil */ getAllLogLevel = () => { return LogLeve_ENUM; } checkIsNode = () => { // if (typeof process === 'undefined' || (process as any).type === 'renderer' || (process as any).browser === true || (process as any).__nwjs) { // return false; // } return false; } /** * * 是否可以使用颜色 * @memberof LogUtil */ useColors = () => { // 如果 node 环境,不使用颜色 if (this.checkIsNode()) return false; // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && (window as any).process && ((window as any).process.type === 'renderer' || (window as any).process.__nwjs)) { return true; } // Internet Explorer and Edge do not support colors. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { return false; } // Is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && (document.documentElement.style as any).WebkitAppearance) // Is firebug? http://stackoverflow.com/a/398120/376773 || (typeof window !== 'undefined' && window.console && ((window.console as any).firebug || (window.console.exception && window.console.table))) // Is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages || (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) // Double check webkit in userAgent just in case we are in a worker || (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * * 创建log实例 * @memberof LogUtil */ create = (namespaces: string, LogOptions = {}): Log | null => { if (!namespaces) { return null; } let instance = this.instances[namespaces]; if (instance) { return instance; } instance = new Log(namespaces, { ...this.defaultLogOption, ...LogOptions, names: this.names, skips: this.skips }); this.instances[namespaces] = instance; return instance; } /** * 过滤条件 * worker:* 可以直接查看worker:a以及worker:b等 * "workera,workerb,-workerc" 可以查看workera和workerb,排除workerc * @memberof LogUtil */ enable = (namespaces: string) => { let i: number; const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); const len = split.length; const skips = []; const names = []; for (i = 0; i < len; i += 1) { if (!split[i]) { // ignore empty strings continue; } const newNamespaces = split[i].replace(/\*/g, '.*?'); if (newNamespaces[0] === '-') { skips.push(new RegExp(`^${newNamespaces.substr(1)}$`)); } else { names.push(new RegExp(`^${newNamespaces}$`)); } } const keys = Object.keys(this.instances); for (i = 0; i < keys.length; i += 1) { const namespacesItem = keys[i]; const instance = this.instances[namespacesItem]; instance.setEnabled(skips, names); } this.names = names; this.skips = skips; } destroy = (namespaces: string) => { const instance = this.instances[namespaces]; if (instance) { delete this.instances[namespaces]; } } } const LogUtils = new LogUtil(); export default LogUtils;
99ef9cf9d1d9dd738308cab3ae7a8f8f00e96d5d
[ "JavaScript", "TypeScript", "Markdown" ]
13
TypeScript
qyjandroid/h5-logutils
1ff82f5412883fdd0f26721eca53d16238079d94
5302bc354d385be2a5703dd35ef1d196736d9a5f
refs/heads/main
<repo_name>Starichok1993/Organizer<file_sep>/src/Organizer.Web/ClientApp/src/app/reducers/index.ts import { createSelector } from '@ngrx/store'; import * as fromTodos from './todo.reducers'; export interface State { todos: fromTodos.State; } export const reducers = { todos: fromTodos.reducer } export const selectTodosState = (state: State) => state.todos; export const selectTodos = createSelector(selectTodosState, fromTodos.selectTodos); export const selectActiveTodos = createSelector(selectTodosState, fromTodos.selectActiveTodos); export const isLoading = createSelector(selectTodosState, fromTodos.isLoading);<file_sep>/hommy-packages/Hommy.CQRS/QueryBase.cs using Hommy.CQRS.Abstractions; using Hommy.ResultModel; using System.Threading.Tasks; namespace Hommy.CQRS { public abstract class QueryBase<TOut> : IQuery<Task<Result<TOut>>> { } } <file_sep>/hommy-packages/Hommy.ApiResult/FailureJsonConverter.cs using Hommy.ResultModel; using System; using System.Text.Json; using System.Text.Json.Serialization; namespace Hommy.ApiResult { public class FailureJsonConverter : JsonConverter<Failure> { protected readonly JsonEncodedText Message = JsonEncodedText.Encode("message"); public override Failure Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { throw new NotImplementedException(); } public override void Write(Utf8JsonWriter writer, Failure value, JsonSerializerOptions options) { if (value.GetType() == typeof(Failure)) { writer.WriteStartObject(); writer.WritePropertyName(Message); writer.WriteStringValue(value.Message); writer.WriteEndObject(); } else { JsonSerializer.Serialize(writer, value, value.GetType(), options); } } } } <file_sep>/src/Organizer.Infrastructure/OrganizerDbContext.cs using Microsoft.EntityFrameworkCore; namespace Organizer.Infrastructure { public class OrganizerDbContext : DbContext { protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.ApplyConfigurationsFromAssembly(GetType().Assembly); } public OrganizerDbContext(DbContextOptions<OrganizerDbContext> options) : base(options) { } } } <file_sep>/db/schema.sql -- business partner db schema ALTER DATABASE CHARACTER SET utf8 COLLATE utf8_general_ci; DROP PROCEDURE IF EXISTS AddColumnUnlessExists; delimiter // create procedure AddColumnUnlessExists( IN dbName tinytext, IN tableName tinytext, IN fieldName tinytext, IN fieldDef text) begin IF NOT EXISTS ( SELECT * FROM information_schema.COLUMNS WHERE column_name=fieldName and table_name=tableName and table_schema=dbName ) THEN set @ddl=CONCAT('ALTER TABLE ',dbName,'.',tableName, ' ADD COLUMN ',fieldName,' ',fieldDef); prepare stmt from @ddl; execute stmt; ELSE select CONCAT('COLUMN: ', fieldName, ' is already exists') AS output; END IF; end// delimiter ; DROP PROCEDURE IF EXISTS DropForeignKeyIfExists; DELIMITER $$ CREATE PROCEDURE DropForeignKeyIfExists( IN dbName tinytext, IN tableName VARCHAR(64), IN constraintName VARCHAR(64)) BEGIN IF EXISTS( SELECT * FROM information_schema.table_constraints WHERE table_schema = dbName AND table_name = tableName AND constraint_name = constraintName AND constraint_type = 'FOREIGN KEY') THEN SET @query = CONCAT('ALTER TABLE ', tableName, ' DROP FOREIGN KEY ', constraintName, ';'); PREPARE stmt FROM @query; EXECUTE stmt; DEALLOCATE PREPARE stmt; END IF; END$$ DELIMITER ; DROP PROCEDURE IF EXISTS AddForeignKeyUnlessExists; DELIMITER $$ CREATE PROCEDURE AddForeignKeyUnlessExists( IN dbName tinytext, IN foreignKeyTableName VARCHAR(64), IN primaryKeyTableName VARCHAR(64), IN foreignKeyFieldName VARCHAR(64), IN primaryKeyFieldName VARCHAR(64), IN constraintName VARCHAR(64)) BEGIN DECLARE idx VARCHAR(256); IF NOT EXISTS( SELECT * FROM information_schema.table_constraints WHERE table_schema = dbName AND table_name = foreignKeyTableName AND constraint_name = constraintName AND constraint_type = 'FOREIGN KEY') THEN SET idx = CONCAT(constraintName, '_idx'); SET @query = CONCAT('ALTER TABLE ', foreignKeyTableName, ' ADD INDEX ', idx, ' ( ', foreignKeyFieldName , ' ASC);');PREPARE stmt FROM @query; EXECUTE stmt; DEALLOCATE PREPARE stmt; SET @query = CONCAT('ALTER TABLE ', foreignKeyTableName, ' ADD CONSTRAINT ', constraintName, ' FOREIGN KEY ( ', foreignKeyFieldName, ') REFERENCES ', primaryKeyTableName, '(' , primaryKeyFieldName , ');'); PREPARE stmt FROM @query; EXECUTE stmt; ELSE select CONCAT('FOREIGN KEY: ', constraintName, ' is already exists') AS output; END IF; END$$ DELIMITER ; -- Table db_version CREATE TABLE db_version ( Id int(11) unsigned NOT NULL, Version VARCHAR(32) NOT NULL, Description VARCHAR(1024) NOT NULL, DateApplied DATETIME NOT NULL, PRIMARY KEY (Id) ); CREATE TABLE to_do ( Id int(11) NOT NULL AUTO_INCREMENT, Description text DEFAULT NULL, IsDone bit(1) NOT NULL DEFAULT 0, PRIMARY KEY(Id) ) AUTO_INCREMENT=1; <file_sep>/src/Organizer.Infrastructure/Mapping/Base/EntityMap.cs using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Organizer.Domain.Entities.Base; namespace Organizer.Infrastructure.Mapping.Base { public abstract class EntityMap<TEntity> : IEntityTypeConfiguration<TEntity> where TEntity : class, IEntity<int> { protected abstract string TableName { get; } public virtual void Configure(EntityTypeBuilder<TEntity> builder) { builder.ToTable(TableName); builder.HasKey(e => e.Id); } } } <file_sep>/hommy-packages/Hommy.CQRS/Decorators/HandlerDecoratorBase.cs using Hommy.CQRS.Abstractions; using Hommy.ResultModel; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Hommy.CQRS.Decorators { public abstract class HandlerDecoratorBase<TIn, TOut> : IHandler<TIn, Task<Result<TOut>>> where TIn : IRequest<Task<Result<TOut>>> { protected readonly IHandler<TIn, Task<Result<TOut>>> Decorated; protected HandlerDecoratorBase(IHandler<TIn, Task<Result<TOut>>> decorated) { Decorated = decorated; } public abstract Task<Result<TOut>> Handle(TIn input); } public abstract class HandlerDecoratorBase<TIn> : IHandler<TIn, Task<Result>> where TIn : IRequest<Task<Result>> { protected readonly IHandler<TIn, Task<Result>> Decorated; protected HandlerDecoratorBase(IHandler<TIn, Task<Result>> decorated) { Decorated = decorated; } public abstract Task<Result> Handle(TIn input); } } <file_sep>/hommy-packages/Hommy.CQRS/CommandBase.cs using Hommy.CQRS.Abstractions; using Hommy.ResultModel; using System.Threading.Tasks; namespace Hommy.CQRS { public abstract class CommandBase<TOut> : ICommand<Task<Result<TOut>>> { } public abstract class CommandBase : ICommand<Task<Result>> { } } <file_sep>/src/Organizer.Web/Models/CreateToDoRequest.cs namespace Organizer.Web.Models { public class CreateToDoRequest { public string Description { get; set; } } } <file_sep>/hommy-packages/Hommy.CQRS/Abstractions/IHandler.cs namespace Hommy.CQRS.Abstractions { public interface IHandler<TIn,TOut> where TIn : IRequest<TOut> { TOut Handle(TIn input); } } <file_sep>/src/Organizer.Web/ClientApp/src/app/todo/todo.component.ts import { Component, EventEmitter, Input, Output } from '@angular/core'; import { ToDo } from './../todo'; @Component({ selector: 'todo', templateUrl: './todo.component.html', styleUrls: ['./todo.component.scss'] }) export class TodoComponent { @Input() todo: ToDo; @Output() statusChanged = new EventEmitter<ToDo>(); @Output() removed = new EventEmitter<ToDo>(); @Output() updated = new EventEmitter<ToDo>(); disabled = true; changeStatus(){ this.todo.isDone = !this.todo.isDone; this.statusChanged.emit(this.todo); } remove(){ this.removed.emit(this.todo); } update(){ this.disabled = true; this.updated.emit(this.todo); } } <file_sep>/src/Organizer.Application/ApplicationLayer.cs namespace Organizer.Application { public class ApplicationLayer { } } <file_sep>/src/Organizer.Infrastructure/Mapping/DbVersionMap.cs using Organizer.Domain.Entities; using Organizer.Infrastructure.Mapping.Base; namespace Organizer.Infrastructure.Mapping { public class DbVersionMap : EntityMap<DbVersion> { protected override string TableName => "db_version"; } } <file_sep>/src/Organizer.Web/Startup.cs using Hommy.ApiResult; using Hommy.CQRS; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.SpaServices.AngularCli; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Organizer.Application; using Organizer.Infrastructure; using SimpleInjector; using System.Text.Json.Serialization; namespace Organizer.Web { public class Startup { private readonly IConfiguration _configuration; private readonly Container _container = new Container(); public Startup(IConfiguration configuration) { _configuration = configuration; } // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddControllers().AddJsonOptions(options => { options.JsonSerializerOptions.IgnoreNullValues = true; options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); options.JsonSerializerOptions.Converters.Add(new FailureJsonConverter()); }); services.AddSwaggerGen(); services.AddSimpleInjector(_container, options => { options.AddAspNetCore().AddControllerActivation(); }); services.AddApiResult(); services.AddCQRS(_container, new[] { typeof(ApplicationLayer).Assembly }); services.AddDbContext<OrganizerDbContext>(options => { options.UseMySql(_configuration["ConnectionStrings:DatabaseConnection"], builder => builder.UseRelationalNulls()); }); services.AddScoped<DbContext, OrganizerDbContext>(); services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseSimpleInjector(_container); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseStaticFiles(); if (!env.IsDevelopment()) { app.UseSpaStaticFiles(); } app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); app.UseSpa(spa => { spa.Options.SourcePath = "ClientApp"; if (env.IsDevelopment()) { spa.UseAngularCliServer(npmScript: "start"); } }); _container.Verify(); //Should be last command } } } <file_sep>/hommy-packages/Hommy.CQRS/Abstractions/IQuery.cs namespace Hommy.CQRS.Abstractions { public class IQuery<TOut> : IRequest <TOut> { } } <file_sep>/hommy-packages/Hommy.CQRS/Abstractions/ICommand.cs namespace Hommy.CQRS.Abstractions { public interface ICommand<TOut> : IRequest<TOut> { } } <file_sep>/hommy-packages/Hommy.CQRS/CQRSServiceCollectionExtensions.cs using FluentValidation; using Hommy.CQRS.Abstractions; using Hommy.CQRS.Decorators; using Microsoft.Extensions.DependencyInjection; using SimpleInjector; using System.Reflection; namespace Hommy.CQRS { public static class CQRSServiceCollectionExtensions { public static IServiceCollection AddCQRS(this IServiceCollection service, Container container, Assembly[] assemblies //, Action<CQRSOptions> setupAction = null ) { //container.Collection.Register(typeof(IAccessFilter<>), assemblies); //container.Collection.Register(typeof(IPermissionValidator<>), assemblies); container.Collection.Register(typeof(IValidator<>), assemblies); container.RegisterSingleton<IHandlerDispatcher, HandlerDispatcher>(); container.Register(typeof(IHandler<,>), assemblies); //container.RegisterDecorator(typeof(IHandler<,>), typeof(TransactionHandlerDecorator<,>)); //container.RegisterDecorator(typeof(IHandler<,>), typeof(TransactionHandlerDecorator<>)); container.RegisterDecorator(typeof(IHandler<,>), typeof(ValidationHandlerDecorator<,>)); container.RegisterDecorator(typeof(IHandler<,>), typeof(ValidationHandlerDecorator<>)); //container.RegisterDecorator(typeof(IHandler<,>), typeof(PermissionValidationHandlerDecorator<,>)); //container.RegisterDecorator(typeof(IHandler<,>), typeof(PermissionValidationHandlerDecorator<>)); //container.RegisterDecorator(typeof(IHandler<,>), typeof(ErrorHandlerDecorator<,>)); //container.RegisterDecorator(typeof(IHandler<,>), typeof(ErrorHandlerDecorator<>)); //if (setupAction != null) //{ // service.Configure(setupAction); //} return service; } } } <file_sep>/src/Organizer.Domain/Entities/DbVersion.cs using Organizer.Domain.Entities.Base; using System; namespace Organizer.Domain.Entities { public class DbVersion : Entity { public string Version { get; private set; } public string Description { get; private set; } public DateTime DateApplied { get; private set; } protected DbVersion() { } } } <file_sep>/src/Organizer.Infrastructure/Mapping/ToDoMap.cs using Organizer.Domain.Entities; using Organizer.Infrastructure.Mapping.Base; namespace Organizer.Infrastructure.Mapping { public class ToDoMap : EntityMap<ToDo> { protected override string TableName => "to_do"; } } <file_sep>/hommy-packages/Hommy.CQRS/QueryHandlerBase.cs using Hommy.CQRS.Abstractions; using Hommy.ResultModel; using System.Threading.Tasks; namespace Hommy.CQRS { public abstract class QueryHandlerBase<TIn, TOut> : IHandler<TIn, Task<Result<TOut>>> where TIn : QueryBase<TOut> { public abstract Task<Result<TOut>> Handle(TIn input); } } <file_sep>/hommy-packages/Hommy.CQRS/Abstractions/IRequest.cs namespace Hommy.CQRS.Abstractions { public interface IRequest<TOut> { } } <file_sep>/src/Organizer.Application/Features/App/Queries/PingQuery.cs using Hommy.CQRS; using Hommy.ResultModel; using Microsoft.EntityFrameworkCore; using Organizer.Domain.Entities; using System.Threading.Tasks; namespace Organizer.Application.Features.App.Queries { public class PingQuery : QueryBase<string> { } public class PingQueryHandler : QueryHandlerBase<PingQuery, string> { private readonly DbContext _dbContext; public PingQueryHandler(DbContext dbContext) { _dbContext = dbContext; } public async override Task<Result<string>> Handle(PingQuery input) { var version = (await _dbContext.Set<DbVersion>().FirstAsync()).Version; return version; } } } <file_sep>/src/Organizer.Application/Features/ToDos/Commands/DeleteToDoCommand.cs using FluentValidation; using Hommy.CQRS; using Hommy.ResultModel; using Microsoft.EntityFrameworkCore; using Organizer.Domain.Entities; using System.Threading.Tasks; namespace Organizer.Application.Features.ToDos.Commands { public class DeleteToDoCommand : CommandBase { public int Id { get; set; } } public class DeleteToDoCommandValidator : AbstractValidator<DeleteToDoCommand> { public DeleteToDoCommandValidator() { RuleFor(x => x.Id).NotEmpty(); } } public class DeleteToDoCommandHandler : CommandHandlerBase<DeleteToDoCommand> { private readonly DbContext _dbContext; public DeleteToDoCommandHandler(DbContext dbContext) { _dbContext = dbContext; } public async override Task<Result> Handle(DeleteToDoCommand input) { var todo = await _dbContext.Set<ToDo>().FindAsync(input.Id); if (todo == null) { return Result.NotFound($"ToDo with Id: {input.Id} doesn't exist!"); } _dbContext.Remove(todo); await _dbContext.SaveChangesAsync(); return Result.Success(); } } } <file_sep>/src/Organizer.Web/ClientApp/src/app/effects/todo.effects.ts import { Injectable } from '@angular/core'; import { Actions, createEffect, ofType } from '@ngrx/effects'; import { EMPTY } from 'rxjs'; import { map, mergeMap, catchError } from 'rxjs/operators'; import { ToDoService } from "../todo.service"; import * as todo from "../actions/todo.actions"; @Injectable() export class TodoEffects { load$ = createEffect(() => this.actions$.pipe( ofType(todo.loadTodos), mergeMap(() => this.todoService.getToDos() .pipe( map(result => todo.todosLoaded({ todos: result.data })), catchError(() => EMPTY))) ) ); constructor(private actions$: Actions, private todoService: ToDoService) { } }<file_sep>/src/Organizer.Web/ClientApp/src/app/reducers/todo.reducers.ts import { createEntityAdapter, EntityAdapter, EntityState } from '@ngrx/entity'; import { createReducer, createSelector, on } from '@ngrx/store'; import { ToDo } from '../todo'; import * as TodoActions from './../actions/todo.actions'; export interface State extends EntityState<ToDo> { loading: boolean; } export const adapter: EntityAdapter<ToDo> = createEntityAdapter<ToDo>({ selectId: (todo: ToDo) => todo.id, sortComparer: false, }); export const initialState: State = adapter.getInitialState({ loading: false }); export const reducer = createReducer( initialState, on( TodoActions.loadTodos, (state) => ({...state, loading: true }) ), on( TodoActions.todosLoaded, (state, { todos }) => adapter.setAll(todos, {...state, loading: false }) ) ); // get the selectors const { selectAll } = adapter.getSelectors(); export const selectTodos = selectAll; export const selectActiveTodos = createSelector(selectTodos, (todos: ToDo[]) => todos.filter(t => !t.isDone)); export const isLoading = (state: State) => state.loading;<file_sep>/src/Organizer.Application/Features/ToDos/Queries/GetAllToDoQuery.cs using Hommy.CQRS; using Hommy.ResultModel; using Microsoft.EntityFrameworkCore; using Organizer.Domain.Entities; using System.Collections.Generic; using System.Threading.Tasks; namespace Organizer.Application.Features.ToDos.Queries { public class GetAllToDoQuery : QueryBase<List<ToDo>> { } public class GetAllToDoQueryHandler : QueryHandlerBase<GetAllToDoQuery, List<ToDo>> { private readonly DbContext _dbContext; public GetAllToDoQueryHandler(DbContext dbContext) { _dbContext = dbContext; } public async override Task<Result<List<ToDo>>> Handle(GetAllToDoQuery input) { var todos = await _dbContext.Set<ToDo>().ToListAsync(); return todos; } } } <file_sep>/src/Organizer.Web/Controllers/AppController.cs using System.Threading.Tasks; using Hommy.CQRS; using Microsoft.AspNetCore.Mvc; using Organizer.Application.Features.App.Queries; namespace Organizer.Web.Controllers { public class AppController : ApiControllerBase { private readonly IHandlerDispatcher _handlerDispatcher; public AppController(IHandlerDispatcher handlerDispatcher) { _handlerDispatcher = handlerDispatcher; } [HttpGet("ping")] public async Task<string> Ping() { var version = (await _handlerDispatcher.Handle<PingQuery, string>(new PingQuery())).Data; return version; } } }<file_sep>/src/Organizer.Web/Controllers/ToDoController.cs using System.Collections.Generic; using System.Threading.Tasks; using Hommy.ApiResult; using Hommy.CQRS; using Microsoft.AspNetCore.Mvc; using Organizer.Application.Features.ToDos.Commands; using Organizer.Application.Features.ToDos.Queries; using Organizer.Domain.Entities; using Organizer.Web.Models; namespace Organizer.Web.Controllers { public class ToDoController : ApiControllerBase { private readonly IHandlerDispatcher _handlerDispatcher; public ToDoController(IHandlerDispatcher handlerDispatcher) { _handlerDispatcher = handlerDispatcher; } [HttpGet("todo")] public async Task<ApiResult> GetAll () { return await _handlerDispatcher.Handle<GetAllToDoQuery, List<ToDo>>(new GetAllToDoQuery()); } [HttpPost("todo")] public async Task<ApiResult> Add([FromBody] CreateToDoRequest item) { return await _handlerDispatcher.Handle<CreateToDoCommand, int>(new CreateToDoCommand { Description = item.Description }); } [HttpPut("todo")] public async Task<ApiResult> Update([FromBody] UpdateToDoRequest item) { return await _handlerDispatcher.Handle(new UpdateToDoCommand { Id = item.Id, Description = item.Description, IsDone = item.IsDone }); } [HttpDelete("todo/{id}")] public async Task<ApiResult> Delete(int id) { return await _handlerDispatcher.Handle(new DeleteToDoCommand { Id = id }); } } } <file_sep>/src/Organizer.Web/ClientApp/src/app/todo.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { ToDo } from './todo'; import { ServerResult } from './serverResult'; import { Observable } from 'rxjs'; @Injectable({providedIn: 'root'}) export class ToDoService { private url = "/api/todo"; constructor(private http: HttpClient) { } getToDos(): Observable<ServerResult<ToDo[]>> { return this.http.get<ServerResult<ToDo[]>>(this.url); } getToDo(id: number): Observable<ServerResult<ToDo>>{ return this.http.get<ServerResult<ToDo>>(this.url + '/' + id); } createToDo(todo: ToDo): Observable<ServerResult<number>> { return this.http.post<ServerResult<number>>(this.url, todo); } updateToDo(todo: ToDo): Observable<ServerResult> { return this.http.put<ServerResult>(this.url, todo); } deleteToDo(id: number): Observable<ServerResult> { return this.http.delete<ServerResult>(this.url + '/' + id); } }<file_sep>/src/Organizer.Domain/Entities/ToDo.cs using Organizer.Domain.Entities.Base; namespace Organizer.Domain.Entities { public class ToDo : Entity { public string Description { get; private set; } public bool IsDone { get; private set; } public ToDo(string description) { Description = description; } public void Update(string description, bool isDone) { Description = description; IsDone = isDone; } } } <file_sep>/README.md # Organizer Todo list project <file_sep>/hommy-packages/Hommy.CQRS/HandlerDispatcher.cs using Hommy.CQRS.Abstractions; using Hommy.ResultModel; using SimpleInjector; using System.Threading.Tasks; namespace Hommy.CQRS { public class HandlerDispatcher : IHandlerDispatcher { private readonly Container _container; public HandlerDispatcher(Container container) { _container = container; } public Task<Result<TOut>> Handle<TIn, TOut>(TIn input) where TIn : IRequest<Task<Result<TOut>>> { var handler = (IHandler<TIn, Task<Result<TOut>>>) _container.GetInstance(typeof(IHandler<TIn, Task<Result<TOut>>>)); return handler.Handle(input); } public Task<Result> Handle<TIn>(TIn input) where TIn : IRequest<Task<Result>> { var handler = (IHandler<TIn, Task<Result>>)_container.GetInstance(typeof(IHandler<TIn, Task<Result>>)); return handler.Handle(input); } } } <file_sep>/src/Organizer.Application/Features/ToDos/Commands/CreateToDoCommand.cs using FluentValidation; using Hommy.CQRS; using Hommy.ResultModel; using Microsoft.EntityFrameworkCore; using Organizer.Domain.Entities; using System.Threading.Tasks; namespace Organizer.Application.Features.ToDos.Commands { public class CreateToDoCommand : CommandBase<int> { public string Description { get; set; } } public class CreateToDoCommandHandler : CommandHandlerBase<CreateToDoCommand, int> { private readonly DbContext _dbContext; public CreateToDoCommandHandler(DbContext dbContext) { _dbContext = dbContext; } public async override Task<Result<int>> Handle(CreateToDoCommand input) { var todo = new ToDo(input.Description); await _dbContext.Set<ToDo>().AddAsync(todo); await _dbContext.SaveChangesAsync(); return todo.Id; } } } <file_sep>/src/Organizer.Application/Features/ToDos/Commands/UpdateToDoCommand.cs using FluentValidation; using FluentValidation.Validators; using Hommy.CQRS; using Hommy.ResultModel; using Microsoft.EntityFrameworkCore; using Organizer.Domain.Entities; using System.Threading.Tasks; namespace Organizer.Application.Features.ToDos.Commands { public class UpdateToDoCommand : CommandBase { public int Id { get; set; } public string Description { get; set; } public bool IsDone { get; set; } } public class UpdateToDoCommandValidator : AbstractValidator<UpdateToDoCommand> { public UpdateToDoCommandValidator() { RuleFor(x => x.Id).NotEmpty(); } } public class UpdateToDoCommandHandler : CommandHandlerBase<UpdateToDoCommand> { private readonly DbContext _dbContext; public UpdateToDoCommandHandler(DbContext dbContext) { _dbContext = dbContext; } public async override Task<Result> Handle(UpdateToDoCommand input) { var todo = await _dbContext.Set<ToDo>().FindAsync(input.Id); if (todo == null) { return Result.NotFound(input.Id.ToString()); } todo.Update(input.Description, input.IsDone); await _dbContext.SaveChangesAsync(); return Result.Success(); } } } <file_sep>/hommy-packages/Hommy.CQRS/CommandHandlerBase.cs using Hommy.CQRS.Abstractions; using Hommy.ResultModel; using System.Threading.Tasks; namespace Hommy.CQRS { public abstract class CommandHandlerBase<TIn, TOut> : IHandler<TIn, Task<Result<TOut>>> where TIn : CommandBase<TOut> { public abstract Task<Result<TOut>> Handle(TIn input); } public abstract class CommandHandlerBase<TIn> : IHandler<TIn, Task<Result>> where TIn : CommandBase { public abstract Task<Result> Handle(TIn input); } } <file_sep>/hommy-packages/Hommy.CQRS/IHandlerDispatcher.cs using Hommy.CQRS.Abstractions; using Hommy.ResultModel; using System.Threading.Tasks; namespace Hommy.CQRS { public interface IHandlerDispatcher { Task<Result<TOut>> Handle<TIn, TOut>(TIn input) where TIn : IRequest<Task<Result<TOut>>>; Task<Result> Handle<TIn>(TIn input) where TIn : IRequest<Task<Result>>; } } <file_sep>/src/Organizer.Web/ClientApp/src/app/actions/todo.actions.ts import { createAction, props } from '@ngrx/store'; import { ToDo } from './../todo'; export const loadTodos = createAction( '[Todos] Load Todos' ); export const todosLoaded = createAction( '[Todos] Todos Loaded', props<{ todos: ToDo[] }>() ); <file_sep>/db/test_data.sql -- test data INSERT INTO `organizer_db`.`to_do` (`Id`, `Description`, `IsDone`) VALUES ('1', 'Buy milk', 0), ('2', 'Send email', 0), ('3', 'Pay installment', 1); <file_sep>/src/Organizer.Web/ClientApp/src/app/app.component.ts import { Component, OnInit } from '@angular/core'; import { ToDoService } from './todo.service'; import { ToDo } from './todo'; import { Observable } from 'rxjs'; import * as fromRoot from './reducers/index'; import { Store } from '@ngrx/store'; import * as fromTodos from './actions/todo.actions'; @Component({ selector: 'app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements OnInit { name = ''; todos$: Observable<ToDo[]>; loading$: Observable<boolean>; constructor(private store: Store<fromRoot.State>) { this.todos$ = this.store.select(fromRoot.selectActiveTodos); this.loading$ = this.store.select(fromRoot.isLoading); } ngOnInit() { this.store.dispatch(fromTodos.loadTodos()); } changeStatus(todo: ToDo) { // this.toDoService.updateToDo(todo).subscribe(); } remove(todo: ToDo) { // this.toDoService.deleteToDo(todo.id).subscribe(() => { // const index = this.todos.indexOf(todo); // if (index > -1) { // this.todos.splice(index, 1); // } // }); } changeDescription(todo: ToDo) { // this.toDoService.updateToDo(todo).subscribe(); } addTodo(){ // var todo = new ToDo(); // this.toDoService.createToDo(todo).subscribe((result) => { // todo.id = result.data; // this.todos.push(todo); // }) } }
7a6cbca317156e609ee9504011d4bc6f7efdf34f
[ "Markdown", "C#", "TypeScript", "SQL" ]
39
TypeScript
Starichok1993/Organizer
3d4977e9d0bcc2bc01dacadef165ec26c3cb2156
2b1ac0d164cbd719c94e53786881d3b6b19a0b4d
refs/heads/master
<file_sep>urllib3>=1.24.1 <file_sep># MyLibrary Organize papers so that relevance papers is easily assessable. This is a 4-week daily coding project. I am planning to build a Python app which will help me to follow other's researches. It's my first time playing with the web, I have no idea how doable it will be... ## Most wanted functionalities 1. retrieve meta data of new papers based on a simple, keyword/author-based matching, algorithm. It will be best if this can be substituted by a machine learning algorithm (in the far future) like what Mendeley and Nature maybe doing. 2. analize mutual citations of the papers in my library. Define the **central** paper in each field and devise a measurement of relevance. Until I figure out the best "formula" for the relevance assessment, manual modification of the weighting shold be possible. 3. Add a searchable note to each paper. 4. Very basic GUI (probably using QT?) 5. Automatically determine 6. ## Optional features 1. Visualize the network of citations. 2. Automatically check if an arxiv paper has been published (by checking on ADS) 3. Main text search. <file_sep>from nltk.stem import WordNetLemmatizer import re from nltk.tokenize import RegexpTokenizer from nltk.corpus import stopwords from sklearn.feature_extraction.text import CountVectorizer ## self.text is a term used in linguistics meaning a large set of text body. stop_words = set(stopwords.words("english")) class Keyword_extractor(): def __init__(self, text=None): self.set_text(text) self.wnl = WordNetLemmatizer() self.stop_words = set(stopwords.words("english")) def set_vectorizer(self, ngram, max_features = 2000, **kwargs): self.vec = CountVectorizer(ngram_range=(ngram, ngram), max_features = max_features, **kwargs) def add_stop_words(self, word_list): self.stop_words = self.stop_words.union(word_list) def set_text(self, corpus): """ corpus is an iterable (list of strings, ... ) """ if corpus is not None: self._has_corpus = True self.corpus = corpus def extract_words(self, corpus=None): if corpus is not None: self.set_text(corpus) assert self._has_corpus for text in self.corpus: try: text = re.sub('[^a-zA-Z]', ' ', text) # text = text.lower() text = re.sub("(\\d|\\W)+"," ",text) # Remove special characters text = re.sub("backslash\w*", " ", text) # Remove Latex equation commands text = re.sub("\s[a-zA-Z]{1,2}\s", ' ', text) # remove one or two-letter words (units: M, K, s, pc, km, ...) text = [self.wnl.lemmatize(word) for word in text.split() if not word in self.stop_words] text = " ".join(text) except: pass self.corpus = [text] def get_top_n_words(self, n=20, ngram=None): if ngram is not None: self.set_vectorizer(ngram) self.vec.fit(self.corpus) bag_of_words = self.vec.transform(self.corpus) # bag meaning not caring their order. sum_words = bag_of_words.sum(axis=0) # why? words_freq = [(word, sum_words[0, idx]) for word, idx in self.vec.vocabulary_.items()] words_freq = sorted(words_freq, key = lambda x : x[1], reverse=True) return words_freq[:n]<file_sep>import json import requests from lxml import etree """ To do 1. How should I store and read my token? 2. Is there other option than json? 3. If I need to use json, can I avoide using xml in arxiv? 4. How to retrieve citation list? 5. """ #User, token = open(".token", "r").readlines() #User = User.strip() #token = token.strip() User = "Hoseung" token = "<KEY>" ADS_fields=["author", "title", "journal", "archivePrefix", "eprint", "keywords", "year", "month", "volume", "eid", "pages", "doi", "adsurl", "adsnote"] def _store_token(token): with open(".token.dat", "w") as f: f.write(token) def get_journal_ref(journal_str): """ To do ----- refer to """ pass class ADS_bib(): """ There're some overlaps between Arxiv and ADS metadata. Figureout how I should deal with these redundancy. """ def __init__(self, bib=None): self.bib = dict( title=None, journal=None, archivePrefix=None, eprint=None, keywords=None, year=None, month=None, volume=None, eid=None, pages=None, doi=None, adsurl=None, adsnote=None) if bib is not None: self.parse_bib(bib) def parse_bib(self, bib): """ To do ----- 1. Identify each name of author. 1.1 Simply removing all {} will make identifying author's last names impossible... Hmm.. 2. Interpret journal abbreviation (with escape characteres) correctly. 3. Keywords field format is a bit complicated...! """ for ll in bib.split("\n"): # fields should appear only once. # Should I remove each field on being mathced? for ff in ADS_fields: if ff in ll: name, value = ll.translate(str.maketrans('', '', "{},'")).split("=") try: self.bib[name.strip()]=int(value) except: self.bib[name.strip()]=value.strip() class ADS(): def __init__(self, bibcode=None, arx_id=None): """ bibcode = {"bibcodes":["2003ApJS..148..175S"]} To do ----- Some keywords of meta are different from those of arxiv.meta. -> Try using a custom format export (http://adsabs.github.io/help/actions/export) """ self.bibcode=bibcode self.arx_id = arx_id self.meta = dict( title=None, journal=None, journal_ref=None, volume=None, page=None, lastpage=None, year=None, month=None, keywords=[], pubdate=None, author=[], url=None, abstract=None, DOI=None, eprintid=None, ) # to be compared with _generate_bibcode if self.bibcode is not None: r= self._ref_by_bibcode() #self.bibcode=self.meta["url"].split("/")[-1] elif self.arx_id is not None: r = self._ref_by_arxiv_id() try: self.parse_bibtex(r) except: pass def _generate_bibcode(self): """ Specification: http://adsabs.github.io/help/actions/bibcode 19 digits: YYYYJJJJJVVVVMPPPPA, where Y = year, J = Journal abbreviation, V = volume, M = qualifer for publication, P = page, A = First letter of the last name of the first author. """ return "{:4d}{:.<5}{:4d}{:1s}{:4d}{:1s}".format(self.meta["year"], self.meta["journal_ref"], self.meta["volume"], ".", self.meta["pages"], self.meta["author"][0][0]) def request_by_bibcode(self, bibcode=None): if bibcode is None: bibcode = self.bibcode return requests.post("https://api.adsabs.harvard.edu/v1/metrics", \ headers={"Authorization": "Bearer {}".format(token), "Content-type": "application/json"}, data=json.dumps(bibcode)).json def _ref_by_arxiv_id(self, arx_id=None): if arx_id is None: arx_id = self.arx_id return requests.get("https://ui.adsabs.harvard.edu/#abs/arXiv:{}".format(arx_id)).json def _ref_by_bibcode(self, bibcode=None, format="refabsxml"): """ format = {bibtex, bibtexabs, ads, endnote, rss, refxml, refabsxml, cusmtom, ...} NOTE ---- bibtexabs = bibtex + abstract. refabsxml = abstract + xml feed """ if bibcode is None: bibcode = self.bibcode return requests.post("https://api.adsabs.harvard.edu/v1/export/"+format, \ headers={"Authorization": "Bearer {}".format(token), "Content-type": "application/json"}, data=json.dumps(bibcode)).json() def parse_bibtex_pybtex(self, json_bib): import pybtex chk = json_bib["msg"] # message db = pybtex.database.parse_string(json_bib["export"], bib_format="bibtex") ent = db.entries[self.extract_bibcode(json_bib)] # Todo # parse ent def parse_bibtex(self, json_bib): parser = etree.XMLParser(ns_clean=True, recover=True, encoding='utf-8') root = etree.fromstring(json_bib["export"].encode("utf-8"), parser=parser) keys = self.meta.keys() for element in root.find("{http://ads.harvard.edu/schema/abs/1.1/abstracts}record"): name = element.tag.split("}")[-1] if name in keys: if isinstance(self.meta[name], list): if len(element.getchildren()) > 0: for Echild in element.getchildren(): self.meta[name].append(Echild.text) else: self.meta[name].append(element.text) else: try: self.meta[name] = element.attrib["term"] except: self.meta[name] = element.text def extract_bibcode(self, json_bib): return json_bib["export"].split("{")[1].split(",")[0] def request_citations(self): return requests.post("https://ui.adsabs.harvard.edu/link_gateway/"+\ self.bibcode+"/citations").json() def standardize_meta(self): # year try: self.meta["month"], self.meta["year"] = self.meta["pubdate"].split() self.meta["year"] = int(self.meat["year"]) except: pass # Journal abbv try: self.meta["journal_ref"] = adsutil.get_journal_ref(self.meta["jorunal"]) except: pass <file_sep>#%% from Arxiv import * arx = Arxiv_meta(1903.00003) #parse_arxiv(arx, arxiv_query_by_id(1903.00003)) #%% <file_sep>""" setuptools.find_packages() automatically determines all the packages needed to run this application. Yeah! """ import setuptools def parse_requirements(filename): """ load requirements from a pip requirements file """ lineiter = (line.strip() for line in open(filename)) return [line for line in lineiter if line and not line.startswith("#")] reqs = parse_requirements("requirements.txt") #reqs = [str(ir.req) for ir in install_reqs] with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name = "mylibrary", version="0.0.1", author="<NAME>", author_email = "<EMAIL>", description="Reference management application for astronomers", long_description=long_description, long_description_content_type="test/markdown", url="https://github.com/Hoseung/MyLibrary", packages=setuptools.find_packages(), classifiers=[ "Programming Languate :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], install_requires=reqs ) <file_sep># Journal abbv. should be standardized. # Titles may include special characters. - what should I do with them? # class PdfParser(): """ Required functionalities: 1. get Arxiv ID or Journal name + doi 2. get title 3. get author list 4. """ def __init__(self): pass class BibTex(): """ Refer to bibtex standard. But I don't need them all. Keep the information field as short as possible. There probably be some tools to work with bibtex. """ def __init__(self): self.fields=dict() def journal(self): """ Based on ADS search result, determine in which journal the paper has been published. """ # Do some string comparing things. -> distance measuring! self.fields["journal"] = "" class Library(): """ Contains global data. Functions to deal with SinglePaper entries. """ def __init__(self): self.keywords=[] self.__Arxiv_url="" self.__ADS_url="" self.__journals=[] class ADS_result(): """ A container of ADS search result. """ def __init__(self): pass class SinglePaper(): """ Note ---- Take advantage of existing bibtex fields as much as possible. Some papers might not appear on Arxiv. -- Those with embargo. """ def __init__(self): self.ArXivID=None #self._title="" #self.author1="" #self.year="" #self.journal="" self.bibtex=BibTex() self._file="" self._keywords=[] def check_published(self): if self.bibtex.journal is not None: return ads = search_ads(self.ArXivID) try: self.bibtex.ads.journal(ads.journal) except: print("preprint since {}. {}.".format(self.bibtex["year"], self.bibtex["month"])) <file_sep>""" Refer to https://arxiv.org/help/api/user-manual for the description of Arxiv API. Summary: ArXiv request returns in the Atom format (). Note: Refer to https://arxiv.org/help/prep for metadata spec. Since new submissions are updated only once in a day, the same query to the ArXiv API will only be updated once a day. Thus, repeated query in the same day should be refrained. To do: ------ Check for replacement of an article. Check if published version is available. - First determine if it will never be published elsewhere. - e.g., white paper. """ from urllib3 import PoolManager def get_sentence_standard(ll, tag): return ll.split("</{}>".format(tag))[-2].split("<{}>".format(tag))[-1] def parse_arxiv(arx, qresult): """ Note ---- Summary is multi-line. One author comprises multiple sub-entries (name/affiliation, and more?), and there may be multiple authors. Non atom-standard fields look arbitrary in formats. I don't expect these hardcoded parsing will always work... """ lines = qresult.decode("UTF-8").split("\n") entry=False _ibeg_summary=None _iend_summary=None read_author=False for i, ll in enumerate(lines): if "</entry>" in ll: break if "<entry>" in ll: entry=True if entry: if arx.id is None and "<id>" in ll: arx.id=get_sentence_standard(ll, "id").split("/")[-1] if arx.updated is None and "<updated>" in ll: arx.updated = get_sentence_standard(ll, "updated") if arx.published is None and "<published>" in ll: arx.published = get_sentence_standard(ll, "published") if arx.title is None and "<title>" in ll: arx.title = get_sentence_standard(ll, "title") if _ibeg_summary is None and "<summary>" in ll: _ibeg_summary = i if _iend_summary is None and "</summary>" in ll: _iend_summary = i if read_author: arx.authors.append(get_sentence_standard(ll, "name")) read_author=False if not read_author and "<author>" in ll: read_author = True if arx.doi is None and "": arx.doi = ll.split(">")[1].split("<")[0] if arx.primary_category is None and "arxiv:primary_category" in ll: arx.primary_category = ll.split('"')[3] if "category term" in ll: arx.categories.append(ll.split('"')[1]) arx.summary = "".join(lines[_ibeg_summary:_iend_summary]).split("<summary>")[1] #def class Arxiv_meta(): """ """ def __init__(self, id=None, load=True): self.title=None self.published=None self.updated=None self.authors=[] self.primary_category=None self.categories=[] self.summary=None self.doi=None self.id=str(id) if load: self.query_by_id(self.id) def query_by_id(self, parse=True, return_raw=False): """ Will it be better to keep PoolManager as a single, global instance? """ http = PoolManager() r = http.request("GET", "http://export.arxiv.org/api/query?id_list={}".format(self.id)) if parse: parse_arxiv(self, r.data) if return_raw: return r.data <file_sep>""" Refer to https://arxiv.org/help/api/user-manual for the description of Arxiv API. Summary: ArXiv request returns in the Atom format (). Note: Refer to https://arxiv.org/help/prep for metadata spec. Since new submissions are updated only once in a day, the same query to the ArXiv API will only be updated once a day. Thus, repeated query in the same day should be refrained. To do: ------ Check for replacement of an article. Check if published version is available. - First determine if it will never be published elsewhere. - e.g., white paper. """ #from urllib3 import PoolManager import requests from lxml import etree """ Will it be better to keep PoolManager as a single, global instance? """ #http = PoolManager() class Arxiv_meta(): """ """ def __init__(self, id=None, load=True): self.meta = dict( title=None, published=None, updated=None, author=[], primary_category=None, category=[], summary=None, doi=None, id=str(id), journal_ref=None, ) if id is not None and load: self.query_by_id(self.meta["id"]) def _get_single_paper(self): return requests.get("http://export.arxiv.org/api/query?id_list={}".format(\ self.meta["id"])).content #return http.request("GET", "http://export.arxiv.org/api/query?id_list={}".format(self.meta["id"])) def query_by_id(self, id=None, parse=True, return_raw=False): if id is not None: self.meta["id"] = id r = self._get_single_paper() if parse: self.parse_xml(r) if return_raw: return r def parse_xml(self, xml_data): root = etree.fromstring(xml_data) for element in root.find("{http://www.w3.org/2005/Atom}entry"): name = element.tag.split("}")[-1] if name == "author": for Echild in element.getchildren(): self.meta[name].append(Echild.text) else: try: if isinstance(self.meta[name], list): try: self.meta[name].append(element.attrib["term"]) except: self.meta[name].append(element.text) else: try: self.meta[name] = element.attrib["term"] except: self.meta[name] = element.text except: continue def _strip_parsed_text(self): pass <file_sep>name="mylibrary" from . import Arxiv, paper <file_sep>""" Measure similarity of keywords of different groups of articles. """
f0d25a3218c5810aafe5f8f393d222e14743f145
[ "Markdown", "Python", "Text" ]
11
Text
Hoseung/MyLibrary
c7e3cd49670bd45edce787eac75a6f702d96d0d4
163b59a2f63f1fae07733e4a227dc7145506b551
refs/heads/master
<repo_name>mousechen/courses<file_sep>/deeplearning1/nbs/myvgg16.py # 自己定义一个Vgg16的类,封装起来。 import os, json from glob import glob import numpy as np from scipy import misc, ndimage from scipy.ndimage.interpolation import zoom from keras import backend as K from keras.utils.data_utils import get_file from keras.models import Sequential from keras.layers import Input,Dense,Activation,ZeroPadding2D,Dropout,Conv2D,MaxPool2D,Flatten,Lambda,BatchNormalization from keras.optimizers import SGD, RMSprop, Adam from keras.preprocessing import image # In case we are going to use the TensorFlow backend we need to explicitly set the Theano image ordering from keras import backend as K K.set_image_dim_ordering('th') vgg_mean = np.array([123.68, 116.779, 103.939], dtype=np.float32).reshape((3,1,1)) def vgg_preprocess(x): """ Subtracts the mean RGB value, and transposes RGB to BGR. The mean RGB was computed on the image set used to train the VGG model. Args: x: Image array (height x width x channels) Returns: Image array (height x width x transposed_channels) """ x = x - vgg_mean return x[:, ::-1] # reverse axis rgb->bgr class Vgg16(): """ Vgg 16模型实现 """ def __init__(self): self.FILES_PATH = 'http://files.fast.ai/models/' self.create() self.get_classes() def get_classes(self): """ 下载Imagenet的图片分类,存在缓冲中目录为.keras """ # 暂时使用fast.ai的目录 fname='imagenet_class_index.json' fpath = get_file(fname,self.FILES_PATH+fname,cache_dir='models') with open(fpath) as f: class_dict = json.load(f) self.classes = [class_dict[str(i)][1] for i in range(len(class_dict))] def predict(self,imgs,detail=False): """ Predict the labels of a set of images using the VGG16 model. Args: imgs (ndarray) : An array of N images (size: N x width x height x channels). details : ?? Returns: preds (np.array) : Highest confidence value of the predictions for each image. idxs (np.ndarray): Class index of the predictions with the max confidence. classes (list) : Class labels of the predictions with the max confidence. """ all_preds = self.model.predict(imgs) #print(all_preds) idxs = np.argmax(all_preds,axis=1) preds = [all_preds[i,idxs[i]] for i in range(len(idxs))] classes = [self.classes[idx] for idx in idxs] return np.array(preds),idxs,classes def ConvBlock(self,n_layers,n_filters): """ Adds a specified number of ZeroPadding and Covolution layers to the model, and a MaxPooling layer at the very end. Args: layers (int): The number of zero padded convolution layers to be added to the model. filters (int): The number of convolution filters to be created for each layer. """ model = self.model for layer in range(n_layers): model.add(ZeroPadding2D(padding=(1,1))) model.add(Conv2D(filters=n_filters,kernel_size=(3,3),strides=(1,1),activation='relu')) model.add(MaxPool2D(pool_size=(2,2),strides=(2,2))) def FcBlock(self): """ Adds a fully connected layer of 4096 neurons to the model with a Dropout of 0.5 Args: None Returns: None """ model = self.model model.add(Dense(4096,activation='relu')) # FC1 model.add(Dropout(rate=0.5)) def create(self): """ Creates the VGG16 network achitecture and loads the pretrained weights. Args: None Returns: None """ model = self.model = Sequential() # 顺序 (Sequential) 模型写法第一add 必须加input_shape model.add(Lambda(vgg_preprocess, input_shape=(3,224,224), output_shape=(3,224,224))) self.ConvBlock(2,64) # 最开始的2层用64个3x3的过滤器,然后pool self.ConvBlock(2,128) self.ConvBlock(3,256) self.ConvBlock(3,512) self.ConvBlock(3,512) model.add(Flatten()) # 拉平,展开 self.FcBlock() self.FcBlock() model.add(Dense(1000,activation='softmax')) # 1000个分类 # 读取预训练好的模型权重 fpath = get_file('vgg16.h5', self.FILES_PATH+'vgg16.h5', cache_subdir='models') # 读取训练好的权重 model.load_weights(fpath) def get_batches(self,path,gen = image.ImageDataGenerator(),class_mode='categorical',batch_size=4,shuffle=True): """ Takes the path to a directory, and generates batches of augmented/normalized data. Yields batches indefinitely, in an infinite loop. See Keras documentation: https://keras.io/preprocessing/image/ """ return gen.flow_from_directory(path,target_size=(224,224), class_mode=class_mode,batch_size=batch_size,shuffle=shuffle) def ft(self,n_neurons): """ 冻结vgg16出去最后一层softmax 1000的全连接层,改为 传递进去的神经元个数 Replace the last layer of the model with a Dense (fully connected) layer of num neurons. Will also lock the weights of all layers except the new layer so that we only learn weights for the last layer in subsequent training. Args: num (int) : Number of neurons in the Dense layer Returns: None """ model = self.model model.pop() for layer in model.layers: layer.trainable = False # 这些层不训练 model.add(Dense(n_neurons,activation='softmax')) self.compile() def finetune(self,batches): """ # 微调模型,更新self.classes 不同的数据需要变动这里。 Modifies the original VGG16 network architecture and updates self.classes for new training data. Args: batches : A keras.preprocessing.image.ImageDataGenerator object. See definition for get_batches(). """ self.ft(batches.num_classes) # 获得数据的类别个数 classes = list(iter(batches.class_indices)) # get a list of all the class labels # batches.class_indices is a dict with the class name as key and an index as value # eg. {'cats': 0, 'dogs': 1} # sort the class labels by index according to batches.class_indices and update model.classes for c in batches.class_indices: classes[batches.class_indices[c]] = c self.classes = classes def compile(self,lr=0.01): """ 用于配置训练模型。 Configures the model for training. See Keras documentation: https://keras.io/models/model/ """ self.model.compile(optimizer=Adam(lr=lr),loss='categorical_crossentropy',metrics=['accuracy']) def fit_data(self,X,y,val,val_lables,batch_size=64,n_epochs=3): """ # 训练模型 See Keras documentation: https://keras.io/models/model/ """ self.model.fit(X,y,validation_data=(val,val_labels),epochs=n_epochs,batch_size=batch_size) def fit(self,batches,val_batches,n_epochs=3): """ 使用 Python 生成器逐批生成的数据,按批次训练模型。 Fits the model on data yielded batch-by-batch by a Python generator. See Keras documentation: https://keras.io/models/model/ """ self.model.fit_generator(batches,validation_data=val_batches,epochs=n_epochs,verbose=1) def test(self,path,batch_size=8): """ 测试 Predicts the classes using the trained model on data yielded batch-by-batch. Args: path (string): Path to the target directory. It should contain one subdirectory per class. batch_size (int): The number of images to be considered in each batch. Returns: test_batches, numpy array(s) of predictions for the test_batches. """ test_batches = self.get_batches(path,shuffle=False,batch_size=batch_size,class_mode=None) return test_batches,self.model.predict_generator(test_batches)
39b775bda49398bb3b5f13dea5e6edcc3792577a
[ "Python" ]
1
Python
mousechen/courses
8eab58a6aa9b3d0c8b926408deb5c88469efa834
ca1e12a0777681cbab342cac90f1d43837303e4d
refs/heads/master
<repo_name>BibhashK/Threads-in-Java<file_sep>/README.md # Threads-in-Java Threads code <file_sep>/Threads/src/ThreadSync.java public class ThreadSync implements Runnable{ public void run() { // TODO Auto-generated method stub } public synchronized void run(String name ){ System.out.println("current thread name: " + Thread.currentThread().getName()); try { Thread.sleep(1000); }catch(Exception e){} } public static void main(String[] args) { // TODO Auto-generated method stub ThreadSync r = new ThreadSync(); r.run("hello"); Thread t1=new Thread(r); Thread t2=new Thread(r); Thread t3=new Thread(r); t1.start(); t2.start(); t3.start(); } } <file_sep>/Threads/src/SleepThread.java public class SleepThread implements Runnable{ public void run() { try{ for(int i=5;i>0;i--){ System.out.println("Child Thread: " + 1); Thread.sleep(100); } }catch(InterruptedException e){ System.out.println("Child Interuppted"); } System.out.println("Exiting child Thread"); } public static void main(String[] args) { // TODO Auto-generated method stub SleepThread fit = new SleepThread(); Thread t =new Thread(fit); t.start(); try{ for(int i = 5;i>0;i--){ System.out.println("Main thread: " + i); Thread.sleep(200); } }catch(InterruptedException e){ System.out.println("main thread exiting"); } } }
51f259540a564644d1f408b99b10059e4b8fec95
[ "Markdown", "Java" ]
3
Markdown
BibhashK/Threads-in-Java
e1f32fb4794dec93a49e284da12647fa5dfe65ab
1e2994e15cf1fa9a3e8867da016adea2ae377ebb
refs/heads/master
<file_sep><?php use Illuminate\Database\Seeder; class UsersTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('users')->insert([ 'first_name' => 'Manuel', 'last_name' => 'Bruña', 'email' => '<EMAIL>', 'password' => app('hash')->make('<PASSWORD>'), 'phone' => '154646464', ]); } } <file_sep># Lumen 5.6 + JWT 1.0-rc2 (Login de usuario) - UPDATED: 16/03/2018. [![License](http://manu.cloud/wp-content/uploads/2017/03/manucloud_creador.png)](https://manu.cloud) [![License](https://poser.pugx.org/laravel/lumen-framework/license.svg)](https://opensource.org/licenses/MIT) Este repositorio cuenta con la version de Lumen 5.6 + JWT 1.0-rc2 para login de usuario, listo para clonar e iniciar todos tus proyectos. ## Correr servicio en localhost Para correr el servicio del repositorio puedes usar el siguiente comando: ```sh php -S localhost:8000 -t public ``` ## Instalación y configuración 1. Recuerda Rellenar tu archivo .env con los datos de tu base de datos. 2. Una vez iniciado el servidor del respositorio, ingresa a la ruta /key para copiar la clave de 32 chars y luego pegarlo en tu archivo .env (APP_KEY). 3. Corre las migraciones y las semillas: ```sh php artisan migrate php artisan db:seed ``` 4. Listo! Configura tu Lumen a gusto. [![N|Solid](http://manu.cloud/wp-content/uploads/2017/03/manucloud_createby.png)](https://manu.cloud) Las instrucciones para generar este proyecto las podras encontrar aquí: http://manu.cloud/framework/lumen/inicio-de-sesion-con-jwt-en-lumen/ Si deseas aprender a instalar Lumen desde cero: http://manu.cloud/framework/lumen/como-instalar-lumen-5-4-en-nuestro-localhost/ ## License The Lumen framework is open-sourced software licensed under the MIT license # Lumen PHP Framework [![Build Status](https://travis-ci.org/laravel/lumen-framework.svg)](https://travis-ci.org/laravel/lumen-framework) [![Total Downloads](https://poser.pugx.org/laravel/lumen-framework/d/total.svg)](https://packagist.org/packages/laravel/lumen-framework) [![Latest Stable Version](https://poser.pugx.org/laravel/lumen-framework/v/stable.svg)](https://packagist.org/packages/laravel/lumen-framework) [![Latest Unstable Version](https://poser.pugx.org/laravel/lumen-framework/v/unstable.svg)](https://packagist.org/packages/laravel/lumen-framework) [![License](https://poser.pugx.org/laravel/lumen-framework/license.svg)](https://packagist.org/packages/laravel/lumen-framework) The Lumen framework is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT) # JWT-AUTH by tymondesigns ![jwt-auth-banner](https://cloud.githubusercontent.com/assets/1801923/9915273/119b9350-5cae-11e5-850b-c941cac60b32.png) [![Build Status](http://img.shields.io/travis/tymondesigns/jwt-auth/master.svg?style=flat-square)](https://travis-ci.org/tymondesigns/jwt-auth) [![Codecov branch](https://img.shields.io/codecov/c/github/tymondesigns/jwt-auth/develop.svg?style=flat-square)](https://codecov.io/github/tymondesigns/jwt-auth) [![StyleCI](https://styleci.io/repos/23680678/shield?style=flat-square)](https://styleci.io/repos/23680678) [![Latest Version](http://img.shields.io/packagist/v/tymon/jwt-auth.svg?style=flat-square)](https://packagist.org/packages/tymon/jwt-auth) [![Latest Dev Version](https://img.shields.io/packagist/vpre/tymon/jwt-auth.svg?style=flat-square)](https://packagist.org/packages/tymon/jwt-auth#dev-develop) [![Monthly Downloads](https://img.shields.io/packagist/dm/tymon/jwt-auth.svg?style=flat-square)](https://packagist.org/packages/tymon/jwt-auth) [![Dependency Status](https://www.versioneye.com/php/tymon:jwt-auth/dev-develop/badge?style=flat-square)](https://www.versioneye.com/php/tymon:jwt-auth/dev-develop) [![PHP-Eye](https://php-eye.com/badge/tymon/jwt-auth/tested.svg?style=flat-square)](https://php-eye.com/package/tymon/jwt-auth) <file_sep>APP_ENV=local APP_DEBUG=true APP_KEY=INSERT_32_RANDOM_CHARS APP_TIMEZONE=UTC DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=jwt_login DB_USERNAME=user DB_PASSWORD=<PASSWORD> CACHE_DRIVER=file QUEUE_DRIVER=file JWT_TTL=1440 JWT_SECRET=INSERT_32_RANDOM_CHARS
b8b366a65955d9ed0c1b716d8404a1047d24d9ba
[ "Markdown", "PHP", "Shell" ]
3
PHP
gemins/Lumen-JWT-login
5bb48fddc909e7321fe3ac6a2c741db45a2ed22a
2085e52dca95f4b0ba2a8ce958b342ec68674f2a
refs/heads/master
<file_sep>// Copyright 2015 <NAME> // // 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. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Grib.Api.Interop.SWIG; using System.Runtime.InteropServices; using Grib.Api.Interop; using Grib.Api.Interop.Util; namespace Grib.Api { /// <summary> /// Encapsulates logic for encoding and decoding a value within a GRIB message. /// </summary> public class GribValue { const uint MAX_KEY_LEN = 255; const uint MAX_VAL_LEN = 1024; private GribHandle _handle; private readonly static GribValueType[] _asStringBlacklist = { GribValueType.IntArray, GribValueType.DoubleArray, GribValueType.Bytes }; /// <summary> /// Initializes a new instance of the <see cref="GribValue" /> class. /// </summary> /// <param name="keyName">Name of the key.</param> internal GribValue (string keyName) { Key = keyName; } /// <summary> /// Initializes a new instance of the <see cref="GribValue"/> class. /// </summary> /// <param name="handle">The handle.</param> /// <param name="keyName">Name of the key.</param> internal GribValue (GribHandle handle, string keyName) { _handle = handle; Key = keyName; } /// <summary> /// Gets the key's value. /// </summary> /// <param name="inDegrees">if set to <c>true</c>, GribApi.NET will convert the value to degrees when possible.</param> /// <returns></returns> public virtual string AsString (bool inDegrees = true) { if (!IsDefined || _asStringBlacklist.Contains(NativeType) ) { return String.Empty; } SizeT ptLen = 0; string valueKey = Key; if (CanConvertToDegrees) { valueKey = BuildTokenForDouble(inDegrees); } // not sure it's worth checking the length here--could just use MAX_VAL_LEN GribApiProxy.GribGetLength(_handle, valueKey, ref ptLen); StringBuilder msg = new StringBuilder((int) ptLen); GribApiProxy.GribGetString(_handle, valueKey, msg, ref ptLen); return msg.ToString().Trim(); } /// <summary> /// Sets the key's value. /// </summary> /// <param name="newValue">The new value.</param> public virtual void AsString (string newValue) { AssertTypeSafe(GribValueType.String); SizeT len = (SizeT) newValue.Length; GribApiProxy.GribSetString(_handle, Key, newValue, ref len); } /// <summary> /// Gets the key's value in bytes. /// </summary> /// <returns></returns> public byte[] AsBytes () { AssertTypeSafe(GribValueType.Bytes); if (!IsDefined) { return new byte[0]; } SizeT sz = 0; GribApiProxy.GribGetSize(_handle, Key, ref sz); byte[] bytes = new byte[sz]; GribApiProxy.GribGetBytes(_handle, Key, bytes, ref sz); return bytes; } /// <summary> /// Sets the key's value in bytes. /// </summary> /// <param name="newBytes">The new bytes.</param> public void AsBytes(byte[] newBytes) { AssertTypeSafe(GribValueType.Bytes); SizeT sz = (SizeT) newBytes.Length; GribApiProxy.GribSetBytes(_handle, Key, newBytes, ref sz); } /// <summary> /// Gets the key's value. /// </summary> /// <returns></returns> public virtual int AsInt () { AssertTypeSafe(GribValueType.Int); if (!IsDefined) { return 0; } int val; GribApiProxy.GribGetLong(_handle, Key, out val); return val; } /// <summary> /// Sets the key's value. /// </summary> /// <param name="newValue">The new value.</param> public virtual void AsInt (int newValue) { AssertTypeSafe(GribValueType.Int); GribApiProxy.GribSetLong(_handle, Key, newValue); } /// <summary> /// Gets a copy of the key's array value. Changing the values of this array does not affect the owning message. /// Call ::AsXArray(alteredArray) to set new values. /// </summary> /// <returns>If the value is defined, returns a *copy* of the key's array. Otherwise returns empty array.</returns> public virtual int[] AsIntArray () { AssertTypeSafe(GribValueType.IntArray); if (!IsDefined) { return new int[0]; } SizeT sz = 0; GribApiProxy.GribGetSize(_handle, Key, ref sz); int[] values = new int[sz]; GribApiProxy.GribGetLongArray(_handle, Key, values, ref sz); return values; } /// <summary> /// Sets the key's value. /// </summary> /// <param name="newValues">The new values.</param> public virtual void AsIntArray (int[] newValues) { AssertTypeSafe(GribValueType.IntArray); GribApiProxy.GribSetLongArray(_handle, Key, newValues, (SizeT)newValues.Length); } /// <summary> /// Gets the key's value. /// </summary> /// <param name="inDegrees">if set to <c>true</c>, GribApi.NET will return the value [in degrees] when possible.</param> /// <returns></returns> public virtual double AsDouble (bool inDegrees = true) { string valueKey = BuildTokenForDouble(inDegrees); AssertTypeSafe(valueKey, NativeTypeForKey(valueKey), GribValueType.Double); if (!IsDefined) { return Double.NaN; } double val; GribApiProxy.GribGetDouble(_handle, valueKey, out val); return val; } /// <summary> /// Sets the key's value. /// </summary> /// <param name="newValue">The new value.</param> /// <param name="inDegrees">if set to <c>true</c> [in degrees], GribApi.NET will set the value [in degrees] when possible.</param> public virtual void AsDouble (double newValue, bool inDegrees = true) { string valueKey = BuildTokenForDouble(inDegrees); AssertTypeSafe(valueKey, NativeTypeForKey(valueKey), GribValueType.Double); GribApiProxy.GribSetDouble(_handle, valueKey, newValue); } /// <summary> /// Gets a copy of the key's array value. Changing the values of this array does not affect the owning message. /// Call ::AsXArray(alteredArray) to set new values. /// </summary> /// <returns>If the value is defined, returns a *copy* of the key's array. Otherwise returns 0-length array.</returns> public virtual double[] AsDoubleArray () { AssertTypeSafe(GribValueType.DoubleArray); if (!IsDefined) { return new double[0]; } SizeT sz = 0; GribApiProxy.GribGetSize(_handle, Key, ref sz); double[] values = new double[sz]; GribApiProxy.GribGetDoubleArray(_handle, Key, values, ref sz); return values; } /// <summary> /// Sets the key's value. /// </summary> /// <param name="newValues">The new values.</param> /// <param name="force">if set to <c>true</c> [force].</param> public virtual void AsDoubleArray (double[] newValues, bool force = false) { if (force) { GribApiProxy.GribSetForceDoubleArray(_handle, Key, newValues, (SizeT)newValues.Length); } else { AssertTypeSafe(GribValueType.DoubleArray); GribApiProxy.GribSetDoubleArray(_handle, Key, newValues, (SizeT)newValues.Length); } } /// <summary> /// Builds the token for accesing/mutating double values, accounting for degree conversions. /// </summary> /// <param name="inDegrees">if set to <c>true</c> [in degrees].</param> /// <returns></returns> protected string BuildTokenForDouble (bool inDegrees) { string valueKey = Key; if (inDegrees && CanConvertToDegrees && !Key.EndsWith("InDegrees")) { valueKey += "InDegrees"; } else if (!inDegrees && Key.EndsWith("InDegrees")) { valueKey = valueKey.Substring(0, Key.Length - "InDegrees".Length); } return valueKey; } /// <summary> /// Returns a <see cref="System.String" /> that represents the value as a string. /// </summary> /// <returns> /// A <see cref="System.String" /> that represents the value as a string. /// </returns> public override string ToString () { return this.AsString(); } /// <summary> /// Determines whether this instance's value [can convert to degrees]. The ECMWF's grib_api /// documentation states degree conversion should be used whenever possible. Only relevant /// to coordinates. /// </summary> /// <returns></returns> public bool CanConvertToDegrees { get { string degreeToken = Key.EndsWith("InDegrees") ? Key : Key + "InDegrees"; return GribApiProxy.GribIsDefined(_handle, degreeToken); } } /// <summary> /// Gets the key name for this value. /// </summary> /// <value> /// The key name. /// </value> public string Key { get; protected set; } /// <summary> /// Gets or sets a value indicating whether the value associated with this key is missing. /// </summary> /// <value> /// <c>true</c> if this value is missing; otherwise, <c>false</c>. /// </value> public bool IsMissing { get { int err; bool isMissing = GribApiProxy.GribIsMissing(_handle, Key, out err); if (err != 0) { throw GribApiException.Create(err); } return isMissing; } } /// <summary> /// Return true if the given key exists (is defined) in the grib message. /// </summary> /// <value> /// <c>true</c> if key is defined; otherwise, <c>false</c>. /// </value> public bool IsDefined { get { return GribApiProxy.GribIsDefined(_handle, Key); } } /// <summary> /// Gets an enum describing the value's representation within the message. /// </summary> /// <value> /// The type of the native. /// </value> public virtual GribValueType NativeType { get { GribValueType nativeType = NativeTypeForKey(Key); // int[] and double[] values are return as int and double, so // determine if the value is an array if (nativeType == GribValueType.Int || nativeType == GribValueType.Double) { SizeT sz = 0; GribApiProxy.GribGetSize(_handle, Key, ref sz); if (sz > 1) { nativeType = (nativeType == GribValueType.Int) ? GribValueType.IntArray : GribValueType.DoubleArray; } } return nativeType; } } /// <summary> /// Gets a value indicating whether this value is read only. /// </summary> /// <value> /// <c>true</c> if this instance is read only; otherwise, <c>false</c>. /// </value> public bool IsReadOnly { get { return GribApiNative.GribKeyIsReadOnly(_handle.Reference, Key); } } /// <summary> /// Gets an enum describing a key's representation within the message. /// </summary> /// <param name="key">The key.</param> /// <returns></returns> private GribValueType NativeTypeForKey(string key) { int type = 0; GribApiProxy.GribGetNativeType(_handle, key, out type); return (GribValueType) type; } /// <summary> /// Tests for type safety when accessing this value. /// </summary> /// <param name="expectedType">The expected type.</param> private void AssertTypeSafe (GribValueType expectedType) { GribValue.AssertTypeSafe(Key, expectedType, NativeType); } /// <summary> /// Tests for type safety when accessing a GRIB value. /// </summary> /// <param name="key">The key.</param> /// <param name="expectedType">The expected type.</param> /// <param name="actualType">The actual type.</param> /// <exception cref="GribValueTypeException"></exception> private static void AssertTypeSafe(string key, GribValueType expectedType, GribValueType actualType) { if (expectedType != actualType) { throw new GribValueTypeException(String.Format("Invalid type conversion. Key {0} is GRIB type {1}", key, expectedType.AsString())); } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Arp.ArpDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using PcapDotNet.Packets.Ethernet; using PcapDotNet.Packets.IpV4; using System; using System.Collections.Generic; using System.Collections.ObjectModel; namespace PcapDotNet.Packets.Arp { public sealed class ArpDatagram : Datagram { public const int HeaderBaseLength = 8; public int HeaderLength { get { return ArpDatagram.GetHeaderLength((int) this.HardwareLength, (int) this.ProtocolLength); } } public ArpHardwareType HardwareType { get { return (ArpHardwareType) this.ReadUShort(0, Endianity.Big); } } public EthernetType ProtocolType { get { return (EthernetType) this.ReadUShort(2, Endianity.Big); } } public byte HardwareLength { get { return this[4]; } } public byte ProtocolLength { get { return this[5]; } } public ArpOperation Operation { get { return (ArpOperation) this.ReadUShort(6, Endianity.Big); } } public ReadOnlyCollection<byte> SenderHardwareAddress { get { return IListExtensions.AsReadOnly<byte>((IList<byte>) this.ReadBytes(8, (int) this.HardwareLength)); } } public ReadOnlyCollection<byte> SenderProtocolAddress { get { return IListExtensions.AsReadOnly<byte>((IList<byte>) this.ReadBytes(this.OffsetSenderProtocolAddress, (int) this.ProtocolLength)); } } public IpV4Address SenderProtocolIpV4Address { get { return this.ReadIpV4Address(this.OffsetSenderProtocolAddress, Endianity.Big); } } public ReadOnlyCollection<byte> TargetHardwareAddress { get { return IListExtensions.AsReadOnly<byte>((IList<byte>) this.ReadBytes(this.OffsetTargetHardwareAddress, (int) this.HardwareLength)); } } public ReadOnlyCollection<byte> TargetProtocolAddress { get { return IListExtensions.AsReadOnly<byte>((IList<byte>) this.ReadBytes(this.OffsetTargetProtocolAddress, (int) this.ProtocolLength)); } } public IpV4Address TargetProtocolIpV4Address { get { return this.ReadIpV4Address(this.OffsetTargetProtocolAddress, Endianity.Big); } } private int OffsetSenderProtocolAddress { get { return 8 + (int) this.HardwareLength; } } private int OffsetTargetHardwareAddress { get { return this.OffsetSenderProtocolAddress + (int) this.ProtocolLength; } } private int OffsetTargetProtocolAddress { get { return this.OffsetTargetHardwareAddress + (int) this.HardwareLength; } } private ArpDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public override ILayer ExtractLayer() { return (ILayer) new ArpLayer() { SenderHardwareAddress = this.SenderHardwareAddress, SenderProtocolAddress = this.SenderProtocolAddress, TargetHardwareAddress = this.TargetHardwareAddress, TargetProtocolAddress = this.TargetProtocolAddress, ProtocolType = this.ProtocolType, Operation = this.Operation }; } protected override bool CalculateIsValid() { if (this.Length >= 8) return this.Length == this.HeaderLength; return false; } internal static ArpDatagram CreateInstance(byte[] buffer, int offset, int length) { if (length <= 8) return new ArpDatagram(buffer, offset, length); int headerLength = ArpDatagram.GetHeaderLength((int) buffer[offset + 4], (int) buffer[offset + 5]); return new ArpDatagram(buffer, offset, Math.Min(length, headerLength)); } internal static int GetHeaderLength(int hardwareLength, int protocolLength) { return 8 + 2 * hardwareLength + 2 * protocolLength; } internal static void WriteHeader(byte[] buffer, int offset, ArpHardwareType hardwareType, EthernetType protocolType, ArpOperation operation, IList<byte> senderHardwareAddress, IList<byte> senderProtocolAddress, IList<byte> targetHardwareAddress, IList<byte> targetProtocolAddress) { ByteArrayExtensions.Write(buffer, ref offset, (ushort) hardwareType, Endianity.Big); ByteArrayExtensions.Write(buffer, ref offset, (ushort) protocolType, Endianity.Big); ByteArrayExtensions.Write(buffer, ref offset, (byte) senderHardwareAddress.Count); ByteArrayExtensions.Write(buffer, ref offset, (byte) senderProtocolAddress.Count); ByteArrayExtensions.Write(buffer, ref offset, (ushort) operation, Endianity.Big); ByteArrayExtensions.Write(buffer, ref offset, (IEnumerable<byte>) senderHardwareAddress); ByteArrayExtensions.Write(buffer, ref offset, (IEnumerable<byte>) senderProtocolAddress); ByteArrayExtensions.Write(buffer, ref offset, (IEnumerable<byte>) targetHardwareAddress); ByteArrayExtensions.Write(buffer, ref offset, (IEnumerable<byte>) targetProtocolAddress); } private static class Offset { public const int HardwareType = 0; public const int ProtocolType = 2; public const int HardwareLength = 4; public const int ProtocolLength = 5; public const int Operation = 6; public const int SenderHardwareAddress = 8; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpRouterAdvertisementEntry // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets.IpV4; using System; namespace PcapDotNet.Packets.Icmp { public sealed class IcmpRouterAdvertisementEntry : IEquatable<IcmpRouterAdvertisementEntry> { private readonly IpV4Address _routerAddress; private readonly int _routerAddressPreference; public IpV4Address RouterAddress { get { return this._routerAddress; } } public int RouterAddressPreference { get { return this._routerAddressPreference; } } public IcmpRouterAdvertisementEntry(IpV4Address routerAddress, int routerAddressPreference) { this._routerAddress = routerAddress; this._routerAddressPreference = routerAddressPreference; } public bool Equals(IcmpRouterAdvertisementEntry other) { if (other != null && this.RouterAddress == other.RouterAddress) return this.RouterAddressPreference == other.RouterAddressPreference; return false; } public override bool Equals(object obj) { return this.Equals(obj as IcmpRouterAdvertisementEntry); } public override int GetHashCode() { return Sequence.GetHashCode((object) this.RouterAddress, (object) this.RouterAddressPreference); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsOptionUpdateLease // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; namespace PcapDotNet.Packets.Dns { public sealed class DnsOptionUpdateLease : DnsOption { public const int ConstDataLength = 4; public int Lease { get; private set; } public override int DataLength { get { return 4; } } public DnsOptionUpdateLease(int lease) : base(DnsOptionCode.UpdateLease) { this.Lease = lease; } internal override bool EqualsData(DnsOption other) { return this.Lease.Equals(((DnsOptionUpdateLease) other).Lease); } internal override int DataGetHashCode() { return this.Lease.GetHashCode(); } internal override void WriteData(byte[] buffer, ref int offset) { ByteArrayExtensions.Write(buffer, ref offset, this.Lease, Endianity.Big); } internal static DnsOptionUpdateLease Read(DataSegment data) { if (data.Length < 4) return (DnsOptionUpdateLease) null; return new DnsOptionUpdateLease(data.ReadInt(0, Endianity.Big)); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataSignature // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.ResourceRecordSignature)] [DnsTypeRegistration(Type = DnsType.Signature)] public sealed class DnsResourceDataSignature : DnsResourceData, IEquatable<DnsResourceDataSignature> { private const int ConstantPartLength = 18; public DnsType TypeCovered { get; private set; } public DnsAlgorithm Algorithm { get; private set; } public byte Labels { get; private set; } public uint OriginalTtl { get; private set; } public SerialNumber32 SignatureExpiration { get; private set; } public SerialNumber32 SignatureInception { get; private set; } public ushort KeyTag { get; private set; } public DnsDomainName SignersName { get; private set; } public DataSegment Signature { get; private set; } public DnsResourceDataSignature(DnsType typeCovered, DnsAlgorithm algorithm, byte labels, uint originalTtl, SerialNumber32 signatureExpiration, SerialNumber32 signatureInception, ushort keyTag, DnsDomainName signersName, DataSegment signature) { this.TypeCovered = typeCovered; this.Algorithm = algorithm; this.Labels = labels; this.OriginalTtl = originalTtl; this.SignatureExpiration = signatureExpiration; this.SignatureInception = signatureInception; this.KeyTag = keyTag; this.SignersName = signersName; this.Signature = signature; } internal DnsResourceDataSignature() : this(DnsType.A, DnsAlgorithm.None, (byte) 0, 0U, (SerialNumber32) 0U, (SerialNumber32) 0U, (ushort) 0, DnsDomainName.Root, DataSegment.Empty) { } public bool Equals(DnsResourceDataSignature other) { if (other != null && this.TypeCovered.Equals((object) other.TypeCovered) && this.Algorithm.Equals((object) other.Algorithm) && this.Labels.Equals(other.Labels) && (this.OriginalTtl.Equals(other.OriginalTtl) && this.SignatureExpiration.Equals(other.SignatureExpiration)) && (this.SignatureInception.Equals(other.SignatureInception) && (this.KeyTag.Equals(other.KeyTag) && this.SignersName.Equals(other.SignersName)))) return this.Signature.Equals(other.Signature); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataSignature); } public override int GetHashCode() { return Sequence.GetHashCode((object) BitSequence.Merge((ushort) this.TypeCovered, (byte) this.Algorithm, this.Labels), (object) this.OriginalTtl, (object) this.SignatureExpiration, (object) this.SignatureInception, (object) this.KeyTag, (object) this.SignersName, (object) this.Signature); } internal override int GetLength(DnsDomainNameCompressionData compressionData, int offsetInDns) { return 18 + this.SignersName.GetLength(compressionData, offsetInDns) + this.Signature.Length; } internal override int WriteData(byte[] buffer, int dnsOffset, int offsetInDns, DnsDomainNameCompressionData compressionData) { ByteArrayExtensions.Write(buffer, dnsOffset + offsetInDns, (ushort) this.TypeCovered, Endianity.Big); ByteArrayExtensions.Write(buffer, dnsOffset + offsetInDns + 2, (byte) this.Algorithm); ByteArrayExtensions.Write(buffer, dnsOffset + offsetInDns + 3, this.Labels); ByteArrayExtensions.Write(buffer, dnsOffset + offsetInDns + 4, this.OriginalTtl, Endianity.Big); ByteArrayExtensions.Write(buffer, dnsOffset + offsetInDns + 8, this.SignatureExpiration.Value, Endianity.Big); ByteArrayExtensions.Write(buffer, dnsOffset + offsetInDns + 12, this.SignatureInception.Value, Endianity.Big); ByteArrayExtensions.Write(buffer, dnsOffset + offsetInDns + 16, this.KeyTag, Endianity.Big); int num1 = 18; int num2 = num1 + this.SignersName.Write(buffer, dnsOffset, compressionData, offsetInDns + num1); this.Signature.Write(buffer, dnsOffset + offsetInDns + num2); return num2 + this.Signature.Length; } internal override DnsResourceData CreateInstance(DnsDatagram dns, int offsetInDns, int length) { if (length < 18) return (DnsResourceData) null; DnsType typeCovered = (DnsType) dns.ReadUShort(offsetInDns, Endianity.Big); DnsAlgorithm algorithm = (DnsAlgorithm) dns[offsetInDns + 2]; byte labels = dns[offsetInDns + 3]; uint originalTtl = dns.ReadUInt(offsetInDns + 4, Endianity.Big); uint num1 = dns.ReadUInt(offsetInDns + 8, Endianity.Big); uint num2 = dns.ReadUInt(offsetInDns + 12, Endianity.Big); ushort keyTag = dns.ReadUShort(offsetInDns + 16, Endianity.Big); offsetInDns += 18; length -= 18; DnsDomainName domainName; int numBytesRead; if (!DnsDomainName.TryParse(dns, offsetInDns, length, out domainName, out numBytesRead)) return (DnsResourceData) null; offsetInDns += numBytesRead; length -= numBytesRead; DataSegment signature = dns.Subsegment(offsetInDns, length); return (DnsResourceData) new DnsResourceDataSignature(typeCovered, algorithm, labels, originalTtl, (SerialNumber32) num1, (SerialNumber32) num2, keyTag, domainName, signature); } private static class Offset { public const int TypeCovered = 0; public const int Algorithm = 2; public const int Labels = 3; public const int OriginalTtl = 4; public const int SignatureExpiration = 8; public const int SignatureInception = 12; public const int KeyTag = 16; public const int SignersName = 18; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IpV4OptionUnknown // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace PcapDotNet.Packets.IpV4 { public sealed class IpV4OptionUnknown : IpV4OptionComplex, IOptionUnknownFactory<IpV4OptionType>, IEquatable<IpV4OptionUnknown> { public const int OptionMinimumLength = 2; public const int OptionValueMinimumLength = 0; public ReadOnlyCollection<byte> Data { get; private set; } public override int Length { get { return 2 + this.Data.Count; } } public override bool IsAppearsAtMostOnce { get { return false; } } public IpV4OptionUnknown(IpV4OptionType optionType, IList<byte> data) : base(optionType) { this.Data = new ReadOnlyCollection<byte>(data); } public IpV4OptionUnknown() : this((IpV4OptionType) 255, (IList<byte>) new byte[0]) { } public bool Equals(IpV4OptionUnknown other) { if (other == null || this.OptionType != other.OptionType) return false; return Enumerable.SequenceEqual<byte>((IEnumerable<byte>) this.Data, (IEnumerable<byte>) other.Data); } public override bool Equals(IpV4Option other) { return this.Equals(other as IpV4OptionUnknown); } public override int GetHashCode() { return base.GetHashCode() ^ IEnumerableExtensions.BytesSequenceGetHashCode((IEnumerable<byte>) this.Data); } public Option CreateInstance(IpV4OptionType optionType, byte[] buffer, ref int offset, byte valueLength) { if ((int) valueLength < 0) return (Option) null; byte[] destination = new byte[(int) valueLength]; ByteArrayExtensions.BlockCopy(buffer, offset, destination, 0, (int) valueLength); offset += (int) valueLength; return (Option) new IpV4OptionUnknown(optionType, (IList<byte>) destination); } internal override void Write(byte[] buffer, ref int offset) { base.Write(buffer, ref offset); foreach (byte num in this.Data) ByteArrayExtensions.Write(buffer, ref offset, num); } } } <file_sep>namespace ForecastIOPortable.Models { using System; using System.Runtime.Serialization; /// <summary> /// The weather conditions for a particular minute. /// </summary> [DataContract] public class MinuteDataPoint { /// <summary> /// Unix time at which this data point applies. /// </summary> [DataMember] private int time; /// <summary> /// Gets or sets the time of this data point. /// </summary> public DateTimeOffset Time { get { return this.time.ToDateTimeOffset(); } set { this.time = value.ToUnixTime(); } } /// <summary> /// Gets or sets the average expected precipitation assuming any precipitation occurs. /// </summary> [DataMember(Name = "precipIntensity")] public float PrecipitationIntensity { get; set; } /// <summary> /// Gets or sets the probability of precipitation (from 0 to 1). /// </summary> [DataMember(Name = "precipProbability")] public float PrecipitationProbability { get; set; } /// <summary> /// Gets or sets the type of precipitation. /// </summary> [DataMember(Name = "precipType")] public string PrecipitationType { get; set; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IIpV4NextLayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; namespace PcapDotNet.Packets.IpV4 { public interface IIpV4NextLayer : ILayer { IpV4Protocol PreviousLayerProtocol { get; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.ListSegment`1 // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using System.Collections; using System.Collections.Generic; namespace PcapDotNet.Packets.Dns { internal class ListSegment<T> : IEnumerable<T>, IEnumerable { private readonly IList<T> _data; private readonly int _startIndex; public int Count { get; private set; } public T this[int index] { get { return this._data[this._startIndex + index]; } } public ListSegment(IList<T> data, int startIndex, int count) { this._data = data; this._startIndex = startIndex; this.Count = count; } public ListSegment(IList<T> data, int startIndex) : this(data, startIndex, data.Count - startIndex) { } public IEnumerator<T> GetEnumerator() { for (int i = 0; i != this.Count; ++i) yield return this[i]; } IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator) this.GetEnumerator(); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Layer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using System; namespace PcapDotNet.Packets { public abstract class Layer : ILayer, IEquatable<Layer> { public abstract int Length { get; } public virtual DataLinkKind? DataLink { get { return new DataLinkKind?(); } } public abstract void Write(byte[] buffer, int offset, int payloadLength, ILayer previousLayer, ILayer nextLayer); public virtual void Finalize(byte[] buffer, int offset, int payloadLength, ILayer nextLayer) { } public abstract bool Equals(Layer other); public override sealed bool Equals(object obj) { return this.Equals(obj as Layer); } public override int GetHashCode() { return this.Length.GetHashCode() ^ this.DataLink.GetHashCode(); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpDomainNameRequestDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; namespace PcapDotNet.Packets.Icmp { [IcmpDatagramRegistration(IcmpMessageType.DomainNameRequest)] public sealed class IcmpDomainNameRequestDatagram : IcmpIdentifiedDatagram { private IcmpDomainNameRequestDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public override ILayer ExtractLayer() { IcmpDomainNameRequestLayer nameRequestLayer = new IcmpDomainNameRequestLayer(); nameRequestLayer.Checksum = new ushort?(this.Checksum); nameRequestLayer.Identifier = this.Identifier; nameRequestLayer.SequenceNumber = this.SequenceNumber; return (ILayer) nameRequestLayer; } internal override IcmpDatagram CreateInstance(byte[] buffer, int offset, int length) { return (IcmpDatagram) new IcmpDomainNameRequestDatagram(buffer, offset, length); } } } <file_sep>using Grib.Api.Interop.SWIG; using System; namespace Grib.Api.Interop { /// <summary> /// Wraps a grib_iterator struct. /// </summary> public class GribValuesIterator : AutoRef { /// <summary> /// Initializes a new instance of the <see cref="GribValuesIterator"/> class. /// </summary> /// <param name="h">The h.</param> internal GribValuesIterator (IntPtr h) : base(h) { } /// <summary> /// Gets the next value in a series. /// </summary> /// <param name="isMissingFlag">The is missing flag.</param> /// <param name="gsVal">The gs value.</param> /// <returns>False if there are no more values.</returns> public bool Next (double isMissingFlag, out GeoSpatialValue gsVal) { double lat, lon, val; bool success = GribApiProxy.GribIteratorNext(this, out lat, out lon, out val) != 0; gsVal = new GeoSpatialValue(lat, lon, val, val == isMissingFlag); return success; } /// <summary> /// Called when [dispose]. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected override void OnDispose (bool disposing) { GribApiProxy.GribIteratorDelete(this); } /// <summary> /// Creates an instance of GribValuesIterator. /// </summary> /// <param name="h">The handle of the message to iterate.</param> /// <param name="filters">The filters.</param> /// <returns></returns> public static GribValuesIterator Create (GribHandle h, uint filters) { int err = 0; GribValuesIterator iter = GribApiProxy.GribIteratorNew(h, filters, out err); if (err != 0) { throw GribApiException.Create(err); } return iter; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Igmp.IgmpReplyVersion0Code // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Igmp { public enum IgmpReplyVersion0Code : byte { RequestGranted, RequestDeniedNoResources, RequestDeniedInvalidCode, RequestDeniedInvalidGroupAddress, RequestDeniedInvalidAccessKey, RequestPendingRetryIn5Seconds, RequestPendingRetryIn6Seconds, RequestPendingRetryIn7Seconds, RequestPendingRetryIn8Seconds, RequestPendingRetryIn9Seconds, RequestPendingRetryIn10Seconds, RequestPendingRetryIn11Seconds, RequestPendingRetryIn12Seconds, RequestPendingRetryIn13Seconds, RequestPendingRetryIn14Seconds, RequestPendingRetryIn15Seconds, RequestPendingRetryIn16Seconds, RequestPendingRetryIn17Seconds, RequestPendingRetryIn18Seconds, RequestPendingRetryIn19Seconds, RequestPendingRetryIn20Seconds, RequestPendingRetryIn21Seconds, RequestPendingRetryIn22Seconds, RequestPendingRetryIn23Seconds, RequestPendingRetryIn24Seconds, RequestPendingRetryIn25Seconds, RequestPendingRetryIn26Seconds, RequestPendingRetryIn27Seconds, RequestPendingRetryIn28Seconds, RequestPendingRetryIn29Seconds, RequestPendingRetryIn30Seconds, RequestPendingRetryIn31Seconds, RequestPendingRetryIn32Seconds, RequestPendingRetryIn33Seconds, RequestPendingRetryIn34Seconds, RequestPendingRetryIn35Seconds, RequestPendingRetryIn36Seconds, RequestPendingRetryIn37Seconds, RequestPendingRetryIn38Seconds, RequestPendingRetryIn39Seconds, RequestPendingRetryIn40Seconds, RequestPendingRetryIn41Seconds, RequestPendingRetryIn42Seconds, RequestPendingRetryIn43Seconds, RequestPendingRetryIn44Seconds, RequestPendingRetryIn45Seconds, RequestPendingRetryIn46Seconds, RequestPendingRetryIn47Seconds, RequestPendingRetryIn48Seconds, RequestPendingRetryIn49Seconds, RequestPendingRetryIn50Seconds, RequestPendingRetryIn51Seconds, RequestPendingRetryIn52Seconds, RequestPendingRetryIn53Seconds, RequestPendingRetryIn54Seconds, RequestPendingRetryIn55Seconds, RequestPendingRetryIn56Seconds, RequestPendingRetryIn57Seconds, RequestPendingRetryIn58Seconds, RequestPendingRetryIn59Seconds, RequestPendingRetryIn60Seconds, RequestPendingRetryIn61Seconds, RequestPendingRetryIn62Seconds, RequestPendingRetryIn63Seconds, RequestPendingRetryIn64Seconds, RequestPendingRetryIn65Seconds, RequestPendingRetryIn66Seconds, RequestPendingRetryIn67Seconds, RequestPendingRetryIn68Seconds, RequestPendingRetryIn69Seconds, RequestPendingRetryIn70Seconds, RequestPendingRetryIn71Seconds, RequestPendingRetryIn72Seconds, RequestPendingRetryIn73Seconds, RequestPendingRetryIn74Seconds, RequestPendingRetryIn75Seconds, RequestPendingRetryIn76Seconds, RequestPendingRetryIn77Seconds, RequestPendingRetryIn78Seconds, RequestPendingRetryIn79Seconds, RequestPendingRetryIn80Seconds, RequestPendingRetryIn81Seconds, RequestPendingRetryIn82Seconds, RequestPendingRetryIn83Seconds, RequestPendingRetryIn84Seconds, RequestPendingRetryIn85Seconds, RequestPendingRetryIn86Seconds, RequestPendingRetryIn87Seconds, RequestPendingRetryIn88Seconds, RequestPendingRetryIn89Seconds, RequestPendingRetryIn90Seconds, RequestPendingRetryIn91Seconds, RequestPendingRetryIn92Seconds, RequestPendingRetryIn93Seconds, RequestPendingRetryIn94Seconds, RequestPendingRetryIn95Seconds, RequestPendingRetryIn96Seconds, RequestPendingRetryIn97Seconds, RequestPendingRetryIn98Seconds, RequestPendingRetryIn99Seconds, RequestPendingRetryIn100Seconds, RequestPendingRetryIn101Seconds, RequestPendingRetryIn102Seconds, RequestPendingRetryIn103Seconds, RequestPendingRetryIn104Seconds, RequestPendingRetryIn105Seconds, RequestPendingRetryIn106Seconds, RequestPendingRetryIn107Seconds, RequestPendingRetryIn108Seconds, RequestPendingRetryIn109Seconds, RequestPendingRetryIn110Seconds, RequestPendingRetryIn111Seconds, RequestPendingRetryIn112Seconds, RequestPendingRetryIn113Seconds, RequestPendingRetryIn114Seconds, RequestPendingRetryIn115Seconds, RequestPendingRetryIn116Seconds, RequestPendingRetryIn117Seconds, RequestPendingRetryIn118Seconds, RequestPendingRetryIn119Seconds, RequestPendingRetryIn120Seconds, RequestPendingRetryIn121Seconds, RequestPendingRetryIn122Seconds, RequestPendingRetryIn123Seconds, RequestPendingRetryIn124Seconds, RequestPendingRetryIn125Seconds, RequestPendingRetryIn126Seconds, RequestPendingRetryIn127Seconds, RequestPendingRetryIn128Seconds, RequestPendingRetryIn129Seconds, RequestPendingRetryIn130Seconds, RequestPendingRetryIn131Seconds, RequestPendingRetryIn132Seconds, RequestPendingRetryIn133Seconds, RequestPendingRetryIn134Seconds, RequestPendingRetryIn135Seconds, RequestPendingRetryIn136Seconds, RequestPendingRetryIn137Seconds, RequestPendingRetryIn138Seconds, RequestPendingRetryIn139Seconds, RequestPendingRetryIn140Seconds, RequestPendingRetryIn141Seconds, RequestPendingRetryIn142Seconds, RequestPendingRetryIn143Seconds, RequestPendingRetryIn144Seconds, RequestPendingRetryIn145Seconds, RequestPendingRetryIn146Seconds, RequestPendingRetryIn147Seconds, RequestPendingRetryIn148Seconds, RequestPendingRetryIn149Seconds, RequestPendingRetryIn150Seconds, RequestPendingRetryIn151Seconds, RequestPendingRetryIn152Seconds, RequestPendingRetryIn153Seconds, RequestPendingRetryIn154Seconds, RequestPendingRetryIn155Seconds, RequestPendingRetryIn156Seconds, RequestPendingRetryIn157Seconds, RequestPendingRetryIn158Seconds, RequestPendingRetryIn159Seconds, RequestPendingRetryIn160Seconds, RequestPendingRetryIn161Seconds, RequestPendingRetryIn162Seconds, RequestPendingRetryIn163Seconds, RequestPendingRetryIn164Seconds, RequestPendingRetryIn165Seconds, RequestPendingRetryIn166Seconds, RequestPendingRetryIn167Seconds, RequestPendingRetryIn168Seconds, RequestPendingRetryIn169Seconds, RequestPendingRetryIn170Seconds, RequestPendingRetryIn171Seconds, RequestPendingRetryIn172Seconds, RequestPendingRetryIn173Seconds, RequestPendingRetryIn174Seconds, RequestPendingRetryIn175Seconds, RequestPendingRetryIn176Seconds, RequestPendingRetryIn177Seconds, RequestPendingRetryIn178Seconds, RequestPendingRetryIn179Seconds, RequestPendingRetryIn180Seconds, RequestPendingRetryIn181Seconds, RequestPendingRetryIn182Seconds, RequestPendingRetryIn183Seconds, RequestPendingRetryIn184Seconds, RequestPendingRetryIn185Seconds, RequestPendingRetryIn186Seconds, RequestPendingRetryIn187Seconds, RequestPendingRetryIn188Seconds, RequestPendingRetryIn189Seconds, RequestPendingRetryIn190Seconds, RequestPendingRetryIn191Seconds, RequestPendingRetryIn192Seconds, RequestPendingRetryIn193Seconds, RequestPendingRetryIn194Seconds, RequestPendingRetryIn195Seconds, RequestPendingRetryIn196Seconds, RequestPendingRetryIn197Seconds, RequestPendingRetryIn198Seconds, RequestPendingRetryIn199Seconds, RequestPendingRetryIn200Seconds, RequestPendingRetryIn201Seconds, RequestPendingRetryIn202Seconds, RequestPendingRetryIn203Seconds, RequestPendingRetryIn204Seconds, RequestPendingRetryIn205Seconds, RequestPendingRetryIn206Seconds, RequestPendingRetryIn207Seconds, RequestPendingRetryIn208Seconds, RequestPendingRetryIn209Seconds, RequestPendingRetryIn210Seconds, RequestPendingRetryIn211Seconds, RequestPendingRetryIn212Seconds, RequestPendingRetryIn213Seconds, RequestPendingRetryIn214Seconds, RequestPendingRetryIn215Seconds, RequestPendingRetryIn216Seconds, RequestPendingRetryIn217Seconds, RequestPendingRetryIn218Seconds, RequestPendingRetryIn219Seconds, RequestPendingRetryIn220Seconds, RequestPendingRetryIn221Seconds, RequestPendingRetryIn222Seconds, RequestPendingRetryIn223Seconds, RequestPendingRetryIn224Seconds, RequestPendingRetryIn225Seconds, RequestPendingRetryIn226Seconds, RequestPendingRetryIn227Seconds, RequestPendingRetryIn228Seconds, RequestPendingRetryIn229Seconds, RequestPendingRetryIn230Seconds, RequestPendingRetryIn231Seconds, RequestPendingRetryIn232Seconds, RequestPendingRetryIn233Seconds, RequestPendingRetryIn234Seconds, RequestPendingRetryIn235Seconds, RequestPendingRetryIn236Seconds, RequestPendingRetryIn237Seconds, RequestPendingRetryIn238Seconds, RequestPendingRetryIn239Seconds, RequestPendingRetryIn240Seconds, RequestPendingRetryIn241Seconds, RequestPendingRetryIn242Seconds, RequestPendingRetryIn243Seconds, RequestPendingRetryIn244Seconds, RequestPendingRetryIn245Seconds, RequestPendingRetryIn246Seconds, RequestPendingRetryIn247Seconds, RequestPendingRetryIn248Seconds, RequestPendingRetryIn249Seconds, RequestPendingRetryIn250Seconds, RequestPendingRetryIn251Seconds, RequestPendingRetryIn252Seconds, RequestPendingRetryIn253Seconds, RequestPendingRetryIn254Seconds, RequestPendingRetryIn255Seconds, } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CGurus.Weather.WundergroundAPI.Models { public enum AMPM : int { AM = 0, PM = 1 } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataX400Pointer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.PointerX400)] public sealed class DnsResourceDataX400Pointer : DnsResourceData, IEquatable<DnsResourceDataX400Pointer> { private const int ConstantPartLength = 2; public ushort Preference { get; private set; } public DnsDomainName Map822 { get; private set; } public DnsDomainName MapX400 { get; private set; } public DnsResourceDataX400Pointer(ushort preference, DnsDomainName map822, DnsDomainName mapX400) { this.Preference = preference; this.Map822 = map822; this.MapX400 = mapX400; } internal DnsResourceDataX400Pointer() : this((ushort) 0, DnsDomainName.Root, DnsDomainName.Root) { } public bool Equals(DnsResourceDataX400Pointer other) { if (other != null && (this.Preference.Equals(other.Preference) && this.Map822.Equals(other.Map822))) return this.MapX400.Equals(other.MapX400); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataX400Pointer); } public override int GetHashCode() { return Sequence.GetHashCode((object) this.Preference, (object) this.Map822, (object) this.MapX400); } internal override int GetLength(DnsDomainNameCompressionData compressionData, int offsetInDns) { return 2 + this.Map822.GetLength(compressionData, offsetInDns) + this.MapX400.GetLength(compressionData, offsetInDns); } internal override int WriteData(byte[] buffer, int dnsOffset, int offsetInDns, DnsDomainNameCompressionData compressionData) { ByteArrayExtensions.Write(buffer, dnsOffset + offsetInDns, this.Preference, Endianity.Big); int num = this.Map822.Write(buffer, dnsOffset, compressionData, offsetInDns + 2); return 2 + (num + this.MapX400.Write(buffer, dnsOffset, compressionData, offsetInDns + 2 + num)); } internal override DnsResourceData CreateInstance(DnsDatagram dns, int offsetInDns, int length) { if (length < 2) return (DnsResourceData) null; ushort preference = dns.ReadUShort(offsetInDns, Endianity.Big); offsetInDns += 2; length -= 2; DnsDomainName domainName1; int numBytesRead1; if (!DnsDomainName.TryParse(dns, offsetInDns, length, out domainName1, out numBytesRead1)) return (DnsResourceData) null; offsetInDns += numBytesRead1; length -= numBytesRead1; DnsDomainName domainName2; int numBytesRead2; if (!DnsDomainName.TryParse(dns, offsetInDns, length, out domainName2, out numBytesRead2)) return (DnsResourceData) null; length -= numBytesRead2; if (length != 0) return (DnsResourceData) null; return (DnsResourceData) new DnsResourceDataX400Pointer(preference, domainName1, domainName2); } private static class Offset { public const int Preference = 0; public const int Map822 = 2; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IpV4OptionTraceRoute // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.IpV4 { [OptionTypeRegistration(typeof (IpV4OptionType), IpV4OptionType.TraceRoute)] public sealed class IpV4OptionTraceRoute : IpV4OptionComplex, IOptionComplexFactory, IEquatable<IpV4OptionTraceRoute> { public const int OptionLength = 12; public const int OptionValueLength = 10; private readonly ushort _identification; private readonly ushort _outboundHopCount; private readonly ushort _returnHopCount; private readonly IpV4Address _originatorIpAddress; public ushort Identification { get { return this._identification; } } public IpV4Address OriginatorIpAddress { get { return this._originatorIpAddress; } } public ushort OutboundHopCount { get { return this._outboundHopCount; } } public ushort ReturnHopCount { get { return this._returnHopCount; } } public override int Length { get { return 12; } } public override bool IsAppearsAtMostOnce { get { return true; } } public IpV4OptionTraceRoute(ushort identification, ushort outboundHopCount, ushort returnHopCount, IpV4Address originatorIpAddress) : base(IpV4OptionType.TraceRoute) { this._identification = identification; this._outboundHopCount = outboundHopCount; this._returnHopCount = returnHopCount; this._originatorIpAddress = originatorIpAddress; } public IpV4OptionTraceRoute() : this((ushort) 0, (ushort) 0, (ushort) 0, IpV4Address.Zero) { } public bool Equals(IpV4OptionTraceRoute other) { if (other == null || (int) this.Identification != (int) other.Identification || ((int) this.OutboundHopCount != (int) other.OutboundHopCount || (int) this.ReturnHopCount != (int) other.ReturnHopCount)) return false; return this.OriginatorIpAddress == other.OriginatorIpAddress; } public override bool Equals(IpV4Option other) { return this.Equals(other as IpV4OptionTraceRoute); } public override int GetHashCode() { return base.GetHashCode() ^ Sequence.GetHashCode((object) this.Identification, (object) BitSequence.Merge(this.OutboundHopCount, this.ReturnHopCount), (object) this.OriginatorIpAddress); } Option IOptionComplexFactory.CreateInstance(byte[] buffer, ref int offset, byte valueLength) { if ((int) valueLength != 10) return (Option) null; return (Option) new IpV4OptionTraceRoute(ByteArrayExtensions.ReadUShort(buffer, ref offset, Endianity.Big), ByteArrayExtensions.ReadUShort(buffer, ref offset, Endianity.Big), ByteArrayExtensions.ReadUShort(buffer, ref offset, Endianity.Big), ByteArrayExtensions.ReadIpV4Address(buffer, ref offset, Endianity.Big)); } internal override void Write(byte[] buffer, ref int offset) { base.Write(buffer, ref offset); ByteArrayExtensions.Write(buffer, ref offset, this.Identification, Endianity.Big); ByteArrayExtensions.Write(buffer, ref offset, this.OutboundHopCount, Endianity.Big); ByteArrayExtensions.Write(buffer, ref offset, this.ReturnHopCount, Endianity.Big); ByteArrayExtensions.Write(buffer, ref offset, this.OriginatorIpAddress, Endianity.Big); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataNextDomain // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.NextDomain)] public sealed class DnsResourceDataNextDomain : DnsResourceData, IEquatable<DnsResourceDataNextDomain> { public const int MaxTypeBitmapLength = 16; public const DnsType MaxTypeBitmapDnsType = (DnsType) 128; public DnsDomainName NextDomainName { get; private set; } public DataSegment TypeBitmap { get; private set; } public IEnumerable<DnsType> TypesExist { get { ushort typeValue = (ushort) 0; for (int byteOffset = 0; byteOffset != this.TypeBitmap.Length; ++byteOffset) { byte mask = (byte) sbyte.MinValue; for (int i = 0; i != 8; ++i) { if (this.TypeBitmap.ReadBool(byteOffset, mask)) yield return (DnsType) typeValue; ++typeValue; mask >>= 1; } } } } public DnsResourceDataNextDomain(DnsDomainName nextDomainName, DataSegment typeBitmap) { if (typeBitmap == null) throw new ArgumentNullException("typeBitmap"); if (typeBitmap.Length > 16) throw new ArgumentOutOfRangeException("typeBitmap", (object) typeBitmap.Length, string.Format((IFormatProvider) CultureInfo.InvariantCulture, "Cannot be longer than {0} bytes.", new object[1] { (object) 16 })); if (typeBitmap.Length > 0 && (int) typeBitmap.Last == 0) throw new ArgumentOutOfRangeException("typeBitmap", (object) typeBitmap, "Last byte cannot be 0x00"); this.NextDomainName = nextDomainName; this.TypeBitmap = typeBitmap; } internal DnsResourceDataNextDomain() : this(DnsDomainName.Root, DataSegment.Empty) { } public bool IsTypePresentForOwner(DnsType dnsType) { if (dnsType >= (DnsType) 128) throw new ArgumentOutOfRangeException("dnsType", (object) dnsType, string.Format((IFormatProvider) CultureInfo.InvariantCulture, "Cannot be bigger than {0}.", new object[1] { (object) (DnsType) 128 })); int byteOffset; byte mask; DnsResourceDataNextDomain.DnsTypeToByteOffsetAndMask(out byteOffset, out mask, dnsType); if (byteOffset > this.TypeBitmap.Length) return false; return this.TypeBitmap.ReadBool(byteOffset, mask); } public static DataSegment CreateTypeBitmap(IEnumerable<DnsType> typesPresentForOwner) { if (typesPresentForOwner == null) throw new ArgumentNullException("typesPresentForOwner"); int length = (int) (Enumerable.Max<DnsType>(typesPresentForOwner) + (ushort) 7) / 8; if (length == 0) return DataSegment.Empty; byte[] buffer = new byte[length]; foreach (DnsType dnsType in typesPresentForOwner) { int byteOffset; byte mask; DnsResourceDataNextDomain.DnsTypeToByteOffsetAndMask(out byteOffset, out mask, dnsType); buffer[byteOffset] |= mask; } return new DataSegment(buffer); } public bool Equals(DnsResourceDataNextDomain other) { if (other != null && this.NextDomainName.Equals(other.NextDomainName)) return this.TypeBitmap.Equals(other.TypeBitmap); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataNextDomain); } public override int GetHashCode() { return Sequence.GetHashCode((object) this.NextDomainName, (object) this.TypeBitmap); } internal override int GetLength(DnsDomainNameCompressionData compressionData, int offsetInDns) { return this.NextDomainName.GetLength(compressionData, offsetInDns) + this.TypeBitmap.Length; } internal override int WriteData(byte[] buffer, int dnsOffset, int offsetInDns, DnsDomainNameCompressionData compressionData) { int num = this.NextDomainName.Write(buffer, dnsOffset, compressionData, offsetInDns); this.TypeBitmap.Write(buffer, dnsOffset + offsetInDns + num); return num + this.TypeBitmap.Length; } internal override DnsResourceData CreateInstance(DnsDatagram dns, int offsetInDns, int length) { DnsDomainName domainName; int numBytesRead; if (!DnsDomainName.TryParse(dns, offsetInDns, length, out domainName, out numBytesRead)) return (DnsResourceData) null; offsetInDns += numBytesRead; length -= numBytesRead; if (length > 16) return (DnsResourceData) null; DataSegment typeBitmap = dns.Subsegment(offsetInDns, length); if (length != 0 && (int) typeBitmap.Last == 0) return (DnsResourceData) null; return (DnsResourceData) new DnsResourceDataNextDomain(domainName, typeBitmap); } private static void DnsTypeToByteOffsetAndMask(out int byteOffset, out byte mask, DnsType dnsType) { byteOffset = (int) dnsType / 8; mask = (byte) (1 << (int) dnsType % 8); } } } <file_sep>using System.Collections.Generic; namespace CGurus.Weather.WundergroundAPI.Models { public class Response { public Dictionary<string, string> Features { get; set; } public string TermsOfService { get; set; } public string Version { get; set; } public Dictionary<string, string> Error { get; set; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataNextDomainSecure3Parameters // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System; using System.Diagnostics.CodeAnalysis; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.NSec3Parameters)] public sealed class DnsResourceDataNextDomainSecure3Parameters : DnsResourceDataNextDomainSecure3Base, IEquatable<DnsResourceDataNextDomainSecure3Parameters> { [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "flags")] public DnsResourceDataNextDomainSecure3Parameters(DnsSecNSec3HashAlgorithm hashAlgorithm, DnsSecNSec3Flags flags, ushort iterations, DataSegment salt) : base(hashAlgorithm, flags, iterations, salt) { } internal DnsResourceDataNextDomainSecure3Parameters() : this(DnsSecNSec3HashAlgorithm.Sha1, DnsSecNSec3Flags.None, (ushort) 0, DataSegment.Empty) { } public bool Equals(DnsResourceDataNextDomainSecure3Parameters other) { return this.EqualsParameters((DnsResourceDataNextDomainSecure3Base) other); } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataNextDomainSecure3Parameters); } public override int GetHashCode() { return this.GetHashCodeParameters(); } internal override int GetLength() { return this.ParametersLength; } internal override void WriteDataSimple(byte[] buffer, int offset) { this.WriteParameters(buffer, offset); } internal override DnsResourceData CreateInstance(DataSegment data) { DnsSecNSec3HashAlgorithm hashAlgorithm; DnsSecNSec3Flags flags; ushort iterations; DataSegment salt; if (!DnsResourceDataNextDomainSecure3Base.TryReadParameters(data, out hashAlgorithm, out flags, out iterations, out salt)) return (DnsResourceData) null; if (data.Length != DnsResourceDataNextDomainSecure3Base.GetParametersLength(salt.Length)) return (DnsResourceData) null; return (DnsResourceData) new DnsResourceDataNextDomainSecure3Parameters(hashAlgorithm, flags, iterations, salt); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataNoCompression // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Dns { public abstract class DnsResourceDataNoCompression : DnsResourceData { internal override sealed int GetLength(DnsDomainNameCompressionData compressionData, int offsetInDns) { return this.GetLength(); } internal override sealed int WriteData(byte[] buffer, int dnsOffset, int offsetInDns, DnsDomainNameCompressionData compressionData) { return this.WriteData(buffer, dnsOffset + offsetInDns); } internal abstract int GetLength(); internal abstract int WriteData(byte[] buffer, int offset); } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsAfsDatabaseSubtype // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Dns { public enum DnsAfsDatabaseSubtype : ushort { None, AfsCell, DceNcaCell, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpParameterProblemDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; namespace PcapDotNet.Packets.Icmp { [IcmpDatagramRegistration(IcmpMessageType.ParameterProblem)] public sealed class IcmpParameterProblemDatagram : IcmpIpV4HeaderPlus64BitsPayloadDatagram { public byte Pointer { get { return this[4]; } } private IcmpParameterProblemDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public override ILayer ExtractLayer() { IcmpParameterProblemLayer parameterProblemLayer = new IcmpParameterProblemLayer(); parameterProblemLayer.Checksum = new ushort?(this.Checksum); parameterProblemLayer.Pointer = this.Pointer; return (ILayer) parameterProblemLayer; } protected override bool CalculateIsValid() { if (base.CalculateIsValid()) return (int) this.Pointer < this.IpV4.Length; return false; } internal override IcmpDatagram CreateInstance(byte[] buffer, int offset, int length) { return (IcmpDatagram) new IcmpParameterProblemDatagram(buffer, offset, length); } private static class Offset { public const int Pointer = 4; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Ethernet.MacAddress // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using System; using System.Globalization; namespace PcapDotNet.Packets.Ethernet { public struct MacAddress : IEquatable<MacAddress> { private static readonly MacAddress _zero = new MacAddress((UInt48) 0U); public const int SizeOf = 6; private readonly UInt48 _value; public static MacAddress Zero { get { return MacAddress._zero; } } public MacAddress(UInt48 value) { this._value = value; } public MacAddress(string address) { if (address == null) throw new ArgumentNullException("address"); string[] strArray = address.Split(':'); if (strArray.Length != 6) throw new ArgumentException("Failed parsing " + (object) address + " as mac address. Expected 6 hexes and got " + (string) (object) strArray.Length + " hexes", "address"); this._value = BitSequence.Merge(Convert.ToByte(strArray[0], 16), Convert.ToByte(strArray[1], 16), Convert.ToByte(strArray[2], 16), Convert.ToByte(strArray[3], 16), Convert.ToByte(strArray[4], 16), Convert.ToByte(strArray[5], 16)); } public static bool operator ==(MacAddress macAddress1, MacAddress macAddress2) { return macAddress1.Equals(macAddress2); } public static bool operator !=(MacAddress macAddress1, MacAddress macAddress2) { return !(macAddress1 == macAddress2); } public UInt48 ToValue() { return this._value; } public bool Equals(MacAddress other) { return this._value == other._value; } public override bool Equals(object obj) { if (obj is MacAddress) return this.Equals((MacAddress) obj); return false; } public override int GetHashCode() { return this._value.GetHashCode(); } public override string ToString() { return string.Format((IFormatProvider) CultureInfo.InvariantCulture, "{0:X2}:{1:X2}:{2:X2}:{3:X2}:{4:X2}:{5:X2}", (object) (byte) ((long) this._value >> 40), (object) (byte) ((long) this._value >> 32), (object) (byte) ((long) this._value >> 24), (object) (byte) ((long) this._value >> 16), (object) (byte) ((long) this._value >> 8), (object) (byte) this._value); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpSourceQuenchDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; namespace PcapDotNet.Packets.Icmp { [IcmpDatagramRegistration(IcmpMessageType.SourceQuench)] public sealed class IcmpSourceQuenchDatagram : IcmpIpV4HeaderPlus64BitsPayloadDatagram { private IcmpSourceQuenchDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public override ILayer ExtractLayer() { IcmpSourceQuenchLayer sourceQuenchLayer = new IcmpSourceQuenchLayer(); sourceQuenchLayer.Checksum = new ushort?(this.Checksum); return (ILayer) sourceQuenchLayer; } internal override IcmpDatagram CreateInstance(byte[] buffer, int offset, int length) { return (IcmpDatagram) new IcmpSourceQuenchDatagram(buffer, offset, length); } } } <file_sep>using Grib.Api.Interop.SWIG; using System; namespace Grib.Api.Interop { /// <summary> /// Wraps grib_handle struct. /// </summary> public class GribHandle : AutoRef { /// <summary> /// Initializes a new instance of the <see cref="GribHandle"/> class. /// </summary> /// <param name="h">The h.</param> public GribHandle (IntPtr h) : base(h) { } /// <summary> /// Called when [dispose]. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected override void OnDispose (bool disposing) { GribApiProxy.GribHandleDelete(this); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Igmp.IgmpGroupRecord // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using PcapDotNet.Packets.IpV4; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace PcapDotNet.Packets.Igmp { public sealed class IgmpGroupRecord : IEquatable<IgmpGroupRecord> { public IgmpRecordType RecordType { get; private set; } public IpV4Address MulticastAddress { get; private set; } public ReadOnlyCollection<IpV4Address> SourceAddresses { get; private set; } public Datagram AuxiliaryData { get; private set; } public IgmpGroupRecord(IgmpRecordType recordType, IpV4Address multicastAddress, ReadOnlyCollection<IpV4Address> sourceAddresses, Datagram auxiliaryData) { if (auxiliaryData == null) throw new ArgumentNullException("auxiliaryData"); if (auxiliaryData.Length % 4 != 0) throw new ArgumentException("Auxiliary data length must divide by 4 and can't be " + (object) auxiliaryData.Length, "auxiliaryData"); this.RecordType = recordType; this.MulticastAddress = multicastAddress; this.SourceAddresses = sourceAddresses; this.AuxiliaryData = auxiliaryData; } public IgmpGroupRecord(IgmpRecordType recordType, IpV4Address multicastAddress, IList<IpV4Address> sourceAddresses, Datagram auxiliaryData) : this(recordType, multicastAddress, new ReadOnlyCollection<IpV4Address>(sourceAddresses), auxiliaryData) { } public override string ToString() { return (string) (object) this.RecordType + (object) " " + (string) (object) this.MulticastAddress + " " + IEnumerableExtensions.SequenceToString<IpV4Address>((IEnumerable<IpV4Address>) this.SourceAddresses, ", ", "[", "]") + " Aux=" + (string) (object) this.AuxiliaryData.Length; } public bool Equals(IgmpGroupRecord other) { if (other == null || this.RecordType != other.RecordType || (!(this.MulticastAddress == other.MulticastAddress) || !Enumerable.SequenceEqual<IpV4Address>((IEnumerable<IpV4Address>) this.SourceAddresses, (IEnumerable<IpV4Address>) other.SourceAddresses))) return false; return this.AuxiliaryData.Equals((DataSegment) other.AuxiliaryData); } public override bool Equals(object obj) { return this.Equals(obj as IgmpGroupRecord); } public override int GetHashCode() { return Sequence.GetHashCode((object) this.RecordType, (object) this.MulticastAddress) ^ IEnumerableExtensions.SequenceGetHashCode<IpV4Address>((IEnumerable<IpV4Address>) this.SourceAddresses) ^ IEnumerableExtensions.BytesSequenceGetHashCode((IEnumerable<byte>) this.AuxiliaryData); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpTraceRouteDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System.Linq; namespace PcapDotNet.Packets.Icmp { [IcmpDatagramRegistration(IcmpMessageType.TraceRoute)] public sealed class IcmpTraceRouteDatagram : IcmpDatagram { private static readonly byte _minCode = (byte) Enumerable.Min<IcmpCodeTraceRoute>(TypeExtensions.GetEnumValues<IcmpCodeTraceRoute>(typeof (IcmpCodeTraceRoute))); private static readonly byte _maxCode = (byte) Enumerable.Max<IcmpCodeTraceRoute>(TypeExtensions.GetEnumValues<IcmpCodeTraceRoute>(typeof (IcmpCodeTraceRoute))); public const int DatagramLength = 20; public const int PayloadLength = 12; public const ushort OutboundReturnHopCountValue = (ushort) 65535; public ushort Identification { get { return this.ReadUShort(4, Endianity.Big); } } public ushort OutboundHopCount { get { return this.ReadUShort(8, Endianity.Big); } } public ushort ReturnHopCount { get { return this.ReadUShort(10, Endianity.Big); } } public uint OutputLinkSpeed { get { return this.ReadUInt(12, Endianity.Big); } } public uint OutputLinkMaximumTransmissionUnit { get { return this.ReadUInt(16, Endianity.Big); } } public bool IsOutbound { get { return (int) this.ReturnHopCount == (int) ushort.MaxValue; } } protected override byte MinCodeValue { get { return IcmpTraceRouteDatagram._minCode; } } protected override byte MaxCodeValue { get { return IcmpTraceRouteDatagram._maxCode; } } private IcmpTraceRouteDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public override ILayer ExtractLayer() { IcmpTraceRouteLayer icmpTraceRouteLayer = new IcmpTraceRouteLayer(); icmpTraceRouteLayer.Code = (IcmpCodeTraceRoute) this.Code; icmpTraceRouteLayer.Checksum = new ushort?(this.Checksum); icmpTraceRouteLayer.Identification = this.Identification; icmpTraceRouteLayer.OutboundHopCount = this.OutboundHopCount; icmpTraceRouteLayer.ReturnHopCount = this.ReturnHopCount; icmpTraceRouteLayer.OutputLinkSpeed = this.OutputLinkSpeed; icmpTraceRouteLayer.OutputLinkMaximumTransmissionUnit = this.OutputLinkMaximumTransmissionUnit; return (ILayer) icmpTraceRouteLayer; } protected override bool CalculateIsValid() { if (base.CalculateIsValid()) return this.Length == 20; return false; } internal override IcmpDatagram CreateInstance(byte[] buffer, int offset, int length) { return (IcmpDatagram) new IcmpTraceRouteDatagram(buffer, offset, length); } internal static void WriteHeaderAdditional(byte[] buffer, int offset, ushort outboundHopCount, ushort returnHopCount, uint outputLinkSpeed, uint outputLinkMtu) { ByteArrayExtensions.Write(buffer, ref offset, outboundHopCount, Endianity.Big); ByteArrayExtensions.Write(buffer, ref offset, returnHopCount, Endianity.Big); ByteArrayExtensions.Write(buffer, ref offset, outputLinkSpeed, Endianity.Big); ByteArrayExtensions.Write(buffer, offset, outputLinkMtu, Endianity.Big); } private static class Offset { public const int Identifier = 4; public const int OutboundHopCount = 8; public const int ReturnHopCount = 10; public const int OutputLinkSpeed = 12; public const int OutputLinkMtu = 16; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsAlgorithm // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Dns { public enum DnsAlgorithm : byte { None = (byte) 0, RsaMd5 = (byte) 1, DiffieHellman = (byte) 2, Dsa = (byte) 3, EllipticCurveCrypto = (byte) 4, RsaSha1 = (byte) 5, DsaNextSecure3Sha1 = (byte) 6, RsaSha1NextSecure3Sha1 = (byte) 7, RsaSha256 = (byte) 8, RsaSha512 = (byte) 10, EllipticCurveCryptoGost = (byte) 12, Indirect = (byte) 252, PrivateDns = (byte) 253, PrivateObjectIdentifier = (byte) 254, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Http.ByteExtensions // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using System; using System.Globalization; namespace PcapDotNet.Packets.Http { internal static class ByteExtensions { public static bool IsChar(this byte value) { return (int) value <= (int) sbyte.MaxValue; } public static bool IsDigit(this byte value) { if ((int) value >= 48) return (int) value <= 57; return false; } public static bool IsHexadecimalDigit(this byte value) { if (((int) value < 65 || (int) value > 70) && ((int) value < 97 || (int) value > 102)) return ByteExtensions.IsDigit(value); return true; } public static int ToHexadecimalValue(this byte value) { if ((int) value >= 48 && (int) value <= 57) return (int) value - 48; if ((int) value >= 97 && (int) value <= 102) return (int) value - 97 + 10; if ((int) value >= 65 && (int) value <= 70) return (int) value - 65 + 10; throw new ArgumentOutOfRangeException("value", (object) value, string.Format((IFormatProvider) CultureInfo.InvariantCulture, "Must be a valid ASCII hexadecimal character ({0}-{1}, {2}-{3}, {4}-{5})", (object) 48, (object) 57, (object) 97, (object) 102, (object) 65, (object) 70)); } public static bool IsSpaceOrHorizontalTab(this byte value) { if ((int) value != 32) return (int) value == 9; return true; } public static bool IsControl(this byte value) { if ((int) value > 31) return (int) value == (int) sbyte.MaxValue; return true; } public static bool IsSeparator(this byte value) { byte num = value; if ((uint) num <= 44U) { switch (num) { case (byte) 9: case (byte) 32: case (byte) 34: case (byte) 40: case (byte) 41: case (byte) 44: break; default: goto label_6; } } else if ((uint) num <= 64U) { switch (num) { case (byte) 47: case (byte) 58: case (byte) 59: case (byte) 60: case (byte) 61: case (byte) 62: case (byte) 63: case (byte) 64: break; default: goto label_6; } } else { switch (num) { case (byte) 91: case (byte) 92: case (byte) 93: case (byte) 123: case (byte) 125: break; default: goto label_6; } } return true; label_6: return false; } public static bool IsToken(this byte value) { if (ByteExtensions.IsChar(value) && !ByteExtensions.IsControl(value)) return !ByteExtensions.IsSeparator(value); return false; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IpV4TimeOfDay // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using System; namespace PcapDotNet.Packets.IpV4 { public struct IpV4TimeOfDay : IEquatable<IpV4TimeOfDay> { private readonly uint _millisecondsSinceMidnightUniversalTime; public uint MillisecondsSinceMidnightUniversalTime { get { return this._millisecondsSinceMidnightUniversalTime; } } public TimeSpan TimeSinceMidnightUniversalTime { get { return TimeSpan.FromMilliseconds((double) this.MillisecondsSinceMidnightUniversalTime); } } public IpV4TimeOfDay(uint millisecondsSinceMidnightUniversalTime) { this._millisecondsSinceMidnightUniversalTime = millisecondsSinceMidnightUniversalTime; } public IpV4TimeOfDay(TimeSpan timeOfDaySinceMidnightUniversalTime) { this = new IpV4TimeOfDay((uint) timeOfDaySinceMidnightUniversalTime.TotalMilliseconds); } public static bool operator ==(IpV4TimeOfDay value1, IpV4TimeOfDay value2) { return value1.Equals(value2); } public static bool operator !=(IpV4TimeOfDay value1, IpV4TimeOfDay value2) { return !(value1 == value2); } public bool Equals(IpV4TimeOfDay other) { return (int) this.MillisecondsSinceMidnightUniversalTime == (int) other.MillisecondsSinceMidnightUniversalTime; } public override bool Equals(object obj) { if (obj is IpV4TimeOfDay) return this.Equals((IpV4TimeOfDay) obj); return false; } public override int GetHashCode() { return this.MillisecondsSinceMidnightUniversalTime.GetHashCode(); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Base.Sequence // Assembly: PcapDotNet.Base, Version=0.10.0.20668, Culture=neutral, PublicKeyToken=<KEY> // MVID: E9656A63-0145-422C-B8C8-79FDD7FB4270 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Base.dll using System; namespace PcapDotNet.Base { public static class Sequence { public static int GetHashCode(object value1, object value2) { if (value1 == null) throw new ArgumentNullException("value1"); if (value2 == null) throw new ArgumentNullException("value2"); return value1.GetHashCode() ^ value2.GetHashCode(); } public static int GetHashCode(object value1, object value2, object value3) { if (value3 == null) throw new ArgumentNullException("value3"); return Sequence.GetHashCode(value1, value2) ^ value3.GetHashCode(); } public static int GetHashCode(params object[] values) { if (values == null) throw new ArgumentNullException("values"); int num = 0; for (int index = 0; index != values.Length; ++index) num ^= values[index].GetHashCode(); return num; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.TcpDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using PcapDotNet.Packets.Http; using System; using System.Collections.Generic; using System.Collections.ObjectModel; namespace PcapDotNet.Packets.Transport { public sealed class TcpDatagram : TransportDatagram { public const int HeaderMinimumLength = 20; public const int HeaderMaximumLength = 60; private TcpOptions _options; private ReadOnlyCollection<HttpDatagram> _httpCollection; public uint SequenceNumber { get { return this.ReadUInt(4, Endianity.Big); } } public uint NextSequenceNumber { get { return (uint) ((ulong) this.SequenceNumber + (ulong) this.PayloadLength); } } public uint AcknowledgmentNumber { get { return this.ReadUInt(8, Endianity.Big); } } public int HeaderLength { get { return 4 * ((int) this[12] >> 4); } } public int RealHeaderLength { get { return Math.Min(this.HeaderLength, this.Length); } } public byte Reserved { get { return (byte) (((int) this[12] & 14) >> 1); } } public TcpControlBits ControlBits { get { return (TcpControlBits) ((uint) this.ReadUShort(12, Endianity.Big) & 511U); } } public ushort Window { get { return this.ReadUShort(14, Endianity.Big); } } public override ushort Checksum { get { return this.ReadUShort(16, Endianity.Big); } } public override bool IsChecksumOptional { get { return false; } } public ushort UrgentPointer { get { return this.ReadUShort(18, Endianity.Big); } } public TcpOptions Options { get { if (this._options == null && this.Length >= 20 && this.HeaderLength >= 20) this._options = new TcpOptions(this.Buffer, this.StartOffset + 20, this.RealHeaderLength - 20); return this._options; } } public int PayloadLength { get { return this.Length - this.HeaderLength; } } public bool IsCongestionWindowReduced { get { return (this.ControlBits & TcpControlBits.CongestionWindowReduced) == TcpControlBits.CongestionWindowReduced; } } public bool IsExplicitCongestionNotificationEcho { get { return (this.ControlBits & TcpControlBits.ExplicitCongestionNotificationEcho) == TcpControlBits.ExplicitCongestionNotificationEcho; } } public bool IsUrgent { get { return (this.ControlBits & TcpControlBits.Urgent) == TcpControlBits.Urgent; } } public bool IsAcknowledgment { get { return (this.ControlBits & TcpControlBits.Acknowledgment) == TcpControlBits.Acknowledgment; } } public bool IsPush { get { return (this.ControlBits & TcpControlBits.Push) == TcpControlBits.Push; } } public bool IsReset { get { return (this.ControlBits & TcpControlBits.Reset) == TcpControlBits.Reset; } } public bool IsSynchronize { get { return (this.ControlBits & TcpControlBits.Synchronize) == TcpControlBits.Synchronize; } } public bool IsFin { get { return (this.ControlBits & TcpControlBits.Fin) == TcpControlBits.Fin; } } public HttpDatagram Http { get { if (this.HttpCollection != null) return this.HttpCollection[0]; return (HttpDatagram) null; } } public ReadOnlyCollection<HttpDatagram> HttpCollection { get { if (this._httpCollection == null && this.Length >= 20 && this.Length >= this.HeaderLength) { List<HttpDatagram> list = new List<HttpDatagram>(); int num = 0; do { HttpDatagram datagram = HttpDatagram.CreateDatagram(this.Buffer, this.StartOffset + this.HeaderLength + num, this.Length - this.HeaderLength - num); num += datagram.Length; list.Add(datagram); } while (this.Length > this.HeaderLength + num); this._httpCollection = list.AsReadOnly(); } return this._httpCollection; } } public override Datagram Payload { get { if (this.Length < 20 || this.Length < this.HeaderLength) return (Datagram) null; return new Datagram(this.Buffer, this.StartOffset + this.HeaderLength, this.PayloadLength); } } internal override int ChecksumOffset { get { return 16; } } internal TcpDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public override ILayer ExtractLayer() { TcpLayer tcpLayer = new TcpLayer(); tcpLayer.Checksum = new ushort?(this.Checksum); tcpLayer.SourcePort = this.SourcePort; tcpLayer.DestinationPort = this.DestinationPort; tcpLayer.SequenceNumber = this.SequenceNumber; tcpLayer.AcknowledgmentNumber = this.AcknowledgmentNumber; tcpLayer.ControlBits = this.ControlBits; tcpLayer.Window = this.Window; tcpLayer.UrgentPointer = this.UrgentPointer; tcpLayer.Options = this.Options; return (ILayer) tcpLayer; } protected override bool CalculateIsValid() { if (this.Length >= 20 && this.Length >= this.HeaderLength && this.HeaderLength >= 20) return this.Options.IsValid; return false; } internal static void WriteHeader(byte[] buffer, int offset, ushort sourcePort, ushort destinationPort, uint sequenceNumber, uint acknowledgmentNumber, TcpControlBits controlBits, ushort window, ushort urgentPointer, TcpOptions options) { int num = 20 + options.BytesLength; TransportDatagram.WriteHeader(buffer, offset, sourcePort, destinationPort); ByteArrayExtensions.Write(buffer, offset + 4, sequenceNumber, Endianity.Big); ByteArrayExtensions.Write(buffer, offset + 8, acknowledgmentNumber, Endianity.Big); ByteArrayExtensions.Write(buffer, offset + 12, (ushort) ((TcpControlBits) (num / 4 << 12) | controlBits), Endianity.Big); ByteArrayExtensions.Write(buffer, offset + 14, window, Endianity.Big); ByteArrayExtensions.Write(buffer, offset + 18, urgentPointer, Endianity.Big); options.Write(buffer, offset + 20); } internal static class Offset { public const int SequenceNumber = 4; public const int AcknowledgmentNumber = 8; public const int HeaderLengthAndFlags = 12; public const int Window = 14; public const int Checksum = 16; public const int UrgentPointer = 18; public const int Options = 20; } private static class Mask { public const byte Reserved = (byte) 14; public const ushort ControlBits = (ushort) 511; } private static class Shift { public const int HeaderLength = 4; public const int Reserved = 1; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Igmp.IgmpReportVersion2Layer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Igmp { public sealed class IgmpReportVersion2Layer : IgmpVersion2Layer { public override IgmpMessageType MessageType { get { return IgmpMessageType.MembershipReportVersion2; } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: AcuLink_Bridge_Reader_CSharp.Properties.Settings // Assembly: AcuLink_Bridge_Reader_CS, Version=2014.9.18.2041, Culture=neutral, PublicKeyToken=null // MVID: 2DF0938E-D9D0-414E-AB5D-7B9A655FB464 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\AcuLink_Bridge_Reader_CS.exe using System; using System.CodeDom.Compiler; using System.Configuration; using System.Diagnostics; using System.Runtime.CompilerServices; namespace AcuLink_Bridge_Reader_CSharp.Properties { [CompilerGenerated] [GeneratedCode("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "192.168.3.11")] internal sealed class Settings : ApplicationSettingsBase { private static Settings defaultInstance = (Settings) SettingsBase.Synchronized((SettingsBase) new Settings()); public static Settings Default { get { Settings settings = Settings.defaultInstance; return settings; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("0")] public double pressureOffset { get { return (double) this["pressureOffset"]; } set { this["pressureOffset"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string wuStation { get { return (string) this["wuStation"]; } set { this["wuStation"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string wuPwd { get { return (string) this["wuPwd"]; } set { this["wuPwd"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string networkDevice { get { return (string) this["networkDevice"]; } set { this["networkDevice"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("False")] public bool postToWunderground { get { return (bool) this["postToWunderground"]; } set { this["postToWunderground"] = (object) (bool) (value ? 1 : 0); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("False")] public bool postToWeatherBug { get { return (bool) this["postToWeatherBug"]; } set { this["postToWeatherBug"] = (object) (bool) (value ? 1 : 0); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string wbStation { get { return (string) this["wbStation"]; } set { this["wbStation"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string wbPub { get { return (string) this["wbPub"]; } set { this["wbPub"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string wbPwd { get { return (string) this["wbPwd"]; } set { this["wbPwd"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("False")] public bool writeToCSV { get { return (bool) this["writeToCSV"]; } set { this["writeToCSV"] = (object) (bool) (value ? 1 : 0); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("False")] public bool postToPws { get { return (bool) this["postToPws"]; } set { this["postToPws"] = (object) (bool) (value ? 1 : 0); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string pwsStation { get { return (string) this["pwsStation"]; } set { this["pwsStation"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string pwsPwd { get { return (string) this["pwsPwd"]; } set { this["pwsPwd"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string filterOnSensorId { get { return (string) this["filterOnSensorId"]; } set { this["filterOnSensorId"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("5n1")] public string sensorType { get { return (string) this["sensorType"]; } set { this["sensorType"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string awStation { get { return (string) this["awStation"]; } set { this["awStation"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string awPwd { get { return (string) this["awPwd"]; } set { this["awPwd"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("False")] public bool postToAWeather { get { return (bool) this["postToAWeather"]; } set { this["postToAWeather"] = (object) (bool) (value ? 1 : 0); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string sensorIdTemp { get { return (string) this["sensorIdTemp"]; } set { this["sensorIdTemp"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string sensorIdHumidity { get { return (string) this["sensorIdHumidity"]; } set { this["sensorIdHumidity"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string sensorIdWind { get { return (string) this["sensorIdWind"]; } set { this["sensorIdWind"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string sensorIdRain { get { return (string) this["sensorIdRain"]; } set { this["sensorIdRain"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string sensorTypeTemp { get { return (string) this["sensorTypeTemp"]; } set { this["sensorTypeTemp"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string sensorTypeHumidity { get { return (string) this["sensorTypeHumidity"]; } set { this["sensorTypeHumidity"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string sensorTypeWind { get { return (string) this["sensorTypeWind"]; } set { this["sensorTypeWind"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string sensorTypeRain { get { return (string) this["sensorTypeRain"]; } set { this["sensorTypeRain"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string csvFilePath { get { return (string) this["csvFilePath"]; } set { this["csvFilePath"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("0")] public Decimal tempOffset { get { return (Decimal) this["tempOffset"]; } set { this["tempOffset"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("False")] public bool debugMode { get { return (bool) this["debugMode"]; } set { this["debugMode"] = (object) (bool) (value ? 1 : 0); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("0")] public double rainDay { get { return (double) this["rainDay"]; } set { this["rainDay"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("04/20/2014 04:20:00")] public DateTime timestamp { get { return (DateTime) this["timestamp"]; } set { this["timestamp"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string sensorTypeSoil { get { return (string) this["sensorTypeSoil"]; } set { this["sensorTypeSoil"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string sensorIdSoil { get { return (string) this["sensorIdSoil"]; } set { this["sensorIdSoil"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("False")] public bool autoRestart { get { return (bool) this["autoRestart"]; } set { this["autoRestart"] = (object) (bool) (value ? 1 : 0); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("100")] public Decimal windOffsetPct { get { return (Decimal) this["windOffsetPct"]; } set { this["windOffsetPct"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("0")] public Decimal soilTempOffset { get { return (Decimal) this["soilTempOffset"]; } set { this["soilTempOffset"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string owUsername { get { return (string) this["owUsername"]; } set { this["owUsername"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string owPwd { get { return (string) this["owPwd"]; } set { this["owPwd"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string owLat { get { return (string) this["owLat"]; } set { this["owLat"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string owLon { get { return (string) this["owLon"]; } set { this["owLon"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string owAlt { get { return (string) this["owAlt"]; } set { this["owAlt"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("False")] public bool postToOw { get { return (bool) this["postToOw"]; } set { this["postToOw"] = (object) (bool) (value ? 1 : 0); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string owStationName { get { return (string) this["owStationName"]; } set { this["owStationName"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("False")] public bool postToCw { get { return (bool) this["postToCw"]; } set { this["postToCw"] = (object) (bool) (value ? 1 : 0); } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string cwRegNum { get { return (string) this["cwRegNum"]; } set { this["cwRegNum"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("cwop.aprs.net")] public string cwHostName { get { return (string) this["cwHostName"]; } set { this["cwHostName"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string cwLat { get { return (string) this["cwLat"]; } set { this["cwLat"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("")] public string cwLon { get { return (string) this["cwLon"]; } set { this["cwLon"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("-1")] public string cwPasscode { get { return (string) this["cwPasscode"]; } set { this["cwPasscode"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("5")] public int cwUpdateMinutes { get { return (int) this["cwUpdateMinutes"]; } set { this["cwUpdateMinutes"] = (object) value; } } [UserScopedSetting] [DebuggerNonUserCode] [DefaultSettingValue("0")] public Decimal humidityOffset { get { return (Decimal) this["humidityOffset"]; } set { this["humidityOffset"] = (object) value; } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Gre.GreSourceRouteEntryUnknown // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; namespace PcapDotNet.Packets.Gre { public sealed class GreSourceRouteEntryUnknown : GreSourceRouteEntry { private readonly GreSourceRouteEntryAddressFamily _addressFamily; private readonly Datagram _data; private readonly int _offset; public override GreSourceRouteEntryAddressFamily AddressFamily { get { return this._addressFamily; } } public override byte PayloadLength { get { return (byte) this.Data.Length; } } public override byte PayloadOffset { get { return (byte) this._offset; } } public Datagram Data { get { return this._data; } } protected override int PayloadHashCode { get { return this.Data.GetHashCode(); } } public GreSourceRouteEntryUnknown(GreSourceRouteEntryAddressFamily addressFamily, Datagram data, int offset) { this._addressFamily = addressFamily; this._data = data; this._offset = offset; } protected override bool EqualsPayloads(GreSourceRouteEntry other) { return this.Data.Equals((DataSegment) ((GreSourceRouteEntryUnknown) other).Data); } protected override void WritePayload(byte[] buffer, int offset) { ByteArrayExtensions.Write(buffer, offset, (DataSegment) this.Data); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Http.HttpResponseDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System.Collections.Generic; namespace PcapDotNet.Packets.Http { public sealed class HttpResponseDatagram : HttpDatagram { public override bool IsRequest { get { return false; } } public uint? StatusCode { get; private set; } public Datagram ReasonPhrase { get; private set; } internal HttpResponseDatagram(byte[] buffer, int offset, int length) : this(buffer, offset, HttpResponseDatagram.Parse(buffer, offset, length)) { } private HttpResponseDatagram(byte[] buffer, int offset, HttpResponseDatagram.ParseInfo parseInfo) : base(buffer, offset, parseInfo.Length, parseInfo.Version, parseInfo.Header, parseInfo.Body) { this.StatusCode = parseInfo.StatusCode; this.ReasonPhrase = parseInfo.ReasonPhrase; } public override ILayer ExtractLayer() { HttpResponseLayer httpResponseLayer = new HttpResponseLayer(); httpResponseLayer.Version = this.Version; httpResponseLayer.StatusCode = this.StatusCode; httpResponseLayer.ReasonPhrase = (DataSegment) this.ReasonPhrase; httpResponseLayer.Header = this.Header; httpResponseLayer.Body = this.Body; return (ILayer) httpResponseLayer; } private static HttpResponseDatagram.ParseInfo Parse(byte[] buffer, int offset, int length) { HttpParser httpParser = new HttpParser(buffer, offset, length); HttpVersion version; uint? number; Datagram reasonPhrase; httpParser.Version(out version).Space().DecimalNumber(3, out number).Space().SkipSpaces().ReasonPhrase(out reasonPhrase).CarriageReturnLineFeed(); HttpResponseDatagram.ParseInfo parseInfo1 = new HttpResponseDatagram.ParseInfo(); parseInfo1.Length = length; parseInfo1.Version = version; parseInfo1.StatusCode = number; parseInfo1.ReasonPhrase = reasonPhrase; HttpResponseDatagram.ParseInfo parseInfo2 = parseInfo1; if (!httpParser.Success) return parseInfo2; int num1 = httpParser.Offset - offset; int? endOffset; HttpHeader header = new HttpHeader((IEnumerable<KeyValuePair<string, IEnumerable<byte>>>) HttpDatagram.GetHeaderFields(out endOffset, buffer, offset + num1, length - num1)); parseInfo2.Header = header; if (!endOffset.HasValue) return parseInfo2; int num2 = endOffset.Value - offset - num1; Datagram datagram = HttpDatagram.ParseBody(buffer, offset + num1 + num2, length - num1 - num2, HttpResponseDatagram.IsBodyPossible(number.Value), header); parseInfo2.Body = datagram; parseInfo2.Length = num1 + num2 + datagram.Length; return parseInfo2; } private static bool IsBodyPossible(uint statusCode) { return (statusCode < 100U || statusCode > 199U) && ((int) statusCode != 204 && (int) statusCode != 205) && (int) statusCode != 304; } private class ParseInfo : HttpDatagram.ParseInfoBase { public Datagram ReasonPhrase { get; set; } public uint? StatusCode { get; set; } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Http.HttpFieldParameters // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Text; namespace PcapDotNet.Packets.Http { public sealed class HttpFieldParameters : IEnumerable<KeyValuePair<string, string>>, IEnumerable, IEquatable<HttpFieldParameters> { private readonly Dictionary<string, string> _parameters = new Dictionary<string, string>(); public int Count { get { return this._parameters.Count; } } public string this[string name] { get { string str; if (!this._parameters.TryGetValue(name, out str)) return (string) null; return str; } } public HttpFieldParameters(params KeyValuePair<string, string>[] parameters) : this((IEnumerable<KeyValuePair<string, string>>) parameters) { } [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public HttpFieldParameters(IEnumerable<KeyValuePair<string, string>> parameters) { this._parameters = Enumerable.ToDictionary<KeyValuePair<string, string>, string, string>(parameters, (Func<KeyValuePair<string, string>, string>) (pair => pair.Key), (Func<KeyValuePair<string, string>, string>) (pair => pair.Value)); } internal HttpFieldParameters(IEnumerable<string> parametersNames, IEnumerable<string> parametersValues) { IEnumerator<string> enumerator1 = parametersNames.GetEnumerator(); IEnumerator<string> enumerator2 = parametersValues.GetEnumerator(); while (enumerator1.MoveNext()) { if (!enumerator2.MoveNext()) throw new ArgumentException(string.Format((IFormatProvider) CultureInfo.InvariantCulture, "more names ({0}) were given than values ({1})", new object[2] { (object) Enumerable.Count<string>(parametersNames), (object) Enumerable.Count<string>(parametersValues) }), "parametersValues"); this._parameters.Add(enumerator1.Current, enumerator2.Current); } if (enumerator2.MoveNext()) throw new ArgumentException(string.Format((IFormatProvider) CultureInfo.InvariantCulture, "more values ({0}) were given than names ({1})", new object[2] { (object) Enumerable.Count<string>(parametersValues), (object) Enumerable.Count<string>(parametersNames) }), "parametersNames"); } public IEnumerator<KeyValuePair<string, string>> GetEnumerator() { return (IEnumerator<KeyValuePair<string, string>>) this._parameters.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator) this.GetEnumerator(); } public bool Equals(HttpFieldParameters other) { if (other != null) return IDictionaryExtensions.DictionaryEquals<string, string>((IDictionary<string, string>) this._parameters, (IDictionary<string, string>) other._parameters); return false; } public override bool Equals(object obj) { return this.Equals(obj as HttpFieldParameters); } public override int GetHashCode() { return IEnumerableExtensions.Xor<KeyValuePair<string, string>>(Enumerable.Select<KeyValuePair<string, string>, KeyValuePair<string, string>>((IEnumerable<KeyValuePair<string, string>>) this._parameters, (Func<KeyValuePair<string, string>, KeyValuePair<string, string>>) (pair => new KeyValuePair<string, string>(pair.Key.ToUpperInvariant(), pair.Value))), (Func<KeyValuePair<string, string>, int>) (pair => Sequence.GetHashCode((object) pair.Key, (object) pair.Value))); } public override string ToString() { if (!Enumerable.Any<KeyValuePair<string, string>>((IEnumerable<KeyValuePair<string, string>>) this)) return string.Empty; StringBuilder stringBuilder = new StringBuilder(); foreach (KeyValuePair<string, string> keyValuePair in this) { stringBuilder.Append(";"); stringBuilder.Append(keyValuePair.Key); stringBuilder.Append("="); stringBuilder.Append(keyValuePair.Value); } return stringBuilder.ToString(); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.TcpOptionConnectionCountBase // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Transport { public abstract class TcpOptionConnectionCountBase : TcpOptionComplex, IEquatable<TcpOptionConnectionCountBase> { public const int OptionLength = 6; public const int OptionValueLength = 4; public uint ConnectionCount { get; private set; } public override sealed int Length { get { return 6; } } public override sealed bool IsAppearsAtMostOnce { get { return true; } } protected TcpOptionConnectionCountBase(TcpOptionType optionType, uint connectionCount) : base(optionType) { this.ConnectionCount = connectionCount; } public bool Equals(TcpOptionConnectionCountBase other) { if (other == null || this.OptionType != other.OptionType) return false; return (int) this.ConnectionCount == (int) other.ConnectionCount; } public override sealed bool Equals(TcpOption other) { return this.Equals(other as TcpOptionConnectionCountBase); } public override sealed int GetHashCode() { return base.GetHashCode() ^ this.ConnectionCount.GetHashCode(); } internal override sealed void Write(byte[] buffer, ref int offset) { base.Write(buffer, ref offset); ByteArrayExtensions.Write(buffer, ref offset, this.ConnectionCount, Endianity.Big); } protected static bool TryRead(out uint connectionCount, byte[] buffer, ref int offset, byte valueLength) { if ((int) valueLength != 4) { connectionCount = 0U; return false; } connectionCount = ByteArrayExtensions.ReadUInt(buffer, ref offset, Endianity.Big); return true; } } } <file_sep>namespace ForecastIOPortable.Models { using System.Collections.Generic; using System.Runtime.Serialization; /// <summary> /// A day-by-day forecast. /// </summary> [DataContract] public class DailyForecast { /// <summary> /// Gets or sets a human-readable summary of the forecast. /// </summary> [DataMember(Name = "summary")] public string Summary { get; set; } /// <summary> /// Gets or sets machine-readable text that can be used to select an icon to display. /// </summary> [DataMember(Name = "icon")] public string Icon { get; set; } /// <summary> /// Gets or sets the individual days that make up this forecast. /// </summary> [DataMember(Name = "data")] public IList<DayDataPoint> Days { get; set; } } } <file_sep>using System; namespace CGurus.Weather.WundergroundAPI.Models { public class Alert { public string Date { get; set; } public long Date_Epoch { get; set; } public DateTime Date_EpochDate { get { return Utilities.EpochConverter.FromUnixTime(this.Date_Epoch); } } public string Description { get; set; } public string Expires { get; set; } public long Expires_Epoch { get; set; } public DateTime Expires_EpochDate { get { return Utilities.EpochConverter.FromUnixTime(this.Expires_Epoch); } } public string Message { get; set; } public string Phenomena { get; set; } public string Significance { get; set; } public string Type { get; set; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpInformationReplyLayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Icmp { public sealed class IcmpInformationReplyLayer : IcmpIdentifiedLayer { public override IcmpMessageType MessageType { get { return IcmpMessageType.InformationReply; } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.UdpLayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using PcapDotNet.Packets.IpV4; namespace PcapDotNet.Packets.Transport { public sealed class UdpLayer : TransportLayer { public override bool CalculateChecksum { get { return this.CalculateChecksumValue; } } public bool CalculateChecksumValue { get; set; } public override IpV4Protocol PreviousLayerProtocol { get { return IpV4Protocol.Udp; } } public override int ChecksumOffset { get { return 6; } } public override bool IsChecksumOptional { get { return true; } } public override int Length { get { return 8; } } public override void Write(byte[] buffer, int offset, int payloadLength, ILayer previousLayer, ILayer nextLayer) { UdpDatagram.WriteHeader(buffer, offset, this.SourcePort, this.DestinationPort, payloadLength); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpIdentifiedLayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; namespace PcapDotNet.Packets.Icmp { public abstract class IcmpIdentifiedLayer : IcmpLayer { public ushort Identifier { get; set; } public ushort SequenceNumber { get; set; } protected override sealed uint Variable { get { return BitSequence.Merge(this.Identifier, this.SequenceNumber); } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpLayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using PcapDotNet.Packets.IpV4; using System.Diagnostics.CodeAnalysis; namespace PcapDotNet.Packets.Icmp { public abstract class IcmpLayer : SimpleLayer, IIpV4NextLayer, ILayer { public abstract IcmpMessageType MessageType { get; } public virtual byte CodeValue { get { return (byte) 0; } } public IcmpMessageTypeAndCode MessageTypeAndCode { get { return (IcmpMessageTypeAndCode) BitSequence.Merge((byte) this.MessageType, this.CodeValue); } } public ushort? Checksum { get; set; } protected virtual uint Variable { get { return 0U; } } public override sealed int Length { get { return 8 + this.PayloadLength; } } protected virtual int PayloadLength { get { return 0; } } public IpV4Protocol PreviousLayerProtocol { get { return IpV4Protocol.InternetControlMessageProtocol; } } [SuppressMessage("Microsoft.Usage", "CA2233:OperationsShouldNotOverflow", MessageId = "offset+8")] protected override sealed void Write(byte[] buffer, int offset) { IcmpDatagram.WriteHeader(buffer, offset, this.MessageType, this.CodeValue, this.Variable); this.WritePayload(buffer, offset + 8); } protected virtual void WritePayload(byte[] buffer, int offset) { } public override sealed void Finalize(byte[] buffer, int offset, int payloadLength, ILayer nextLayer) { IcmpDatagram.WriteChecksum(buffer, offset, this.Length + payloadLength, this.Checksum); } public bool Equals(IcmpLayer other) { if (other != null && this.MessageType == other.MessageType && (int) this.CodeValue == (int) other.CodeValue) { ushort? checksum1 = this.Checksum; ushort? checksum2 = other.Checksum; if (((int) checksum1.GetValueOrDefault() != (int) checksum2.GetValueOrDefault() ? 0 : (checksum1.HasValue == checksum2.HasValue ? 1 : 0)) != 0 && (int) this.Variable == (int) other.Variable) return this.EqualPayload(other); } return false; } public override sealed bool Equals(Layer other) { return this.Equals(other as IcmpLayer); } public override sealed int GetHashCode() { return base.GetHashCode() ^ Sequence.GetHashCode((object) this.MessageTypeAndCode, (object) this.Variable) ^ this.Checksum.GetHashCode(); } public override sealed string ToString() { return (string) (object) this.MessageType + (object) "." + (string) (object) this.CodeValue + "(" + (string) (object) this.Variable + ")"; } protected virtual bool EqualPayload(IcmpLayer other) { return true; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataTransactionKey // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Globalization; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.TKey)] public sealed class DnsResourceDataTransactionKey : DnsResourceData, IEquatable<DnsResourceDataTransactionKey> { private const int ConstantPartLength = 16; public DnsDomainName Algorithm { get; private set; } public SerialNumber32 Inception { get; private set; } public SerialNumber32 Expiration { get; private set; } public DnsTransactionKeyMode Mode { get; private set; } public DnsResponseCode Error { get; private set; } public DataSegment Key { get; private set; } public DataSegment Other { get; private set; } public DnsResourceDataTransactionKey(DnsDomainName algorithm, SerialNumber32 inception, SerialNumber32 expiration, DnsTransactionKeyMode mode, DnsResponseCode error, DataSegment key, DataSegment other) { if (key == null) throw new ArgumentNullException("key"); if (other == null) throw new ArgumentNullException("other"); if (key.Length > (int) ushort.MaxValue) throw new ArgumentOutOfRangeException("key", (object) key.Length, string.Format((IFormatProvider) CultureInfo.InvariantCulture, "Cannot be longer than {0}", new object[1] { (object) ushort.MaxValue })); if (other.Length > (int) ushort.MaxValue) throw new ArgumentOutOfRangeException("other", (object) other.Length, string.Format((IFormatProvider) CultureInfo.InvariantCulture, "Cannot be longer than {0}", new object[1] { (object) ushort.MaxValue })); this.Algorithm = algorithm; this.Inception = inception; this.Expiration = expiration; this.Mode = mode; this.Error = error; this.Key = key; this.Other = other; } internal DnsResourceDataTransactionKey() : this(DnsDomainName.Root, (SerialNumber32) 0U, (SerialNumber32) 0U, DnsTransactionKeyMode.DiffieHellmanExchange, DnsResponseCode.NoError, DataSegment.Empty, DataSegment.Empty) { } public bool Equals(DnsResourceDataTransactionKey other) { if (other != null && this.Algorithm.Equals(other.Algorithm) && this.Inception.Equals(other.Inception) && (this.Expiration.Equals(other.Expiration) && this.Mode.Equals((object) other.Mode) && (this.Error.Equals((object) other.Error) && this.Key.Equals(other.Key)))) return this.Other.Equals(other.Other); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataTransactionKey); } public override int GetHashCode() { return Sequence.GetHashCode((object) this.Algorithm, (object) this.Inception, (object) this.Expiration, (object) BitSequence.Merge((ushort) this.Mode, (ushort) this.Error), (object) this.Key, (object) this.Other); } internal override int GetLength(DnsDomainNameCompressionData compressionData, int offsetInDns) { return this.Algorithm.GetLength(compressionData, offsetInDns) + 16 + this.Key.Length + this.Other.Length; } internal override int WriteData(byte[] buffer, int dnsOffset, int offsetInDns, DnsDomainNameCompressionData compressionData) { int num = this.Algorithm.Write(buffer, dnsOffset, compressionData, offsetInDns); int offset1 = dnsOffset + offsetInDns + num; ByteArrayExtensions.Write(buffer, offset1, this.Inception.Value, Endianity.Big); ByteArrayExtensions.Write(buffer, offset1 + 4, this.Expiration.Value, Endianity.Big); ByteArrayExtensions.Write(buffer, offset1 + 8, (ushort) this.Mode, Endianity.Big); ByteArrayExtensions.Write(buffer, offset1 + 10, (ushort) this.Error, Endianity.Big); ByteArrayExtensions.Write(buffer, offset1 + 12, (ushort) this.Key.Length, Endianity.Big); this.Key.Write(buffer, offset1 + 14); int offset2 = offset1 + 14 + this.Key.Length; ByteArrayExtensions.Write(buffer, offset2, (ushort) this.Other.Length, Endianity.Big); this.Other.Write(buffer, offset2 + 2); return num + 16 + this.Key.Length + this.Other.Length; } internal override DnsResourceData CreateInstance(DnsDatagram dns, int offsetInDns, int length) { if (length < 17) return (DnsResourceData) null; DnsDomainName domainName; int numBytesRead; if (!DnsDomainName.TryParse(dns, offsetInDns, length - 16, out domainName, out numBytesRead)) return (DnsResourceData) null; offsetInDns += numBytesRead; length -= numBytesRead; if (length < 16) return (DnsResourceData) null; uint num1 = dns.ReadUInt(offsetInDns, Endianity.Big); uint num2 = dns.ReadUInt(offsetInDns + 4, Endianity.Big); DnsTransactionKeyMode mode = (DnsTransactionKeyMode) dns.ReadUShort(offsetInDns + 8, Endianity.Big); DnsResponseCode error = (DnsResponseCode) dns.ReadUShort(offsetInDns + 10, Endianity.Big); int length1 = (int) dns.ReadUShort(offsetInDns + 12, Endianity.Big); if (length < 16 + length1) return (DnsResourceData) null; DataSegment key = dns.Subsegment(offsetInDns + 14, length1); int num3 = 14 + length1; offsetInDns += num3; length -= num3; int length2 = (int) dns.ReadUShort(offsetInDns, Endianity.Big); if (length != 2 + length2) return (DnsResourceData) null; DataSegment other = dns.Subsegment(offsetInDns + 2, length2); return (DnsResourceData) new DnsResourceDataTransactionKey(domainName, (SerialNumber32) num1, (SerialNumber32) num2, mode, error, key, other); } private static class OffsetAfterAlgorithm { public const int Inception = 0; public const int Expiration = 4; public const int Mode = 8; public const int Error = 10; public const int KeySize = 12; public const int KeyData = 14; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataSshFingerprint // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.SshFingerprint)] public sealed class DnsResourceDataSshFingerprint : DnsResourceDataSimple, IEquatable<DnsResourceDataSshFingerprint> { private const int ConstPartLength = 2; public DnsFingerprintPublicKeyAlgorithm Algorithm { get; private set; } public DnsFingerprintType FingerprintType { get; private set; } public DataSegment Fingerprint { get; private set; } public DnsResourceDataSshFingerprint(DnsFingerprintPublicKeyAlgorithm algorithm, DnsFingerprintType fingerprintType, DataSegment fingerprint) { this.Algorithm = algorithm; this.FingerprintType = fingerprintType; this.Fingerprint = fingerprint; } internal DnsResourceDataSshFingerprint() : this(DnsFingerprintPublicKeyAlgorithm.Rsa, DnsFingerprintType.Sha1, DataSegment.Empty) { } public bool Equals(DnsResourceDataSshFingerprint other) { if (other != null && this.Algorithm.Equals((object) other.Algorithm) && this.FingerprintType.Equals((object) other.FingerprintType)) return this.Fingerprint.Equals(other.Fingerprint); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataSshFingerprint); } public override int GetHashCode() { return Sequence.GetHashCode((object) BitSequence.Merge((byte) this.Algorithm, (byte) this.FingerprintType), (object) this.Fingerprint); } internal override int GetLength() { return 2 + this.Fingerprint.Length; } internal override void WriteDataSimple(byte[] buffer, int offset) { ByteArrayExtensions.Write(buffer, offset, (byte) this.Algorithm); ByteArrayExtensions.Write(buffer, offset + 1, (byte) this.FingerprintType); this.Fingerprint.Write(buffer, offset + 2); } internal override DnsResourceData CreateInstance(DataSegment data) { return (DnsResourceData) new DnsResourceDataSshFingerprint((DnsFingerprintPublicKeyAlgorithm) data[0], (DnsFingerprintType) data[1], data.Subsegment(2, data.Length - 2)); } private static class Offset { public const int Algorithm = 0; public const int FingerprintType = 1; public const int Fingerprint = 2; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Igmp.IgmpDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using PcapDotNet.Packets.IpV4; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace PcapDotNet.Packets.Igmp { public sealed class IgmpDatagram : Datagram { private static readonly TimeSpan _maxMaxResponseTime = TimeSpan.FromSeconds(25.5) + TimeSpan.FromSeconds(0.1) - TimeSpan.FromTicks(1L); private static readonly TimeSpan _maxVersion3MaxResponseTime = TimeSpan.FromSeconds(0.1 * (double) IgmpDatagram.CodeToValue(byte.MaxValue)) + TimeSpan.FromSeconds(0.1) - TimeSpan.FromTicks(1L); private static readonly TimeSpan _maxQueryInterval = TimeSpan.FromSeconds((double) IgmpDatagram.CodeToValue(byte.MaxValue)) + TimeSpan.FromSeconds(1.0) - TimeSpan.FromTicks(1L); public const int HeaderLength = 8; public const int QueryVersion3HeaderLength = 12; public const byte MaxQueryRobustnessVariable = (byte) 7; private bool? _isChecksumCorrect; private ReadOnlyCollection<IpV4Address> _sourceAddresses; private ReadOnlyCollection<IgmpGroupRecordDatagram> _groupRecords; public static TimeSpan MaxMaxResponseTime { get { return IgmpDatagram._maxMaxResponseTime; } } public static TimeSpan MaxVersion3MaxResponseTime { get { return IgmpDatagram._maxVersion3MaxResponseTime; } } public static TimeSpan MaxQueryInterval { get { return IgmpDatagram._maxQueryInterval; } } public IgmpMessageType MessageType { get { return (IgmpMessageType) this[0]; } } public int Version { get { switch (this.MessageType) { case IgmpMessageType.MembershipQuery: switch (this.QueryVersion) { case IgmpQueryVersion.Version1: return 1; case IgmpQueryVersion.Version2: return 2; case IgmpQueryVersion.Version3: return 3; default: throw new InvalidOperationException("Invalid Query Version " + (object) this.QueryVersion); } case IgmpMessageType.MembershipReportVersion1: return 1; case IgmpMessageType.MembershipReportVersion2: return 2; case IgmpMessageType.LeaveGroupVersion2: return 2; case IgmpMessageType.MembershipReportVersion3: return 3; default: throw new InvalidOperationException("Invalid IGMP Message Type " + (object) this.MessageType); } } } public IgmpQueryVersion QueryVersion { get { if (this.MessageType != IgmpMessageType.MembershipQuery) return IgmpQueryVersion.None; if (this.Length >= 12) return IgmpQueryVersion.Version3; if (this.Length != 8) return IgmpQueryVersion.Unknown; return (int) this.MaxResponseCode == 0 ? IgmpQueryVersion.Version1 : IgmpQueryVersion.Version2; } } public byte MaxResponseCode { get { return this[1]; } } public TimeSpan MaxResponseTime { get { byte maxResponseCode = this.MaxResponseCode; return TimeSpan.FromMilliseconds((double) (100 * ((int) maxResponseCode < 128 || this.MessageType != IgmpMessageType.MembershipQuery || this.QueryVersion != IgmpQueryVersion.Version3 ? (int) maxResponseCode : IgmpDatagram.CodeToValue(maxResponseCode)))); } } public ushort Checksum { get { return this.ReadUShort(2, Endianity.Big); } } public bool IsChecksumCorrect { get { if (!this._isChecksumCorrect.HasValue) this._isChecksumCorrect = new bool?((int) this.CalculateChecksum() == (int) this.Checksum); return this._isChecksumCorrect.Value; } } public IpV4Address GroupAddress { get { return this.ReadIpV4Address(4, Endianity.Big); } } public bool IsSuppressRouterSideProcessing { get { return ((int) this[8] >> 3 & 1) == 1; } } public byte QueryRobustnessVariable { get { return (byte) ((uint) this[8] & 7U); } } public byte QueryIntervalCode { get { return this[9]; } } public TimeSpan QueryInterval { get { return TimeSpan.FromSeconds((int) this.QueryIntervalCode < 128 ? (double) this.QueryIntervalCode : (double) IgmpDatagram.CodeToValue(this.QueryIntervalCode)); } } public ushort NumberOfSources { get { return this.ReadUShort(10, Endianity.Big); } } public ReadOnlyCollection<IpV4Address> SourceAddresses { get { if (this._sourceAddresses == null) { IpV4Address[] ipV4AddressArray = new IpV4Address[Math.Min((int) this.NumberOfSources, (this.Length - 12) / 4)]; for (int index = 0; index != ipV4AddressArray.Length; ++index) ipV4AddressArray[index] = this.ReadIpV4Address(12 + 4 * index, Endianity.Big); this._sourceAddresses = new ReadOnlyCollection<IpV4Address>((IList<IpV4Address>) ipV4AddressArray); } return this._sourceAddresses; } } public ushort NumberOfGroupRecords { get { return this.ReadUShort(6, Endianity.Big); } } public ReadOnlyCollection<IgmpGroupRecordDatagram> GroupRecords { get { if (this._groupRecords == null) { IgmpGroupRecordDatagram[] groupRecordDatagramArray = new IgmpGroupRecordDatagram[(int) this.NumberOfGroupRecords]; int offset = this.StartOffset + 8; for (int index = 0; index != groupRecordDatagramArray.Length; ++index) { groupRecordDatagramArray[index] = new IgmpGroupRecordDatagram(this.Buffer, offset); offset += groupRecordDatagramArray[index].Length; } this._groupRecords = new ReadOnlyCollection<IgmpGroupRecordDatagram>((IList<IgmpGroupRecordDatagram>) groupRecordDatagramArray); } return this._groupRecords; } } internal IgmpDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public override ILayer ExtractLayer() { switch (this.MessageType) { case IgmpMessageType.MembershipQuery: switch (this.QueryVersion) { case IgmpQueryVersion.Version1: IgmpQueryVersion1Layer queryVersion1Layer = new IgmpQueryVersion1Layer(); queryVersion1Layer.GroupAddress = this.GroupAddress; return (ILayer) queryVersion1Layer; case IgmpQueryVersion.Version2: IgmpQueryVersion2Layer queryVersion2Layer = new IgmpQueryVersion2Layer(); queryVersion2Layer.MaxResponseTime = this.MaxResponseTime; queryVersion2Layer.GroupAddress = this.GroupAddress; return (ILayer) queryVersion2Layer; case IgmpQueryVersion.Version3: return (ILayer) new IgmpQueryVersion3Layer() { SourceAddresses = this.SourceAddresses, MaxResponseTime = this.MaxResponseTime, GroupAddress = this.GroupAddress, IsSuppressRouterSideProcessing = this.IsSuppressRouterSideProcessing, QueryRobustnessVariable = this.QueryRobustnessVariable, QueryInterval = this.QueryInterval }; default: throw new InvalidOperationException("Invalid Query Version " + (object) this.QueryVersion); } case IgmpMessageType.MembershipReportVersion1: IgmpReportVersion1Layer reportVersion1Layer = new IgmpReportVersion1Layer(); reportVersion1Layer.GroupAddress = this.GroupAddress; return (ILayer) reportVersion1Layer; case IgmpMessageType.MembershipReportVersion2: IgmpReportVersion2Layer reportVersion2Layer = new IgmpReportVersion2Layer(); reportVersion2Layer.MaxResponseTime = this.MaxResponseTime; reportVersion2Layer.GroupAddress = this.GroupAddress; return (ILayer) reportVersion2Layer; case IgmpMessageType.LeaveGroupVersion2: IgmpLeaveGroupVersion2Layer groupVersion2Layer = new IgmpLeaveGroupVersion2Layer(); groupVersion2Layer.MaxResponseTime = this.MaxResponseTime; groupVersion2Layer.GroupAddress = this.GroupAddress; return (ILayer) groupVersion2Layer; case IgmpMessageType.MembershipReportVersion3: return (ILayer) new IgmpReportVersion3Layer() { GroupRecords = Enumerable.ToList<IgmpGroupRecord>(Enumerable.Select<IgmpGroupRecordDatagram, IgmpGroupRecord>((IEnumerable<IgmpGroupRecordDatagram>) this.GroupRecords, (Func<IgmpGroupRecordDatagram, IgmpGroupRecord>) (record => record.ToGroupRecord()))).AsReadOnly() }; default: throw new InvalidOperationException("Invalid message type " + (object) this.MessageType); } } internal static int GetQueryVersion3Length(int numSourceAddresses) { return 12 + 4 * numSourceAddresses; } internal static int GetReportVersion3Length(IEnumerable<IgmpGroupRecord> igmpGroupRecords) { return 8 + Enumerable.Sum<IgmpGroupRecord>(igmpGroupRecords, (Func<IgmpGroupRecord, int>) (record => IgmpGroupRecordDatagram.GetLength(record.SourceAddresses.Count, record.AuxiliaryData.Length))); } internal static void WriteHeader(byte[] buffer, int offset, IgmpMessageType igmpMessageType, TimeSpan maxResponseTime, IpV4Address groupAddress) { ByteArrayExtensions.Write(buffer, offset, (byte) igmpMessageType); double num = maxResponseTime.TotalSeconds * 10.0; if (num >= 256.0 || num < 0.0) throw new ArgumentOutOfRangeException("maxResponseTime", (object) maxResponseTime, "must be in the range [" + (object) TimeSpan.Zero + ", " + (string) (object) TimeSpan.FromSeconds(25.5) + "]"); ByteArrayExtensions.Write(buffer, offset + 1, (byte) num); ByteArrayExtensions.Write(buffer, offset + 4, groupAddress, Endianity.Big); IgmpDatagram.WriteChecksum(buffer, offset, 8); } internal static void WriteQueryVersion3(byte[] buffer, int offset, TimeSpan maxResponseTime, IpV4Address groupAddress, bool isSuppressRouterSideProcessing, byte queryRobustnessVariable, TimeSpan queryInterval, IEnumerable<IpV4Address> sourceAddresses) { ByteArrayExtensions.Write(buffer, offset, (byte) 17); if (maxResponseTime < TimeSpan.Zero || maxResponseTime > IgmpDatagram.MaxVersion3MaxResponseTime) throw new ArgumentOutOfRangeException("maxResponseTime", (object) maxResponseTime, "must be in the range [" + (object) TimeSpan.Zero + ", " + (string) (object) IgmpDatagram.MaxVersion3MaxResponseTime + "]"); double num1 = maxResponseTime.TotalSeconds * 10.0; byte num2 = num1 < 128.0 ? (byte) num1 : (byte) (double) IgmpDatagram.ValueToCode((int) num1); ByteArrayExtensions.Write(buffer, offset + 1, num2); ByteArrayExtensions.Write(buffer, offset + 4, groupAddress, Endianity.Big); if ((int) queryRobustnessVariable > 7) throw new ArgumentOutOfRangeException("queryRobustnessVariable", (object) queryRobustnessVariable, "must be in range [0, 7]"); ByteArrayExtensions.Write(buffer, offset + 8, (byte) ((int) queryRobustnessVariable | (isSuppressRouterSideProcessing ? 8 : 0))); if (queryInterval < TimeSpan.Zero || queryInterval > IgmpDatagram.MaxQueryInterval) throw new ArgumentOutOfRangeException("queryInterval", (object) maxResponseTime, "must be in the range [" + (object) TimeSpan.Zero + ", " + (string) (object) IgmpDatagram.MaxQueryInterval + "]"); double totalSeconds = queryInterval.TotalSeconds; byte num3 = totalSeconds < 128.0 ? (byte) totalSeconds : (byte) (double) IgmpDatagram.ValueToCode((int) totalSeconds); ByteArrayExtensions.Write(buffer, offset + 9, num3); int num4 = 0; foreach (IpV4Address ipV4Address in sourceAddresses) { ByteArrayExtensions.Write(buffer, offset + 12 + 4 * num4, ipV4Address, Endianity.Big); ++num4; } ByteArrayExtensions.Write(buffer, offset + 10, (ushort) num4, Endianity.Big); IgmpDatagram.WriteChecksum(buffer, offset, 12 + 4 * num4); } internal static void WriteReportVersion3(byte[] buffer, int offset, IEnumerable<IgmpGroupRecord> groupRecords) { ByteArrayExtensions.Write(buffer, offset, (byte) 34); ushort num = (ushort) 0; int offset1 = offset + 8; foreach (IgmpGroupRecord igmpGroupRecord in groupRecords) { IgmpGroupRecordDatagram.Write(buffer, ref offset1, igmpGroupRecord.RecordType, igmpGroupRecord.AuxiliaryData, igmpGroupRecord.MulticastAddress, igmpGroupRecord.SourceAddresses); ++num; } ByteArrayExtensions.Write(buffer, offset + 6, num, Endianity.Big); IgmpDatagram.WriteChecksum(buffer, offset, offset1 - offset); } protected override bool CalculateIsValid() { if (this.Length < 8 || !this.IsChecksumCorrect) return false; switch (this.MessageType) { case IgmpMessageType.MembershipQuery: switch (this.QueryVersion) { case IgmpQueryVersion.Version1: case IgmpQueryVersion.Version2: return this.Length == 8; case IgmpQueryVersion.Version3: return this.Length == IgmpDatagram.GetQueryVersion3Length((int) this.NumberOfSources); default: return false; } case IgmpMessageType.MembershipReportVersion1: if (this.Length == 8) return (int) this.MaxResponseCode == 0; return false; case IgmpMessageType.MembershipReportVersion2: case IgmpMessageType.LeaveGroupVersion2: return this.Length == 8; case IgmpMessageType.MembershipReportVersion3: if ((int) this.MaxResponseCode == 0 && this.Length == 8 + Enumerable.Sum<IgmpGroupRecordDatagram>((IEnumerable<IgmpGroupRecordDatagram>) this.GroupRecords, (Func<IgmpGroupRecordDatagram, int>) (record => record.Length))) return Enumerable.All<IgmpGroupRecordDatagram>((IEnumerable<IgmpGroupRecordDatagram>) this.GroupRecords, (Func<IgmpGroupRecordDatagram, bool>) (record => record.IsValid)); return false; default: return false; } } private ushort CalculateChecksum() { return DataSegment.Sum16BitsToChecksum(DataSegment.Sum16Bits(this.Buffer, this.StartOffset, Math.Min(2, this.Length)) + DataSegment.Sum16Bits(this.Buffer, this.StartOffset + 2 + 2, this.Length - 2 - 2)); } private static void WriteChecksum(byte[] buffer, int offset, int length) { ByteArrayExtensions.Write(buffer, offset + 2, DataSegment.Sum16BitsToChecksum(DataSegment.Sum16Bits(buffer, offset, length)), Endianity.Big); } private static int CodeToValue(byte code) { return ((int) code & 15 | 16) << (((int) code & 112) >> 4) + 3; } private static byte ValueToCode(int value) { int num1 = (int) (Math.Log((double) value, 2.0) - 7.0); if (num1 > 7 || num1 < 0) throw new ArgumentOutOfRangeException("value", (object) value, "exp " + (object) num1 + " is out of range"); int num2 = (int) ((double) value * Math.Pow(2.0, (double) (-num1 - 3)) - 16.0); if (num2 > 15 || num2 < 0) throw new ArgumentOutOfRangeException("value", (object) value, "mant " + (object) num2 + " is out of range"); return (byte) (128 | num1 << 4 | num2); } private static class Offset { public const int MessageType = 0; public const int MaxResponseCode = 1; public const int Checksum = 2; public const int GroupAddress = 4; public const int IsSuppressRouterSideProcessing = 8; public const int QueryRobustnessVariable = 8; public const int QueryIntervalCode = 9; public const int NumberOfSources = 10; public const int SourceAddresses = 12; public const int NumberOfGroupRecords = 6; public const int GroupRecords = 8; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Igmp.IgmpGroupRecordDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using PcapDotNet.Packets.IpV4; using System; using System.Collections.Generic; using System.Collections.ObjectModel; namespace PcapDotNet.Packets.Igmp { public sealed class IgmpGroupRecordDatagram : Datagram { public const int HeaderLength = 8; private ReadOnlyCollection<IpV4Address> _sourceAddresses; public IgmpRecordType RecordType { get { return (IgmpRecordType) this[0]; } } public int AuxiliaryDataLength { get { return 4 * (int) this[1]; } } public int NumberOfSources { get { return (int) this.ReadUShort(2, Endianity.Big); } } public IpV4Address MulticastAddress { get { return this.ReadIpV4Address(4, Endianity.Big); } } public ReadOnlyCollection<IpV4Address> SourceAddresses { get { if (this._sourceAddresses == null) { IpV4Address[] ipV4AddressArray = new IpV4Address[Math.Min(this.NumberOfSources, (this.Length - 8) / 4)]; for (int index = 0; index != ipV4AddressArray.Length; ++index) ipV4AddressArray[index] = this.ReadIpV4Address(8 + 4 * index, Endianity.Big); this._sourceAddresses = new ReadOnlyCollection<IpV4Address>((IList<IpV4Address>) ipV4AddressArray); } return this._sourceAddresses; } } public Datagram AuxiliaryData { get { return new Datagram(this.Buffer, this.StartOffset + this.Length - this.AuxiliaryDataLength, this.AuxiliaryDataLength); } } internal IgmpGroupRecordDatagram(byte[] buffer, int offset) : base(buffer, offset, buffer.Length - offset < 8 ? buffer.Length - offset : Math.Min(buffer.Length - offset, 8 + 4 * (int) ByteArrayExtensions.ReadUShort(buffer, offset + 2, Endianity.Big) + 4 * (int) ByteArrayExtensions.ReadByte(buffer, offset + 1))) { } public IgmpGroupRecord ToGroupRecord() { return new IgmpGroupRecord(this.RecordType, this.MulticastAddress, this.SourceAddresses, this.AuxiliaryData); } internal static int GetLength(int numSourceAddresses, int auxiliaryDataLength) { return 8 + 4 * numSourceAddresses + auxiliaryDataLength; } internal static void Write(byte[] buffer, ref int offset, IgmpRecordType recordType, Datagram auxiliaryData, IpV4Address multicastAddress, ReadOnlyCollection<IpV4Address> sourceAddresses) { ByteArrayExtensions.Write(buffer, offset, (byte) recordType); ByteArrayExtensions.Write(buffer, offset + 1, (byte) (auxiliaryData.Length / 4)); int count = sourceAddresses.Count; ByteArrayExtensions.Write(buffer, offset + 2, (ushort) count, Endianity.Big); ByteArrayExtensions.Write(buffer, offset + 4, multicastAddress, Endianity.Big); for (int index = 0; index != count; ++index) ByteArrayExtensions.Write(buffer, offset + 8 + 4 * index, sourceAddresses[index], Endianity.Big); offset += 8 + count * 4; ByteArrayExtensions.Write(buffer, ref offset, (DataSegment) auxiliaryData); } protected override bool CalculateIsValid() { if (this.Length >= 8) return this.Length == 8 + 4 * this.NumberOfSources + this.AuxiliaryDataLength; return false; } private static class Offset { public const int RecordType = 0; public const int AuxiliaryDataLength = 1; public const int NumberOfSources = 2; public const int MulticastAddress = 4; public const int SourceAddresses = 8; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpTimestampLayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets.IpV4; namespace PcapDotNet.Packets.Icmp { public class IcmpTimestampLayer : IcmpIdentifiedLayer { public IpV4TimeOfDay OriginateTimestamp { get; set; } public IpV4TimeOfDay ReceiveTimestamp { get; set; } public IpV4TimeOfDay TransmitTimestamp { get; set; } public override IcmpMessageType MessageType { get { return IcmpMessageType.Timestamp; } } protected override sealed int PayloadLength { get { return 12; } } protected override sealed void WritePayload(byte[] buffer, int offset) { IcmpTimestampDatagram.WriteHeaderAdditional(buffer, offset, this.OriginateTimestamp, this.ReceiveTimestamp, this.TransmitTimestamp); } protected override sealed bool EqualPayload(IcmpLayer other) { return this.EqualPayload(other as IcmpTimestampLayer); } private bool EqualPayload(IcmpTimestampLayer other) { if (other != null && this.OriginateTimestamp == other.OriginateTimestamp && this.ReceiveTimestamp == other.ReceiveTimestamp) return this.TransmitTimestamp == other.TransmitTimestamp; return false; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Http.HttpRegex // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using System; using System.Collections.Generic; using System.Globalization; using System.Text; using System.Text.RegularExpressions; namespace PcapDotNet.Packets.Http { internal static class HttpRegex { private static readonly Regex _carriageReturnLineFeed = HttpRegex.Build("\\r\\n"); private static readonly Regex _charRegex = HttpRegex.Build("[\\x00-\\x7F]"); private static readonly Regex _quotedPairRegex = HttpRegex.Concat(HttpRegex.Build("\\\\"), HttpRegex._charRegex); private static readonly Regex _linearWhiteSpaceRegex = HttpRegex.Concat(HttpRegex.Optional(HttpRegex.CarriageReturnLineFeed), HttpRegex.AtLeastOne(HttpRegex.Build("[ \\t]"))); private static readonly Regex _qdtextRegex = HttpRegex.Or(HttpRegex._linearWhiteSpaceRegex, HttpRegex.Build("[^\\x00-\\x1F\\x7F\"]")); private static readonly Regex _quotedStringRegex = HttpRegex.Concat(HttpRegex.Build('"'), HttpRegex.Any(HttpRegex.Or(HttpRegex._qdtextRegex, HttpRegex._quotedPairRegex)), HttpRegex.Build('"')); private static readonly Regex _tokenRegex = HttpRegex.AtLeastOne(HttpRegex.Build("[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2E0-9A-Z\\x5E-\\x7A\\x7C\\x7E-\\xFE]")); private static readonly Regex _valueRegex = HttpRegex.Or(HttpRegex.Token, HttpRegex.QuotedString); private static readonly Regex _parameterRegex = HttpRegex.Concat(HttpRegex.Capture(HttpRegex._tokenRegex, "ParameterName"), HttpRegex.Build("="), HttpRegex.Capture(HttpRegex._valueRegex, "ParameterValue")); private static readonly Regex _optionalParametersRegex = HttpRegex.Any(HttpRegex.Concat(HttpRegex.Build(";"), HttpRegex.Optional(HttpRegex._linearWhiteSpaceRegex), HttpRegex._parameterRegex)); private static readonly Encoding _encoding = EncodingExtensions.Iso88591; public const string ParameterNameGroupName = "ParameterName"; public const string ParameterValueGroupName = "ParameterValue"; public static Regex CarriageReturnLineFeed { get { return HttpRegex._carriageReturnLineFeed; } } public static Regex LinearWhiteSpace { get { return HttpRegex._linearWhiteSpaceRegex; } } public static Regex Token { get { return HttpRegex._tokenRegex; } } public static Regex QuotedString { get { return HttpRegex._quotedStringRegex; } } public static Regex OptionalParameters { get { return HttpRegex._optionalParametersRegex; } } public static string GetString(byte[] buffer, int offset, int count) { return HttpRegex._encoding.GetString(buffer, offset, count); } public static string GetString(byte[] buffer) { return HttpRegex.GetString(buffer, 0, buffer.Length); } public static Regex Build(string pattern) { return new Regex(HttpRegex.Bracket(pattern), RegexOptions.Compiled | RegexOptions.Singleline); } public static Regex Build(char pattern) { return HttpRegex.Build(pattern.ToString()); } public static Regex Concat(params Regex[] regexes) { return HttpRegex.Build(HttpRegex.Bracket(IEnumerableExtensions.SequenceToString<Regex>((IEnumerable<Regex>) regexes))); } public static Regex Or(params Regex[] regexes) { return HttpRegex.Build(HttpRegex.Bracket(IEnumerableExtensions.SequenceToString<Regex>((IEnumerable<Regex>) regexes, "|"))); } public static Regex Optional(Regex regex) { return HttpRegex.Build(HttpRegex.Bracket(string.Format((IFormatProvider) CultureInfo.InvariantCulture, "{0}?", new object[1] { (object) regex }))); } public static Regex Any(Regex regex) { return HttpRegex.Build(HttpRegex.Bracket(string.Format((IFormatProvider) CultureInfo.InvariantCulture, "{0}*", new object[1] { (object) regex }))); } public static Regex AtLeastOne(Regex regex) { return HttpRegex.Build(HttpRegex.Bracket(string.Format((IFormatProvider) CultureInfo.InvariantCulture, "{0}+", new object[1] { (object) regex }))); } public static Regex AtLeast(Regex regex, int minCount) { if (minCount <= 0) return HttpRegex.Any(regex); if (minCount == 1) return HttpRegex.AtLeastOne(regex); return HttpRegex.Build(string.Format((IFormatProvider) CultureInfo.InvariantCulture, "(?:{0}){{{1},}}", new object[2] { (object) regex, (object) minCount })); } public static Regex CommaSeparatedRegex(Regex element, int minCount) { Regex regex1 = HttpRegex.Any(HttpRegex.LinearWhiteSpace); Regex regex2 = HttpRegex.Concat(HttpRegex.Build(string.Format((IFormatProvider) CultureInfo.InvariantCulture, "{0}{1}", new object[2] { (object) regex1, (object) element })), HttpRegex.AtLeast(HttpRegex.Build(string.Format((IFormatProvider) CultureInfo.InvariantCulture, "{0},{1}{2}", (object) regex1, (object) regex1, (object) element)), minCount - 1)); if (minCount > 0) return regex2; return HttpRegex.Optional(regex2); } public static Regex Capture(Regex regex, string captureName) { return HttpRegex.Build(string.Format((IFormatProvider) CultureInfo.InvariantCulture, "(?<{0}>{1})", new object[2] { (object) captureName, (object) regex })); } public static Regex MatchEntire(Regex regex) { return HttpRegex.Build(string.Format((IFormatProvider) CultureInfo.InvariantCulture, "^{0}$", new object[1] { (object) regex })); } private static string Bracket(string pattern) { return string.Format((IFormatProvider) CultureInfo.InvariantCulture, "(?:{0})", new object[1] { (object) pattern }); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsDomainName // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PcapDotNet.Packets.Dns { public sealed class DnsDomainName : IEquatable<DnsDomainName> { private static readonly char[] Colon = new char[1] { '.' }; private static readonly DnsDomainName _root = new DnsDomainName(""); public const int RootLength = 1; private const byte MaxLabelLength = (byte) 63; private const ushort CompressionMarker = (ushort) 49152; internal const ushort OffsetMask = (ushort) 16383; private readonly List<DataSegment> _labels; private string _utf8; public static DnsDomainName Root { get { return DnsDomainName._root; } } public int LabelsCount { get { return this._labels.Count; } } public bool IsRoot { get { return this.LabelsCount == 0; } } public int NonCompressedLength { get { return Enumerable.Sum<DataSegment>((IEnumerable<DataSegment>) this._labels, (Func<DataSegment, int>) (label => label.Length + 1)) + 1; } } public DnsDomainName(string domainName) { if (domainName == null) throw new ArgumentNullException("domainName"); this._labels = Enumerable.ToList<DataSegment>(Enumerable.Select<string, DataSegment>((IEnumerable<string>) domainName.Split(DnsDomainName.Colon, StringSplitOptions.RemoveEmptyEntries), (Func<string, DataSegment>) (label => new DataSegment(Encoding.UTF8.GetBytes(label))))); } private DnsDomainName(List<DataSegment> labels) { this._labels = labels; } public override string ToString() { if (this._utf8 == null) this._utf8 = IEnumerableExtensions.SequenceToString<string>(Enumerable.Select<DataSegment, string>((IEnumerable<DataSegment>) this._labels, (Func<DataSegment, string>) (label => label.Decode(Encoding.UTF8))), '.') + "."; return this._utf8; } public bool Equals(DnsDomainName other) { if (other != null) return string.Equals(this.ToString(), other.ToString(), StringComparison.OrdinalIgnoreCase); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsDomainName); } public override int GetHashCode() { return this.ToString().GetHashCode(); } internal int GetLength(DnsDomainNameCompressionData compressionData, int offsetInDns) { int num = 0; for (int startIndex = 0; startIndex != this.LabelsCount; ++startIndex) { ListSegment<DataSegment> labels = new ListSegment<DataSegment>((IList<DataSegment>) this._labels, startIndex); if (compressionData.IsAvailable(labels)) return num + 2; compressionData.AddCompressionData(labels, offsetInDns + num); num += 1 + labels[0].Length; } return num + 1; } internal static bool TryParse(DnsDatagram dns, int offsetInDns, int maximumLength, out DnsDomainName domainName, out int numBytesRead) { List<DataSegment> labels = new List<DataSegment>(); if (!DnsDomainName.TryReadLabels(dns, offsetInDns, out numBytesRead, labels) || numBytesRead > maximumLength) { domainName = (DnsDomainName) null; return false; } domainName = new DnsDomainName(labels); return true; } internal void WriteUncompressed(byte[] buffer, int offset) { foreach (DataSegment dataSegment in this._labels) { ByteArrayExtensions.Write(buffer, ref offset, (byte) dataSegment.Length); dataSegment.Write(buffer, ref offset); } } internal int Write(byte[] buffer, int dnsOffset, DnsDomainNameCompressionData compressionData, int offsetInDns) { int num1 = 0; for (int startIndex = 0; startIndex != this.LabelsCount; ++startIndex) { ListSegment<DataSegment> labels = new ListSegment<DataSegment>((IList<DataSegment>) this._labels, startIndex); int offsetInDns1; if (compressionData.TryGetOffset(labels, out offsetInDns1)) { ByteArrayExtensions.Write(buffer, dnsOffset + offsetInDns + num1, (ushort) (49152U | (uint) (ushort) offsetInDns1), Endianity.Big); return num1 + 2; } DataSegment dataSegment = labels[0]; compressionData.AddCompressionData(labels, offsetInDns + num1); ByteArrayExtensions.Write(buffer, dnsOffset + offsetInDns + num1, (byte) dataSegment.Length); int num2 = num1 + 1; dataSegment.Write(buffer, dnsOffset + offsetInDns + num2); num1 = num2 + dataSegment.Length; } return num1 + 1; } private static bool TryReadLabels(DnsDatagram dns, int offsetInDns, out int numBytesRead, List<DataSegment> labels) { numBytesRead = 0; while (offsetInDns < dns.Length) { byte num = dns[offsetInDns]; ++numBytesRead; if ((int) num > 63) { if (offsetInDns + 1 >= dns.Length) return false; int offsetInDns1 = (int) dns.ReadUShort(offsetInDns, Endianity.Big) & 16383; if (offsetInDns1 >= offsetInDns) return false; ++numBytesRead; int numBytesRead1; return DnsDomainName.TryReadLabels(dns, offsetInDns1, out numBytesRead1, labels); } if ((int) num != 0) { ++offsetInDns; if (offsetInDns + (int) num >= dns.Length) return false; labels.Add(dns.Subsegment(offsetInDns, (int) num)); numBytesRead += (int) num; offsetInDns += (int) num; } if ((int) num == 0) return true; } return false; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataUShortDomainName // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Dns { public abstract class DnsResourceDataUShortDomainName : DnsResourceData, IEquatable<DnsResourceDataUShortDomainName> { private const int ConstantPartLength = 2; internal ushort Value { get; private set; } internal DnsDomainName DomainName { get; private set; } internal DnsResourceDataUShortDomainName(ushort value, DnsDomainName domainName) { this.Value = value; this.DomainName = domainName; } public bool Equals(DnsResourceDataUShortDomainName other) { if (other != null && this.GetType().Equals(other.GetType()) && this.Value.Equals(other.Value)) return this.DomainName.Equals(other.DomainName); return false; } public override sealed bool Equals(object obj) { return this.Equals(obj as DnsResourceDataUShortDomainName); } public override sealed int GetHashCode() { return Sequence.GetHashCode((object) this.GetType(), (object) this.Value, (object) this.DomainName); } internal override int GetLength(DnsDomainNameCompressionData compressionData, int offsetInDns) { return 2 + this.DomainName.GetLength(compressionData, offsetInDns); } internal override int WriteData(byte[] buffer, int dnsOffset, int offsetInDns, DnsDomainNameCompressionData compressionData) { ByteArrayExtensions.Write(buffer, dnsOffset + offsetInDns, this.Value, Endianity.Big); return 2 + this.DomainName.Write(buffer, dnsOffset, compressionData, offsetInDns + 2); } internal static bool TryRead(out ushort value, out DnsDomainName domainName, DnsDatagram dns, int offsetInDns, int length) { if (length < 2) { value = (ushort) 0; domainName = (DnsDomainName) null; return false; } value = dns.ReadUShort(offsetInDns, Endianity.Big); length -= 2; int numBytesRead; if (!DnsDomainName.TryParse(dns, offsetInDns + 2, length, out domainName, out numBytesRead)) return false; length -= numBytesRead; return length == 0; } private static class Offset { public const int Value = 0; public const int DomainName = 2; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IpV4Fragmentation // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.IpV4 { public struct IpV4Fragmentation : IEquatable<IpV4Fragmentation> { private static readonly IpV4Fragmentation _none = new IpV4Fragmentation(IpV4FragmentationOptions.None, (ushort) 0); private readonly ushort _value; public static IpV4Fragmentation None { get { return IpV4Fragmentation._none; } } public IpV4FragmentationOptions Options { get { return (IpV4FragmentationOptions) ((uint) this._value & 57344U); } } public ushort Offset { get { return (ushort) (((int) this._value & 8191) * 8); } } public IpV4Fragmentation(IpV4FragmentationOptions options, ushort offset) { this = new IpV4Fragmentation((ushort) (options | (IpV4FragmentationOptions) ((int) offset / 8))); if ((int) offset % 8 != 0) throw new ArgumentException("offset must divide by 8", "offset"); if ((options & (IpV4FragmentationOptions) 8191) != IpV4FragmentationOptions.None) throw new ArgumentException("invalid options " + (object) options); } internal IpV4Fragmentation(ushort value) { this._value = value; } public static bool operator ==(IpV4Fragmentation value1, IpV4Fragmentation value2) { return value1.Equals(value2); } public static bool operator !=(IpV4Fragmentation value1, IpV4Fragmentation value2) { return !(value1 == value2); } public bool Equals(IpV4Fragmentation other) { return (int) this._value == (int) other._value; } public override bool Equals(object obj) { if (obj is IpV4Fragmentation) return this.Equals((IpV4Fragmentation) obj); return false; } public override int GetHashCode() { return this._value.GetHashCode(); } internal void Write(byte[] buffer, int offset) { ByteArrayExtensions.Write(buffer, offset, this._value, Endianity.Big); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.IpV6SocketAddress // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using PcapDotNet.Base; using PcapDotNet.Packets.IpV6; using System; using System.Text; namespace PcapDotNet.Core { public sealed class IpV6SocketAddress : SocketAddress { private IpV6Address _address; public IpV6Address Address { get { return this._address; } } internal unsafe IpV6SocketAddress(sockaddr* address) : base(*(ushort*) address) { this._address = new IpV6Address(BitSequence.Merge(*(byte*) ((IntPtr) address + 8L), *(byte*) ((IntPtr) address + 8L + 1L), *(byte*) ((IntPtr) address + 8L + 2L), *(byte*) ((IntPtr) address + 8L + 3L), *(byte*) ((IntPtr) address + 8L + 4L), *(byte*) ((IntPtr) address + 8L + 5L), *(byte*) ((IntPtr) address + 8L + 6L), *(byte*) ((IntPtr) address + 8L + 7L), *(byte*) ((IntPtr) address + 8L + 8L), *(byte*) ((IntPtr) address + 8L + 9L), *(byte*) ((IntPtr) address + 8L + 10L), *(byte*) ((IntPtr) address + 8L + 11L), *(byte*) ((IntPtr) address + 8L + 12L), *(byte*) ((IntPtr) address + 8L + 13L), *(byte*) ((IntPtr) address + 8L + 14L), *(byte*) ((IntPtr) address + 8L + 15L))); } public override sealed string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(base.ToString()); stringBuilder.Append(" "); IpV6Address ipV6Address = this._address; stringBuilder.Append((object) ipV6Address); return stringBuilder.ToString(); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataAnything // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.EId)] [DnsTypeRegistration(Type = DnsType.Null)] [DnsTypeRegistration(Type = DnsType.DynamicHostConfigurationId)] [DnsTypeRegistration(Type = DnsType.NimrodLocator)] public sealed class DnsResourceDataAnything : DnsResourceDataSimple, IEquatable<DnsResourceDataAnything> { public DataSegment Data { get; private set; } public DnsResourceDataAnything() { this.Data = DataSegment.Empty; } public DnsResourceDataAnything(DataSegment data) { this.Data = data; } public bool Equals(DnsResourceDataAnything other) { if (other != null) return this.Data.Equals(other.Data); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataAnything); } public override int GetHashCode() { return this.Data.GetHashCode(); } internal override int GetLength() { return this.Data.Length; } internal override void WriteDataSimple(byte[] buffer, int offset) { this.Data.Write(buffer, offset); } internal override DnsResourceData CreateInstance(DataSegment data) { return (DnsResourceData) new DnsResourceDataAnything(data); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.TransportLayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using PcapDotNet.Packets.IpV4; using System; namespace PcapDotNet.Packets.Transport { public abstract class TransportLayer : Layer, IIpV4NextTransportLayer, IIpV4NextLayer, ILayer, IEquatable<TransportLayer> { public ushort? Checksum { get; set; } public ushort SourcePort { get; set; } public ushort DestinationPort { get; set; } public abstract IpV4Protocol PreviousLayerProtocol { get; } public virtual bool CalculateChecksum { get { return true; } } public abstract int ChecksumOffset { get; } public abstract bool IsChecksumOptional { get; } public bool Equals(TransportLayer other) { if (other != null && this.PreviousLayerProtocol == other.PreviousLayerProtocol) { ushort? checksum1 = this.Checksum; ushort? checksum2 = other.Checksum; if (((int) checksum1.GetValueOrDefault() != (int) checksum2.GetValueOrDefault() ? 0 : (checksum1.HasValue == checksum2.HasValue ? 1 : 0)) != 0 && (int) this.SourcePort == (int) other.SourcePort && (int) this.DestinationPort == (int) other.DestinationPort) return this.EqualFields(other); } return false; } public override sealed bool Equals(Layer other) { return this.Equals(other as TransportLayer); } public override sealed int GetHashCode() { return base.GetHashCode() ^ this.Checksum.GetHashCode() ^ BitSequence.Merge(this.SourcePort, this.DestinationPort).GetHashCode(); } protected virtual bool EqualFields(TransportLayer other) { return true; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Igmp.IgmpRecordType // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Igmp { public enum IgmpRecordType : byte { None, CurrentStateRecordModeIsInclude, CurrentStateRecordModeIsExclude, FilterModeChangeToInclude, FilterModeChangeToExclude, SourceListChangeAllowNewSources, SourceListChangeBlockOldSources, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.DeviceAddress // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using System; using System.Text; namespace PcapDotNet.Core { public sealed class DeviceAddress { private SocketAddress _address; private SocketAddress _netmask; private SocketAddress _broadcast; private SocketAddress _destination; public SocketAddress Destination { get { return this._destination; } } public SocketAddress Broadcast { get { return this._broadcast; } } public SocketAddress Netmask { get { return this._netmask; } } public SocketAddress Address { get { return this._address; } } internal unsafe DeviceAddress(pcap_addr* pcapAddress) { long num1 = *(long*) ((IntPtr) pcapAddress + 8L); SocketAddressFamily socketAddressFamily = (SocketAddressFamily) *(ushort*) num1; switch (socketAddressFamily) { case SocketAddressFamily.Internet: if (num1 != 0L) this._address = (SocketAddress) new IpV4SocketAddress((sockaddr*) num1); ulong num2 = (ulong) *(long*) ((IntPtr) pcapAddress + 16L); if ((long) num2 != 0L) this._netmask = (SocketAddress) new IpV4SocketAddress((sockaddr*) num2); ulong num3 = (ulong) *(long*) ((IntPtr) pcapAddress + 24L); if ((long) num3 != 0L) this._broadcast = (SocketAddress) new IpV4SocketAddress((sockaddr*) num3); ulong num4 = (ulong) *(long*) ((IntPtr) pcapAddress + 32L); if ((long) num4 == 0L) break; this._destination = (SocketAddress) new IpV4SocketAddress((sockaddr*) num4); break; case SocketAddressFamily.Internet6: if (num1 != 0L) this._address = (SocketAddress) new IpV6SocketAddress((sockaddr*) num1); ulong num5 = (ulong) *(long*) ((IntPtr) pcapAddress + 16L); if ((long) num5 != 0L) this._netmask = (SocketAddress) new IpV6SocketAddress((sockaddr*) num5); ulong num6 = (ulong) *(long*) ((IntPtr) pcapAddress + 24L); if ((long) num6 != 0L) this._broadcast = (SocketAddress) new IpV6SocketAddress((sockaddr*) num6); ulong num7 = (ulong) *(long*) ((IntPtr) pcapAddress + 32L); if ((long) num7 == 0L) break; this._destination = (SocketAddress) new IpV6SocketAddress((sockaddr*) num7); break; default: throw new NotImplementedException("Device of family " + socketAddressFamily.ToString() + " is unsupported"); } } public override sealed string ToString() { StringBuilder stringBuilder = new StringBuilder(); SocketAddress socketAddress1 = this._address; string str1 = "Address"; if (socketAddress1 != null) { if (stringBuilder.Length != 0) stringBuilder.Append(" "); stringBuilder.Append(str1); stringBuilder.Append(": "); stringBuilder.Append((object) socketAddress1); } SocketAddress socketAddress2 = this._netmask; string str2 = "Netmask"; if (socketAddress2 != null) { if (stringBuilder.Length != 0) stringBuilder.Append(" "); stringBuilder.Append(str2); stringBuilder.Append(": "); stringBuilder.Append((object) socketAddress2); } SocketAddress socketAddress3 = this._broadcast; string str3 = "Broadcast"; if (socketAddress3 != null) { if (stringBuilder.Length != 0) stringBuilder.Append(" "); stringBuilder.Append(str3); stringBuilder.Append(": "); stringBuilder.Append((object) socketAddress3); } SocketAddress socketAddress4 = this._destination; string str4 = "Destination"; if (socketAddress4 != null) { if (stringBuilder.Length != 0) stringBuilder.Append(" "); stringBuilder.Append(str4); stringBuilder.Append(": "); stringBuilder.Append((object) socketAddress4); } return stringBuilder.ToString(); } private static void AppendSocketAddressString(StringBuilder stringBuilder, SocketAddress socketAddress, string title) { if (socketAddress == null) return; if (stringBuilder.Length != 0) stringBuilder.Append(" "); stringBuilder.Append(title); stringBuilder.Append(": "); stringBuilder.Append((object) socketAddress); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Endianity // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets { public enum Endianity : byte { Small, Big, } } <file_sep># ForecastPCL An unofficial C# Portable Class Library for the [Forecast.io](http://developer.forecast.io) weather service. Compatible with .NET 4.5, Windows 8/8.1, Windows Phone 8/8.1, Silverlight 5, and Universal Windows Apps. ## Installation [NuGet](https://www.nuget.org/packages/ForecastIOPortable/): `Install-Package ForecastIOPortable` ## New in Version 2.3.1 * Rebuilt the project in Release mode (thanks, [@bklabs](https://github.com/bklabs)!) * Added missing Precipitation Type field (thanks, [@lynnroth](https://github.com/lynnroth)!) * Additional language support: Greek, Croatian, Ukrainian, and Traditional Chinese. ## Quick Start ### Current Conditions ```C# using ForecastIOPortable; ... var client = new ForecastApi("YOUR API KEY HERE"); Forecast result = await client.GetWeatherDataAsync(37.8267, -122.423); ... ``` ![](http://i.imgur.com/lLuBO0C.png) Note that the Forecast.io service doesn't always return all fields for each region. In these cases, some properties may be null or zero. ### Conditions for a specific date ```C# using ForecastIOPortable; ... var client = new ForecastApi("YOUR API KEY HERE"); Forecast result = await client.GetTimeMachineWeatherAsync(37.8267, -122.423, DateTimeOffset.Now); ... ``` The `Helpers` class contains extension methods to convert a DateTimeOffset to Unix time, and back: ```C# int unixTime = DateTimeOffset.Now.ToUnixTime(); DateTimeOffset date = unixTime.ToDateTimeOffset(); ``` ### API Usage Information After making a request for data (be it current or historical), the ForecastApi instance's `ApiCallsMade` property will contain the number of calls made today, using the given API key. The property will be null if no requests have been made through the particular instance. ## Dependencies Microsoft.Bcl (≥ 1.1.9) Microsoft.Bcl.Async (≥ 1.0.168) Microsoft.Bcl.Build (≥ 1.0.14) Microsoft.Bcl.Compression (≥ 3.9.81) Microsoft.Net.Http (≥ 2.2.22) ## Design This library uses a client-oriented approach, instead of a request-response model: the `ForecastApi` object is intended to be an abstraction from which weather data (`Forecast`s) can be obtained. `Forecast`s do contain all the fields that can appear in the raw JSON obtained through making a direct request to the web service, but exposes them through more .NET convention-friendly properties: for example, `precipIntensityMax` is exposed as `MaxPrecipitationIntensity`. These properties are (as shown here) sometimes more verbose, but were intended to match the style commonly used in .NET projects. ## Tests NUnit is used for some simple integration tests with the actual web service. To run the tests, a valid API key must be added to the `app.config` file in the `ForecastPCL.Test` folder.<file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpRouterAdvertisementDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace PcapDotNet.Packets.Icmp { [IcmpDatagramRegistration(IcmpMessageType.RouterAdvertisement)] public sealed class IcmpRouterAdvertisementDatagram : IcmpDatagram { public const int DefaultAddressEntrySize = 2; private ReadOnlyCollection<IcmpRouterAdvertisementEntry> _entries; public byte NumberOfAddresses { get { return this[4]; } } public byte AddressEntrySize { get { return this[5]; } } public ushort LifetimeSeconds { get { return this.ReadUShort(6, Endianity.Big); } } public TimeSpan Lifetime { get { return TimeSpan.FromSeconds((double) this.LifetimeSeconds); } } public ReadOnlyCollection<IcmpRouterAdvertisementEntry> Entries { get { if (this._entries == null) { IcmpRouterAdvertisementEntry[] advertisementEntryArray = new IcmpRouterAdvertisementEntry[(int) this.NumberOfAddresses]; int offset = 8; for (int index = 0; index != advertisementEntryArray.Length && offset + 4 <= this.Length; ++index) { advertisementEntryArray[index] = new IcmpRouterAdvertisementEntry(this.ReadIpV4Address(offset, Endianity.Big), this.ReadInt(offset + 4, Endianity.Big)); offset += (int) this.AddressEntrySize * 4; } this._entries = new ReadOnlyCollection<IcmpRouterAdvertisementEntry>((IList<IcmpRouterAdvertisementEntry>) advertisementEntryArray); } return this._entries; } } private IcmpRouterAdvertisementDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public override ILayer ExtractLayer() { IcmpRouterAdvertisementLayer advertisementLayer = new IcmpRouterAdvertisementLayer(); advertisementLayer.Entries = Enumerable.ToList<IcmpRouterAdvertisementEntry>((IEnumerable<IcmpRouterAdvertisementEntry>) this.Entries).AsReadOnly(); advertisementLayer.Checksum = new ushort?(this.Checksum); advertisementLayer.Lifetime = this.Lifetime; return (ILayer) advertisementLayer; } protected override bool CalculateIsValid() { if (base.CalculateIsValid() && (int) this.AddressEntrySize == 2) return this.Length == 8 + (int) this.NumberOfAddresses * (int) this.AddressEntrySize * 4; return false; } internal override IcmpDatagram CreateInstance(byte[] buffer, int offset, int length) { return (IcmpDatagram) new IcmpRouterAdvertisementDatagram(buffer, offset, length); } internal static int GetPayloadLength(int numEntries) { return numEntries * 2 * 4; } internal static void WriteHeaderAdditional(byte[] buffer, int offset, IEnumerable<IcmpRouterAdvertisementEntry> entries) { foreach (IcmpRouterAdvertisementEntry advertisementEntry in entries) { ByteArrayExtensions.Write(buffer, ref offset, advertisementEntry.RouterAddress, Endianity.Big); ByteArrayExtensions.Write(buffer, ref offset, advertisementEntry.RouterAddressPreference, Endianity.Big); } } private static class Offset { public const int NumberOfAddresses = 4; public const int AddressEntrySize = 5; public const int Lifetime = 6; public const int Addresses = 8; } } } <file_sep>using Grib.Api.Interop; using Grib.Api.Interop.SWIG; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Grib.Api.Tests { [TestFixture] public class Index { [Test] public void IndexTest () { //int err = 0; //var c = GribApiProxy.GribContextGetDefault(); //var index = GribApiProxy.GribIndexNew(c, "shortName,level,number,step", out err); //GribApiProxy.GribIndexAddFile(index, Settings.GRIB); //SizeT sz = new SizeT(); //GribApiProxy.GribIndexGetSize(index, "step", ref sz); //int[] values = new int[sz]; //GribApiProxy.GribIndexGetLong(index, "step", values, ref sz); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.TcpOptionWindowScale // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Transport { [OptionTypeRegistration(typeof (TcpOptionType), TcpOptionType.WindowScale)] public sealed class TcpOptionWindowScale : TcpOptionComplex, IOptionComplexFactory, IEquatable<TcpOptionWindowScale> { public const int OptionLength = 3; public const int OptionValueLength = 1; public byte ScaleFactorLog { get; private set; } public override int Length { get { return 3; } } public override bool IsAppearsAtMostOnce { get { return true; } } public TcpOptionWindowScale(byte scaleFactorLog) : base(TcpOptionType.WindowScale) { this.ScaleFactorLog = scaleFactorLog; } public TcpOptionWindowScale() : this((byte) 0) { } public bool Equals(TcpOptionWindowScale other) { if (other == null) return false; return (int) this.ScaleFactorLog == (int) other.ScaleFactorLog; } public override bool Equals(TcpOption other) { return this.Equals(other as TcpOptionWindowScale); } public override int GetHashCode() { return base.GetHashCode() ^ this.ScaleFactorLog.GetHashCode(); } Option IOptionComplexFactory.CreateInstance(byte[] buffer, ref int offset, byte valueLength) { if ((int) valueLength != 1) return (Option) null; return (Option) new TcpOptionWindowScale(ByteArrayExtensions.ReadByte(buffer, ref offset)); } internal override void Write(byte[] buffer, ref int offset) { base.Write(buffer, ref offset); ByteArrayExtensions.Write(buffer, ref offset, this.ScaleFactorLog); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IpV4OptionTimestamp // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.IpV4 { public abstract class IpV4OptionTimestamp : IpV4OptionComplex, IEquatable<IpV4OptionTimestamp> { public const int OptionMinimumLength = 4; public const int OptionValueMinimumLength = 2; public const int OverflowMaxValue = 15; public const int PointedIndexMaxValue = 62; private readonly IpV4OptionTimestampType _timestampType; private readonly byte _overflow; private readonly byte _pointedIndex; public IpV4OptionTimestampType TimestampType { get { return this._timestampType; } } public byte Overflow { get { return this._overflow; } } public byte PointedIndex { get { return this._pointedIndex; } } public abstract int CountTimestamps { get; } public override sealed int Length { get { return 4 + this.ValuesLength; } } public override sealed bool IsAppearsAtMostOnce { get { return true; } } protected abstract int ValuesLength { get; } protected IpV4OptionTimestamp(IpV4OptionTimestampType timestampType, byte overflow, byte pointedIndex) : base(IpV4OptionType.InternetTimestamp) { if ((int) overflow > 15) throw new ArgumentOutOfRangeException("overflow", (object) overflow, "Maximum value is " + (object) 15); if ((int) pointedIndex > 62) throw new ArgumentOutOfRangeException("pointedIndex", (object) pointedIndex, "Maximum value is " + (object) 62); this._timestampType = timestampType; this._overflow = overflow; this._pointedIndex = pointedIndex; } public bool Equals(IpV4OptionTimestamp other) { if (other == null || this.TimestampType != other.TimestampType || ((int) this.Overflow != (int) other.Overflow || (int) this.PointedIndex != (int) other.PointedIndex)) return false; return this.EqualValues(other); } public override sealed bool Equals(IpV4Option other) { return this.Equals(other as IpV4OptionTimestamp); } public override int GetHashCode() { return base.GetHashCode() ^ Sequence.GetHashCode((object) BitSequence.Merge((byte) this.TimestampType, this.Overflow), (object) this.PointedIndex); } internal override sealed void Write(byte[] buffer, ref int offset) { base.Write(buffer, ref offset); buffer[offset++] = (byte) (5 + (int) this.PointedIndex * 4); buffer[offset++] = (byte) ((IpV4OptionTimestampType) ((uint) this.Overflow << 4) | this.TimestampType); this.WriteValues(buffer, ref offset); } protected abstract bool EqualValues(IpV4OptionTimestamp other); protected abstract void WriteValues(byte[] buffer, ref int offset); [OptionTypeRegistration(typeof (IpV4OptionType), IpV4OptionType.InternetTimestamp)] internal class IpV4OptionTimestampFactory : IOptionComplexFactory { Option IOptionComplexFactory.CreateInstance(byte[] buffer, ref int offset, byte valueLength) { if ((int) valueLength < 2 || (int) valueLength % 4 != 2) return (Option) null; byte num1 = buffer[offset++]; if ((int) num1 % 4 != 1 || (int) num1 < 5) return (Option) null; byte pointedIndex = (byte) ((int) num1 / 4 - 1); byte num2 = buffer[offset++]; IpV4OptionTimestampType timestampType = (IpV4OptionTimestampType) ((uint) num2 & 15U); byte overflow = (byte) ((uint) num2 >> 4); int numValues = (int) valueLength / 4; switch (timestampType) { case IpV4OptionTimestampType.TimestampOnly: return (Option) IpV4OptionTimestampOnly.Read(overflow, pointedIndex, buffer, ref offset, numValues); case IpV4OptionTimestampType.AddressAndTimestamp: case IpV4OptionTimestampType.AddressPrespecified: return (Option) IpV4OptionTimestampAndAddress.Read(timestampType, overflow, pointedIndex, buffer, ref offset, numValues); default: return (Option) null; } } } } } <file_sep>using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Grib.Api.Tests { [TestFixture] public class Precision { [Test] public void TestPrecision () { var file = new GribFile(Settings.GAUSS); var msg = file.First(); Assert.AreEqual(msg["bitsPerValue"].AsInt(), 13); msg.DecimalPrecision = 4; Assert.AreEqual(msg["bitsPerValue"].AsInt(), 20); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.UdpDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using PcapDotNet.Packets.Dns; namespace PcapDotNet.Packets.Transport { public sealed class UdpDatagram : TransportDatagram { public const int HeaderLength = 8; private DnsDatagram _dns; public ushort TotalLength { get { return this.ReadUShort(4, Endianity.Big); } } public override ushort Checksum { get { return this.ReadUShort(6, Endianity.Big); } } public override bool IsChecksumOptional { get { return true; } } public override Datagram Payload { get { return new Datagram(this.Buffer, this.StartOffset + 8, this.Length - 8); } } public DnsDatagram Dns { get { if (this._dns == null && this.Length >= 8) this._dns = new DnsDatagram(this.Buffer, this.StartOffset + 8, this.Length - 8); return this._dns; } } internal override int ChecksumOffset { get { return 6; } } internal UdpDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public override ILayer ExtractLayer() { UdpLayer udpLayer = new UdpLayer(); udpLayer.Checksum = new ushort?(this.Checksum); udpLayer.SourcePort = this.SourcePort; udpLayer.DestinationPort = this.DestinationPort; udpLayer.CalculateChecksumValue = (int) this.Checksum != 0; return (ILayer) udpLayer; } internal static void WriteHeader(byte[] buffer, int offset, ushort sourcePort, ushort destinationPort, int payloadLength) { TransportDatagram.WriteHeader(buffer, offset, sourcePort, destinationPort); ByteArrayExtensions.Write(buffer, offset + 4, (ushort) (8 + payloadLength), Endianity.Big); } protected override bool CalculateIsValid() { return this.Length >= 8; } internal static class Offset { public const int TotalLength = 4; public const int Checksum = 6; } } } <file_sep> namespace CGurus.Weather.WundergroundAPI.Models { public class TemperatureEM { public double? English { get; set; } public double? Metric { get; set; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataRKey // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Diagnostics.CodeAnalysis; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.RKey)] public sealed class DnsResourceDataRKey : DnsResourceDataSimple, IEquatable<DnsResourceDataRKey> { private const int ConstantPartLength = 4; [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Flags")] public ushort Flags { get; private set; } public byte Protocol { get; private set; } public DnsAlgorithm Algorithm { get; private set; } public DataSegment PublicKey { get; private set; } [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "flags")] public DnsResourceDataRKey(ushort flags, byte protocol, DnsAlgorithm algorithm, DataSegment publicKey) { this.Flags = flags; this.Protocol = protocol; this.Algorithm = algorithm; this.PublicKey = publicKey; } internal DnsResourceDataRKey() : this((ushort) 0, (byte) 1, DnsAlgorithm.None, DataSegment.Empty) { } public bool Equals(DnsResourceDataRKey other) { if (other != null && this.Flags.Equals(other.Flags) && (this.Protocol.Equals(other.Protocol) && this.Algorithm.Equals((object) other.Algorithm))) return this.PublicKey.Equals(other.PublicKey); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataRKey); } public override int GetHashCode() { return BitSequence.Merge(this.Flags, this.Protocol, (byte) this.Algorithm).GetHashCode(); } internal override int GetLength() { return 4 + this.PublicKey.Length; } internal override void WriteDataSimple(byte[] buffer, int offset) { ByteArrayExtensions.Write(buffer, offset, this.Flags, Endianity.Big); ByteArrayExtensions.Write(buffer, offset + 2, this.Protocol); ByteArrayExtensions.Write(buffer, offset + 3, (byte) this.Algorithm); this.PublicKey.Write(buffer, offset + 4); } internal override DnsResourceData CreateInstance(DataSegment data) { if (data.Length < 4) return (DnsResourceData) null; return (DnsResourceData) new DnsResourceDataRKey(data.ReadUShort(0, Endianity.Big), data[2], (DnsAlgorithm) data[3], data.Subsegment(4, data.Length - 4)); } private static class Offset { public const int Flags = 0; public const int Protocol = 2; public const int Algorithm = 3; public const int PublicKey = 4; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.TcpOptionType // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using System.Diagnostics.CodeAnalysis; namespace PcapDotNet.Packets.Transport { public enum TcpOptionType : byte { EndOfOptionList = (byte) 0, NoOperation = (byte) 1, MaximumSegmentSize = (byte) 2, WindowScale = (byte) 3, SelectiveAcknowledgmentPermitted = (byte) 4, SelectiveAcknowledgment = (byte) 5, Echo = (byte) 6, EchoReply = (byte) 7, Timestamp = (byte) 8, PartialOrderConnectionPermitted = (byte) 9, PartialOrderServiceProfile = (byte) 10, ConnectionCount = (byte) 11, [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] ConnectionCountNew = (byte) 12, ConnectionCountEcho = (byte) 13, AlternateChecksumRequest = (byte) 14, AlternateChecksumData = (byte) 15, Md5Signature = (byte) 19, SelectiveNegativeAcknowledgements = (byte) 21, Mood = (byte) 25, QuickStartResponse = (byte) 27, UserTimeout = (byte) 28, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IpV4OptionTimestampAndAddress // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace PcapDotNet.Packets.IpV4 { public sealed class IpV4OptionTimestampAndAddress : IpV4OptionTimestamp { private readonly ReadOnlyCollection<IpV4OptionTimedAddress> _addressesAndTimestamps; public override int CountTimestamps { get { return Enumerable.Count<IpV4OptionTimedAddress>((IEnumerable<IpV4OptionTimedAddress>) this.TimedRoute); } } public ReadOnlyCollection<IpV4OptionTimedAddress> TimedRoute { get { return this._addressesAndTimestamps; } } protected override int ValuesLength { get { return this.TimedRoute.Count * 8; } } public IpV4OptionTimestampAndAddress(IpV4OptionTimestampType timestampType, byte overflow, byte pointedIndex, IList<IpV4OptionTimedAddress> timedRoute) : base(timestampType, overflow, pointedIndex) { if (timestampType != IpV4OptionTimestampType.AddressAndTimestamp && timestampType != IpV4OptionTimestampType.AddressPrespecified) throw new ArgumentException("Illegal timestamp type " + (object) timestampType, "timestampType"); this._addressesAndTimestamps = IListExtensions.AsReadOnly<IpV4OptionTimedAddress>(timedRoute); } public IpV4OptionTimestampAndAddress(IpV4OptionTimestampType timestampType, byte overflow, byte pointedIndex, params IpV4OptionTimedAddress[] timedRoute) : this(timestampType, overflow, pointedIndex, (IList<IpV4OptionTimedAddress>) timedRoute) { } public override int GetHashCode() { return base.GetHashCode() ^ IEnumerableExtensions.SequenceGetHashCode<IpV4OptionTimedAddress>((IEnumerable<IpV4OptionTimedAddress>) this.TimedRoute); } internal static IpV4OptionTimestampAndAddress Read(IpV4OptionTimestampType timestampType, byte overflow, byte pointedIndex, byte[] buffer, ref int offset, int numValues) { if (numValues % 2 != 0) return (IpV4OptionTimestampAndAddress) null; IpV4OptionTimedAddress[] optionTimedAddressArray = new IpV4OptionTimedAddress[numValues / 2]; for (int index = 0; index != numValues / 2; ++index) optionTimedAddressArray[index] = new IpV4OptionTimedAddress(ByteArrayExtensions.ReadIpV4Address(buffer, ref offset, Endianity.Big), ByteArrayExtensions.ReadIpV4TimeOfDay(buffer, ref offset, Endianity.Big)); return new IpV4OptionTimestampAndAddress(timestampType, overflow, pointedIndex, optionTimedAddressArray); } protected override bool EqualValues(IpV4OptionTimestamp other) { return Enumerable.SequenceEqual<IpV4OptionTimedAddress>((IEnumerable<IpV4OptionTimedAddress>) this.TimedRoute, (IEnumerable<IpV4OptionTimedAddress>) ((IpV4OptionTimestampAndAddress) other).TimedRoute); } protected override void WriteValues(byte[] buffer, ref int offset) { foreach (IpV4OptionTimedAddress optionTimedAddress in this.TimedRoute) { ByteArrayExtensions.Write(buffer, ref offset, optionTimedAddress.Address, Endianity.Big); ByteArrayExtensions.Write(buffer, ref offset, optionTimedAddress.TimeOfDay, Endianity.Big); } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Igmp.IgmpQueryVersion // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Igmp { public enum IgmpQueryVersion { None, Version1, Version2, Version3, Unknown, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsCertificateType // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Dns { public enum DnsCertificateType : ushort { None = (ushort) 0, Pkix = (ushort) 1, SimplePublicKeyInfrastructure = (ushort) 2, Pgp = (ushort) 3, IPkix = (ushort) 4, IndirectSimplePublicKeyInfrastructure = (ushort) 5, Ipgp = (ushort) 6, AttributeCertificatePkix = (ushort) 7, IndirectAttributeCertificatePkix = (ushort) 8, Uri = (ushort) 253, ObjectIdentifier = (ushort) 254, } } <file_sep>using System; namespace CGurus.Weather.WundergroundAPI.Models { public class FctTime { public string Age { get; set; } public AMPM AmPm { get; set; } public string Civil { get; set; } public long Epoch { get; set; } public DateTime EpochDate { get { return Utilities.EpochConverter.FromUnixTime(this.Epoch); } } public Int16? Hour { get; set; } public string Hour_Padded { get; set; } public bool IsDst { get; set; } public Int16? MDay { get; set; } public string MDay_Padded { get; set; } public Int16? Min { get; set; } public Int16? Mon { get; set; } public string Mon_Abbrev { get; set; } public string Mon_Padded { get; set; } public string Month_Name { get; set; } public string Month_Name_Abbrev { get; set; } public string Pretty { get; set; } public Int16? Sec { get; set; } public string Tz { get; set; } public DayOfWeek WeekDay_Name { get; set; } public string Weekday_Name_Abbrev { get; set; } public string Weekday_Name_Night { get; set; } public string Weekday_Name_Night_UnLang { get; set; } public string Weekday_Name_UnLang { get; set; } public Int16? YDay { get; set; } public Int16? Year { get; set; } } } <file_sep>// Copyright 2015 <NAME> // // 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. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Grib.Api.Interop { /// <summary> /// Bitwise OR-able bitflags used to filter message keys when iterating. /// </summary> public enum KeyFilters : uint { All = 0, SkipReadOnly = 1<<0, SkipOptional = 1<<1, SkipEditionSpecific = 1<<2, SkipCoded = 1<<3, SkipComputed = 1<<4, SkipDuplicates = 1<<5, SkipFunction = 1<<6 } } <file_sep>// Decompiled with JetBrains decompiler // Type: AcuLink_Bridge_Reader_CSharp.RainData // Assembly: AcuLink_Bridge_Reader_CS, Version=2014.9.18.2041, Culture=neutral, PublicKeyToken=null // MVID: 2DF0938E-D9D0-414E-AB5D-7B9A655FB464 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\AcuLink_Bridge_Reader_CS.exe using System; namespace AcuLink_Bridge_Reader_CSharp { public class RainData { public DateTime time { get; set; } public double rain { get; set; } public RainData(DateTime time, double rain) { this.time = time; this.rain = rain; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsOptFlags // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using System; using System.Diagnostics.CodeAnalysis; namespace PcapDotNet.Packets.Dns { [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Flags")] [Flags] public enum DnsOptFlags : ushort { DnsSecOk = (ushort) 32768, } } <file_sep>// Decompiled with JetBrains decompiler // Type: std.allocator<char> // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using Microsoft.VisualC; using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace std { [MiscellaneousBits(64)] [DebugInfoInPDB] [NativeCppClass] [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct allocator\u003Cchar\u003E { [SpecialName] public static unsafe void \u003CMarshalCopy\u003E(allocator\u003Cchar\u003E* _param1, allocator\u003Cchar\u003E* _param2) { } [DebugInfoInPDB] [NativeCppClass] [MiscellaneousBits(65)] [CLSCompliant(false)] [StructLayout(LayoutKind.Sequential, Size = 1)] public struct rebind\u003Cchar\u003E { } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IpV4OptionSecurityProtectionAuthorities // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using System; namespace PcapDotNet.Packets.IpV4 { [Flags] public enum IpV4OptionSecurityProtectionAuthorities : byte { None = (byte) 0, Genser = (byte) 128, SingleIntegrationOptionalPlanExtremelySensitiveInformation = (byte) 64, SensitiveCompartmentedInformation = (byte) 32, Nsa = (byte) 16, DepartmentOfEnergy = (byte) 8, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Packet // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets.Ethernet; using PcapDotNet.Packets.IpV4; using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; namespace PcapDotNet.Packets { public sealed class Packet : IList<byte>, ICollection<byte>, IEnumerable<byte>, IEnumerable, IEquatable<Packet> { private readonly byte[] _data; private readonly DateTime _timestamp; private readonly IDataLink _dataLink; private bool? _isValid; private EthernetDatagram _ethernet; private IpV4Datagram _ipV4; public int Length { get { return this._data.Length; } } public DateTime Timestamp { get { return this._timestamp; } } public IDataLink DataLink { get { return this._dataLink; } } [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public byte[] Buffer { get { return this._data; } } public byte this[int index] { get { return this.Buffer[index]; } set { throw new InvalidOperationException("Immutable collection"); } } public int Count { get { return this.Length; } } public bool IsReadOnly { get { return true; } } public bool IsValid { get { if (!this._isValid.HasValue) this._isValid = new bool?(this.CalculateIsValid()); return this._isValid.Value; } } public EthernetDatagram Ethernet { get { return this._ethernet ?? (this._ethernet = new EthernetDatagram(this.Buffer, 0, this.Length)); } } public IpV4Datagram IpV4 { get { return this._ipV4 ?? (this._ipV4 = new IpV4Datagram(this.Buffer, 0, this.Length)); } } public Packet(byte[] data, DateTime timestamp, DataLinkKind dataLink) : this(data, timestamp, (IDataLink) new PcapDotNet.Packets.DataLink(dataLink)) { } public Packet(byte[] data, DateTime timestamp, IDataLink dataLink) { this._data = data; this._timestamp = timestamp; this._dataLink = dataLink; } public static Packet FromHexadecimalString(string value, DateTime timestamp, DataLinkKind dataLink) { if (value == null) throw new ArgumentNullException("value"); byte[] data = new byte[value.Length / 2]; int startIndex = 0; while (startIndex < value.Length) { data[startIndex / 2] = Convert.ToByte(value.Substring(startIndex, 2), 16); startIndex += 2; } return new Packet(data, timestamp, dataLink); } public bool Equals(Packet other) { if (other != null && this.Length == other.Length) return Enumerable.SequenceEqual<byte>((IEnumerable<byte>) this, (IEnumerable<byte>) other); return false; } public override bool Equals(object obj) { return this.Equals(obj as Packet); } public override int GetHashCode() { return IEnumerableExtensions.BytesSequenceGetHashCode((IEnumerable<byte>) this); } public override string ToString() { return typeof (Packet).Name + (object) " <" + (string) (object) this.DataLink + ", " + (string) (object) this.Length + ">"; } public IEnumerator<byte> GetEnumerator() { return ((IEnumerable<byte>) this.Buffer).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator) this.GetEnumerator(); } public int IndexOf(byte item) { return ((IList<byte>) this.Buffer).IndexOf(item); } public void Insert(int index, byte item) { throw new InvalidOperationException("Immutable collection"); } public void RemoveAt(int index) { throw new InvalidOperationException("Immutable collection"); } public void Add(byte item) { throw new InvalidOperationException("Immutable collection"); } public void Clear() { throw new InvalidOperationException("Immutable collection"); } public bool Contains(byte item) { return Enumerable.Contains<byte>((IEnumerable<byte>) this.Buffer, item); } public void CopyTo(byte[] array, int arrayIndex) { ByteArrayExtensions.BlockCopy(this.Buffer, 0, array, arrayIndex, this.Length); } public bool Remove(byte item) { throw new InvalidOperationException("Immutable collection"); } private bool CalculateIsValid() { switch (this.DataLink.Kind) { case DataLinkKind.Ethernet: return this.Ethernet.IsValid; case DataLinkKind.IpV4: return this.IpV4.IsValid; default: return false; } } } } <file_sep>using System; using CGurus.Weather.WundergroundAPI.Models; using CGurus.Weather.WundergroundAPI.Utilities; namespace CGurus.Weather.WundergroundAPI { public class WUApi { private string _apiKey { get; set; } private const string _baseUrl = "http://api.wunderground.com/api"; public WUApi(string ApiKey) { _apiKey = ApiKey; } public AlertData GetAlertsUS(string State, string City) { ValidateState(State); //Example: http://api.wunderground.com/api/{API_Key}/alerts/q/IA/Des_Moines.json string uri = string.Format("{0}/{1}/alerts/q/{2}/{3}.json", _baseUrl, _apiKey, State, City.Replace(" ", "_")); return RestRequest.Execute<AlertData>(uri); } public ForecastData GetForecastUS(string State, string City) { ValidateState(State); //Example: http://api.wunderground.com/api/{API_Key}/forecast/q/CA/San_Francisco.json string uri = string.Format("{0}/{1}/forecast/q/{2}/{3}.json", _baseUrl, _apiKey, State, City.Replace(" ", "_")); return RestRequest.Execute<ForecastData>(uri); } public ForecastData GetForecast10DayUS(string State, string City) { ValidateState(State); //Example: http://api.wunderground.com/api/{API_Key}/forecast10day/q/CA/San_Francisco.json string uri = string.Format("{0}/{1}/forecast10day/q/{2}/{3}.json", _baseUrl, _apiKey, State, City.Replace(" ", "_")); return RestRequest.Execute<ForecastData>(uri); } public ForecastHourlyData GetForecastHourlyUS(string State, string City) { ValidateState(State); //Example: http://api.wunderground.com/api/{API_Key}/hourly/q/CA/San_Francisco.json string uri = string.Format("{0}/{1}/hourly/q/{2}/{3}.json", _baseUrl, _apiKey, State, City.Replace(" ", "_")); return RestRequest.Execute<ForecastHourlyData>(uri); } private void ValidateState(string State) { if (State.Length > 2) { throw new ArgumentException("State must be a two character abbreviation."); } } } } <file_sep>using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("AcuLink_Bridge_Reader_CSharp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AcuLink_Bridge_Reader_CSharp")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("2e6ecc06-3636-4282-a690-8a01d28b2b3e")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyVersion("2014.9.18.2041")] <file_sep>// Copyright 2015 <NAME> // // 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. using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace Grib.Api.Interop { /// <summary> /// SizeT is a variable-size, platform-dependent unsigned integer. /// It can store the maximum size of a theoretically possible object /// of any type (including array). Implicitly convertable to UInt. /// <para>&#160;</para> /// Example: /// <code> /// <para>&#160;&#160;SizeT size = 1;</para> /// <para>&#160;&#160;int[] myArray = new int[size];</para> /// <para>&#160;&#160;size = (SizeT) getSomeInt();</para> /// <para>&#160;&#160;Int64 big = (Int64) size;</para> /// </code> /// </summary> public struct SizeT { /// <summary> /// The value. /// </summary> public UIntPtr Value; /// <summary> /// Initializes a new instance of the <see cref="SizeT"/> struct. /// </summary> /// <param name="val">The value.</param> private SizeT (UIntPtr val) : this() { Value = val; } /// <summary> /// Initializes a new instance of the <see cref="SizeT"/> struct. /// </summary> /// <param name="val">The value.</param> private SizeT (uint val = 0) : this((UIntPtr)val) { } /// <summary> /// Initializes a new instance of the <see cref="SizeT"/> struct. /// </summary> /// <param name="val">The value.</param> private SizeT (int val) : this((UIntPtr)val) { } /// <summary> /// Gets the size of the value's container. 4 on x86, 8 on x64. /// </summary> /// <value> /// The size. /// </value> public static int Size { get { return Marshal.SizeOf(UIntPtr.Zero); } } /// <summary> /// Performs an implicit conversion from <see cref="UIntPtr"/> to <see cref="SizeT"/>. /// </summary> /// <param name="s">The s.</param> /// <returns> /// The result of the conversion. /// </returns> public static implicit operator SizeT (UIntPtr s) { return new SizeT(s); } /// <summary> /// Performs an implicit conversion from <see cref="UInt32"/> to <see cref="SizeT"/>. /// </summary> /// <param name="s">The s.</param> /// <returns> /// The result of the conversion. /// </returns> public static implicit operator SizeT (UInt32 s) { return new SizeT((UIntPtr)s); } /// <summary> /// Performs an explicit conversion from <see cref="UInt64"/> to <see cref="SizeT"/>. /// </summary> /// <param name="s">The s.</param> /// <returns> /// The result of the conversion. /// </returns> public static explicit operator SizeT (UInt64 s) { return new SizeT((UIntPtr)s); } /// <summary> /// Performs an explicit conversion from <see cref="Int32"/> to <see cref="SizeT"/>. /// </summary> /// <param name="s">The s.</param> /// <returns> /// The result of the conversion. /// </returns> public static explicit operator SizeT (Int32 s) { return new SizeT((UIntPtr) s); } /// <summary> /// Performs an explicit conversion from <see cref="Int64"/> to <see cref="SizeT"/>. /// </summary> /// <param name="s">The s.</param> /// <returns> /// The result of the conversion. /// </returns> public static explicit operator SizeT (Int64 s) { return new SizeT((UIntPtr) s); } /// <summary> /// Performs an implicit conversion from <see cref="SizeT"/> to <see cref="UIntPtr"/>. /// </summary> /// <param name="s">The s.</param> /// <returns> /// The result of the conversion. /// </returns> public static implicit operator UIntPtr (SizeT s) { return s.Value; } /// <summary> /// Performs an implicit conversion from <see cref="SizeT"/> to <see cref="UInt32"/>. /// </summary> /// <param name="s">The s.</param> /// <returns> /// The result of the conversion. /// </returns> public static implicit operator UInt32 (SizeT s) { return s.Value.ToUInt32(); } /// <summary> /// Performs an implicit conversion from <see cref="SizeT"/> to <see cref="UInt64"/>. /// </summary> /// <param name="s">The s.</param> /// <returns> /// The result of the conversion. /// </returns> public static implicit operator UInt64 (SizeT s) { return s.Value.ToUInt64(); } /// <summary> /// Performs an explicit conversion from <see cref="SizeT"/> to <see cref="Int32"/>. /// </summary> /// <param name="s">The s.</param> /// <returns> /// The result of the conversion. /// </returns> public static explicit operator Int32 (SizeT s) { return (Int32) s.Value.ToUInt32(); } /// <summary> /// Performs an explicit conversion from <see cref="SizeT"/> to <see cref="Int64"/>. /// </summary> /// <param name="s">The s.</param> /// <returns> /// The result of the conversion. /// </returns> public static explicit operator Int64 (SizeT s) { return (Int64) s.Value.ToUInt64(); } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { return this.Value.GetHashCode(); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="a">a.</param> /// <param name="b">The b.</param> /// <returns> /// The result of the operator. /// </returns> public static bool operator ==(SizeT a, SizeT b) { return a.Value == b.Value; } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="a">a.</param> /// <param name="b">The b.</param> /// <returns> /// The result of the operator. /// </returns> public static bool operator !=(SizeT a, SizeT b) { return a.Value != b.Value; } /// <summary> /// Determines whether the specified <see cref="System.Object" />, is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { bool isEqual = false; if (obj != null && typeof(SizeT).IsAssignableFrom(obj.GetType())) { isEqual = this == (SizeT) obj; } return isEqual; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Gre.GreSourceRouteEntryAddressFamily // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Gre { public enum GreSourceRouteEntryAddressFamily : ushort { None = (ushort) 0, IpSourceRoute = (ushort) 2048, AsSourceRoute = (ushort) 65534, } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; using System.Diagnostics; using System.IO; using System.Reflection; using Grib.Api.Interop; using System.Text.RegularExpressions; using System.Threading; namespace Grib.Api.Tests { [TestFixture] public class Get { [Test] public void TestGetBox () { using (GribFile file = new GribFile(Settings.GAUSS)) { Assert.IsTrue(file.MessageCount > 0); foreach (var msg in file) { var pts = msg.Box(new GeoCoordinate(60, -10), new GeoCoordinate(10, 30)); foreach (var val in pts.Latitudes) { Assert.GreaterOrEqual(60, val); Assert.LessOrEqual(10, val); } foreach (var val in pts.Longitudes) { Assert.GreaterOrEqual(val, -10); Assert.LessOrEqual(val, 30); } } } } [Test] public void TestOpenPng () { using (GribFile file = new GribFile(Settings.PNG_COMPRESSION)) { Assert.IsTrue(file.MessageCount > 0); var msg = file.First(); try { Assert.IsTrue(msg["packingType"].AsString().ToLower().EndsWith("_png")); Assert.IsTrue(msg.ValuesCount > 0); Assert.IsTrue(msg.GeoSpatialValues.Any()); int i = 0; foreach (var v in msg.GeoSpatialValues) { Assert.AreNotEqual(Double.NaN, v.Value); if (i++ > 1000) break; } } catch (GribApiException e) { Console.WriteLine(e.Message); Console.WriteLine(msg.ShortName); Console.WriteLine(msg.ToString()); Assert.IsTrue(false); } } } [Test] public void TestOpenComplex () { using (GribFile file = new GribFile(Settings.COMPLEX_GRID)) { Assert.IsTrue(file.MessageCount > 0); foreach (var msg in file) { try { Assert.IsTrue(msg["packingType"].AsString().ToLower().Contains("complex")); Assert.IsTrue(msg.ValuesCount > 0); double[] vals; msg.Values(out vals); Assert.IsTrue(vals.Any()); foreach (var v in vals) { Assert.AreNotEqual(Double.NaN, v); } } catch (GribApiException e) { Console.WriteLine(e.Message); Console.WriteLine(msg.ShortName); Console.WriteLine(msg.ToString()); Assert.IsTrue(false); } } } } [Test] public void TestGetCounts () { using (GribFile file = new GribFile(Settings.GRIB)) { Assert.IsTrue(file.MessageCount > 0); foreach (var msg in file) { Assert.AreNotEqual(msg.DataPointsCount, 0); Assert.AreNotEqual(msg.ValuesCount, 0); Assert.AreEqual(msg.ValuesCount, msg["numberOfCodedValues"].AsInt()); Assert.IsTrue(msg["numberOfCodedValues"].IsReadOnly); Assert.AreEqual(msg.DataPointsCount, msg.ValuesCount + msg.MissingCount); } } } [Test] public void TestGetVersion () { Regex re = new Regex(@"^(\d+\.)?(\d+\.)?(\*|\d+)$"); Assert.IsTrue(re.IsMatch(GribEnvironment.GribApiVersion)); } [Test] public void TestGetNativeType () { using (GribFile file = new GribFile(Settings.REG_LATLON_GRB1)) { var msg = file.First(); Assert.AreEqual(msg["packingType"].NativeType, GribValueType.String); Assert.AreEqual(msg["longitudeOfFirstGridPointInDegrees"].NativeType, GribValueType.Double); Assert.AreEqual(msg["numberOfPointsAlongAParallel"].NativeType, GribValueType.Int); Assert.AreEqual(msg["values"].NativeType, GribValueType.DoubleArray); // TODO: test other types } } [Test] public void TestCanConvertToDegress () { using (GribFile file = new GribFile(Settings.REDUCED_LATLON_GRB2)) { var msg = file.First(); // true Assert.IsTrue(msg["latitudeOfFirstGridPointInDegrees"].CanConvertToDegrees); Assert.IsTrue(msg["latitudeOfFirstGridPoint"].CanConvertToDegrees); Assert.IsTrue(msg["longitudeOfFirstGridPointInDegrees"].CanConvertToDegrees); Assert.IsTrue(msg["longitudeOfFirstGridPoint"].CanConvertToDegrees); Assert.IsTrue(msg["latitudeOfLastGridPointInDegrees"].CanConvertToDegrees); Assert.IsTrue(msg["latitudeOfLastGridPoint"].CanConvertToDegrees); Assert.IsTrue(msg["jDirectionIncrement"].CanConvertToDegrees); Assert.IsTrue(msg["iDirectionIncrement"].CanConvertToDegrees); // false Assert.IsFalse(msg["numberOfPointsAlongAParallel"].CanConvertToDegrees); Assert.IsFalse(msg["numberOfPointsAlongAParallelInDegrees"].CanConvertToDegrees); Assert.IsFalse(msg["numberOfPointsAlongAMeridian"].CanConvertToDegrees); Assert.IsFalse(msg["numberOfPointsAlongAMeridianInDegrees"].CanConvertToDegrees); Assert.IsFalse(msg["packingType"].CanConvertToDegrees); } } [Test] public void TestGetGrib2 () { double delta = 0.1d; using (GribFile file = new GribFile(Settings.REDUCED_LATLON_GRB2)) { var msg = file.First(); // "InDegrees" is a magic token that converts coordinate double values to degrees // explicit degree conversion via key name double latitudeOfFirstGridPointInDegrees = msg["latitudeOfFirstGridPoint"].AsDouble(); Assert.AreEqual(latitudeOfFirstGridPointInDegrees, 90, delta); // degree conversion via accessor double longitudeOfFirstGridPointInDegrees = msg["longitudeOfFirstGridPoint"].AsDouble(/* inDegrees == true */); Assert.AreEqual(longitudeOfFirstGridPointInDegrees, 0, delta); // degree conversion via accessor double latitudeOfLastGridPointInDegrees = msg["latitudeOfLastGridPoint"].AsDouble(/* inDegrees == true */); Assert.AreEqual(latitudeOfLastGridPointInDegrees, -90, delta); // degree conversion via accessor double longitudeOfLastGridPointInDegrees = msg["longitudeOfLastGridPoint"].AsDouble(/* inDegrees == true */); Assert.AreEqual(longitudeOfLastGridPointInDegrees, 360, .5); // degree conversion via accessor double jDirectionIncrementInDegrees = msg["jDirectionIncrement"].AsDouble(/* inDegrees == true */); Assert.AreEqual(jDirectionIncrementInDegrees, 0.36, delta); // degree conversion via accessor double iDirectionIncrementInDegrees = msg["iDirectionIncrement"].AsDouble(/* inDegrees == true */); Assert.AreEqual(iDirectionIncrementInDegrees, -1.0E+100, delta); int numberOfPointsAlongAParallel = msg["numberOfPointsAlongAParallel"].AsInt(); Assert.AreEqual(numberOfPointsAlongAParallel, -1); int numberOfPointsAlongAMeridian = msg["numberOfPointsAlongAMeridian"].AsInt(); Assert.AreEqual(numberOfPointsAlongAMeridian, 501); string packingType = msg["packingType"].AsString(); Assert.AreEqual("grid_simple", packingType); } } [Test] public void TestGetParallel () { var files = new[] { Settings.REDUCED_LATLON_GRB2, Settings.BIN, Settings.COMPLEX_GRID, Settings.REG_LATLON_GRB1, Settings.GAUSS, Settings.PACIFIC_WIND }; Parallel.ForEach(files, (path, s) => { using (var file = new GribFile(path)) { Parallel.ForEach(file, (msg, s2) => { if (msg.ShortName == "shww") return; try { foreach (var v in msg.GeoSpatialValues) { Assert.AreNotEqual(Double.NaN, v.Latitude); Assert.AreNotEqual(Double.NaN, v.Longitude); Assert.AreNotEqual(Double.NaN, v.Value); } } catch (GribApiException e) { Console.WriteLine(e.Message); Console.WriteLine(msg.ShortName); Console.WriteLine(msg.ToString()); Assert.IsTrue(false); } }); } }); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataResponsiblePerson // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.ResponsiblePerson)] public sealed class DnsResourceDataResponsiblePerson : DnsResourceData2DomainNames { public DnsDomainName Mailbox { get { return this.First; } } public DnsDomainName TextDomain { get { return this.Second; } } public DnsResourceDataResponsiblePerson(DnsDomainName mailbox, DnsDomainName textDomain) : base(mailbox, textDomain) { } internal DnsResourceDataResponsiblePerson() : this(DnsDomainName.Root, DnsDomainName.Root) { } internal override DnsResourceData CreateInstance(DnsDatagram dns, int offsetInDns, int length) { DnsDomainName first; DnsDomainName second; if (!DnsResourceData2DomainNames.TryRead(out first, out second, dns, offsetInDns, length)) return (DnsResourceData) null; return (DnsResourceData) new DnsResourceDataResponsiblePerson(first, second); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Http.HttpRequestKnownMethod // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Http { public enum HttpRequestKnownMethod { Options, Get, Head, Post, Put, Delete, Trace, Connect, Unknown, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Http.HttpTrailerField // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text.RegularExpressions; namespace PcapDotNet.Packets.Http { public sealed class HttpTrailerField : HttpField, IEquatable<HttpTrailerField> { private static readonly Regex _regex = HttpRegex.MatchEntire(HttpRegex.CommaSeparatedRegex(HttpRegex.Capture(HttpRegex.Token, "FieldName"), 1)); public const string FieldName = "Trailer"; public const string FieldNameUpper = "TRAILER"; private const string FieldNameGroupName = "FieldName"; private ReadOnlyCollection<string> _fieldNames; public ReadOnlyCollection<string> FieldsNames { get { return this._fieldNames; } } public HttpTrailerField(IEnumerable<string> fieldsNames) : base("Trailer", IEnumerableExtensions.SequenceToString<string>(fieldsNames, ',')) { this.SetFieldNames(fieldsNames); } internal HttpTrailerField(byte[] fieldValue) : base("Trailer", (IList<byte>) fieldValue) { string @string = HttpRegex.GetString(fieldValue); Match match = HttpTrailerField._regex.Match(@string); if (!match.Success) return; this.SetFieldNames(MatchExtensions.GroupCapturesValues(match, "FieldName")); } public bool Equals(HttpTrailerField other) { if (other != null) return Enumerable.SequenceEqual<string>((IEnumerable<string>) this.FieldsNames, (IEnumerable<string>) other.FieldsNames); return false; } public override bool Equals(HttpField other) { return this.Equals(other as HttpTrailerField); } private void SetFieldNames(IEnumerable<string> fieldNames) { this._fieldNames = IListExtensions.AsReadOnly<string>((IList<string>) Enumerable.ToArray<string>(Enumerable.Select<string, string>(fieldNames, (Func<string, string>) (name => name.ToUpperInvariant())))); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataString // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.X25)] public sealed class DnsResourceDataString : DnsResourceDataSimple, IEquatable<DnsResourceDataString> { public DataSegment String { get; private set; } public DnsResourceDataString(DataSegment value) { this.String = value; } internal DnsResourceDataString() : this(DataSegment.Empty) { } public bool Equals(DnsResourceDataString other) { if (other != null) return this.String.Equals(other.String); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataString); } public override int GetHashCode() { return this.String.GetHashCode(); } internal override int GetLength() { return DnsResourceData.GetStringLength(this.String); } internal override void WriteDataSimple(byte[] buffer, int offset) { DnsResourceData.WriteString(buffer, ref offset, this.String); } internal override DnsResourceData CreateInstance(DataSegment data) { int offset = 0; DataSegment dataSegment = DnsResourceData.ReadString(data, ref offset); if (dataSegment == null) return (DnsResourceData) null; return (DnsResourceData) new DnsResourceDataString(dataSegment); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataMailingListInfo // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.MInfo)] public sealed class DnsResourceDataMailingListInfo : DnsResourceData2DomainNames { public DnsDomainName MailingList { get { return this.First; } } public DnsDomainName ErrorMailbox { get { return this.Second; } } public DnsResourceDataMailingListInfo(DnsDomainName mailingList, DnsDomainName errorMailbox) : base(mailingList, errorMailbox) { } internal DnsResourceDataMailingListInfo() : this(DnsDomainName.Root, DnsDomainName.Root) { } internal override DnsResourceData CreateInstance(DnsDatagram dns, int offsetInDns, int length) { DnsDomainName first; DnsDomainName second; if (!DnsResourceData2DomainNames.TryRead(out first, out second, dns, offsetInDns, length)) return (DnsResourceData) null; return (DnsResourceData) new DnsResourceDataMailingListInfo(first, second); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.DataLinkKind // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets { public enum DataLinkKind { Ethernet, IpV4, Docsis, } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets; using System.Net; using System.Threading; using System.Data.SqlClient; namespace UpdateCWOP { class Program { static void Main(string[] args) { SqlCommand command; SqlDataReader reader; //replace [servername] with the name of the database server // [dbname] is name of database you set up in WDTU // [user] this is the SQL user you are connecting with // [password] this is the password for the user account using (SqlConnection connection = new SqlConnection(@"Data Source=[servername];Initial Catalog=[dbname];Persist Security Info=True;User ID=[user];Password=[<PASSWORD>];Network Library=dbmssocn")) { connection.Open(); command = new SqlCommand(@"SELECT TOP 1 [ReceiverRecID] ,[ChannelIndex] ,[RecDateTime] ,[TempOut] ,[HumOut] ,[WindSpeed] ,[DominantDir] ,[DewPoint] ,[Barometer] ,[RainfallHour] ,[RainfallDay] ,[WindGust] ,[Rainfall24] FROM [Weather].[dbo].[Wunderground] ORDER BY RecDateTime DESC;", connection); reader = command.ExecuteReader(); reader.Read(); if (reader.HasRows) { TcpClient client = new TcpClient(); client.Connect("cwop.aprs.net", 14580); NetworkStream clientStream = client.GetStream(); ASCIIEncoding encoder = new ASCIIEncoding(); // Replace [stationid] with your CWOP station id - CWXXXX or DWXXXX byte[] buffer = encoder.GetBytes("user [stationid] pass -1 vers ThreePines Weather 1.0\r\n"); clientStream.Write(buffer, 0, buffer.Length); clientStream.Flush(); Thread.Sleep(3000); // Replace [stationid] with your CWOP station id - CWXXXX or DWXXXX string datapacket = "[stationid]>APRS,TCPXX*:"; datapacket += "@" + DateTime.Parse(reader[2].ToString()).ToUniversalTime().ToString("ddHHmm") + "z"; //day/time //replace with your lat/lon in the line below datapacket += "4153.27N/07253.55W"; //lat/lon datapacket += "_" + ((byte)reader[6]).ToString("000"); //direction of wind datapacket += "/" + ((decimal)reader[5]).ToString("000"); //average wind speed datapacket += "g" + ((decimal)reader[11]).ToString("000"); //gust windspeed if ((short)reader[3] >= 0 && (short)reader[3] < 1000) { datapacket += "t" + ((short)reader[3] * .1).ToString("000"); //temperature } else if ((short)reader[3] >= 0 && (short)reader[3] >= 1000) { datapacket += "t" + ((short)reader[3]).ToString("00"); } else { datapacket += "t" + ((short)reader[3]).ToString("00"); } datapacket += "r" + ((decimal)reader[9]).ToString("000"); //rainfall last hour datapacket += "p" + ((decimal)reader[12]).ToString("000"); //rainfall last 24 hours datapacket += "P" + ((decimal)reader[10]).ToString("000"); //rainfaill since midnight if (reader[4].ToString() == "100") { datapacket += "h" + "00"; //humidity } else { datapacket += "h" + reader[4].ToString(); } datapacket += "b" + (((short)reader[8] / (double)1000) * 33.8637526 * 10).ToString("00000"); //barometer datapacket += "eEnvoy8x\r\n"; byte[] buffer2 = encoder.GetBytes(datapacket); clientStream.Write(buffer2, 0, buffer2.Length); clientStream.Flush(); Thread.Sleep(3000); client.Close(); } reader.Close(); } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Gre.GreLayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using PcapDotNet.Packets.Ethernet; using PcapDotNet.Packets.IpV4; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Linq; namespace PcapDotNet.Packets.Gre { public sealed class GreLayer : EthernetBaseLayer, IIpV4NextLayer, ILayer, IEquatable<GreLayer> { public GreVersion Version { get; set; } public EthernetType ProtocolType { get { return this.EtherType; } set { this.EtherType = value; } } public byte RecursionControl { get; set; } public byte FutureUseBits { get; set; } public bool ChecksumPresent { get; set; } public ushort? Checksum { get; set; } public uint? Key { get; set; } public ushort? KeyPayloadLength { get { if (this.Key.HasValue) return new ushort?((ushort) ((this.Key.Value & 4294901760U) >> 16)); return new ushort?(); } } public ushort? KeyCallId { get { if (this.Key.HasValue) return new ushort?((ushort) (this.Key.Value & (uint) ushort.MaxValue)); return new ushort?(); } } public uint? SequenceNumber { get; set; } public uint? AcknowledgmentSequenceNumber { get; set; } public ushort? RoutingOffset { get; set; } [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ReadOnlyCollection<GreSourceRouteEntry> Routing { get; set; } public bool StrictSourceRoute { get; set; } public override int Length { get { return GreDatagram.GetHeaderLength(this.ChecksumPresent, this.Key.HasValue, this.SequenceNumber.HasValue, this.AcknowledgmentSequenceNumber.HasValue, (IEnumerable<GreSourceRouteEntry>) this.Routing); } } public IpV4Protocol PreviousLayerProtocol { get { return IpV4Protocol.Gre; } } public void SetKey(ushort keyPayloadLength, ushort keyCallId) { this.Key = new uint?(BitSequence.Merge(keyPayloadLength, keyCallId)); } public override void Write(byte[] buffer, int offset, int payloadLength, ILayer previousLayer, ILayer nextLayer) { EthernetType protocolType = this.ProtocolType; if (protocolType == EthernetType.None) { if (nextLayer == null) throw new ArgumentException("Can't determine protocol type automatically from next layer because there is not next layer"); IEthernetNextLayer ethernetNextLayer = nextLayer as IEthernetNextLayer; if (ethernetNextLayer == null) throw new ArgumentException("Can't determine protocol type automatically from next layer (" + (object) nextLayer.GetType() + ")"); protocolType = ethernetNextLayer.PreviousLayerEtherType; } GreDatagram.WriteHeader(buffer, offset, this.RecursionControl, this.FutureUseBits, this.Version, protocolType, this.ChecksumPresent, this.Key, this.SequenceNumber, this.AcknowledgmentSequenceNumber, this.Routing, this.RoutingOffset, this.StrictSourceRoute); } public override void Finalize(byte[] buffer, int offset, int payloadLength, ILayer nextLayer) { if (!this.ChecksumPresent) return; GreDatagram.WriteChecksum(buffer, offset, this.Length + payloadLength, this.Checksum); } public bool Equals(GreLayer other) { if (other != null && this.Version.Equals((object) other.Version) && this.ProtocolType.Equals((object) other.ProtocolType) && this.RecursionControl.Equals(other.RecursionControl) && (this.FutureUseBits.Equals(other.FutureUseBits) && this.ChecksumPresent.Equals(other.ChecksumPresent))) { ushort? checksum1 = this.Checksum; int num1; if ((checksum1.HasValue ? new int?((int) checksum1.GetValueOrDefault()) : new int?()).HasValue) { num1 = this.Checksum.Equals((object) other.Checksum) ? 1 : 0; } else { ushort? checksum2 = other.Checksum; num1 = !(checksum2.HasValue ? new int?((int) checksum2.GetValueOrDefault()) : new int?()).HasValue ? 1 : 0; } if (num1 != 0 && (!this.Key.HasValue ? (!other.Key.HasValue ? 1 : 0) : (this.Key.Equals((object) other.Key) ? 1 : 0)) != 0 && ((!this.SequenceNumber.HasValue ? (!other.SequenceNumber.HasValue ? 1 : 0) : (this.SequenceNumber.Equals((object) other.SequenceNumber) ? 1 : 0)) != 0 && (!this.AcknowledgmentSequenceNumber.HasValue ? (!other.AcknowledgmentSequenceNumber.HasValue ? 1 : 0) : (this.AcknowledgmentSequenceNumber.Equals((object) other.AcknowledgmentSequenceNumber) ? 1 : 0)) != 0)) { ushort? routingOffset1 = this.RoutingOffset; int num2; if ((routingOffset1.HasValue ? new int?((int) routingOffset1.GetValueOrDefault()) : new int?()).HasValue) { num2 = this.RoutingOffset.Equals((object) other.RoutingOffset) ? 1 : 0; } else { ushort? routingOffset2 = other.RoutingOffset; num2 = !(routingOffset2.HasValue ? new int?((int) routingOffset2.GetValueOrDefault()) : new int?()).HasValue ? 1 : 0; } if (num2 != 0 && (this.Routing == null ? (other.Routing == null ? 1 : 0) : (Enumerable.SequenceEqual<GreSourceRouteEntry>((IEnumerable<GreSourceRouteEntry>) this.Routing, (IEnumerable<GreSourceRouteEntry>) other.Routing) ? 1 : 0)) != 0) return this.StrictSourceRoute.Equals(other.StrictSourceRoute); } } return false; } public override bool Equals(Layer other) { return this.Equals(other as GreLayer); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IIpV4NextTransportLayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; namespace PcapDotNet.Packets.IpV4 { public interface IIpV4NextTransportLayer : IIpV4NextLayer, ILayer { ushort? Checksum { get; set; } bool CalculateChecksum { get; } int ChecksumOffset { get; } bool IsChecksumOptional { get; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpTimestampDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using PcapDotNet.Packets.IpV4; namespace PcapDotNet.Packets.Icmp { [IcmpDatagramRegistration(IcmpMessageType.Timestamp)] public class IcmpTimestampDatagram : IcmpIdentifiedDatagram { public const int DatagramLength = 20; public const int PayloadLength = 12; public IpV4TimeOfDay OriginateTimestamp { get { return this.ReadIpV4TimeOfDay(8, Endianity.Big); } } public IpV4TimeOfDay ReceiveTimestamp { get { return this.ReadIpV4TimeOfDay(12, Endianity.Big); } } public IpV4TimeOfDay TransmitTimestamp { get { return this.ReadIpV4TimeOfDay(16, Endianity.Big); } } internal IcmpTimestampDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public override ILayer ExtractLayer() { IcmpTimestampLayer icmpTimestampLayer = new IcmpTimestampLayer(); icmpTimestampLayer.Checksum = new ushort?(this.Checksum); icmpTimestampLayer.Identifier = this.Identifier; icmpTimestampLayer.SequenceNumber = this.SequenceNumber; icmpTimestampLayer.OriginateTimestamp = this.OriginateTimestamp; icmpTimestampLayer.ReceiveTimestamp = this.ReceiveTimestamp; icmpTimestampLayer.TransmitTimestamp = this.TransmitTimestamp; return (ILayer) icmpTimestampLayer; } protected override sealed bool CalculateIsValid() { if (base.CalculateIsValid()) return this.Length == 20; return false; } internal override IcmpDatagram CreateInstance(byte[] buffer, int offset, int length) { return (IcmpDatagram) new IcmpTimestampDatagram(buffer, offset, length); } internal static void WriteHeaderAdditional(byte[] buffer, int offset, IpV4TimeOfDay originateTimestamp, IpV4TimeOfDay receiveTimestamp, IpV4TimeOfDay transmitTimestamp) { ByteArrayExtensions.Write(buffer, ref offset, originateTimestamp, Endianity.Big); ByteArrayExtensions.Write(buffer, ref offset, receiveTimestamp, Endianity.Big); ByteArrayExtensions.Write(buffer, offset, transmitTimestamp, Endianity.Big); } private static class Offset { public const int OriginateTimestamp = 8; public const int ReceiveTimestamp = 12; public const int TransmitTimestamp = 16; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataNInfo // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Collections.ObjectModel; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.NInfo)] public sealed class DnsResourceDataNInfo : DnsResourceDataStrings { private const int MinNumStrings = 1; public DnsResourceDataNInfo(ReadOnlyCollection<DataSegment> strings) : base(strings) { if (strings == null) throw new ArgumentNullException("strings"); if (strings.Count < 1) throw new ArgumentOutOfRangeException("strings", (object) strings.Count, "There must be at least one string."); } public DnsResourceDataNInfo(params DataSegment[] strings) : this(IListExtensions.AsReadOnly<DataSegment>((IList<DataSegment>) strings)) { } internal DnsResourceDataNInfo() : this(new DataSegment[1] { DataSegment.Empty }) { } internal override DnsResourceData CreateInstance(DataSegment data) { List<DataSegment> list = DnsResourceDataStrings.ReadStrings(data, 1); if (list == null || list.Count < 1) return (DnsResourceData) null; return (DnsResourceData) new DnsResourceDataNInfo(list.AsReadOnly()); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Base.BitSequence // Assembly: PcapDotNet.Base, Version=0.10.0.20668, Culture=neutral, PublicKeyToken=<KEY> // MVID: E9656A63-0145-422C-B8C8-79FDD7FB4270 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Base.dll using System.Diagnostics.CodeAnalysis; namespace PcapDotNet.Base { public static class BitSequence { public static byte ToByte(this bool value) { return !value ? (byte) 0 : (byte) 1; } public static byte Merge(bool value1, bool value2) { return (byte) ((uint) BitSequence.ToByte(value1) << 1 | (uint) BitSequence.ToByte(value2)); } public static byte Merge(bool value1, bool value2, bool value3) { return (byte) ((uint) BitSequence.Merge(value1, value2) << 1 | (uint) BitSequence.ToByte(value3)); } [SuppressMessage("Microsoft.Design", "CA1025:ReplaceRepetitiveArgumentsWithParamsArray")] public static byte Merge(bool value1, bool value2, bool value3, bool value4) { return (byte) ((uint) BitSequence.Merge(value1, value2, value3) << 1 | (uint) BitSequence.ToByte(value4)); } [SuppressMessage("Microsoft.Design", "CA1025:ReplaceRepetitiveArgumentsWithParamsArray")] public static byte Merge(bool value1, bool value2, bool value3, bool value4, bool value5) { return (byte) ((uint) BitSequence.Merge(value1, value2, value3, value4) << 1 | (uint) BitSequence.ToByte(value5)); } [SuppressMessage("Microsoft.Design", "CA1025:ReplaceRepetitiveArgumentsWithParamsArray")] public static byte Merge(bool value1, bool value2, bool value3, bool value4, bool value5, bool value6) { return (byte) ((uint) BitSequence.Merge(value1, value2, value3, value4, value5) << 1 | (uint) BitSequence.ToByte(value6)); } [SuppressMessage("Microsoft.Design", "CA1025:ReplaceRepetitiveArgumentsWithParamsArray")] public static byte Merge(bool value1, bool value2, bool value3, bool value4, bool value5, bool value6, bool value7) { return (byte) ((uint) BitSequence.Merge(value1, value2, value3, value4, value5, value6) << 1 | (uint) BitSequence.ToByte(value7)); } [SuppressMessage("Microsoft.Design", "CA1025:ReplaceRepetitiveArgumentsWithParamsArray")] public static byte Merge(bool value1, bool value2, bool value3, bool value4, bool value5, bool value6, bool value7, bool value8) { return (byte) ((uint) BitSequence.Merge(value1, value2, value3, value4, value5, value6, value7) << 1 | (uint) BitSequence.ToByte(value8)); } public static ushort Merge(byte value1, byte value2) { return (ushort) ((uint) value1 << 8 | (uint) value2); } public static UInt24 Merge(byte value1, byte value2, byte value3) { return (UInt24) BitSequence.Merge((byte) 0, value1, value2, value3); } [SuppressMessage("Microsoft.Design", "CA1025:ReplaceRepetitiveArgumentsWithParamsArray")] public static uint Merge(byte value1, byte value2, byte value3, byte value4) { return BitSequence.Merge(BitSequence.Merge(value1, value2), BitSequence.Merge(value3, value4)); } [SuppressMessage("Microsoft.Design", "CA1025:ReplaceRepetitiveArgumentsWithParamsArray")] public static UInt48 Merge(byte value1, byte value2, byte value3, byte value4, byte value5, byte value6) { return (UInt48) BitSequence.Merge((byte) 0, (byte) 0, value1, value2, value3, value4, value5, value6); } [SuppressMessage("Microsoft.Design", "CA1025:ReplaceRepetitiveArgumentsWithParamsArray")] public static ulong Merge(byte value1, byte value2, byte value3, byte value4, byte value5, byte value6, byte value7, byte value8) { return BitSequence.Merge(BitSequence.Merge(value1, value2, value3, value4), BitSequence.Merge(value5, value6, value7, value8)); } [SuppressMessage("Microsoft.Design", "CA1025:ReplaceRepetitiveArgumentsWithParamsArray")] public static UInt128 Merge(byte value1, byte value2, byte value3, byte value4, byte value5, byte value6, byte value7, byte value8, byte value9, byte value10, byte value11, byte value12, byte value13, byte value14, byte value15, byte value16) { return BitSequence.Merge(BitSequence.Merge(value1, value2, value3, value4, value5, value6, value7, value8), BitSequence.Merge(value9, value10, value11, value12, value13, value14, value15, value16)); } public static uint Merge(ushort value1, ushort value2) { return (uint) value1 << 16 | (uint) value2; } public static UInt24 Merge(byte value1, ushort value2) { return (UInt24) BitSequence.Merge((byte) 0, value1, value2); } public static uint Merge(ushort value1, byte value2, byte value3) { return BitSequence.Merge(value1, BitSequence.Merge(value2, value3)); } public static uint Merge(byte value1, ushort value2, byte value3) { return (uint) ((int) value1 << 24 | (int) value2 << 8) | (uint) value3; } public static uint Merge(byte value1, byte value2, ushort value3) { return BitSequence.Merge(BitSequence.Merge(value1, value2), value3); } public static ulong Merge(uint value1, uint value2) { return (ulong) value1 << 32 | (ulong) value2; } public static UInt128 Merge(ulong value1, ulong value2) { return new UInt128(value1, value2); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Ethernet.EthernetBaseDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using PcapDotNet.Packets.Arp; using PcapDotNet.Packets.IpV4; namespace PcapDotNet.Packets.Ethernet { public abstract class EthernetBaseDatagram : Datagram { private EthernetPayloadDatagrams _payloadDatagrams; public abstract int HeaderLength { get; } public abstract EthernetType EtherType { get; } public Datagram Payload { get { return this.PayloadDatagrams.Payload; } } public Datagram Trailer { get { if (this.PayloadByEtherType == null) return (Datagram) null; int length = this.PayloadByEtherType.Length; Datagram frameCheckSequence = this.FrameCheckSequence; return new Datagram(this.Buffer, this.StartOffset + this.HeaderLength + length, this.Length - this.HeaderLength - length - (frameCheckSequence == null ? 0 : frameCheckSequence.Length)); } } public Datagram FrameCheckSequence { get { Datagram payloadByEtherType = this.PayloadByEtherType; if (payloadByEtherType == null) return (Datagram) null; if (this.Length - this.HeaderLength - payloadByEtherType.Length >= 4 && this.Length >= 68) return new Datagram(this.Buffer, this.Length - 4, 4); return (Datagram) null; } } public VLanTaggedFrameDatagram VLanTaggedFrame { get { return this.PayloadDatagrams.VLanTaggedFrame; } } public IpV4Datagram IpV4 { get { return this.PayloadDatagrams.IpV4; } } public ArpDatagram Arp { get { return this.PayloadDatagrams.Arp; } } internal Datagram PayloadByEtherType { get { return this.PayloadDatagrams.Get(this.EtherType); } } private EthernetPayloadDatagrams PayloadDatagrams { get { return this._payloadDatagrams ?? (this._payloadDatagrams = new EthernetPayloadDatagrams(this.Length >= this.HeaderLength ? new Datagram(this.Buffer, this.StartOffset + this.HeaderLength, this.Length - this.HeaderLength) : (Datagram) null)); } } internal EthernetBaseDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsOptionAnything // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; namespace PcapDotNet.Packets.Dns { public sealed class DnsOptionAnything : DnsOption { public DataSegment Data { get; private set; } public override int DataLength { get { return this.Data.Length; } } public DnsOptionAnything(DnsOptionCode code, DataSegment data) : base(code) { this.Data = data; } internal override bool EqualsData(DnsOption other) { return this.Data.Equals(((DnsOptionAnything) other).Data); } internal override int DataGetHashCode() { return this.Data.GetHashCode(); } internal override void WriteData(byte[] buffer, ref int offset) { this.Data.Write(buffer, ref offset); } } } <file_sep>// Copyright 2015 <NAME> // // 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. using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace Grib.Api.Interop { /// <summary> /// RAII-patterned wrapper for unmanaged references. /// </summary> public class AutoRef : IDisposable { // to detect redundant calls private bool _disposed = false; /// <summary> /// Initializes a new instance of the <see cref="AutoRef"/> class. /// </summary> public AutoRef () : this(IntPtr.Zero) { } /// <summary> /// Initializes a new instance of the <see cref="AutoRef"/> class. /// </summary> /// <param name="handle">The handle.</param> public AutoRef (IntPtr handle) { Reference = new HandleRef(this, handle); } /// <summary> /// Finalizes an instance of the <see cref="AutoRef"/> class. /// </summary> ~AutoRef () { Dispose(false); } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected void Dispose (bool disposing) { if (!_disposed) { _disposed = true; OnDispose(disposing); } } /// <summary> /// Called when [dispose]. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void OnDispose (bool disposing) { } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose () { Dispose(true); GC.SuppressFinalize(this); } public HandleRef Reference { get; protected set; } public IntPtr pReference { get { return Reference.Handle; } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataNextDomainSecure3Base // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace PcapDotNet.Packets.Dns { public abstract class DnsResourceDataNextDomainSecure3Base : DnsResourceDataSimple { private const int ConstantPartLength = 5; public DnsSecNSec3HashAlgorithm HashAlgorithm { get; private set; } [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Flags")] public DnsSecNSec3Flags Flags { get; private set; } public ushort Iterations { get; private set; } public DataSegment Salt { get; private set; } internal int ParametersLength { get { return DnsResourceDataNextDomainSecure3Base.GetParametersLength(this.Salt.Length); } } internal DnsResourceDataNextDomainSecure3Base(DnsSecNSec3HashAlgorithm hashAlgorithm, DnsSecNSec3Flags flags, ushort iterations, DataSegment salt) { if (salt.Length > (int) byte.MaxValue) throw new ArgumentOutOfRangeException("salt", (object) salt.Length, string.Format((IFormatProvider) CultureInfo.InvariantCulture, "Cannot bigger than {0}.", new object[1] { (object) byte.MaxValue })); this.HashAlgorithm = hashAlgorithm; this.Flags = flags; this.Iterations = iterations; this.Salt = salt; } internal bool EqualsParameters(DnsResourceDataNextDomainSecure3Base other) { if (other != null && this.HashAlgorithm.Equals((object) other.HashAlgorithm) && this.Flags.Equals((object) other.Flags) && this.Iterations.Equals(other.Iterations)) return this.Salt.Equals(other.Salt); return false; } internal int GetHashCodeParameters() { return Sequence.GetHashCode((object) BitSequence.Merge(this.Iterations, (byte) this.HashAlgorithm, (byte) this.Flags), (object) this.Salt); } internal static int GetParametersLength(int saltLength) { return 5 + saltLength; } internal void WriteParameters(byte[] buffer, int offset) { ByteArrayExtensions.Write(buffer, offset, (byte) this.HashAlgorithm); ByteArrayExtensions.Write(buffer, offset + 1, (byte) this.Flags); ByteArrayExtensions.Write(buffer, offset + 2, this.Iterations, Endianity.Big); ByteArrayExtensions.Write(buffer, offset + 4, (byte) this.Salt.Length); this.Salt.Write(buffer, offset + 5); } internal static bool TryReadParameters(DataSegment data, out DnsSecNSec3HashAlgorithm hashAlgorithm, out DnsSecNSec3Flags flags, out ushort iterations, out DataSegment salt) { if (data.Length < 5) { hashAlgorithm = DnsSecNSec3HashAlgorithm.Sha1; flags = DnsSecNSec3Flags.None; iterations = (ushort) 0; salt = (DataSegment) null; return false; } hashAlgorithm = (DnsSecNSec3HashAlgorithm) data[0]; flags = (DnsSecNSec3Flags) data[1]; iterations = data.ReadUShort(2, Endianity.Big); int length = (int) data[4]; if (data.Length - 5 < length) { salt = (DataSegment) null; return false; } salt = data.Subsegment(5, length); return true; } private static class Offset { public const int HashAlgorithm = 0; public const int Flags = 1; public const int Iterations = 2; public const int SaltLength = 4; public const int Salt = 5; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.PacketCommunicatorMode // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll namespace PcapDotNet.Core { public enum PacketCommunicatorMode { Capture = 0, Statistics = 1, KernelMonitor = 2, KernelDump = 16, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Ethernet.EthernetDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Ethernet { public sealed class EthernetDatagram : EthernetBaseDatagram { private static readonly MacAddress _broadcastAddress = new MacAddress("FF:FF:FF:FF:FF:FF"); public const int HeaderLengthValue = 14; public override int HeaderLength { get { return 14; } } public static MacAddress BroadcastAddress { get { return EthernetDatagram._broadcastAddress; } } public int PayloadLength { get { return Math.Max(0, this.Length - this.HeaderLength); } } public MacAddress Source { get { return this.ReadMacAddress(6, Endianity.Big); } } public MacAddress Destination { get { return this.ReadMacAddress(0, Endianity.Big); } } public override EthernetType EtherType { get { return (EthernetType) this.ReadUShort(12, Endianity.Big); } } internal EthernetDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public override ILayer ExtractLayer() { EthernetLayer ethernetLayer = new EthernetLayer(); ethernetLayer.Source = this.Source; ethernetLayer.Destination = this.Destination; ethernetLayer.EtherType = this.EtherType; return (ILayer) ethernetLayer; } internal static void WriteHeader(byte[] buffer, int offset, MacAddress ethernetSource, MacAddress ethernetDestination, EthernetType ethernetType) { ByteArrayExtensions.Write(buffer, offset + 6, ethernetSource, Endianity.Big); ByteArrayExtensions.Write(buffer, offset, ethernetDestination, Endianity.Big); ByteArrayExtensions.Write(buffer, offset + 12, (ushort) ethernetType, Endianity.Big); } protected override bool CalculateIsValid() { if (this.Length < this.HeaderLength) return false; Datagram payloadByEtherType = this.PayloadByEtherType; if (payloadByEtherType != null) return payloadByEtherType.IsValid; return true; } private static class Offset { public const int Destination = 0; public const int Source = 6; public const int EtherTypeLength = 12; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Base.MatchExtensions // Assembly: PcapDotNet.Base, Version=0.10.0.20668, Culture=neutral, PublicKeyToken=<KEY> // MVID: E9656A63-0145-422C-B8C8-79FDD7FB4270 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Base.dll using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace PcapDotNet.Base { public static class MatchExtensions { public static IEnumerable<string> GroupCapturesValues(this Match match, string groupName) { if (match == null) throw new ArgumentNullException("match"); return Enumerable.Select<Capture, string>(Enumerable.Cast<Capture>((IEnumerable) match.Groups[groupName].Captures), (Func<Capture, string>) (capture => capture.Value)); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsGatewayNone // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using System; namespace PcapDotNet.Packets.Dns { public sealed class DnsGatewayNone : DnsGateway, IEquatable<DnsGatewayNone> { public override DnsGatewayType GatewayType { get { return DnsGatewayType.None; } } public override int Length { get { return 0; } } internal DnsGatewayNone() { } public bool Equals(DnsGatewayNone other) { return other != null; } public override bool Equals(DnsGateway other) { return this.Equals(other as DnsGatewayNone); } internal override int DataGetHashCode() { return 0; } internal override void Write(byte[] buffer, int offset) { } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IpV4OptionQuickStartFunction // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.IpV4 { public enum IpV4OptionQuickStartFunction : byte { RateRequest = (byte) 0, RateReport = (byte) 128, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataAddressPrefixList // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.Apl)] public sealed class DnsResourceDataAddressPrefixList : DnsResourceDataSimple, IEquatable<DnsResourceDataAddressPrefixList> { public ReadOnlyCollection<DnsAddressPrefix> Items { get; private set; } public int Length { get; private set; } public DnsResourceDataAddressPrefixList(IList<DnsAddressPrefix> items) { this.Items = IListExtensions.AsReadOnly<DnsAddressPrefix>(items); } public DnsResourceDataAddressPrefixList(params DnsAddressPrefix[] items) : this((IList<DnsAddressPrefix>) items) { this.Length = Enumerable.Sum<DnsAddressPrefix>((IEnumerable<DnsAddressPrefix>) items, (Func<DnsAddressPrefix, int>) (item => item.Length)); } internal DnsResourceDataAddressPrefixList() : this(new DnsAddressPrefix[0]) { } public bool Equals(DnsResourceDataAddressPrefixList other) { if (other != null) return Enumerable.SequenceEqual<DnsAddressPrefix>((IEnumerable<DnsAddressPrefix>) this.Items, (IEnumerable<DnsAddressPrefix>) other.Items); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataAddressPrefixList); } public override int GetHashCode() { return IEnumerableExtensions.SequenceGetHashCode<DnsAddressPrefix>((IEnumerable<DnsAddressPrefix>) this.Items); } internal override int GetLength() { return this.Length; } internal override void WriteDataSimple(byte[] buffer, int offset) { foreach (DnsAddressPrefix dnsAddressPrefix in this.Items) dnsAddressPrefix.Write(buffer, ref offset); } internal override DnsResourceData CreateInstance(DataSegment data) { List<DnsAddressPrefix> list = new List<DnsAddressPrefix>(); DnsAddressPrefix dnsAddressPrefix; for (; data.Length != 0; data = data.Subsegment(dnsAddressPrefix.Length, data.Length - dnsAddressPrefix.Length)) { dnsAddressPrefix = DnsAddressPrefix.Read(data); if (dnsAddressPrefix == null) return (DnsResourceData) null; list.Add(dnsAddressPrefix); } return (DnsResourceData) new DnsResourceDataAddressPrefixList((IList<DnsAddressPrefix>) list); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpIpV4HeaderPlus64BitsPayloadDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Icmp { public abstract class IcmpIpV4HeaderPlus64BitsPayloadDatagram : IcmpIpV4PayloadDatagram { public const int OriginalDatagramPayloadLength = 8; internal IcmpIpV4HeaderPlus64BitsPayloadDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } protected override bool CalculateIsValid() { if (!base.CalculateIsValid()) return false; return this.IpV4.Payload.Length == 8; } } } <file_sep> namespace CGurus.Weather.WundergroundAPI.Models { public class TemperatureCF { public double? Celsius { get; set; } public double? Fahrenheit { get; set; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsOptResourceRecord // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace PcapDotNet.Packets.Dns { public sealed class DnsOptResourceRecord : DnsDataResourceRecord { public ushort SendersUdpPayloadSize { get { return (ushort) this.DnsClass; } } public byte ExtendedReturnCode { get { return (byte) (this.Ttl >> 24); } } public DnsOptVersion Version { get { return (DnsOptVersion) (this.Ttl >> 16); } } [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Flags")] public DnsOptFlags Flags { get { return (DnsOptFlags) this.Ttl; } } [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "flags")] public DnsOptResourceRecord(DnsDomainName domainName, ushort sendersUdpPayloadSize, byte extendedReturnCode, DnsOptVersion version, DnsOptFlags flags, DnsResourceDataOptions data) : this(domainName, (DnsClass) sendersUdpPayloadSize, (int) BitSequence.Merge(extendedReturnCode, (byte) version, (ushort) flags), (DnsResourceData) data) { } internal DnsOptResourceRecord(DnsDomainName domainName, DnsClass dnsClass, int ttl, DnsResourceData data) : base(domainName, DnsType.Opt, dnsClass, ttl, data) { } public override string ToString() { return string.Format((IFormatProvider) CultureInfo.InvariantCulture, "{0} {1} {2} {3} {4} {5} {6}", (object) this.DomainName, (object) this.DnsType, (object) this.SendersUdpPayloadSize, (object) this.ExtendedReturnCode, (object) this.Version, (object) this.Flags, (object) this.Data); } } } <file_sep>namespace ForecastIOPortable.Models { using System.Collections.Generic; using System.Runtime.Serialization; /// <summary> /// A forecast for a particular location. /// Models the response returned by the service. /// </summary> [DataContract] public class Forecast { /// <summary> /// Gets or sets the latitude of this forecast. /// </summary> [DataMember(Name = "latitude")] public float Latitude { get; set; } /// <summary> /// Gets or sets the longitude of this forecast. /// </summary> [DataMember(Name = "longitude")] public float Longitude { get; set; } /// <summary> /// Gets or sets the IANA time zone name for this location. /// </summary> [DataMember(Name = "timezone")] public string TimeZone { get; set; } /// <summary> /// Gets or sets the time zone offset, in hours from GMT. /// </summary> [DataMember(Name = "offset")] public double TimeZoneOffset { get; set; } /// <summary> /// Gets or sets the current conditions at the requested location. /// </summary> [DataMember(Name = "currently")] public CurrentDataPoint Currently { get; set; } /// <summary> /// Gets or sets the minute-by-minute conditions for the next hour. /// </summary> [DataMember(Name = "minutely")] public MinutelyForecast Minutely { get; set; } /// <summary> /// Gets or sets the hour-by-hour conditions for the next two days. /// </summary> [DataMember(Name = "hourly")] public HourlyForecast Hourly { get; set; } /// <summary> /// Gets or sets the daily conditions for the next week. /// </summary> [DataMember(Name = "daily")] public DailyForecast Daily { get; set; } /// <summary> /// Gets or sets the metadata (flags) associated with this forecast. /// </summary> [DataMember(Name = "flags")] public Flags Flags { get; set; } /// <summary> /// Gets or sets any weather alerts related to this location. /// </summary> [DataMember(Name = "alerts")] public IList<Alert> Alerts { get; set; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Base.IEnumerableExtensions // Assembly: PcapDotNet.Base, Version=0.10.0.20668, Culture=neutral, PublicKeyToken=<KEY> // MVID: E9656A63-0145-422C-B8C8-79FDD7FB4270 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Base.dll using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; namespace PcapDotNet.Base { public static class IEnumerableExtensions { public static bool IsNullOrEmpty<T>(this IEnumerable<T> sequence) { if (sequence != null) return !Enumerable.Any<T>(sequence); return true; } public static IEnumerable<T> Concat<T>(this IEnumerable<T> sequence, params T[] values) { return Enumerable.Concat<T>(sequence, (IEnumerable<T>) values); } public static long Xor(this IEnumerable<long> sequence) { return IEnumerableExtensions.Xor<long>(sequence, (Func<long, long>) (value => value)); } public static int Xor(this IEnumerable<int> sequence) { return IEnumerableExtensions.Xor<int>(sequence, (Func<int, int>) (value => value)); } public static long Xor<T>(this IEnumerable<T> sequence, Func<T, long> selector) { return Enumerable.Aggregate<T, long>(sequence, 0L, (Func<long, T, long>) ((xorTotal, current) => xorTotal ^ selector(current))); } public static int Xor<T>(this IEnumerable<T> sequence, Func<T, int> selector) { return Enumerable.Aggregate<T, int>(sequence, 0, (Func<int, T, int>) ((xorTotal, current) => xorTotal ^ selector(current))); } public static string SequenceToString<T>(this IEnumerable<T> sequence, string separator, string prefix, string suffix) { if (sequence == null) throw new ArgumentNullException("sequence"); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(prefix); bool flag = true; foreach (T obj in sequence) { if (flag) flag = false; else stringBuilder.Append(separator); stringBuilder.Append((object) obj); } stringBuilder.Append(suffix); return stringBuilder.ToString(); } public static string SequenceToString<T>(this IEnumerable<T> sequence, string separator, string prefix) { return IEnumerableExtensions.SequenceToString<T>(sequence, separator, prefix, string.Empty); } public static string SequenceToString<T>(this IEnumerable<T> sequence, string separator) { return IEnumerableExtensions.SequenceToString<T>(sequence, separator, string.Empty); } public static string SequenceToString<T>(this IEnumerable<T> sequence, char separator) { return IEnumerableExtensions.SequenceToString<T>(sequence, separator.ToString()); } public static string SequenceToString<T>(this IEnumerable<T> sequence) { return IEnumerableExtensions.SequenceToString<T>(sequence, string.Empty); } public static string BytesSequenceToHexadecimalString(this IEnumerable<byte> sequence, string separator) { return Enumerable.Aggregate<byte, string>(sequence, string.Empty, (Func<string, byte, string>) ((result, value) => { if (!string.IsNullOrEmpty(result)) result += separator; return result + string.Format((IFormatProvider) CultureInfo.InvariantCulture, "{0:x2}", new object[1] { (object) value }); })); } public static string BytesSequenceToHexadecimalString(this IEnumerable<byte> sequence) { return IEnumerableExtensions.BytesSequenceToHexadecimalString(sequence, string.Empty); } public static int SequenceGetHashCode<T>(this IEnumerable<T> sequence) { return IEnumerableExtensions.Xor<T>(sequence, (Func<T, int>) (value => value.GetHashCode())); } public static int BytesSequenceGetHashCode(this IEnumerable<byte> sequence) { int i = 0; return IEnumerableExtensions.Xor<byte>(sequence, (Func<byte, int>) (b => (int) b << 8 * (i++ % 4))); } public static int UShortsSequenceGetHashCode(this IEnumerable<ushort> sequence) { int i = 0; return IEnumerableExtensions.Xor<ushort>(sequence, (Func<ushort, int>) (b => (int) b << 16 * (i++ % 2))); } public static int Count<T>(this IEnumerable<T> sequence, T value) { return Enumerable.Count<T>(sequence, (Func<T, bool>) (element => element.Equals((object) (T) value))); } public static bool IsStrictOrdered<T>(this IEnumerable<T> sequence) { return IEnumerableExtensions.IsStrictOrdered<T, T>(sequence, (Func<T, T>) (element => element)); } public static bool IsStrictOrdered<T, TKey>(this IEnumerable<T> sequence, Func<T, TKey> keySelector) { return IEnumerableExtensions.IsStrictOrdered<T, TKey>(sequence, keySelector, (IComparer<TKey>) Comparer<TKey>.Default); } public static bool IsStrictOrdered<T, TKey>(this IEnumerable<T> sequence, Func<T, TKey> keySelector, IComparer<TKey> comparer) { if (comparer == null) throw new ArgumentNullException("comparer"); if (!Enumerable.Any<T>(sequence)) return true; IEnumerable<TKey> source = Enumerable.Select<T, TKey>(sequence, keySelector); TKey x = Enumerable.First<TKey>(source); foreach (TKey y in Enumerable.Skip<TKey>(source, 1)) { if (comparer.Compare(x, y) >= 0) return false; x = y; } return true; } } } <file_sep> namespace CGurus.Weather.WundergroundAPI.Models { public class TxtForecast { public string Date { get; set; } public ForecastDay[] ForecastDay { get; set; } } } <file_sep>using RestSharp; using Newtonsoft.Json; namespace CGurus.Weather.WundergroundAPI.Utilities { internal class RestRequest { internal static T Execute<T>(string Uri) where T : new() { RestSharp.IRestRequest request = new RestSharp.RestRequest(); var client = new RestClient(); client.BaseUrl = Uri; var response = client.Execute<T>(request); if (response.ErrorException != null) { if (response.Content.Length > 0) { return JsonConvert.DeserializeObject<T>(response.Content, new Utilities.BoolConverter(), new Utilities.DoubleConverter()); } else { throw response.ErrorException; } } return response.Data; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.TcpOptionConnectionCountNew // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System.Diagnostics.CodeAnalysis; namespace PcapDotNet.Packets.Transport { [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [OptionTypeRegistration(typeof (TcpOptionType), TcpOptionType.ConnectionCountNew)] public class TcpOptionConnectionCountNew : TcpOptionConnectionCountBase, IOptionComplexFactory { public TcpOptionConnectionCountNew(uint connectionCount) : base(TcpOptionType.ConnectionCountNew, connectionCount) { } public TcpOptionConnectionCountNew() : this(0U) { } Option IOptionComplexFactory.CreateInstance(byte[] buffer, ref int offset, byte valueLength) { uint connectionCount; if (!TcpOptionConnectionCountBase.TryRead(out connectionCount, buffer, ref offset, valueLength)) return (Option) null; return (Option) new TcpOptionConnectionCountNew(connectionCount); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.TcpOptionSelectiveAcknowledgmentPermitted // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Transport { [OptionTypeRegistration(typeof (TcpOptionType), TcpOptionType.SelectiveAcknowledgmentPermitted)] public sealed class TcpOptionSelectiveAcknowledgmentPermitted : TcpOptionComplex, IOptionComplexFactory, IEquatable<TcpOptionSelectiveAcknowledgmentPermitted> { private static readonly TcpOptionSelectiveAcknowledgmentPermitted _instance = new TcpOptionSelectiveAcknowledgmentPermitted(); public const int OptionLength = 2; public const int OptionValueLength = 0; public override int Length { get { return 2; } } public override bool IsAppearsAtMostOnce { get { return true; } } public TcpOptionSelectiveAcknowledgmentPermitted() : base(TcpOptionType.SelectiveAcknowledgmentPermitted) { } public bool Equals(TcpOptionSelectiveAcknowledgmentPermitted other) { return other != null; } public override bool Equals(TcpOption other) { return this.Equals(other as TcpOptionSelectiveAcknowledgmentPermitted); } Option IOptionComplexFactory.CreateInstance(byte[] buffer, ref int offset, byte valueLength) { if ((int) valueLength != 0) return (Option) null; return (Option) TcpOptionSelectiveAcknowledgmentPermitted._instance; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IpV4Datagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using PcapDotNet.Packets.Gre; using PcapDotNet.Packets.Icmp; using PcapDotNet.Packets.Igmp; using PcapDotNet.Packets.Transport; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace PcapDotNet.Packets.IpV4 { public sealed class IpV4Datagram : Datagram { public const int HeaderMinimumLength = 20; public const int HeaderMaximumLength = 60; public const int DefaultVersion = 4; private IpV4Address? _destination; private bool? _isHeaderChecksumCorrect; private bool? _isTransportChecksumCorrect; private IpV4Options _options; private Datagram _payload; private IpV4Datagram _ipV4; private IcmpDatagram _icmp; private IgmpDatagram _igmp; private GreDatagram _gre; private TcpDatagram _tcp; private UdpDatagram _udp; public int Version { get { return ((int) this[0] & 240) >> 4; } } public int HeaderLength { get { return ((int) this[0] & 15) * 4; } } public int RealHeaderLength { get { return Math.Min(this.HeaderLength, this.Length); } } public byte TypeOfService { get { return this[1]; } } public ushort TotalLength { get { return this.ReadUShort(2, Endianity.Big); } } public ushort Identification { get { return this.ReadUShort(4, Endianity.Big); } } public IpV4Fragmentation Fragmentation { get { return new IpV4Fragmentation(this.ReadUShort(6, Endianity.Big)); } } public byte Ttl { get { return this[8]; } } public IpV4Protocol Protocol { get { return (IpV4Protocol) this[9]; } } public ushort HeaderChecksum { get { return this.ReadUShort(10, Endianity.Big); } } public bool IsHeaderChecksumCorrect { get { if (!this._isHeaderChecksumCorrect.HasValue) this._isHeaderChecksumCorrect = new bool?((int) this.CalculateHeaderChecksum() == (int) this.HeaderChecksum); return this._isHeaderChecksumCorrect.Value; } } public IpV4Address Source { get { return this.ReadIpV4Address(12, Endianity.Big); } } public IpV4Address CurrentDestination { get { return this.ReadIpV4Address(16, Endianity.Big); } } public IpV4Address Destination { get { if (!this._destination.HasValue) this._destination = new IpV4Address?(IpV4Datagram.CalculateDestination(this.CurrentDestination, this.Options)); return this._destination.Value; } } public IpV4Options Options { get { if (this._options == null && this.RealHeaderLength >= 20) this._options = new IpV4Options(this.Buffer, this.StartOffset + 20, this.RealHeaderLength - 20); return this._options; } } public bool IsTransportChecksumCorrect { get { if (!this._isTransportChecksumCorrect.HasValue) { ushort checksum = this.Transport.Checksum; this._isTransportChecksumCorrect = new bool?(this.Length >= (int) this.TotalLength && this.Transport.IsChecksumOptional && (int) checksum == 0 || (int) this.CalculateTransportChecksum() == (int) checksum); } return this._isTransportChecksumCorrect.Value; } } public Datagram Payload { get { if (this._payload == null && this.Length >= this.HeaderLength) this._payload = new Datagram(this.Buffer, this.StartOffset + this.HeaderLength, this.Length - this.HeaderLength); return this._payload; } } public IpV4Datagram IpV4 { get { if (this._ipV4 == null && this.Length >= this.HeaderLength) this._ipV4 = new IpV4Datagram(this.Buffer, this.StartOffset + this.HeaderLength, this.Length - this.HeaderLength); return this._ipV4; } } public IcmpDatagram Icmp { get { if (this._icmp == null && this.Length >= 20 && this.Length >= this.HeaderLength) this._icmp = IcmpDatagram.CreateDatagram(this.Buffer, this.StartOffset + this.HeaderLength, this.Length - this.HeaderLength); return this._icmp; } } public IgmpDatagram Igmp { get { if (this._igmp == null && this.Length >= 20 && this.Length >= this.HeaderLength) this._igmp = new IgmpDatagram(this.Buffer, this.StartOffset + this.HeaderLength, this.Length - this.HeaderLength); return this._igmp; } } public TcpDatagram Tcp { get { if (this._tcp == null && this.Length >= 20 && this.Length >= this.HeaderLength) this._tcp = new TcpDatagram(this.Buffer, this.StartOffset + this.HeaderLength, this.Length - this.HeaderLength); return this._tcp; } } public GreDatagram Gre { get { if (this._gre == null && this.Length >= 20 && this.Length >= this.HeaderLength) this._gre = new GreDatagram(this.Buffer, this.StartOffset + this.HeaderLength, this.Length - this.HeaderLength); return this._gre; } } public UdpDatagram Udp { get { if (this._udp == null && this.Length >= 20 && this.Length >= this.HeaderLength) this._udp = new UdpDatagram(this.Buffer, this.StartOffset + this.HeaderLength, this.Length - this.HeaderLength); return this._udp; } } public TransportDatagram Transport { get { switch (this.Protocol) { case IpV4Protocol.Tcp: return (TransportDatagram) this.Tcp; case IpV4Protocol.Udp: return (TransportDatagram) this.Udp; default: return (TransportDatagram) null; } } } internal IpV4Datagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public override ILayer ExtractLayer() { return (ILayer) new IpV4Layer() { TypeOfService = this.TypeOfService, Identification = this.Identification, Fragmentation = this.Fragmentation, Ttl = this.Ttl, Protocol = new IpV4Protocol?(this.Protocol), HeaderChecksum = new ushort?(this.HeaderChecksum), Source = this.Source, CurrentDestination = this.CurrentDestination, Options = this.Options }; } internal static int GetTotalLength(Datagram ipV4Datagram) { if (ipV4Datagram.Length < 20) return ipV4Datagram.Length; ushort num = ipV4Datagram.ReadUShort(2, Endianity.Big); if (ipV4Datagram.Length < (int) num) return ipV4Datagram.Length; return (int) num; } internal static IpV4Address CalculateDestination(IpV4Address currentDestination, IpV4Options options) { if (options == null) return currentDestination; IpV4OptionRoute ipV4OptionRoute = (IpV4OptionRoute) Enumerable.FirstOrDefault<IpV4Option>((IEnumerable<IpV4Option>) options.OptionsCollection, (Func<IpV4Option, bool>) (option => { if (option.OptionType != IpV4OptionType.LooseSourceRouting) return option.OptionType == IpV4OptionType.StrictSourceRouting; return true; })); if (ipV4OptionRoute != null) { ReadOnlyCollection<IpV4Address> route = ipV4OptionRoute.Route; if ((int) ipV4OptionRoute.PointedAddressIndex < route.Count) return route[route.Count - 1]; } return currentDestination; } internal static void WriteHeader(byte[] buffer, int offset, byte typeOfService, ushort identification, IpV4Fragmentation fragmentation, byte ttl, IpV4Protocol protocol, ushort? headerChecksum, IpV4Address source, IpV4Address destination, IpV4Options options, int payloadLength) { int length = 20 + options.BytesLength; buffer[offset] = (byte) (64 + length / 4); buffer[offset + 1] = typeOfService; ByteArrayExtensions.Write(buffer, offset + 2, (ushort) (length + payloadLength), Endianity.Big); ByteArrayExtensions.Write(buffer, offset + 4, identification, Endianity.Big); fragmentation.Write(buffer, offset + 6); buffer[offset + 8] = ttl; buffer[offset + 9] = (byte) protocol; ByteArrayExtensions.Write(buffer, offset + 12, source, Endianity.Big); ByteArrayExtensions.Write(buffer, offset + 16, destination, Endianity.Big); options.Write(buffer, offset + 20); ushort? nullable = headerChecksum; ushort num = !(nullable.HasValue ? new int?((int) nullable.GetValueOrDefault()) : new int?()).HasValue ? DataSegment.Sum16BitsToChecksum(DataSegment.Sum16Bits(buffer, offset, length)) : headerChecksum.Value; ByteArrayExtensions.Write(buffer, offset + 10, num, Endianity.Big); } internal static void WriteTransportChecksum(byte[] buffer, int offset, int headerLength, ushort transportLength, int transportChecksumOffset, bool isChecksumOptional, ushort? checksum, IpV4Address destination) { ushort? nullable = checksum; ushort num = !(nullable.HasValue ? new int?((int) nullable.GetValueOrDefault()) : new int?()).HasValue ? IpV4Datagram.CalculateTransportChecksum(buffer, offset, headerLength, transportLength, transportChecksumOffset, isChecksumOptional, destination) : checksum.Value; ByteArrayExtensions.Write(buffer, offset + headerLength + transportChecksumOffset, num, Endianity.Big); } protected override bool CalculateIsValid() { if (this.Length < 20 || this.Length < this.HeaderLength || !this.IsHeaderChecksumCorrect) return false; IpV4Protocol protocol = this.Protocol; if ((uint) protocol <= 6U) { switch (protocol) { case IpV4Protocol.InternetControlMessageProtocol: return this.Icmp.IsValid; case IpV4Protocol.InternetGroupManagementProtocol: return this.Igmp.IsValid; case IpV4Protocol.Tcp: break; default: goto label_14; } } else if (protocol != IpV4Protocol.Udp) { if (protocol == IpV4Protocol.Gre) return this.Gre.IsValid; goto label_14; } if (!this.Transport.IsValid) return false; if (!this.Transport.IsChecksumOptional || (int) this.Transport.Checksum != 0) return this.IsTransportChecksumCorrect; return true; label_14: return true; } private ushort CalculateHeaderChecksum() { return DataSegment.Sum16BitsToChecksum(DataSegment.Sum16Bits(this.Buffer, this.StartOffset, Math.Min(10, this.Length)) + DataSegment.Sum16Bits(this.Buffer, this.StartOffset + 10 + 2, this.RealHeaderLength - 10 - 2)); } private ushort CalculateTransportChecksum() { return IpV4Datagram.CalculateTransportChecksum(this.Buffer, this.StartOffset, this.HeaderLength, (ushort) this.Transport.Length, this.Transport.ChecksumOffset, this.Transport.IsChecksumOptional, this.Destination); } private static ushort CalculateTransportChecksum(byte[] buffer, int offset, int headerLength, ushort transportLength, int transportChecksumOffset, bool isChecksumOptional, IpV4Address destination) { int offset1 = offset + headerLength + transportChecksumOffset + 2; ushort num = DataSegment.Sum16BitsToChecksum(DataSegment.Sum16Bits(buffer, offset + 12, 4) + DataSegment.Sum16Bits(destination) + (uint) buffer[offset + 9] + (uint) transportLength + DataSegment.Sum16Bits(buffer, offset + headerLength, transportChecksumOffset) + DataSegment.Sum16Bits(buffer, offset1, (int) transportLength - transportChecksumOffset - 2)); if ((int) num == 0 && isChecksumOptional) return ushort.MaxValue; return num; } private static class Offset { public const int VersionAndHeaderLength = 0; public const int TypeOfService = 1; public const int TotalLength = 2; public const int Identification = 4; public const int Fragmentation = 6; public const int Ttl = 8; public const int Protocol = 9; public const int HeaderChecksum = 10; public const int Source = 12; public const int Destination = 16; public const int Options = 20; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpAddressMaskRequestDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using PcapDotNet.Packets.IpV4; namespace PcapDotNet.Packets.Icmp { [IcmpDatagramRegistration(IcmpMessageType.AddressMaskRequest)] public class IcmpAddressMaskRequestDatagram : IcmpIdentifiedDatagram { public const int DatagramLength = 12; public const int PayloadLength = 4; public IpV4Address AddressMask { get { return this.ReadIpV4Address(8, Endianity.Big); } } internal IcmpAddressMaskRequestDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public override ILayer ExtractLayer() { IcmpAddressMaskRequestLayer maskRequestLayer = new IcmpAddressMaskRequestLayer(); maskRequestLayer.Checksum = new ushort?(this.Checksum); maskRequestLayer.Identifier = this.Identifier; maskRequestLayer.SequenceNumber = this.SequenceNumber; maskRequestLayer.AddressMask = this.AddressMask; return (ILayer) maskRequestLayer; } protected override sealed bool CalculateIsValid() { if (base.CalculateIsValid()) return this.Length == 12; return false; } internal override IcmpDatagram CreateInstance(byte[] buffer, int offset, int length) { return (IcmpDatagram) new IcmpAddressMaskRequestDatagram(buffer, offset, length); } internal static void WriteHeaderAdditional(byte[] buffer, int offset, IpV4Address addressMask) { ByteArrayExtensions.Write(buffer, offset, addressMask, Endianity.Big); } private static class Offset { public const int AddressMask = 8; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpAddressMaskReplyDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; namespace PcapDotNet.Packets.Icmp { [IcmpDatagramRegistration(IcmpMessageType.AddressMaskReply)] public sealed class IcmpAddressMaskReplyDatagram : IcmpAddressMaskRequestDatagram { private IcmpAddressMaskReplyDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public override ILayer ExtractLayer() { IcmpAddressMaskReplyLayer addressMaskReplyLayer = new IcmpAddressMaskReplyLayer(); addressMaskReplyLayer.Checksum = new ushort?(this.Checksum); addressMaskReplyLayer.Identifier = this.Identifier; addressMaskReplyLayer.SequenceNumber = this.SequenceNumber; addressMaskReplyLayer.AddressMask = this.AddressMask; return (ILayer) addressMaskReplyLayer; } internal override IcmpDatagram CreateInstance(byte[] buffer, int offset, int length) { return (IcmpDatagram) new IcmpAddressMaskReplyDatagram(buffer, offset, length); } } } <file_sep>// Copyright 2015 <NAME> // // 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. using Grib.Api.Interop.SWIG; using Grib.Api.Interop; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Diagnostics; namespace Grib.Api { /// <summary> /// Grib message object. Each grib message has attributes corresponding to grib message keys for GRIB1 and GRIB2. /// Parameter names are are given by the name, shortName and paramID keys. When iterated, returns instances of the /// <seealso cref="Grib.Api.GribValue"/> class. /// </summary> public class GribMessage: IEnumerable<GribValue> { private static readonly string[] _ignoreKeys = { "zero","one","eight","eleven","false","thousand","file", "localDir","7777","oneThousand" }; /// <summary> /// The key namespaces. Set the <see cref="Namespace"/> property with these values to /// filter the keys return when iterating this message. Default value is [all]. /// </summary> public static readonly string[] Namespaces = { "all", "ls", "parameter", "statistics", "time", "geography", "vertical", "mars" }; /// <summary> /// Initializes a new instance of the <see cref="GribMessage" /> class. /// </summary> /// <param name="handle">The handle.</param> /// <param name="context">The context.</param> /// <param name="index">The index.</param> protected GribMessage (GribHandle handle, GribContext context = null, int index = 0) : base() { Handle = handle; Namespace = Namespaces[0]; KeyFilters |= Interop.KeyFilters.All; Index = index; } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1" /> that can be used to iterate through the collection. /// </returns> public IEnumerator<GribValue> GetEnumerator () { // null returns keys from all namespaces string nspace = Namespace == "all" ? null : Namespace; using (var keyIter = GribKeysIterator.Create(Handle, (uint) KeyFilters, nspace)) { while (keyIter.Next()) { string key = keyIter.Name; if (_ignoreKeys.Contains(key)) { continue; } yield return this[key]; } } } /// <summary> /// NOT IMPLEMENTED. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection. /// </returns> /// <exception cref="System.NotImplementedException"></exception> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () { throw new NotImplementedException(); } /// <summary> /// Clones this instance. /// </summary> /// <returns></returns> public GribMessage Clone() { var newHandle = GribApiProxy.GribHandleClone(this.Handle); return new GribMessage(newHandle); } /// <summary> /// Returns a subdomain defined by the given north/west/south/east boundaries. /// At this time, boxes are only supported for regular and reduced Gaussian grids. /// </summary> /// <param name="nw">The NW corner of the box.</param> /// <param name="se">The SE corner of the box.</param> /// <returns></returns> public GribBox Box(GeoCoordinate nw, GeoCoordinate se) { if (!GridType.Contains("regular_gg") && !GridType.Contains("reduced_gg")) { throw new GribApiException("Only regular and reduced Gaussian grids support boxes."); } return new GribBox(Handle, nw, se); } /// <summary> /// Creates a GribMessage instance from a <seealso cref="Grib.Api.GribFile"/>. /// </summary> /// <param name="file">The file.</param> /// <param name="index">The index.</param> /// <returns></returns> public static GribMessage Create(GribFile file, int index) { GribMessage msg = null; int err = 0; // grib_api moves to the next message in a stream for each new handle GribHandle handle = GribApiProxy.GribHandleNewFromFile(file.Context, file, out err); if (err != 0) { throw GribApiException.Create(err); } if (handle != null) { msg = new GribMessage(handle, file.Context, index); } return msg; } /// <summary> /// Returns a <see cref="System.String" /> containing metadata about this instance. /// </summary> /// <returns> /// A <see cref="System.String" /> containing metadata about this instance. /// </returns> public override string ToString () { //{Index}:{parameterName} ({stepType }):{grid_type}:{typeOfLevel} {level}:fcst time {stepRange} hrs {if ({stepType == 'avg'})}:from {dataDate}{dataTime} string stepType = this["stepType"].AsString(); string timeQaulifier = stepType == "avg" ? String.Format("({0})", stepType) : ""; return String.Format("{0}:[{10}] \"{1}\" ({2}):{3}:{4} {5}:fcst time {6} {7}s {8}:from {9}", Index, Name, StepType, GridType, TypeOfLevel, Level, StepRange, "hr", timeQaulifier, Time.ToString("yyyy-MM-dd HHmm"), ShortName); } /// <summary> /// Gets a *copy* of the raw data associated with this message. This data is static, /// regardless of the projection used. /// </summary> /// <remarks> /// This is an explicit function rather than a property because C# property semantics tempt devs /// to iterate directly on the values array. For each call to the indexer, however, (eg msg.Values[i]) /// the *entire* array gets copied, leading to terrible performance. At some point we can handle /// this on the native side. /// </remarks> /// <param name="values">The values.</param> public void Values(out double[] values) { values = this["values"].AsDoubleArray(); } /// <summary> /// Sets the raw data associated with this message. The array is *copied*. /// </summary> /// <param name="values">The values.</param> public void SetValues(double[] values) { this["values"].AsDoubleArray(values); } #region Properties /// <summary> /// Gets the parameter name. /// </summary> /// <value> /// The name. /// </value> public string Name { get { return this["parameterName"].AsString(); } } /// <summary> /// Gets the parameter's short name. /// </summary> /// <value> /// The short name. /// </value> public string ShortName { get { return this["shortName"].AsString(); } } /// <summary> /// Gets or sets the parameter number. /// </summary> /// <value> /// The parameter number. /// </value> public int ParameterNumber { get { return this["parameterNumber"].AsInt(); } set { this["parameterNumber"].AsInt(value); } } /// <summary> /// Gets or sets the parameter units. /// </summary> /// <value> /// The units. /// </value> public string Units { get { return this["parameterUnits"].AsString(); } } /// <summary> /// Gets or sets the type of the step. /// </summary> /// <value> /// The type of the step. /// </value> public string StepType { get { return this["stepType"].AsString(); } set { this["stepType"].AsString(value); } } /// <summary> /// Gets or sets the step range. /// </summary> /// <value> /// The step range. /// </value> public string StepRange { get { return this["stepRange"].AsString(); } set { this["stepRange"].AsString(value); } } /// <summary> /// Gets or sets the start step. /// </summary> /// <value> /// The start step. /// </value> public string StartStep { get { return this["startStep"].AsString(); } set { this["startStep"].AsString(value); } } /// <summary> /// Gets or sets the end step. /// </summary> /// <value> /// The end step. /// </value> public string EndStep { get { return this["endStep"].AsString(); } set { this["endStep"].AsString(value); } } /// <summary> /// Gets or sets the type of level. /// </summary> /// <value> /// The type of level. /// </value> public string TypeOfLevel { get { return this["typeOfLevel"].AsString(); } set { this["typeOfLevel"].AsString(value); } } /// <summary> /// Gets or sets the level. /// </summary> /// <value> /// The level. /// </value> public int Level { get { return this["level"].AsInt(); } set { this["level"].AsInt(value); } } /// <summary> /// Gets or sets the time range unit. /// </summary> /// <value> /// The time range unit. /// </value> public string TimeRangeUnit { get { return this["unitOfTimeRange"].AsString(); } set { this["unitOfTimeRange"].AsString(value); } } /// <summary> /// Gets or set the time of the measurement. Time is UTC. /// </summary> /// <value> /// The time. /// </value> public DateTime Time { get { return new DateTime(this["year"].AsInt(), this["month"].AsInt(), this["day"].AsInt(), this["hour"].AsInt(), this["minute"].AsInt(), this["second"].AsInt(), DateTimeKind.Utc); } set { this["year"].AsInt(value.Year); this["month"].AsInt(value.Month); this["day"].AsInt(value.Day); this["hour"].AsInt(value.Hour); this["minute"].AsInt(value.Minute); this["second"].AsInt(value.Second); } } /// <summary> /// The total number of points on the grid and includes missing as well as 'real' values. DataPointsCount = <see cref="ValuesCount"/> + <see cref="MissingCount"/>. /// </summary> /// <value> /// The data points count. /// </value> public int DataPointsCount { get { return this["numberOfDataPoints"].AsInt(); } } /// <summary> /// This is the number of 'real' values in the field and excludes the number of missing ones. Identical to 'numberOfCodedValues' /// </summary> /// <value> /// The values count. /// </value> public int ValuesCount { get { return this["numberOfCodedValues"].AsInt(); } } /// <summary> /// The number of missing values in the field. /// </summary> /// <value> /// The missing count. /// </value> public int MissingCount { get { return this["numberOfMissing"].AsInt(); } } /// <summary> /// Gets the index of the message within the file. /// </summary> /// <value> /// The index. /// </value> public int Index { get; protected set; } /// <summary> /// Gets or sets the grib_handle. /// </summary> /// <value> /// The handle. /// </value> protected GribHandle Handle { get; set; } /// <summary> /// Gets or sets the value used to represent a missing value. This value is used by grib_api, /// does not exist in the message itself. /// </summary> /// <value> /// The missing value. /// </value> public int MissingValue { get { return this["missingValue"].AsInt(); } set { this["missingValue"].AsInt(value); } } /// <summary> /// Gets or sets a value indicating whether this instance has a bitmap. /// </summary> /// <value> /// <c>true</c> if this instance has bitmap; otherwise, <c>false</c>. /// </value> public bool HasBitmap { get { return this["bitmapPresent"].AsInt() == 1; } set { this["bitmapPresent"].AsInt(value ? 1 : 0); } } /// <summary> /// Set this property with a value in <see cref="Namespaces"/> to /// filter the keys return when iterating this message. /// </summary> /// <value> /// The namespace. /// </value> public string Namespace { get; set; } /// <summary> /// Gets or sets the key filters. The default is KeyFilters::All. /// </summary> /// <value> /// The key filter flags. They are OR-able bitflags. /// </value> public KeyFilters KeyFilters { get; set; } /// <summary> /// Gets the type of the grid. /// </summary> /// <value> /// The type of the grid. /// </value> public string GridType { get { return this["gridType"].AsString(); } } /// <summary> /// Gets or sets the decimal precision. Setting this value currently /// updates all packed values to the new precision. This key is only /// valid for simple packing. /// </summary> /// <value> /// The decimal precision. /// </value> /// <exception cref="GribApiException">You may only change decimal precision on messages that use simple packing.</exception> public int DecimalPrecision { get { return this["changeDecimalPrecision"].AsInt(); } set { if (this["packingType"].AsString() != "grid_simple") { throw new GribApiException("You may only change decimal precision on messages that use simple packing."); } // 'changeDecimalPrecision' updates all packed values to the new precision; // 'decimalPrecision' does not -- should offer way to toggle this["changeDecimalPrecision"].AsInt(value); } } /// <summary> /// Gets the messages values with coordinates. /// </summary> /// <value> /// The geo spatial values. /// </value> public IEnumerable<GeoSpatialValue> GeoSpatialValues { get { GeoSpatialValue gsVal; using (GribValuesIterator iter = GribValuesIterator.Create(Handle, (uint) KeyFilters)) { int mVal = this.MissingValue; while (iter.Next(mVal, out gsVal)) { yield return gsVal; } } } } /// <summary> /// Gets the message size. /// </summary> /// <value> /// The size. /// </value> public ulong Size { get { SizeT sz = 0; GribApiProxy.GribGetMessageSize(Handle, ref sz); return sz; } } /// <summary> /// Gets a copy of the message's buffer. /// </summary> /// <value> /// The buffer. /// </value> public byte[] Buffer { get { SizeT sz = 0; GribApiProxy.GribGetMessageSize(this.Handle, ref sz); // grib_api returns the data buffer pointer, but continues to own the memory, so no de/allocation is necessary IntPtr p = IntPtr.Zero; GribApiProxy.GribGetMessage(this.Handle, out p, ref sz); byte[] bytes = new byte[sz]; Marshal.Copy(p, bytes, 0, (int)sz); return bytes; } } #endregion Properties /// <summary> /// Gets the <see cref="GribValue"/> with the specified key name. /// </summary> /// <value> /// The <see cref="GribValue"/>. /// </value> /// <param name="keyName">Name of the key.</param> /// <returns></returns> public GribValue this[string keyName] { get { return new GribValue(Handle, keyName); } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpCodeSecurityFailure // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Icmp { public enum IcmpCodeSecurityFailure : byte { BadSecurityParametersIndex, AuthenticationFailed, DecompressionFailed, DecryptionFailed, NeedAuthentication, NeedAuthorization, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceRecord // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Globalization; namespace PcapDotNet.Packets.Dns { public abstract class DnsResourceRecord { private const int MinimumLengthAfterDomainName = 4; public DnsDomainName DomainName { get; private set; } public DnsType DnsType { get; private set; } public DnsClass DnsClass { get; private set; } public abstract int Ttl { get; protected set; } public abstract DnsResourceData Data { get; protected set; } internal DnsResourceRecord(DnsDomainName domainName, DnsType type, DnsClass dnsClass) { this.DomainName = domainName; this.DnsType = type; this.DnsClass = dnsClass; } public override string ToString() { return string.Format((IFormatProvider) CultureInfo.InvariantCulture, "{0} {1} {2}", (object) this.DomainName, (object) this.DnsType, (object) this.DnsClass); } internal bool EqualsBase(DnsResourceRecord other) { if (other != null && this.DomainName.Equals(other.DomainName) && this.DnsType.Equals((object) other.DnsType)) return this.DnsClass.Equals((object) other.DnsClass); return false; } internal int GetHashCodeBase() { return Sequence.GetHashCode((object) this.DomainName, (object) BitSequence.Merge((ushort) this.DnsType, (ushort) this.DnsClass)); } internal static bool TryParseBase(DnsDatagram dns, int offsetInDns, out DnsDomainName domainName, out DnsType type, out DnsClass dnsClass, out int numBytesRead) { type = DnsType.Any; dnsClass = DnsClass.Any; if (!DnsDomainName.TryParse(dns, offsetInDns, dns.Length - offsetInDns, out domainName, out numBytesRead) || offsetInDns + numBytesRead + 4 > dns.Length) return false; type = (DnsType) dns.ReadUShort(offsetInDns + numBytesRead, Endianity.Big); dnsClass = (DnsClass) dns.ReadUShort(offsetInDns + numBytesRead + 2, Endianity.Big); numBytesRead += 4; return true; } internal int GetLength(DnsDomainNameCompressionData compressionData, int offsetInDns) { return this.DomainName.GetLength(compressionData, offsetInDns) + 4 + this.GetLengthAfterBase(compressionData, offsetInDns); } internal abstract int GetLengthAfterBase(DnsDomainNameCompressionData compressionData, int offsetInDns); internal virtual int Write(byte[] buffer, int dnsOffset, DnsDomainNameCompressionData compressionData, int offsetInDns) { int num1 = 0; int num2 = num1 + this.DomainName.Write(buffer, dnsOffset, compressionData, offsetInDns + num1); ByteArrayExtensions.Write(buffer, dnsOffset + offsetInDns + num2, (ushort) this.DnsType, Endianity.Big); int num3 = num2 + 2; ByteArrayExtensions.Write(buffer, dnsOffset + offsetInDns + num3, (ushort) this.DnsClass, Endianity.Big); return num3 + 2; } private static class OffsetAfterDomainName { public const int Type = 0; public const int DnsClass = 2; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataTrustAnchorLink // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using System; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.TrustAnchorLink)] public sealed class DnsResourceDataTrustAnchorLink : DnsResourceDataNoCompression, IEquatable<DnsResourceDataTrustAnchorLink> { private const int MinimumLength = 2; public DnsDomainName Previous { get; private set; } public DnsDomainName Next { get; private set; } public DnsResourceDataTrustAnchorLink(DnsDomainName previous, DnsDomainName next) { this.Previous = previous; this.Next = next; } internal DnsResourceDataTrustAnchorLink() : this(DnsDomainName.Root, DnsDomainName.Root) { } public bool Equals(DnsResourceDataTrustAnchorLink other) { if (other != null && this.Previous.Equals(other.Previous)) return this.Next.Equals(other.Next); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataTrustAnchorLink); } public override int GetHashCode() { return Sequence.GetHashCode((object) this.Previous, (object) this.Next); } internal override int GetLength() { return this.Previous.NonCompressedLength + this.Next.NonCompressedLength; } internal override int WriteData(byte[] buffer, int offset) { this.Previous.WriteUncompressed(buffer, offset); int compressedLength = this.Previous.NonCompressedLength; this.Next.WriteUncompressed(buffer, offset + compressedLength); return compressedLength + this.Next.NonCompressedLength; } internal override DnsResourceData CreateInstance(DnsDatagram dns, int offsetInDns, int length) { if (length < 2) return (DnsResourceData) null; DnsDomainName domainName1; int numBytesRead1; if (!DnsDomainName.TryParse(dns, offsetInDns, length - 1, out domainName1, out numBytesRead1)) return (DnsResourceData) null; offsetInDns += numBytesRead1; length -= numBytesRead1; DnsDomainName domainName2; int numBytesRead2; if (!DnsDomainName.TryParse(dns, offsetInDns, length, out domainName2, out numBytesRead2)) return (DnsResourceData) null; if (length != numBytesRead2) return (DnsResourceData) null; return (DnsResourceData) new DnsResourceDataTrustAnchorLink(domainName1, domainName2); } } } <file_sep>using System.Configuration; using System.Diagnostics; using WUnderground.Client; using WUnderground.Client.Models; namespace WUnderground.Test { class WUndergroundTest { static void Main(string[] args) { //Configure the client by setting the API Key. Get yours at http://www.wunderground.com WUnderground.Client.WUndergroundClient.Config.ApiKey = ConfigurationSettings.AppSettings["ApiKey"]; //Get the current weather conditions for the specified location WeatherResponse current = WUndergroundClient.GetConditionsForLocationAsync(51.4800, 0.0).Result; Debug.WriteLine(current.current_observation.feelslike_string); //Get the weather forecast for the specified location WeatherResponse forecast = WUndergroundClient.GetConditionsAndForecastForLocationAsync(51.4800, 0.0).Result; Debug.WriteLine(forecast.forecast.txt_forecast.forecastday[0].fcttext); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataCertificate // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.Cert)] public sealed class DnsResourceDataCertificate : DnsResourceDataSimple, IEquatable<DnsResourceDataCertificate> { private const int ConstantPartLength = 5; public DnsCertificateType CertificateType { get; private set; } public ushort KeyTag { get; private set; } public DnsAlgorithm Algorithm { get; private set; } public DataSegment Certificate { get; private set; } public DnsResourceDataCertificate(DnsCertificateType certificateType, ushort keyTag, DnsAlgorithm algorithm, DataSegment certificate) { this.CertificateType = certificateType; this.KeyTag = keyTag; this.Algorithm = algorithm; this.Certificate = certificate; } internal DnsResourceDataCertificate() : this(DnsCertificateType.Pkix, (ushort) 0, DnsAlgorithm.None, DataSegment.Empty) { } public bool Equals(DnsResourceDataCertificate other) { if (other != null && this.CertificateType.Equals((object) other.CertificateType) && (this.KeyTag.Equals(other.KeyTag) && this.Algorithm.Equals((object) other.Algorithm))) return this.Certificate.Equals(other.Certificate); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataCertificate); } public override int GetHashCode() { return Sequence.GetHashCode((object) BitSequence.Merge((ushort) this.CertificateType, this.KeyTag), (object) this.Algorithm, (object) this.Certificate); } internal override int GetLength() { return 5 + this.Certificate.Length; } internal override void WriteDataSimple(byte[] buffer, int offset) { ByteArrayExtensions.Write(buffer, offset, (ushort) this.CertificateType, Endianity.Big); ByteArrayExtensions.Write(buffer, offset + 2, this.KeyTag, Endianity.Big); ByteArrayExtensions.Write(buffer, offset + 4, (byte) this.Algorithm); this.Certificate.Write(buffer, offset + 5); } internal override DnsResourceData CreateInstance(DataSegment data) { if (data.Length < 5) return (DnsResourceData) null; return (DnsResourceData) new DnsResourceDataCertificate((DnsCertificateType) data.ReadUShort(0, Endianity.Big), data.ReadUShort(2, Endianity.Big), (DnsAlgorithm) data[4], data.Subsegment(5, data.Length - 5)); } private static class Offset { public const int Type = 0; public const int KeyTag = 2; public const int Algorithm = 4; public const int Certificate = 5; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsSecNSec3Flags // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using System; using System.Diagnostics.CodeAnalysis; namespace PcapDotNet.Packets.Dns { [Flags] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Flags")] public enum DnsSecNSec3Flags : byte { None = (byte) 0, OptOut = (byte) 1, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.TcpOptionMoodEmotion // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Transport { public enum TcpOptionMoodEmotion { Happy, Sad, Amused, Confused, Bored, Surprised, Silly, Frustrated, Angry, Apathetic, Sneaky, Evil, None, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.SamplingMethodFirstAfterInterval // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using System; namespace PcapDotNet.Core { public sealed class SamplingMethodFirstAfterInterval : SamplingMethod { private int _intervalInMs; internal override int Value { get { return this._intervalInMs; } } internal override int Method { get { return 2; } } public SamplingMethodFirstAfterInterval(TimeSpan interval) { double totalMilliseconds = interval.TotalMilliseconds; if (totalMilliseconds > (double) int.MaxValue) { TimeSpan timeSpan = TimeSpan.FromMilliseconds((double) int.MaxValue); throw new ArgumentOutOfRangeException("interval", (object) interval, "Must be smaller than " + timeSpan.ToString()); } if (totalMilliseconds < 0.0) throw new ArgumentOutOfRangeException("interval", (object) interval, "Must be non negative"); this._intervalInMs = (int) totalMilliseconds; } public SamplingMethodFirstAfterInterval(int intervalInMs) { if (intervalInMs < 0) throw new ArgumentOutOfRangeException("intervalInMs", (object) intervalInMs, "Must be non negative"); this._intervalInMs = intervalInMs; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Ethernet.VLanTaggedFrameLayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Ethernet { public sealed class VLanTaggedFrameLayer : EthernetBaseLayer, IEquatable<VLanTaggedFrameLayer>, IEthernetNextLayer, ILayer { public ClassOfService PriorityCodePoint { get; set; } public bool CanonicalFormatIndicator { get; set; } public ushort VLanIdentifier { get; set; } public ushort TagControlInformation { get { return VLanTaggedFrameDatagram.CalculateTagControlInformation(this.PriorityCodePoint, this.CanonicalFormatIndicator, this.VLanIdentifier); } } public override int Length { get { return 4; } } public EthernetType PreviousLayerEtherType { get { return EthernetType.VLanTaggedFrame; } } public MacAddress? PreviousLayerDefaultDestination { get { return new MacAddress?(); } } public VLanTaggedFrameLayer() { this.PriorityCodePoint = ClassOfService.BestEffort; this.CanonicalFormatIndicator = false; this.VLanIdentifier = (ushort) 0; } public override void Write(byte[] buffer, int offset, int payloadLength, ILayer previousLayer, ILayer nextLayer) { EthernetType ethernetType = EthernetBaseLayer.GetEthernetType(this.EtherType, nextLayer); VLanTaggedFrameDatagram.WriteHeader(buffer, offset, this.PriorityCodePoint, this.CanonicalFormatIndicator, this.VLanIdentifier, ethernetType); } public bool Equals(VLanTaggedFrameLayer other) { if (other != null && this.PriorityCodePoint == other.PriorityCodePoint && (this.CanonicalFormatIndicator == other.CanonicalFormatIndicator && (int) this.VLanIdentifier == (int) other.VLanIdentifier)) return this.EtherType == other.EtherType; return false; } public override bool Equals(Layer other) { return this.Equals(other as VLanTaggedFrameLayer); } public override int GetHashCode() { return base.GetHashCode() ^ BitSequence.Merge(this.TagControlInformation, (ushort) this.EtherType).GetHashCode(); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: AcuLink_Bridge_Reader_CSharp.frmSetup // Assembly: AcuLink_Bridge_Reader_CS, Version=2014.9.18.2041, Culture=neutral, PublicKeyToken=null // MVID: 2DF0938E-D9D0-414E-AB5D-7B9A655FB464 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\AcuLink_Bridge_Reader_CS.exe using AcuLink_Bridge_Reader_CSharp.Properties; using PcapDotNet.Core; using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace AcuLink_Bridge_Reader_CSharp { public class frmSetup : Form { private IContainer components = (IContainer) null; internal Button btnCancel; internal Button btnSave; internal GroupBox GroupBox1; internal CheckBox cbPostToWunderground; internal Label Label1; internal TextBox txtWuPwd; internal TextBox txtWuID; internal Label Label2; internal TextBox txtPressureOffset; internal Label Label4; internal Label Label3; internal ComboBox cmbDeviceId; internal GroupBox groupBox2; internal Label label7; internal TextBox txtWbStationNum; internal CheckBox cbPostToWeatherbug; internal Label label5; internal TextBox txtWbPassword; internal TextBox txtWbPubID; internal Label label6; internal CheckBox cbWriteToCSV; internal GroupBox groupBox3; internal CheckBox cbPostToPWS; internal Label label8; internal TextBox txtPwsPassword; internal TextBox txtPwsStationId; internal Label label9; internal TextBox txtFilterOnSensorId; internal Label label10; internal Label label11; private ComboBox cmbSensorType; private GroupBox groupBox4; internal Label label12; internal TextBox txtAwPwd; internal TextBox txtAwID; internal Label label13; internal CheckBox cbPostToAWeather; private GroupBox groupBox5; private Label label23; private Label label24; internal TextBox txtSensorIdRain; private Label label25; private ComboBox cmbSensorTypeRain; private Label label20; private Label label21; internal TextBox txtSensorIdWind; private Label label22; private ComboBox cmbSensorTypeWind; private Label label17; private Label label18; internal TextBox txtSensorIdHumidity; private Label label19; private ComboBox cmbSensorTypeHumidity; private Label label16; private Label label15; internal TextBox txtSensorIdTemperature; private Label label14; private ComboBox cmbSensorTypeTemperature; private TextBox txtCsvFilePath; private Label label26; internal TextBox txtTempOffset; internal Label label27; private CheckBox cbDebugMode; private GroupBox groupBox6; private Label label30; private Label label28; private ComboBox cmbSensorTypeSoil; private Label label29; internal TextBox txtSensorIdSoil; internal TextBox txtWindOffsetPct; internal Label label31; internal Label label32; private Label label33; internal TextBox txtSoilTempOffset; private GroupBox groupBox7; internal TextBox txtOwAlt; internal Label label38; internal Label label36; internal TextBox txtOwLon; internal TextBox txtOwLat; internal Label label37; internal Label label34; internal TextBox txtOwPwd; internal TextBox txtOwUsername; internal Label label35; internal CheckBox cbPostToOpenWeatherMap; internal Label label39; internal TextBox txtOwStationName; internal GroupBox groupBox8; internal CheckBox cbPostToCw; internal Label label40; internal TextBox txtCwHostName; internal TextBox txtCwRegNum; internal Label label41; internal Label label43; internal Label label42; internal TextBox txtCwLon; internal TextBox txtCwLat; internal Label label44; internal TextBox txtCwPasscode; internal Label label45; private ComboBox cmbCwUpdateMinutes; internal TextBox txtHumidityOffset; internal Label label46; public frmSetup() { this.InitializeComponent(); IList<LivePacketDevice> list = (IList<LivePacketDevice>) LivePacketDevice.AllLocalMachine; if (list.Count == 0) { this.cmbDeviceId.Items.Add((object) "No interfaces found! Make sure WinPcap is installed."); } else { for (int index = 0; index != list.Count; ++index) { LivePacketDevice livePacketDevice = list[index]; string name = livePacketDevice.Name; this.cmbDeviceId.Items.Add(livePacketDevice.Description == null ? (object) (name + " (No description available)") : (object) (name + " (" + livePacketDevice.Description.ToString() + ")")); } this.cmbSensorType.Items.Add((object) ""); this.cmbSensorType.Items.Add((object) "5n1"); this.cmbSensorType.Items.Add((object) "3n1"); this.cmbSensorType.Items.Add((object) "tower"); this.cmbSensorType.Items.Add((object) "water"); this.cmbSensorTypeHumidity.Items.Add((object) ""); this.cmbSensorTypeHumidity.Items.Add((object) "5n1"); this.cmbSensorTypeHumidity.Items.Add((object) "3n1"); this.cmbSensorTypeHumidity.Items.Add((object) "tower"); this.cmbSensorTypeTemperature.Items.Add((object) ""); this.cmbSensorTypeTemperature.Items.Add((object) "5n1"); this.cmbSensorTypeTemperature.Items.Add((object) "3n1"); this.cmbSensorTypeTemperature.Items.Add((object) "tower"); this.cmbSensorTypeTemperature.Items.Add((object) "water"); this.cmbSensorTypeWind.Items.Add((object) ""); this.cmbSensorTypeWind.Items.Add((object) "5n1"); this.cmbSensorTypeWind.Items.Add((object) "3n1"); this.cmbSensorTypeRain.Items.Add((object) ""); this.cmbSensorTypeRain.Items.Add((object) "5n1"); this.cmbSensorTypeRain.Items.Add((object) "3n1"); this.cmbSensorTypeRain.Items.Add((object) "rain"); this.cmbSensorTypeSoil.Items.Add((object) ""); this.cmbSensorTypeSoil.Items.Add((object) "5n1"); this.cmbSensorTypeSoil.Items.Add((object) "3n1"); this.cmbSensorTypeSoil.Items.Add((object) "tower"); this.cmbSensorTypeSoil.Items.Add((object) "water"); this.cmbCwUpdateMinutes.Items.Add((object) "5"); this.cmbCwUpdateMinutes.Items.Add((object) "6"); this.cmbCwUpdateMinutes.Items.Add((object) "7"); this.cmbCwUpdateMinutes.Items.Add((object) "8"); this.cmbCwUpdateMinutes.Items.Add((object) "9"); this.cmbCwUpdateMinutes.Items.Add((object) "10"); this.cmbCwUpdateMinutes.Items.Add((object) "15"); this.cmbCwUpdateMinutes.Items.Add((object) "20"); this.cmbCwUpdateMinutes.Items.Add((object) "25"); this.cmbCwUpdateMinutes.Items.Add((object) "30"); this.cmbCwUpdateMinutes.Items.Add((object) "45"); this.cmbCwUpdateMinutes.Items.Add((object) "60"); this.txtWuID.Text = Settings.Default.wuStation; this.txtWuPwd.Text = Settings.Default.wuPwd; this.txtPressureOffset.Text = Settings.Default.pressureOffset.ToString(); this.cmbDeviceId.SelectedItem = (object) Settings.Default.networkDevice; this.cbPostToWunderground.Checked = Settings.Default.postToWunderground; this.cbPostToWeatherbug.Checked = Settings.Default.postToWeatherBug; this.txtWbPubID.Text = Settings.Default.wbPub; this.txtWbStationNum.Text = Settings.Default.wbStation; this.txtWbPassword.Text = Settings.Default.wbPwd; this.cbWriteToCSV.Checked = Settings.Default.writeToCSV; this.cbPostToPWS.Checked = Settings.Default.postToPws; this.txtPwsStationId.Text = Settings.Default.pwsStation; this.txtPwsPassword.Text = Settings.Default.pwsPwd; this.txtFilterOnSensorId.Text = Settings.Default.filterOnSensorId; this.cmbSensorType.SelectedItem = (object) Settings.Default.sensorType; this.txtAwID.Text = Settings.Default.awStation; this.txtAwPwd.Text = Settings.Default.awPwd; this.cbPostToAWeather.Checked = Settings.Default.postToAWeather; this.txtSensorIdHumidity.Text = Settings.Default.sensorIdHumidity; this.txtSensorIdRain.Text = Settings.Default.sensorIdRain; this.txtSensorIdTemperature.Text = Settings.Default.sensorIdTemp; this.txtSensorIdWind.Text = Settings.Default.sensorIdWind; this.cmbSensorTypeHumidity.SelectedItem = (object) Settings.Default.sensorTypeHumidity; this.cmbSensorTypeRain.SelectedItem = (object) Settings.Default.sensorTypeRain; this.cmbSensorTypeTemperature.SelectedItem = (object) Settings.Default.sensorTypeTemp; this.cmbSensorTypeWind.SelectedItem = (object) Settings.Default.sensorTypeWind; this.txtCsvFilePath.Text = Settings.Default.csvFilePath; TextBox textBox1 = this.txtTempOffset; Decimal num = Settings.Default.tempOffset; string str1 = num.ToString(); textBox1.Text = str1; this.cbDebugMode.Checked = Settings.Default.debugMode; this.cmbSensorTypeSoil.SelectedItem = (object) Settings.Default.sensorTypeSoil; this.txtSensorIdSoil.Text = Settings.Default.sensorIdSoil; TextBox textBox2 = this.txtWindOffsetPct; num = Settings.Default.windOffsetPct; string str2 = num.ToString(); textBox2.Text = str2; TextBox textBox3 = this.txtSoilTempOffset; num = Settings.Default.soilTempOffset; string str3 = num.ToString(); textBox3.Text = str3; this.cbPostToOpenWeatherMap.Checked = Settings.Default.postToOw; this.txtOwUsername.Text = Settings.Default.owUsername; this.txtOwPwd.Text = Settings.Default.owPwd; this.txtOwLat.Text = Settings.Default.owLat; this.txtOwLon.Text = Settings.Default.owLon; this.txtOwAlt.Text = Settings.Default.owAlt; this.txtOwStationName.Text = Settings.Default.owStationName; this.cbPostToCw.Checked = Settings.Default.postToCw; this.txtCwRegNum.Text = Settings.Default.cwRegNum; this.txtCwHostName.Text = Settings.Default.cwHostName; this.txtCwLat.Text = Settings.Default.cwLat; this.txtCwLon.Text = Settings.Default.cwLon; this.txtCwPasscode.Text = Settings.Default.cwPasscode; this.cmbCwUpdateMinutes.SelectedItem = (object) Settings.Default.cwUpdateMinutes.ToString(); TextBox textBox4 = this.txtHumidityOffset; num = Settings.Default.humidityOffset; string str4 = num.ToString(); textBox4.Text = str4; } } private void btnSave_Click(object sender, EventArgs e) { double result1 = 0.0; if (!double.TryParse(this.txtPressureOffset.Text, out result1)) { int num = (int) MessageBox.Show("Please enter a Pressure Offset value between -9.99 and 9.99."); this.txtPressureOffset.Focus(); } else if (double.Parse(this.txtPressureOffset.Text) < -9.99 & double.Parse(this.txtPressureOffset.Text) <= 9.99) { int num = (int) MessageBox.Show("Please enter a Pressure Offset value between -9.99 and 9.99."); this.txtPressureOffset.Focus(); } else { double result2 = 0.0; if (!double.TryParse(this.txtTempOffset.Text, out result2)) { int num = (int) MessageBox.Show("Please enter a Temperature Offset value between -99.9 and 99.9."); this.txtTempOffset.Focus(); } else if (double.Parse(this.txtTempOffset.Text) < -99.9 & double.Parse(this.txtTempOffset.Text) <= 99.9) { int num = (int) MessageBox.Show("Please enter a Temperature Offset value between -99.9 and 99.9."); this.txtTempOffset.Focus(); this.txtTempOffset.Focus(); this.txtTempOffset.Focus(); } else if (!double.TryParse(this.txtSoilTempOffset.Text, out result2)) { int num = (int) MessageBox.Show("Please enter a Soil/Water Temperature Offset value between -99.9 and 99.9."); this.txtSoilTempOffset.Focus(); } else if (double.Parse(this.txtSoilTempOffset.Text) < -99.9 & double.Parse(this.txtSoilTempOffset.Text) <= 99.9) { int num = (int) MessageBox.Show("Please enter a Soil/Water Temperature Offset value between -99.9 and 99.9."); this.txtSoilTempOffset.Focus(); } else if (!double.TryParse(this.txtHumidityOffset.Text, out result2)) { int num = (int) MessageBox.Show("Please enter a Humidity Offset value between -99.9 and 99.9."); this.txtHumidityOffset.Focus(); } else if (double.Parse(this.txtHumidityOffset.Text) < -99.9 & double.Parse(this.txtHumidityOffset.Text) <= 99.9) { int num = (int) MessageBox.Show("Please enter a Humidity Offset value between -99.9 and 99.9."); this.txtHumidityOffset.Focus(); } else { // ISSUE: variable of a compiler-generated type Settings @default = Settings.Default; @default.wuStation = this.txtWuID.Text.ToUpper(); @default.wuPwd = this.txtWuPwd.Text; @default.pressureOffset = double.Parse(this.txtPressureOffset.Text); @default.networkDevice = this.cmbDeviceId.SelectedItem.ToString(); @default.postToWunderground = this.cbPostToWunderground.Checked; @default.postToWeatherBug = this.cbPostToWeatherbug.Checked; @default.wbPub = this.txtWbPubID.Text; @default.wbPwd = this.txtWbPassword.Text; @default.wbStation = this.txtWbStationNum.Text; @default.writeToCSV = this.cbWriteToCSV.Checked; @default.postToPws = this.cbPostToPWS.Checked; @default.postToPws = this.cbPostToPWS.Checked; @default.pwsStation = this.txtPwsStationId.Text; @default.pwsPwd = <PASSWORD>.txtPwsPassword.Text; @default.filterOnSensorId = this.txtFilterOnSensorId.Text; @default.sensorType = this.cmbSensorType.SelectedItem.ToString(); @default.awStation = this.txtAwID.Text; @default.awPwd = this.txtAwPwd.Text; @default.postToAWeather = this.cbPostToAWeather.Checked; @default.sensorIdHumidity = this.txtSensorIdHumidity.Text; @default.sensorIdRain = this.txtSensorIdRain.Text; @default.sensorIdTemp = this.txtSensorIdTemperature.Text; @default.sensorIdWind = this.txtSensorIdWind.Text; @default.sensorTypeHumidity = this.cmbSensorTypeHumidity.SelectedItem.ToString(); @default.sensorTypeRain = this.cmbSensorTypeRain.SelectedItem.ToString(); @default.sensorTypeTemp = this.cmbSensorTypeTemperature.SelectedItem.ToString(); @default.sensorTypeWind = this.cmbSensorTypeWind.SelectedItem.ToString(); @default.csvFilePath = this.txtCsvFilePath.Text; @default.tempOffset = Decimal.Parse(this.txtTempOffset.Text); @default.debugMode = this.cbDebugMode.Checked; @default.sensorTypeSoil = this.cmbSensorTypeSoil.SelectedItem.ToString(); @default.sensorIdSoil = this.txtSensorIdSoil.Text; @default.windOffsetPct = Decimal.Parse(this.txtWindOffsetPct.Text); @default.soilTempOffset = Decimal.Parse(this.txtSoilTempOffset.Text); @default.postToOw = this.cbPostToOpenWeatherMap.Checked; @default.owUsername = this.txtOwUsername.Text; @default.owPwd = this.txtOwPwd.Text; @default.owLat = this.txtOwLat.Text; @default.owLon = this.txtOwLon.Text; @default.owAlt = this.txtOwAlt.Text; @default.owStationName = this.txtOwStationName.Text; @default.postToCw = this.cbPostToCw.Checked; @default.cwRegNum = this.txtCwRegNum.Text; @default.cwHostName = this.txtCwHostName.Text; @default.cwLat = this.txtCwLat.Text; @default.cwLon = this.txtCwLon.Text; @default.cwPasscode = this.txtCwPasscode.Text; @default.cwUpdateMinutes = int.Parse(this.cmbCwUpdateMinutes.SelectedItem.ToString()); @default.humidityOffset = Decimal.Parse(this.txtHumidityOffset.Text); @default.Save(); this.Close(); } } } private void btnCancel_Click(object sender, EventArgs e) { this.Close(); } private void frmSetup_Load(object sender, EventArgs e) { } protected override void Dispose(bool disposing) { if (disposing && this.components != null) this.components.Dispose(); base.Dispose(disposing); } private void InitializeComponent() { this.btnCancel = new Button(); this.btnSave = new Button(); this.GroupBox1 = new GroupBox(); this.cbPostToWunderground = new CheckBox(); this.Label1 = new Label(); this.txtWuPwd = new TextBox(); this.txtWuID = new TextBox(); this.Label2 = new Label(); this.txtPressureOffset = new TextBox(); this.Label4 = new Label(); this.Label3 = new Label(); this.cmbDeviceId = new ComboBox(); this.groupBox2 = new GroupBox(); this.label7 = new Label(); this.txtWbStationNum = new TextBox(); this.cbPostToWeatherbug = new CheckBox(); this.label5 = new Label(); this.txtWbPassword = new TextBox(); this.txtWbPubID = new TextBox(); this.label6 = new Label(); this.cbWriteToCSV = new CheckBox(); this.groupBox3 = new GroupBox(); this.cbPostToPWS = new CheckBox(); this.label8 = new Label(); this.txtPwsPassword = new TextBox(); this.txtPwsStationId = new TextBox(); this.label9 = new Label(); this.txtFilterOnSensorId = new TextBox(); this.label10 = new Label(); this.label11 = new Label(); this.cmbSensorType = new ComboBox(); this.groupBox4 = new GroupBox(); this.label12 = new Label(); this.txtAwPwd = new TextBox(); this.txtAwID = new TextBox(); this.label13 = new Label(); this.cbPostToAWeather = new CheckBox(); this.groupBox5 = new GroupBox(); this.label23 = new Label(); this.label24 = new Label(); this.txtSensorIdRain = new TextBox(); this.label25 = new Label(); this.cmbSensorTypeRain = new ComboBox(); this.label20 = new Label(); this.label21 = new Label(); this.txtSensorIdWind = new TextBox(); this.label22 = new Label(); this.cmbSensorTypeWind = new ComboBox(); this.label17 = new Label(); this.label18 = new Label(); this.txtSensorIdHumidity = new TextBox(); this.label19 = new Label(); this.cmbSensorTypeHumidity = new ComboBox(); this.label16 = new Label(); this.label15 = new Label(); this.txtSensorIdTemperature = new TextBox(); this.label14 = new Label(); this.cmbSensorTypeTemperature = new ComboBox(); this.txtCsvFilePath = new TextBox(); this.label26 = new Label(); this.txtTempOffset = new TextBox(); this.label27 = new Label(); this.cbDebugMode = new CheckBox(); this.groupBox6 = new GroupBox(); this.label33 = new Label(); this.txtSoilTempOffset = new TextBox(); this.label30 = new Label(); this.label28 = new Label(); this.cmbSensorTypeSoil = new ComboBox(); this.label29 = new Label(); this.txtSensorIdSoil = new TextBox(); this.txtWindOffsetPct = new TextBox(); this.label31 = new Label(); this.label32 = new Label(); this.groupBox7 = new GroupBox(); this.label39 = new Label(); this.txtOwAlt = new TextBox(); this.label38 = new Label(); this.txtOwStationName = new TextBox(); this.label36 = new Label(); this.txtOwLon = new TextBox(); this.txtOwLat = new TextBox(); this.label37 = new Label(); this.label34 = new Label(); this.txtOwPwd = new TextBox(); this.txtOwUsername = new TextBox(); this.label35 = new Label(); this.cbPostToOpenWeatherMap = new CheckBox(); this.groupBox8 = new GroupBox(); this.label45 = new Label(); this.cmbCwUpdateMinutes = new ComboBox(); this.label44 = new Label(); this.txtCwPasscode = new TextBox(); this.label43 = new Label(); this.label42 = new Label(); this.txtCwLon = new TextBox(); this.txtCwLat = new TextBox(); this.cbPostToCw = new CheckBox(); this.label40 = new Label(); this.txtCwHostName = new TextBox(); this.txtCwRegNum = new TextBox(); this.label41 = new Label(); this.txtHumidityOffset = new TextBox(); this.label46 = new Label(); this.GroupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.groupBox3.SuspendLayout(); this.groupBox4.SuspendLayout(); this.groupBox5.SuspendLayout(); this.groupBox6.SuspendLayout(); this.groupBox7.SuspendLayout(); this.groupBox8.SuspendLayout(); this.SuspendLayout(); this.btnCancel.Location = new Point(1083, 469); this.btnCancel.Margin = new Padding(4); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new Size(100, 28); this.btnCancel.TabIndex = 5; this.btnCancel.Text = "Cancel"; this.btnCancel.UseVisualStyleBackColor = true; this.btnCancel.Click += new EventHandler(this.btnCancel_Click); this.btnSave.Location = new Point(1083, 415); this.btnSave.Margin = new Padding(4); this.btnSave.Name = "btnSave"; this.btnSave.Size = new Size(100, 28); this.btnSave.TabIndex = 4; this.btnSave.Text = "Save"; this.btnSave.UseVisualStyleBackColor = true; this.btnSave.Click += new EventHandler(this.btnSave_Click); this.GroupBox1.Controls.Add((Control) this.cbPostToWunderground); this.GroupBox1.Controls.Add((Control) this.Label1); this.GroupBox1.Controls.Add((Control) this.txtWuPwd); this.GroupBox1.Controls.Add((Control) this.txtWuID); this.GroupBox1.Controls.Add((Control) this.Label2); this.GroupBox1.Location = new Point(17, 59); this.GroupBox1.Margin = new Padding(4); this.GroupBox1.Name = "GroupBox1"; this.GroupBox1.Padding = new Padding(4); this.GroupBox1.Size = new Size(296, 118); this.GroupBox1.TabIndex = 16; this.GroupBox1.TabStop = false; this.GroupBox1.Text = "Weather Underground"; this.cbPostToWunderground.AutoSize = true; this.cbPostToWunderground.Location = new Point(11, 23); this.cbPostToWunderground.Margin = new Padding(4); this.cbPostToWunderground.Name = "cbPostToWunderground"; this.cbPostToWunderground.Size = new Size(254, 21); this.cbPostToWunderground.TabIndex = 0; this.cbPostToWunderground.Text = "Post Data to Weather Underground"; this.cbPostToWunderground.UseVisualStyleBackColor = true; this.Label1.AutoSize = true; this.Label1.Location = new Point(8, 57); this.Label1.Margin = new Padding(4, 0, 4, 0); this.Label1.Name = "Label1"; this.Label1.Size = new Size(73, 17); this.Label1.TabIndex = 0; this.Label1.Text = "Station ID:"; this.txtWuPwd.Location = new Point(140, 82); this.txtWuPwd.Margin = new Padding(4); this.txtWuPwd.Name = "txtWuPwd"; this.txtWuPwd.Size = new Size(147, 22); this.txtWuPwd.TabIndex = 2; this.txtWuPwd.UseSystemPasswordChar = true; this.txtWuID.Location = new Point(140, 52); this.txtWuID.Margin = new Padding(4); this.txtWuID.Name = "txtWuID"; this.txtWuID.Size = new Size(147, 22); this.txtWuID.TabIndex = 1; this.Label2.AutoSize = true; this.Label2.Location = new Point(9, 86); this.Label2.Margin = new Padding(4, 0, 4, 0); this.Label2.Name = "Label2"; this.Label2.Size = new Size(121, 17); this.Label2.TabIndex = 2; this.Label2.Text = "Station Password:"; this.txtPressureOffset.Location = new Point(733, 254); this.txtPressureOffset.Margin = new Padding(4); this.txtPressureOffset.MaxLength = 5; this.txtPressureOffset.Name = "txtPressureOffset"; this.txtPressureOffset.Size = new Size(40, 22); this.txtPressureOffset.TabIndex = 1; this.Label4.AutoSize = true; this.Label4.Location = new Point(625, 258); this.Label4.Margin = new Padding(4, 0, 4, 0); this.Label4.Name = "Label4"; this.Label4.Size = new Size(111, 17); this.Label4.TabIndex = 14; this.Label4.Text = "Pressure Offset:"; this.Label3.AutoSize = true; this.Label3.Location = new Point(10, 7); this.Label3.Margin = new Padding(4, 0, 4, 0); this.Label3.Name = "Label3"; this.Label3.Size = new Size(110, 17); this.Label3.TabIndex = 15; this.Label3.Text = "Network Device:"; this.cmbDeviceId.DropDownStyle = ComboBoxStyle.DropDownList; this.cmbDeviceId.FormattingEnabled = true; this.cmbDeviceId.Location = new Point(13, 27); this.cmbDeviceId.Margin = new Padding(4); this.cmbDeviceId.Name = "cmbDeviceId"; this.cmbDeviceId.Size = new Size(1015, 24); this.cmbDeviceId.TabIndex = 0; this.groupBox2.Controls.Add((Control) this.label7); this.groupBox2.Controls.Add((Control) this.txtWbStationNum); this.groupBox2.Controls.Add((Control) this.cbPostToWeatherbug); this.groupBox2.Controls.Add((Control) this.label5); this.groupBox2.Controls.Add((Control) this.txtWbPassword); this.groupBox2.Controls.Add((Control) this.txtWbPubID); this.groupBox2.Controls.Add((Control) this.label6); this.groupBox2.Location = new Point(619, 59); this.groupBox2.Margin = new Padding(4); this.groupBox2.Name = "groupBox2"; this.groupBox2.Padding = new Padding(4); this.groupBox2.Size = new Size(290, 145); this.groupBox2.TabIndex = 17; this.groupBox2.TabStop = false; this.groupBox2.Text = "Weatherbug"; this.label7.AutoSize = true; this.label7.Location = new Point(8, 85); this.label7.Margin = new Padding(4, 0, 4, 0); this.label7.Name = "label7"; this.label7.Size = new Size(68, 17); this.label7.TabIndex = 14; this.label7.Text = "Station #:"; this.txtWbStationNum.Location = new Point(139, 81); this.txtWbStationNum.Margin = new Padding(4); this.txtWbStationNum.Name = "txtWbStationNum"; this.txtWbStationNum.Size = new Size(142, 22); this.txtWbStationNum.TabIndex = 2; this.cbPostToWeatherbug.AutoSize = true; this.cbPostToWeatherbug.Location = new Point(11, 23); this.cbPostToWeatherbug.Margin = new Padding(4); this.cbPostToWeatherbug.Name = "cbPostToWeatherbug"; this.cbPostToWeatherbug.Size = new Size(190, 21); this.cbPostToWeatherbug.TabIndex = 0; this.cbPostToWeatherbug.Text = "Post Data to Weatherbug"; this.cbPostToWeatherbug.UseVisualStyleBackColor = true; this.label5.AutoSize = true; this.label5.Location = new Point(8, 55); this.label5.Margin = new Padding(4, 0, 4, 0); this.label5.Name = "label5"; this.label5.Size = new Size(88, 17); this.label5.TabIndex = 0; this.label5.Text = "Publisher ID:"; this.txtWbPassword.Location = new Point(139, 111); this.txtWbPassword.Margin = new Padding(4); this.txtWbPassword.Name = "txtWbPassword"; this.txtWbPassword.Size = new Size(142, 22); this.txtWbPassword.TabIndex = 3; this.txtWbPassword.UseSystemPasswordChar = true; this.txtWbPubID.Location = new Point(139, 51); this.txtWbPubID.Margin = new Padding(4); this.txtWbPubID.Name = "txtWbPubID"; this.txtWbPubID.Size = new Size(142, 22); this.txtWbPubID.TabIndex = 1; this.label6.AutoSize = true; this.label6.Location = new Point(8, 114); this.label6.Margin = new Padding(4, 0, 4, 0); this.label6.Name = "label6"; this.label6.Size = new Size(121, 17); this.label6.TabIndex = 2; this.label6.Text = "Station Password:"; this.cbWriteToCSV.AutoSize = true; this.cbWriteToCSV.Location = new Point(650, 290); this.cbWriteToCSV.Margin = new Padding(4); this.cbWriteToCSV.Name = "cbWriteToCSV"; this.cbWriteToCSV.Size = new Size(136, 21); this.cbWriteToCSV.TabIndex = 3; this.cbWriteToCSV.Text = "Write to CSV File"; this.cbWriteToCSV.UseVisualStyleBackColor = true; this.groupBox3.Controls.Add((Control) this.cbPostToPWS); this.groupBox3.Controls.Add((Control) this.label8); this.groupBox3.Controls.Add((Control) this.txtPwsPassword); this.groupBox3.Controls.Add((Control) this.txtPwsStationId); this.groupBox3.Controls.Add((Control) this.label9); this.groupBox3.Location = new Point(325, 59); this.groupBox3.Margin = new Padding(4); this.groupBox3.Name = "groupBox3"; this.groupBox3.Padding = new Padding(4); this.groupBox3.Size = new Size(289, 118); this.groupBox3.TabIndex = 20; this.groupBox3.TabStop = false; this.groupBox3.Text = "PWSweather"; this.cbPostToPWS.AutoSize = true; this.cbPostToPWS.Location = new Point(11, 23); this.cbPostToPWS.Margin = new Padding(4); this.cbPostToPWS.Name = "cbPostToPWS"; this.cbPostToPWS.Size = new Size(193, 21); this.cbPostToPWS.TabIndex = 0; this.cbPostToPWS.Text = "Post Data to PWSweather"; this.cbPostToPWS.UseVisualStyleBackColor = true; this.label8.AutoSize = true; this.label8.Location = new Point(8, 54); this.label8.Margin = new Padding(4, 0, 4, 0); this.label8.Name = "label8"; this.label8.Size = new Size(73, 17); this.label8.TabIndex = 0; this.label8.Text = "Station ID:"; this.txtPwsPassword.Location = new Point(139, 80); this.txtPwsPassword.Margin = new Padding(4); this.txtPwsPassword.Name = "txtPwsPassword"; this.txtPwsPassword.Size = new Size(142, 22); this.txtPwsPassword.TabIndex = 2; this.txtPwsPassword.UseSystemPasswordChar = true; this.txtPwsStationId.Location = new Point(139, 50); this.txtPwsStationId.Margin = new Padding(4); this.txtPwsStationId.Name = "txtPwsStationId"; this.txtPwsStationId.Size = new Size(142, 22); this.txtPwsStationId.TabIndex = 1; this.label9.AutoSize = true; this.label9.Location = new Point(8, 84); this.label9.Margin = new Padding(4, 0, 4, 0); this.label9.Name = "label9"; this.label9.Size = new Size(121, 17); this.label9.TabIndex = 2; this.label9.Text = "Station Password:"; this.txtFilterOnSensorId.Location = new Point(1153, 221); this.txtFilterOnSensorId.Margin = new Padding(4); this.txtFilterOnSensorId.MaxLength = 5; this.txtFilterOnSensorId.Name = "txtFilterOnSensorId"; this.txtFilterOnSensorId.Size = new Size(64, 22); this.txtFilterOnSensorId.TabIndex = 2; this.label10.AutoSize = true; this.label10.Location = new Point(974, 224); this.label10.Margin = new Padding(4, 0, 4, 0); this.label10.Name = "label10"; this.label10.Size = new Size(177, 17); this.label10.TabIndex = 22; this.label10.Text = "Global Filter On Sensor ID:"; this.label11.AutoSize = true; this.label11.Location = new Point(649, 224); this.label11.Margin = new Padding(4, 0, 4, 0); this.label11.Name = "label11"; this.label11.Size = new Size(193, 17); this.label11.TabIndex = 24; this.label11.Text = "Global Filter on Sensor Type:"; this.cmbSensorType.DropDownStyle = ComboBoxStyle.DropDownList; this.cmbSensorType.FormattingEnabled = true; this.cmbSensorType.Location = new Point(844, 221); this.cmbSensorType.Margin = new Padding(4); this.cmbSensorType.Name = "cmbSensorType"; this.cmbSensorType.Size = new Size(107, 24); this.cmbSensorType.TabIndex = 25; this.groupBox4.Controls.Add((Control) this.label12); this.groupBox4.Controls.Add((Control) this.txtAwPwd); this.groupBox4.Controls.Add((Control) this.txtAwID); this.groupBox4.Controls.Add((Control) this.label13); this.groupBox4.Controls.Add((Control) this.cbPostToAWeather); this.groupBox4.Location = new Point(929, 59); this.groupBox4.Margin = new Padding(4); this.groupBox4.Name = "groupBox4"; this.groupBox4.Padding = new Padding(4); this.groupBox4.Size = new Size(289, 112); this.groupBox4.TabIndex = 26; this.groupBox4.TabStop = false; this.groupBox4.Text = "Anything Weather"; this.label12.AutoSize = true; this.label12.Location = new Point(8, 52); this.label12.Margin = new Padding(4, 0, 4, 0); this.label12.Name = "label12"; this.label12.Size = new Size(73, 17); this.label12.TabIndex = 4; this.label12.Text = "Station ID:"; this.txtAwPwd.Location = new Point(137, 78); this.txtAwPwd.Margin = new Padding(4); this.txtAwPwd.Name = "txtAwPwd"; this.txtAwPwd.Size = new Size(142, 22); this.txtAwPwd.TabIndex = 6; this.txtAwPwd.UseSystemPasswordChar = true; this.txtAwID.Location = new Point(137, 49); this.txtAwID.Margin = new Padding(4); this.txtAwID.Name = "txtAwID"; this.txtAwID.Size = new Size(142, 22); this.txtAwID.TabIndex = 5; this.label13.AutoSize = true; this.label13.Location = new Point(8, 83); this.label13.Margin = new Padding(4, 0, 4, 0); this.label13.Name = "label13"; this.label13.Size = new Size(121, 17); this.label13.TabIndex = 7; this.label13.Text = "Station Password:"; this.cbPostToAWeather.AutoSize = true; this.cbPostToAWeather.Location = new Point(11, 23); this.cbPostToAWeather.Margin = new Padding(4); this.cbPostToAWeather.Name = "cbPostToAWeather"; this.cbPostToAWeather.Size = new Size(225, 21); this.cbPostToAWeather.TabIndex = 3; this.cbPostToAWeather.Text = "Post Data to Anything Weather"; this.cbPostToAWeather.UseVisualStyleBackColor = true; this.groupBox5.Controls.Add((Control) this.label23); this.groupBox5.Controls.Add((Control) this.label24); this.groupBox5.Controls.Add((Control) this.txtSensorIdRain); this.groupBox5.Controls.Add((Control) this.label25); this.groupBox5.Controls.Add((Control) this.cmbSensorTypeRain); this.groupBox5.Controls.Add((Control) this.label20); this.groupBox5.Controls.Add((Control) this.label21); this.groupBox5.Controls.Add((Control) this.txtSensorIdWind); this.groupBox5.Controls.Add((Control) this.label22); this.groupBox5.Controls.Add((Control) this.cmbSensorTypeWind); this.groupBox5.Controls.Add((Control) this.label17); this.groupBox5.Controls.Add((Control) this.label18); this.groupBox5.Controls.Add((Control) this.txtSensorIdHumidity); this.groupBox5.Controls.Add((Control) this.label19); this.groupBox5.Controls.Add((Control) this.cmbSensorTypeHumidity); this.groupBox5.Controls.Add((Control) this.label16); this.groupBox5.Controls.Add((Control) this.label15); this.groupBox5.Controls.Add((Control) this.txtSensorIdTemperature); this.groupBox5.Controls.Add((Control) this.label14); this.groupBox5.Controls.Add((Control) this.cmbSensorTypeTemperature); this.groupBox5.Location = new Point(28, 421); this.groupBox5.Margin = new Padding(4); this.groupBox5.Name = "groupBox5"; this.groupBox5.Padding = new Padding(4); this.groupBox5.Size = new Size(787, 118); this.groupBox5.TabIndex = 27; this.groupBox5.TabStop = false; this.groupBox5.Text = "Multi Sensors (Advanced Settings)"; this.label23.AutoSize = true; this.label23.Location = new Point(588, 58); this.label23.Margin = new Padding(4, 0, 4, 0); this.label23.Name = "label23"; this.label23.Size = new Size(44, 17); this.label23.TabIndex = 45; this.label23.Text = "Type:"; this.label24.AutoSize = true; this.label24.Location = new Point(588, 91); this.label24.Margin = new Padding(4, 0, 4, 0); this.label24.Name = "label24"; this.label24.Size = new Size(89, 17); this.label24.TabIndex = 44; this.label24.Text = "ID (optional):"; this.txtSensorIdRain.Location = new Point(685, 87); this.txtSensorIdRain.Margin = new Padding(4); this.txtSensorIdRain.MaxLength = 5; this.txtSensorIdRain.Name = "txtSensorIdRain"; this.txtSensorIdRain.Size = new Size(64, 22); this.txtSensorIdRain.TabIndex = 43; this.label25.AutoSize = true; this.label25.Location = new Point(588, 25); this.label25.Margin = new Padding(4, 0, 4, 0); this.label25.Name = "label25"; this.label25.Size = new Size(37, 17); this.label25.TabIndex = 42; this.label25.Text = "Rain"; this.cmbSensorTypeRain.DropDownStyle = ComboBoxStyle.DropDownList; this.cmbSensorTypeRain.FormattingEnabled = true; this.cmbSensorTypeRain.Location = new Point(643, 54); this.cmbSensorTypeRain.Margin = new Padding(4); this.cmbSensorTypeRain.Name = "cmbSensorTypeRain"; this.cmbSensorTypeRain.Size = new Size(107, 24); this.cmbSensorTypeRain.TabIndex = 41; this.label20.AutoSize = true; this.label20.Location = new Point(392, 58); this.label20.Margin = new Padding(4, 0, 4, 0); this.label20.Name = "label20"; this.label20.Size = new Size(44, 17); this.label20.TabIndex = 40; this.label20.Text = "Type:"; this.label21.AutoSize = true; this.label21.Location = new Point(392, 91); this.label21.Margin = new Padding(4, 0, 4, 0); this.label21.Name = "label21"; this.label21.Size = new Size(89, 17); this.label21.TabIndex = 39; this.label21.Text = "ID (optional):"; this.txtSensorIdWind.Location = new Point(489, 87); this.txtSensorIdWind.Margin = new Padding(4); this.txtSensorIdWind.MaxLength = 5; this.txtSensorIdWind.Name = "txtSensorIdWind"; this.txtSensorIdWind.Size = new Size(64, 22); this.txtSensorIdWind.TabIndex = 38; this.label22.AutoSize = true; this.label22.Location = new Point(392, 25); this.label22.Margin = new Padding(4, 0, 4, 0); this.label22.Name = "label22"; this.label22.Size = new Size(40, 17); this.label22.TabIndex = 37; this.label22.Text = "Wind"; this.cmbSensorTypeWind.DropDownStyle = ComboBoxStyle.DropDownList; this.cmbSensorTypeWind.FormattingEnabled = true; this.cmbSensorTypeWind.Location = new Point(447, 54); this.cmbSensorTypeWind.Margin = new Padding(4); this.cmbSensorTypeWind.Name = "cmbSensorTypeWind"; this.cmbSensorTypeWind.Size = new Size(107, 24); this.cmbSensorTypeWind.TabIndex = 36; this.label17.AutoSize = true; this.label17.Location = new Point(200, 58); this.label17.Margin = new Padding(4, 0, 4, 0); this.label17.Name = "label17"; this.label17.Size = new Size(44, 17); this.label17.TabIndex = 35; this.label17.Text = "Type:"; this.label18.AutoSize = true; this.label18.Location = new Point(200, 91); this.label18.Margin = new Padding(4, 0, 4, 0); this.label18.Name = "label18"; this.label18.Size = new Size(89, 17); this.label18.TabIndex = 34; this.label18.Text = "ID (optional):"; this.txtSensorIdHumidity.Location = new Point(297, 87); this.txtSensorIdHumidity.Margin = new Padding(4); this.txtSensorIdHumidity.MaxLength = 5; this.txtSensorIdHumidity.Name = "txtSensorIdHumidity"; this.txtSensorIdHumidity.Size = new Size(64, 22); this.txtSensorIdHumidity.TabIndex = 33; this.label19.AutoSize = true; this.label19.Location = new Point(200, 25); this.label19.Margin = new Padding(4, 0, 4, 0); this.label19.Name = "label19"; this.label19.Size = new Size(62, 17); this.label19.TabIndex = 32; this.label19.Text = "Humidity"; this.cmbSensorTypeHumidity.DropDownStyle = ComboBoxStyle.DropDownList; this.cmbSensorTypeHumidity.FormattingEnabled = true; this.cmbSensorTypeHumidity.Location = new Point((int) byte.MaxValue, 54); this.cmbSensorTypeHumidity.Margin = new Padding(4); this.cmbSensorTypeHumidity.Name = "cmbSensorTypeHumidity"; this.cmbSensorTypeHumidity.Size = new Size(107, 24); this.cmbSensorTypeHumidity.TabIndex = 31; this.label16.AutoSize = true; this.label16.Location = new Point(13, 58); this.label16.Margin = new Padding(4, 0, 4, 0); this.label16.Name = "label16"; this.label16.Size = new Size(44, 17); this.label16.TabIndex = 30; this.label16.Text = "Type:"; this.label15.AutoSize = true; this.label15.Location = new Point(13, 91); this.label15.Margin = new Padding(4, 0, 4, 0); this.label15.Name = "label15"; this.label15.Size = new Size(89, 17); this.label15.TabIndex = 29; this.label15.Text = "ID (optional):"; this.txtSensorIdTemperature.Location = new Point(111, 87); this.txtSensorIdTemperature.Margin = new Padding(4); this.txtSensorIdTemperature.MaxLength = 5; this.txtSensorIdTemperature.Name = "txtSensorIdTemperature"; this.txtSensorIdTemperature.Size = new Size(64, 22); this.txtSensorIdTemperature.TabIndex = 28; this.label14.AutoSize = true; this.label14.Location = new Point(13, 25); this.label14.Margin = new Padding(4, 0, 4, 0); this.label14.Name = "label14"; this.label14.Size = new Size(90, 17); this.label14.TabIndex = 27; this.label14.Text = "Temperature"; this.cmbSensorTypeTemperature.DropDownStyle = ComboBoxStyle.DropDownList; this.cmbSensorTypeTemperature.FormattingEnabled = true; this.cmbSensorTypeTemperature.Location = new Point(68, 54); this.cmbSensorTypeTemperature.Margin = new Padding(4); this.cmbSensorTypeTemperature.Name = "cmbSensorTypeTemperature"; this.cmbSensorTypeTemperature.Size = new Size(107, 24); this.cmbSensorTypeTemperature.TabIndex = 26; this.txtCsvFilePath.Location = new Point(944, 287); this.txtCsvFilePath.Margin = new Padding(4); this.txtCsvFilePath.Name = "txtCsvFilePath"; this.txtCsvFilePath.Size = new Size(273, 22); this.txtCsvFilePath.TabIndex = 28; this.label26.AutoSize = true; this.label26.Location = new Point(807, 291); this.label26.Margin = new Padding(4, 0, 4, 0); this.label26.Name = "label26"; this.label26.Size = new Size(133, 17); this.label26.TabIndex = 29; this.label26.Text = "File path and name:"; this.txtTempOffset.Location = new Point(866, 254); this.txtTempOffset.Margin = new Padding(4); this.txtTempOffset.MaxLength = 5; this.txtTempOffset.Name = "txtTempOffset"; this.txtTempOffset.Size = new Size(40, 22); this.txtTempOffset.TabIndex = 30; this.label27.AutoSize = true; this.label27.Location = new Point(778, 258); this.label27.Margin = new Padding(4, 0, 4, 0); this.label27.Name = "label27"; this.label27.Size = new Size(90, 17); this.label27.TabIndex = 31; this.label27.Text = "Temp Offset:"; this.cbDebugMode.AutoSize = true; this.cbDebugMode.Location = new Point(650, 330); this.cbDebugMode.Margin = new Padding(4); this.cbDebugMode.Name = "cbDebugMode"; this.cbDebugMode.Size = new Size(111, 21); this.cbDebugMode.TabIndex = 32; this.cbDebugMode.Text = "Debug Mode"; this.cbDebugMode.UseVisualStyleBackColor = true; this.groupBox6.Controls.Add((Control) this.label33); this.groupBox6.Controls.Add((Control) this.txtSoilTempOffset); this.groupBox6.Controls.Add((Control) this.label30); this.groupBox6.Controls.Add((Control) this.label28); this.groupBox6.Controls.Add((Control) this.cmbSensorTypeSoil); this.groupBox6.Controls.Add((Control) this.label29); this.groupBox6.Controls.Add((Control) this.txtSensorIdSoil); this.groupBox6.Location = new Point(844, 391); this.groupBox6.Margin = new Padding(4); this.groupBox6.Name = "groupBox6"; this.groupBox6.Padding = new Padding(4); this.groupBox6.Size = new Size(220, 148); this.groupBox6.TabIndex = 33; this.groupBox6.TabStop = false; this.groupBox6.Text = "Soil/Water/Other"; this.label33.AutoSize = true; this.label33.Location = new Point(12, 119); this.label33.Margin = new Padding(4, 0, 4, 0); this.label33.Name = "label33"; this.label33.Size = new Size(120, 17); this.label33.TabIndex = 51; this.label33.Text = "S/W Temp Offset:"; this.txtSoilTempOffset.Location = new Point(137, 115); this.txtSoilTempOffset.Margin = new Padding(4); this.txtSoilTempOffset.MaxLength = 5; this.txtSoilTempOffset.Name = "txtSoilTempOffset"; this.txtSoilTempOffset.Size = new Size(64, 22); this.txtSoilTempOffset.TabIndex = 50; this.label30.AutoSize = true; this.label30.Font = new Font("Microsoft Sans Serif", 8.25f, FontStyle.Regular, GraphicsUnit.Point, (byte) 0); this.label30.Location = new Point(8, 25); this.label30.Margin = new Padding(4, 0, 4, 0); this.label30.Name = "label30"; this.label30.Size = new Size(192, 17); this.label30.TabIndex = 46; this.label30.Text = "Post as Soil Temp + Moisture"; this.label28.AutoSize = true; this.label28.Location = new Point(12, 58); this.label28.Margin = new Padding(4, 0, 4, 0); this.label28.Name = "label28"; this.label28.Size = new Size(44, 17); this.label28.TabIndex = 49; this.label28.Text = "Type:"; this.cmbSensorTypeSoil.DropDownStyle = ComboBoxStyle.DropDownList; this.cmbSensorTypeSoil.FormattingEnabled = true; this.cmbSensorTypeSoil.Location = new Point(94, 52); this.cmbSensorTypeSoil.Margin = new Padding(4); this.cmbSensorTypeSoil.Name = "cmbSensorTypeSoil"; this.cmbSensorTypeSoil.Size = new Size(107, 24); this.cmbSensorTypeSoil.TabIndex = 46; this.label29.AutoSize = true; this.label29.Location = new Point(12, 91); this.label29.Margin = new Padding(4, 0, 4, 0); this.label29.Name = "label29"; this.label29.Size = new Size(89, 17); this.label29.TabIndex = 48; this.label29.Text = "ID (optional):"; this.txtSensorIdSoil.Location = new Point(137, 84); this.txtSensorIdSoil.Margin = new Padding(4); this.txtSensorIdSoil.MaxLength = 5; this.txtSensorIdSoil.Name = "txtSensorIdSoil"; this.txtSensorIdSoil.Size = new Size(64, 22); this.txtSensorIdSoil.TabIndex = 47; this.txtWindOffsetPct.Location = new Point(1002, 253); this.txtWindOffsetPct.Margin = new Padding(4); this.txtWindOffsetPct.MaxLength = 5; this.txtWindOffsetPct.Name = "txtWindOffsetPct"; this.txtWindOffsetPct.Size = new Size(40, 22); this.txtWindOffsetPct.TabIndex = 34; this.label31.AutoSize = true; this.label31.Location = new Point(916, 257); this.label31.Margin = new Padding(4, 0, 4, 0); this.label31.Name = "label31"; this.label31.Size = new Size(86, 17); this.label31.TabIndex = 35; this.label31.Text = "Wind Offset:"; this.label32.AutoSize = true; this.label32.Location = new Point(1042, 257); this.label32.Margin = new Padding(4, 0, 4, 0); this.label32.Name = "label32"; this.label32.Size = new Size(20, 17); this.label32.TabIndex = 36; this.label32.Text = "%"; this.groupBox7.Controls.Add((Control) this.label39); this.groupBox7.Controls.Add((Control) this.txtOwAlt); this.groupBox7.Controls.Add((Control) this.label38); this.groupBox7.Controls.Add((Control) this.txtOwStationName); this.groupBox7.Controls.Add((Control) this.label36); this.groupBox7.Controls.Add((Control) this.txtOwLon); this.groupBox7.Controls.Add((Control) this.txtOwLat); this.groupBox7.Controls.Add((Control) this.label37); this.groupBox7.Controls.Add((Control) this.label34); this.groupBox7.Controls.Add((Control) this.txtOwPwd); this.groupBox7.Controls.Add((Control) this.txtOwUsername); this.groupBox7.Controls.Add((Control) this.label35); this.groupBox7.Controls.Add((Control) this.cbPostToOpenWeatherMap); this.groupBox7.Location = new Point(17, 184); this.groupBox7.Name = "groupBox7"; this.groupBox7.Size = new Size(296, 230); this.groupBox7.TabIndex = 37; this.groupBox7.TabStop = false; this.groupBox7.Text = "OpenWeatherMap"; this.label39.AutoSize = true; this.label39.Location = new Point(10, 49); this.label39.Margin = new Padding(4, 0, 4, 0); this.label39.Name = "label39"; this.label39.Size = new Size(97, 17); this.label39.TabIndex = 14; this.label39.Text = "Station Name:"; this.txtOwAlt.Location = new Point(143, 196); this.txtOwAlt.Margin = new Padding(4); this.txtOwAlt.Name = "txtOwAlt"; this.txtOwAlt.Size = new Size(147, 22); this.txtOwAlt.TabIndex = 11; this.label38.AutoSize = true; this.label38.Location = new Point(12, 200); this.label38.Margin = new Padding(4, 0, 4, 0); this.label38.Name = "label38"; this.label38.Size = new Size(116, 17); this.label38.TabIndex = 12; this.label38.Text = "Altitude (meters):"; this.txtOwStationName.Location = new Point(143, 46); this.txtOwStationName.Margin = new Padding(4); this.txtOwStationName.MaxLength = 20; this.txtOwStationName.Name = "txtOwStationName"; this.txtOwStationName.Size = new Size(147, 22); this.txtOwStationName.TabIndex = 13; this.label36.AutoSize = true; this.label36.Location = new Point(11, 141); this.label36.Margin = new Padding(4, 0, 4, 0); this.label36.Name = "label36"; this.label36.Size = new Size(63, 17); this.label36.TabIndex = 7; this.label36.Text = "Latitude:"; this.txtOwLon.Location = new Point(143, 166); this.txtOwLon.Margin = new Padding(4); this.txtOwLon.Name = "txtOwLon"; this.txtOwLon.Size = new Size(147, 22); this.txtOwLon.TabIndex = 9; this.txtOwLat.Location = new Point(143, 136); this.txtOwLat.Margin = new Padding(4); this.txtOwLat.Name = "txtOwLat"; this.txtOwLat.Size = new Size(147, 22); this.txtOwLat.TabIndex = 8; this.label37.AutoSize = true; this.label37.Location = new Point(12, 170); this.label37.Margin = new Padding(4, 0, 4, 0); this.label37.Name = "label37"; this.label37.Size = new Size(75, 17); this.label37.TabIndex = 10; this.label37.Text = "Longitude:"; this.label34.AutoSize = true; this.label34.Location = new Point(9, 81); this.label34.Margin = new Padding(4, 0, 4, 0); this.label34.Name = "label34"; this.label34.Size = new Size(77, 17); this.label34.TabIndex = 3; this.label34.Text = "Username:"; this.txtOwPwd.Location = new Point(141, 106); this.txtOwPwd.Margin = new Padding(4); this.txtOwPwd.Name = "txtOwPwd"; this.txtOwPwd.Size = new Size(147, 22); this.txtOwPwd.TabIndex = 5; this.txtOwPwd.UseSystemPasswordChar = true; this.txtOwUsername.Location = new Point(141, 76); this.txtOwUsername.Margin = new Padding(4); this.txtOwUsername.Name = "txtOwUsername"; this.txtOwUsername.Size = new Size(147, 22); this.txtOwUsername.TabIndex = 4; this.label35.AutoSize = true; this.label35.Location = new Point(10, 110); this.label35.Margin = new Padding(4, 0, 4, 0); this.label35.Name = "label35"; this.label35.Size = new Size(73, 17); this.label35.TabIndex = 6; this.label35.Text = "Password:"; this.cbPostToOpenWeatherMap.AutoSize = true; this.cbPostToOpenWeatherMap.Location = new Point(11, 22); this.cbPostToOpenWeatherMap.Margin = new Padding(4); this.cbPostToOpenWeatherMap.Name = "cbPostToOpenWeatherMap"; this.cbPostToOpenWeatherMap.Size = new Size(228, 21); this.cbPostToOpenWeatherMap.TabIndex = 1; this.cbPostToOpenWeatherMap.Text = "Post Data to OpenWeatherMap"; this.cbPostToOpenWeatherMap.UseVisualStyleBackColor = true; this.groupBox8.Controls.Add((Control) this.label45); this.groupBox8.Controls.Add((Control) this.cmbCwUpdateMinutes); this.groupBox8.Controls.Add((Control) this.label44); this.groupBox8.Controls.Add((Control) this.txtCwPasscode); this.groupBox8.Controls.Add((Control) this.label43); this.groupBox8.Controls.Add((Control) this.label42); this.groupBox8.Controls.Add((Control) this.txtCwLon); this.groupBox8.Controls.Add((Control) this.txtCwLat); this.groupBox8.Controls.Add((Control) this.cbPostToCw); this.groupBox8.Controls.Add((Control) this.label40); this.groupBox8.Controls.Add((Control) this.txtCwHostName); this.groupBox8.Controls.Add((Control) this.txtCwRegNum); this.groupBox8.Controls.Add((Control) this.label41); this.groupBox8.Location = new Point(325, 184); this.groupBox8.Margin = new Padding(4); this.groupBox8.Name = "groupBox8"; this.groupBox8.Padding = new Padding(4); this.groupBox8.Size = new Size(296, 230); this.groupBox8.TabIndex = 17; this.groupBox8.TabStop = false; this.groupBox8.Text = "CWOP"; this.label45.AutoSize = true; this.label45.Location = new Point(9, 200); this.label45.Margin = new Padding(4, 0, 4, 0); this.label45.Name = "label45"; this.label45.Size = new Size(192, 17); this.label45.TabIndex = 27; this.label45.Text = "Update Frequency (minutes):"; this.cmbCwUpdateMinutes.DropDownStyle = ComboBoxStyle.DropDownList; this.cmbCwUpdateMinutes.FormattingEnabled = true; this.cmbCwUpdateMinutes.Location = new Point(209, 196); this.cmbCwUpdateMinutes.Margin = new Padding(4); this.cmbCwUpdateMinutes.Name = "cmbCwUpdateMinutes"; this.cmbCwUpdateMinutes.Size = new Size(78, 24); this.cmbCwUpdateMinutes.TabIndex = 26; this.label44.AutoSize = true; this.label44.Location = new Point(9, 81); this.label44.Margin = new Padding(4, 0, 4, 0); this.label44.Name = "label44"; this.label44.Size = new Size((int) sbyte.MaxValue, 17); this.label44.TabIndex = 7; this.label44.Text = "Passcode or Val #:"; this.txtCwPasscode.Location = new Point(140, 80); this.txtCwPasscode.Margin = new Padding(4); this.txtCwPasscode.Name = "txtCwPasscode"; this.txtCwPasscode.Size = new Size(147, 22); this.txtCwPasscode.TabIndex = 8; this.label43.AutoSize = true; this.label43.Location = new Point(8, 143); this.label43.Margin = new Padding(4, 0, 4, 0); this.label43.Name = "label43"; this.label43.Size = new Size(119, 17); this.label43.TabIndex = 6; this.label43.Text = "Lon dddmm.hhW:"; this.label42.AutoSize = true; this.label42.Location = new Point(9, 112); this.label42.Margin = new Padding(4, 0, 4, 0); this.label42.Name = "label42"; this.label42.Size = new Size(104, 17); this.label42.TabIndex = 5; this.label42.Text = "Lat ddmm.hhN:"; this.txtCwLon.Location = new Point(140, 139); this.txtCwLon.Margin = new Padding(4); this.txtCwLon.MaxLength = 9; this.txtCwLon.Name = "txtCwLon"; this.txtCwLon.Size = new Size(147, 22); this.txtCwLon.TabIndex = 4; this.txtCwLat.Location = new Point(140, 110); this.txtCwLat.Margin = new Padding(4); this.txtCwLat.MaxLength = 8; this.txtCwLat.Name = "txtCwLat"; this.txtCwLat.Size = new Size(147, 22); this.txtCwLat.TabIndex = 3; this.cbPostToCw.AutoSize = true; this.cbPostToCw.Location = new Point(11, 23); this.cbPostToCw.Margin = new Padding(4); this.cbPostToCw.Name = "cbPostToCw"; this.cbPostToCw.Size = new Size(154, 21); this.cbPostToCw.TabIndex = 0; this.cbPostToCw.Text = "Post Data to CWOP"; this.cbPostToCw.UseVisualStyleBackColor = true; this.label40.AutoSize = true; this.label40.Location = new Point(9, 53); this.label40.Margin = new Padding(4, 0, 4, 0); this.label40.Name = "label40"; this.label40.Size = new Size(120, 17); this.label40.TabIndex = 0; this.label40.Text = "Reg # or Callsign:"; this.txtCwHostName.Location = new Point(140, 168); this.txtCwHostName.Margin = new Padding(4); this.txtCwHostName.Name = "txtCwHostName"; this.txtCwHostName.Size = new Size(147, 22); this.txtCwHostName.TabIndex = 2; this.txtCwRegNum.Location = new Point(140, 52); this.txtCwRegNum.Margin = new Padding(4); this.txtCwRegNum.Name = "txtCwRegNum"; this.txtCwRegNum.Size = new Size(147, 22); this.txtCwRegNum.TabIndex = 1; this.label41.AutoSize = true; this.label41.Location = new Point(8, 173); this.label41.Margin = new Padding(4, 0, 4, 0); this.label41.Name = "label41"; this.label41.Size = new Size(82, 17); this.label41.TabIndex = 2; this.label41.Text = "Host Name:"; this.txtHumidityOffset.Location = new Point(1177, 253); this.txtHumidityOffset.Margin = new Padding(4); this.txtHumidityOffset.MaxLength = 5; this.txtHumidityOffset.Name = "txtHumidityOffset"; this.txtHumidityOffset.Size = new Size(40, 22); this.txtHumidityOffset.TabIndex = 38; this.label46.AutoSize = true; this.label46.Location = new Point(1068, 256); this.label46.Margin = new Padding(4, 0, 4, 0); this.label46.Name = "label46"; this.label46.Size = new Size(108, 17); this.label46.TabIndex = 39; this.label46.Text = "Humidity Offset:"; this.AutoScaleDimensions = new SizeF(8f, 16f); this.AutoScaleMode = AutoScaleMode.Font; this.AutoSize = true; this.ClientSize = new Size(1231, 548); this.Controls.Add((Control) this.label46); this.Controls.Add((Control) this.txtHumidityOffset); this.Controls.Add((Control) this.groupBox8); this.Controls.Add((Control) this.groupBox7); this.Controls.Add((Control) this.label32); this.Controls.Add((Control) this.txtWindOffsetPct); this.Controls.Add((Control) this.label31); this.Controls.Add((Control) this.groupBox6); this.Controls.Add((Control) this.cbDebugMode); this.Controls.Add((Control) this.txtTempOffset); this.Controls.Add((Control) this.label27); this.Controls.Add((Control) this.label26); this.Controls.Add((Control) this.txtCsvFilePath); this.Controls.Add((Control) this.groupBox5); this.Controls.Add((Control) this.groupBox4); this.Controls.Add((Control) this.cmbSensorType); this.Controls.Add((Control) this.label11); this.Controls.Add((Control) this.txtFilterOnSensorId); this.Controls.Add((Control) this.label10); this.Controls.Add((Control) this.groupBox3); this.Controls.Add((Control) this.cbWriteToCSV); this.Controls.Add((Control) this.groupBox2); this.Controls.Add((Control) this.btnCancel); this.Controls.Add((Control) this.btnSave); this.Controls.Add((Control) this.GroupBox1); this.Controls.Add((Control) this.txtPressureOffset); this.Controls.Add((Control) this.Label4); this.Controls.Add((Control) this.Label3); this.Controls.Add((Control) this.cmbDeviceId); this.Margin = new Padding(4); this.MaximizeBox = false; this.MinimizeBox = false; this.MinimumSize = new Size(1249, 595); this.Name = "frmSetup"; this.Text = "Setup"; this.Load += new EventHandler(this.frmSetup_Load); this.GroupBox1.ResumeLayout(false); this.GroupBox1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); this.groupBox4.ResumeLayout(false); this.groupBox4.PerformLayout(); this.groupBox5.ResumeLayout(false); this.groupBox5.PerformLayout(); this.groupBox6.ResumeLayout(false); this.groupBox6.PerformLayout(); this.groupBox7.ResumeLayout(false); this.groupBox7.PerformLayout(); this.groupBox8.ResumeLayout(false); this.groupBox8.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Base.UInt128 // Assembly: PcapDotNet.Base, Version=0.10.0.20668, Culture=neutral, PublicKeyToken=<KEY> // MVID: E9656A63-0145-422C-B8C8-79FDD7FB4270 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Base.dll using System; using System.Globalization; using System.Numerics; using System.Runtime.InteropServices; namespace PcapDotNet.Base { [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct UInt128 : IComparable<UInt128>, IEquatable<UInt128>, IFormattable { public static readonly UInt128 MinValue = (UInt128) 0UL; public static readonly UInt128 MaxValue = new UInt128(ulong.MaxValue, ulong.MaxValue); public static readonly UInt128 Zero = (UInt128) 0UL; public static readonly UInt128 One = (UInt128) 1UL; public const int SizeOf = 16; private readonly ulong _leastSignificant; private readonly ulong _mostSignificant; public UInt128(ulong mostSignificant, ulong leastSignificant) { this._mostSignificant = mostSignificant; this._leastSignificant = leastSignificant; } public UInt128(BigInteger value) { this = new UInt128((ulong) (value >> 64), (ulong) (value & (BigInteger) ulong.MaxValue)); } public static explicit operator UInt128(BigInteger value) { return new UInt128(value); } public static implicit operator BigInteger(UInt128 value) { return value.ToBigInteger(); } public static implicit operator UInt128(ulong value) { return new UInt128(0UL, value); } public static explicit operator ulong(UInt128 value) { if ((long) value._mostSignificant != 0L) throw new OverflowException("Value was too large for a UInt64."); return value._leastSignificant; } public static bool operator ==(UInt128 value1, UInt128 value2) { return value1.Equals(value2); } public static bool operator !=(UInt128 value1, UInt128 value2) { return !(value1 == value2); } public static bool operator <(UInt128 value1, UInt128 value2) { return value1.CompareTo(value2) < 0; } public static bool operator >(UInt128 value1, UInt128 value2) { return value1.CompareTo(value2) > 0; } public static bool operator <=(UInt128 value1, UInt128 value2) { return value1.CompareTo(value2) <= 0; } public static bool operator >=(UInt128 value1, UInt128 value2) { return value1.CompareTo(value2) >= 0; } public static UInt128 operator >>(UInt128 value, int numberOfBits) { return UInt128.RightShift(value, numberOfBits); } public static UInt128 operator <<(UInt128 value, int numberOfBits) { return UInt128.LeftShift(value, numberOfBits); } public static UInt128 operator &(UInt128 value1, UInt128 value2) { return UInt128.BitwiseAnd(value1, value2); } public static UInt128 operator +(UInt128 value1, UInt128 value2) { return UInt128.Add(value1, value2); } public static UInt128 operator -(UInt128 value1, UInt128 value2) { return UInt128.Subtract(value1, value2); } public static UInt128 Parse(string value, NumberStyles style, IFormatProvider provider) { BigInteger bigInteger = BigInteger.Parse(value, style, provider); if (bigInteger < 0L || bigInteger > (BigInteger) UInt128.MaxValue) throw new OverflowException("Value was either too large or too small for an UInt128."); return (UInt128) bigInteger; } public static UInt128 Parse(string value, IFormatProvider provider) { return UInt128.Parse(value, NumberStyles.Integer, provider); } public static UInt128 Parse(string value, NumberStyles style) { return UInt128.Parse(value, style, (IFormatProvider) CultureInfo.CurrentCulture); } public static UInt128 Parse(string value) { return UInt128.Parse(value, NumberStyles.Integer, (IFormatProvider) CultureInfo.CurrentCulture); } public static bool TryParse(string value, NumberStyles style, IFormatProvider provider, out UInt128 result) { BigInteger result1; bool flag = BigInteger.TryParse(value, style, provider, out result1); if (flag && (result1 < 0L || result1 > (BigInteger) UInt128.MaxValue)) { result = UInt128.Zero; return false; } result = (UInt128) result1; return flag; } public static bool TryParse(string value, out UInt128 result) { return UInt128.TryParse(value, NumberStyles.Integer, (IFormatProvider) CultureInfo.CurrentCulture, out result); } public bool Equals(UInt128 other) { if ((long) this._mostSignificant == (long) other._mostSignificant) return (long) this._leastSignificant == (long) other._leastSignificant; return false; } public override bool Equals(object obj) { if (obj is UInt128) return this.Equals((UInt128) obj); return false; } public int CompareTo(UInt128 other) { if ((long) this._mostSignificant != (long) other._mostSignificant) return this._mostSignificant.CompareTo(other._mostSignificant); return this._leastSignificant.CompareTo(other._leastSignificant); } public static UInt128 RightShift(UInt128 value, int numberOfBits) { if (numberOfBits >= 128) return UInt128.Zero; if (numberOfBits >= 64) return new UInt128(0UL, value._mostSignificant >> numberOfBits - 64); if (numberOfBits == 0) return value; return new UInt128(value._mostSignificant >> numberOfBits, (value._leastSignificant >> numberOfBits) + (value._mostSignificant << 64 - numberOfBits)); } public static UInt128 LeftShift(UInt128 value, int numberOfBits) { numberOfBits %= 128; if (numberOfBits >= 64) return new UInt128(value._leastSignificant << numberOfBits - 64, 0UL); if (numberOfBits == 0) return value; return new UInt128((value._mostSignificant << numberOfBits) + (value._leastSignificant >> 64 - numberOfBits), value._leastSignificant << numberOfBits); } public static UInt128 BitwiseAnd(UInt128 value1, UInt128 value2) { return new UInt128(value1._mostSignificant & value2._mostSignificant, value1._leastSignificant & value2._leastSignificant); } public static UInt128 Add(UInt128 value1, UInt128 value2) { ulong leastSignificant = value1._leastSignificant + value2._leastSignificant; bool flag = leastSignificant < Math.Max(value1._leastSignificant, value2._leastSignificant); return new UInt128((ulong) ((long) value1._mostSignificant + (long) value2._mostSignificant + (flag ? 1L : 0L)), leastSignificant); } public static UInt128 Subtract(UInt128 value1, UInt128 value2) { ulong leastSignificant = value1._leastSignificant - value2._leastSignificant; bool flag = leastSignificant > value1._leastSignificant; return new UInt128((ulong) ((long) value1._mostSignificant - (long) value2._mostSignificant - (flag ? 1L : 0L)), leastSignificant); } public override int GetHashCode() { return Sequence.GetHashCode((object) this._mostSignificant, (object) this._leastSignificant); } public string ToString(string format, IFormatProvider formatProvider) { return (BigInteger) this.ToString(format, formatProvider); } public string ToString(string format) { return this.ToString(format, (IFormatProvider) CultureInfo.CurrentCulture); } public string ToString(IFormatProvider provider) { return this.ToString("G", provider); } public override string ToString() { return this.ToString((IFormatProvider) CultureInfo.CurrentCulture); } private BigInteger ToBigInteger() { return ((BigInteger) this._mostSignificant << 64) + (BigInteger) this._leastSignificant; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Arp.ArpOperation // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Arp { public enum ArpOperation : ushort { None = (ushort) 0, Request = (ushort) 1, Reply = (ushort) 2, ReverseRequest = (ushort) 3, ReverseReply = (ushort) 4, DynamicReverseRequest = (ushort) 5, DynamicReverseReply = (ushort) 6, DynamicReverseError = (ushort) 7, InverseRequest = (ushort) 8, InverseReply = (ushort) 9, NegativeAtmReply = (ushort) 10, MultipleAccessOverSynchronousOpticalNetworkingOrSynchronousDigitalHierarchyUnsolicitedArp = (ushort) 23, Experimental1 = (ushort) 24, Experimental2 = (ushort) 25, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IpV4OptionBasicSecurity // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.IpV4 { [OptionTypeRegistration(typeof (IpV4OptionType), IpV4OptionType.BasicSecurity)] public sealed class IpV4OptionBasicSecurity : IpV4OptionComplex, IOptionComplexFactory, IEquatable<IpV4OptionBasicSecurity> { public const int OptionMinimumLength = 3; public const int OptionValueMinimumLength = 1; private readonly IpV4OptionSecurityClassificationLevel _classificationLevel; private readonly IpV4OptionSecurityProtectionAuthorities _protectionAuthorities; private readonly byte _length; public IpV4OptionSecurityClassificationLevel ClassificationLevel { get { return this._classificationLevel; } } public IpV4OptionSecurityProtectionAuthorities ProtectionAuthorities { get { return this._protectionAuthorities; } } public override int Length { get { return (int) this._length; } } public override bool IsAppearsAtMostOnce { get { return true; } } public IpV4OptionBasicSecurity(IpV4OptionSecurityClassificationLevel classificationLevel, IpV4OptionSecurityProtectionAuthorities protectionAuthorities, byte length) : base(IpV4OptionType.BasicSecurity) { if ((int) length < 3) throw new ArgumentOutOfRangeException("length", (object) length, "Minimum option length is " + (object) 3); if ((int) length == 3 && protectionAuthorities != IpV4OptionSecurityProtectionAuthorities.None) throw new ArgumentException("Can't have a protection authority without minimum of " + (object) 2 + " length", "protectionAuthorities"); if (classificationLevel != IpV4OptionSecurityClassificationLevel.Confidential && classificationLevel != IpV4OptionSecurityClassificationLevel.Secret && (classificationLevel != IpV4OptionSecurityClassificationLevel.TopSecret && classificationLevel != IpV4OptionSecurityClassificationLevel.Unclassified)) throw new ArgumentException("Invalid classification level " + (object) classificationLevel); this._classificationLevel = classificationLevel; this._protectionAuthorities = protectionAuthorities; this._length = length; } public IpV4OptionBasicSecurity(IpV4OptionSecurityClassificationLevel classificationLevel) : this(classificationLevel, IpV4OptionSecurityProtectionAuthorities.None, (byte) 3) { } public IpV4OptionBasicSecurity() : this(IpV4OptionSecurityClassificationLevel.Unclassified) { } public bool Equals(IpV4OptionBasicSecurity other) { if (other == null || this.ClassificationLevel != other.ClassificationLevel || this.ProtectionAuthorities != other.ProtectionAuthorities) return false; return this.Length == other.Length; } public override bool Equals(IpV4Option other) { return this.Equals(other as IpV4OptionBasicSecurity); } public override int GetHashCode() { return base.GetHashCode() ^ BitSequence.Merge((byte) this.ClassificationLevel, (byte) this.ProtectionAuthorities, (byte) this.Length).GetHashCode(); } Option IOptionComplexFactory.CreateInstance(byte[] buffer, ref int offset, byte valueLength) { if ((int) valueLength < 1) return (Option) null; IpV4OptionSecurityClassificationLevel classificationLevel = (IpV4OptionSecurityClassificationLevel) buffer[offset++]; switch (classificationLevel) { case IpV4OptionSecurityClassificationLevel.Confidential: case IpV4OptionSecurityClassificationLevel.Secret: case IpV4OptionSecurityClassificationLevel.TopSecret: case IpV4OptionSecurityClassificationLevel.Unclassified: int num = (int) valueLength - 1; IpV4OptionSecurityProtectionAuthorities protectionAuthorities = IpV4OptionSecurityProtectionAuthorities.None; if (num > 0) { for (int index = 0; index < num - 1; ++index) { if (((int) buffer[offset + index] & 1) == 0) return (Option) null; } if (((int) buffer[offset + num - 1] & 1) != 0) return (Option) null; protectionAuthorities = (IpV4OptionSecurityProtectionAuthorities) ((uint) buffer[offset] & 254U); } offset += num; return (Option) new IpV4OptionBasicSecurity(classificationLevel, protectionAuthorities, (byte) (3 + num)); default: return (Option) null; } } internal override void Write(byte[] buffer, ref int offset) { base.Write(buffer, ref offset); buffer[offset++] = (byte) this.ClassificationLevel; int num = this.Length - 3; if (num <= 0) return; buffer[offset++] = (byte) this.ProtectionAuthorities; if (num <= 1) return; buffer[offset - 1] |= (byte) 1; for (int index = 0; index != num - 2; ++index) buffer[offset++] = (byte) 1; buffer[offset++] = (byte) 0; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Http.HttpTransferEncodingField // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text.RegularExpressions; namespace PcapDotNet.Packets.Http { public sealed class HttpTransferEncodingField : HttpField, IEquatable<HttpTransferEncodingField> { private static readonly Regex _transferExtensionRegex = HttpRegex.Concat(HttpRegex.Token, HttpRegex.OptionalParameters); private static readonly Regex _transferCodingRegex = HttpRegex.Capture(HttpRegex.Or(HttpRegex.Build("chunked"), HttpTransferEncodingField._transferExtensionRegex), "TransferCoding"); private static readonly Regex _regex = HttpRegex.MatchEntire(HttpRegex.CommaSeparatedRegex(HttpTransferEncodingField._transferCodingRegex, 1)); public const string FieldName = "Transfer-Encoding"; public const string FieldNameUpper = "TRANSFER-ENCODING"; private const string RegexTransferCodingGroupName = "TransferCoding"; private ReadOnlyCollection<string> _transferCodings; public ReadOnlyCollection<string> TransferCodings { get { return this._transferCodings; } } public HttpTransferEncodingField(IList<string> transferCodings) : base("Transfer-Encoding", IEnumerableExtensions.SequenceToString<string>((IEnumerable<string>) transferCodings, ",")) { this.SetTransferCodings(transferCodings); } public HttpTransferEncodingField(params string[] transferCodings) : this((IList<string>) transferCodings) { } internal HttpTransferEncodingField(byte[] fieldValue) : base("Transfer-Encoding", (IList<byte>) fieldValue) { string @string = HttpRegex.GetString(fieldValue); Match match = HttpTransferEncodingField._regex.Match(@string); if (!match.Success) return; this.SetTransferCodings((IList<string>) Enumerable.ToArray<string>(MatchExtensions.GroupCapturesValues(match, "TransferCoding"))); } public bool Equals(HttpTransferEncodingField other) { if (other == null) return false; if (object.ReferenceEquals((object) this.TransferCodings, (object) other.TransferCodings)) return true; if (this.TransferCodings != null && other.TransferCodings != null) return Enumerable.SequenceEqual<string>((IEnumerable<string>) this.TransferCodings, (IEnumerable<string>) other.TransferCodings); return false; } public override bool Equals(HttpField other) { return this.Equals(other as HttpTransferEncodingField); } [SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")] private void SetTransferCodings(IList<string> transferCodings) { if (Enumerable.Any<string>((IEnumerable<string>) transferCodings, (Func<string, bool>) (coding => Enumerable.Any<char>((IEnumerable<char>) coding, (Func<char, bool>) (c => CharExtensions.IsUppercaseAlpha(c)))))) this._transferCodings = IListExtensions.AsReadOnly<string>((IList<string>) Enumerable.ToArray<string>(Enumerable.Select<string, string>((IEnumerable<string>) transferCodings, (Func<string, string>) (coding => coding.ToLowerInvariant())))); else this._transferCodings = IListExtensions.AsReadOnly<string>(transferCodings); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataDomainNames // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace PcapDotNet.Packets.Dns { public abstract class DnsResourceDataDomainNames : DnsResourceData, IEquatable<DnsResourceDataDomainNames> { internal ReadOnlyCollection<DnsDomainName> DomainNames { get; private set; } internal DnsResourceDataDomainNames(ReadOnlyCollection<DnsDomainName> domainNames) { this.DomainNames = domainNames; } internal DnsResourceDataDomainNames(params DnsDomainName[] domainNames) : this(IListExtensions.AsReadOnly<DnsDomainName>((IList<DnsDomainName>) domainNames)) { } public bool Equals(DnsResourceDataDomainNames other) { if (other != null && this.GetType() == other.GetType()) return Enumerable.SequenceEqual<DnsDomainName>((IEnumerable<DnsDomainName>) this.DomainNames, (IEnumerable<DnsDomainName>) other.DomainNames); return false; } public override sealed bool Equals(object obj) { return this.Equals(obj as DnsResourceDataDomainNames); } public override sealed int GetHashCode() { return this.GetType().GetHashCode() ^ IEnumerableExtensions.SequenceGetHashCode<DnsDomainName>((IEnumerable<DnsDomainName>) this.DomainNames); } internal override int GetLength(DnsDomainNameCompressionData compressionData, int offsetInDns) { int num = 0; foreach (DnsDomainName dnsDomainName in this.DomainNames) { int length = dnsDomainName.GetLength(compressionData, offsetInDns); offsetInDns += length; num += length; } return num; } internal override int WriteData(byte[] buffer, int dnsOffset, int offsetInDns, DnsDomainNameCompressionData compressionData) { int num = 0; foreach (DnsDomainName dnsDomainName in this.DomainNames) num += dnsDomainName.Write(buffer, dnsOffset, compressionData, offsetInDns + num); return num; } internal static List<DnsDomainName> ReadDomainNames(DnsDatagram dns, int offsetInDns, int length, int numExpected = 0) { List<DnsDomainName> list = new List<DnsDomainName>(numExpected); while (length != 0) { DnsDomainName domainName; int numBytesRead; if (!DnsDomainName.TryParse(dns, offsetInDns, length, out domainName, out numBytesRead)) return (List<DnsDomainName>) null; offsetInDns += numBytesRead; length -= numBytesRead; list.Add(domainName); } return list; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataUri // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.Uri)] public sealed class DnsResourceDataUri : DnsResourceDataSimple, IEquatable<DnsResourceDataUri> { private const int ConstantPartLength = 4; public ushort Priority { get; private set; } public ushort Weight { get; private set; } public ReadOnlyCollection<DataSegment> Target { get; private set; } public DnsResourceDataUri(ushort priority, ushort weight, IList<DataSegment> target) { this.Priority = priority; this.Weight = weight; this.Target = IListExtensions.AsReadOnly<DataSegment>(target); } internal DnsResourceDataUri() : this((ushort) 0, (ushort) 0, (IList<DataSegment>) new DataSegment[0]) { } public bool Equals(DnsResourceDataUri other) { if (other != null && this.Priority.Equals(other.Priority) && this.Weight.Equals(other.Weight)) return Enumerable.SequenceEqual<DataSegment>((IEnumerable<DataSegment>) this.Target, (IEnumerable<DataSegment>) other.Target); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataUri); } public override int GetHashCode() { return BitSequence.Merge(this.Priority, this.Weight).GetHashCode() ^ IEnumerableExtensions.SequenceGetHashCode<DataSegment>((IEnumerable<DataSegment>) this.Target); } internal override int GetLength() { return 4 + Enumerable.Sum<DataSegment>((IEnumerable<DataSegment>) this.Target, (Func<DataSegment, int>) (targetPart => DnsResourceData.GetStringLength(targetPart))); } internal override void WriteDataSimple(byte[] buffer, int offset) { ByteArrayExtensions.Write(buffer, offset, this.Priority, Endianity.Big); ByteArrayExtensions.Write(buffer, offset + 2, this.Weight, Endianity.Big); int offset1 = offset + 4; foreach (DataSegment str in this.Target) DnsResourceData.WriteString(buffer, ref offset1, str); } internal override DnsResourceData CreateInstance(DataSegment data) { if (data.Length < 4) return (DnsResourceData) null; ushort priority = data.ReadUShort(0, Endianity.Big); ushort weight = data.ReadUShort(2, Endianity.Big); List<DataSegment> list = new List<DataSegment>(); int offset = 4; while (data.Length > offset) { DataSegment dataSegment = DnsResourceData.ReadString(data, ref offset); if (dataSegment == null) return (DnsResourceData) null; list.Add(dataSegment); } return (DnsResourceData) new DnsResourceDataUri(priority, weight, (IList<DataSegment>) list); } private static class Offset { public const int Priority = 0; public const int Weight = 2; public const int Target = 4; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpMessageTypeAndCode // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Icmp { public enum IcmpMessageTypeAndCode : ushort { EchoReply = (ushort) 0, DestinationUnreachableNetUnreachable = (ushort) 768, DestinationUnreachableHostUnreachable = (ushort) 769, DestinationUnreachableProtocolUnreachable = (ushort) 770, DestinationUnreachablePortUnreachable = (ushort) 771, DestinationUnreachableFragmentationNeededAndDoNotFragmentSet = (ushort) 772, DestinationUnreachableSourceRouteFailed = (ushort) 773, SourceQuench = (ushort) 1024, RedirectDatagramsForTheNetwork = (ushort) 1280, RedirectDatagramsForTheHost = (ushort) 1281, RedirectDatagramsForTheTypeOfServiceAndNetwork = (ushort) 1282, RedirectDatagramsForTheTypeOfServiceAndHost = (ushort) 1283, Echo = (ushort) 2048, RouterAdvertisement = (ushort) 2304, RouterSolicitation = (ushort) 2560, TimeExceededTimeToLive = (ushort) 2816, TimeExceededFragmentReassembly = (ushort) 2817, ParameterProblemPointerIndicatesTheError = (ushort) 3072, Timestamp = (ushort) 3328, TimestampReply = (ushort) 3584, InformationRequest = (ushort) 3840, InformationReply = (ushort) 4096, AddressMaskRequest = (ushort) 4352, AddressMaskReply = (ushort) 4608, TraceRouteOutboundPacketSuccessfullyForwarded = (ushort) 7680, TraceRouteNoRouteForOutboundPacketDiscarded = (ushort) 7681, ConversionFailedUnknownOrUnspecifiedError = (ushort) 7936, ConversionFailedDoNotConvertOptionPresent = (ushort) 7937, ConversionFailedUnknownMandatoryOptionPresent = (ushort) 7938, ConversionFailedKnownUnsupportedOptionPresent = (ushort) 7939, ConversionFailedUnsupportedTransportProtocol = (ushort) 7940, ConversionFailedOverallLengthExceeded = (ushort) 7941, ConversionFailedIpHeaderLengthExceeded = (ushort) 7942, ConversionFailedTransportProtocolIsBiggerThan255 = (ushort) 7943, ConversionFailedPortConversionOutOfRange = (ushort) 7944, ConversionFailedTransportHeaderLengthExceeded = (ushort) 7945, ConversionFailed32BitRolloverMissingAndAckSet = (ushort) 7946, ConversionFailedUnknownMandatoryTransportOptionPresent = (ushort) 7947, DomainNameRequest = (ushort) 9472, DomainNameReply = (ushort) 9728, SecurityFailuresBadSecurityParametersIndex = (ushort) 10240, SecurityFailuresAuthenticationFailed = (ushort) 10241, SecurityFailuresDecompressionFailed = (ushort) 10242, SecurityFailuresDecryptionFailed = (ushort) 10243, SecurityFailuresNeedAuthentication = (ushort) 10244, SecurityFailuresNeedAuthorization = (ushort) 10245, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IpV4OptionComplex // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.IpV4 { public abstract class IpV4OptionComplex : IpV4Option { public const int OptionHeaderLength = 2; protected IpV4OptionComplex(IpV4OptionType type) : base(type) { } internal override void Write(byte[] buffer, ref int offset) { base.Write(buffer, ref offset); buffer[offset++] = (byte) this.Length; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataStrings // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace PcapDotNet.Packets.Dns { public abstract class DnsResourceDataStrings : DnsResourceDataSimple, IEquatable<DnsResourceDataStrings> { internal ReadOnlyCollection<DataSegment> Strings { get; private set; } internal DnsResourceDataStrings(ReadOnlyCollection<DataSegment> strings) { this.Strings = strings; } internal DnsResourceDataStrings(params DataSegment[] strings) : this(IListExtensions.AsReadOnly<DataSegment>((IList<DataSegment>) strings)) { } public bool Equals(DnsResourceDataStrings other) { if (other != null && this.GetType() == other.GetType()) return Enumerable.SequenceEqual<DataSegment>((IEnumerable<DataSegment>) this.Strings, (IEnumerable<DataSegment>) other.Strings); return false; } public override sealed bool Equals(object obj) { return this.Equals(obj as DnsResourceDataStrings); } public override int GetHashCode() { return this.GetType().GetHashCode() ^ IEnumerableExtensions.SequenceGetHashCode<DataSegment>((IEnumerable<DataSegment>) this.Strings); } internal override sealed int GetLength() { return Enumerable.Sum<DataSegment>((IEnumerable<DataSegment>) this.Strings, (Func<DataSegment, int>) (str => 1 + str.Length)); } internal override sealed void WriteDataSimple(byte[] buffer, int offset) { foreach (DataSegment dataSegment in this.Strings) { ByteArrayExtensions.Write(buffer, ref offset, (byte) dataSegment.Length); dataSegment.Write(buffer, ref offset); } } internal static List<DataSegment> ReadStrings(DataSegment data, int numExpected = 0) { List<DataSegment> list = new List<DataSegment>(numExpected); int offset = 0; while (offset != data.Length) { DataSegment dataSegment = DnsResourceData.ReadString(data, ref offset); if (dataSegment == null) return (List<DataSegment>) null; list.Add(dataSegment); } return list; } } } <file_sep>Weather Underground .Net API (Also Weather.com) ===================================================== This library implements the forecast features of the Wunderground.com Weather API. http://www.wunderground.com/weather/api NuGet Package: ------------------- https://nuget.org/packages/WUnderground.Net<file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Igmp.IgmpMessageType // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Igmp { public enum IgmpMessageType : byte { None = (byte) 0, CreateGroupRequestVersion0 = (byte) 1, CreateGroupReplyVersion0 = (byte) 2, JoinGroupRequestVersion0 = (byte) 3, JoinGroupReplyVersion0 = (byte) 4, LeaveGroupRequestVersion0 = (byte) 5, LeaveGroupReplyVersion0 = (byte) 6, ConfirmGroupRequestVersion0 = (byte) 7, ConfirmGroupReplyVersion0 = (byte) 8, MembershipQuery = (byte) 17, MembershipReportVersion1 = (byte) 18, MembershipReportVersion2 = (byte) 22, LeaveGroupVersion2 = (byte) 23, MulticastTraceRouteResponse = (byte) 30, MulticastTraceRoute = (byte) 31, MembershipReportVersion3 = (byte) 34, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Arp.IArpPreviousLayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; namespace PcapDotNet.Packets.Arp { public interface IArpPreviousLayer : ILayer { ArpHardwareType PreviousLayerHardwareType { get; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Base.InlineEqualityComparer`1 // Assembly: PcapDotNet.Base, Version=0.10.0.20668, Culture=neutral, PublicKeyToken=<KEY> // MVID: E9656A63-0145-422C-B8C8-79FDD7FB4270 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Base.dll using System; using System.Collections.Generic; namespace PcapDotNet.Base { public class InlineEqualityComparer<T> : IEqualityComparer<T> { private Func<T, T, bool> EqualsFunc { get; set; } private Func<T, int> GetHashCodeFunc { get; set; } public InlineEqualityComparer(Func<T, T, bool> equals, Func<T, int> getHashCode) { this.EqualsFunc = equals; this.GetHashCodeFunc = getHashCode; } bool IEqualityComparer<T>.Equals(T x, T y) { return this.EqualsFunc(x, y); } int IEqualityComparer<T>.GetHashCode(T obj) { return this.GetHashCodeFunc(obj); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.DataLink // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using System; namespace PcapDotNet.Packets { public struct DataLink : IDataLink, IEquatable<DataLink> { private static readonly DataLink _ethernet = new DataLink(DataLinkKind.Ethernet); private static readonly DataLink _ipV4 = new DataLink(DataLinkKind.IpV4); private readonly DataLinkKind _kind; public static DataLink Ethernet { get { return DataLink._ethernet; } } public static DataLink IpV4 { get { return DataLink._ipV4; } } public DataLinkKind Kind { get { return this._kind; } } public DataLink(DataLinkKind kind) { this._kind = kind; } public static bool operator ==(DataLink dataLink1, DataLink dataLink2) { return dataLink1.Equals(dataLink2); } public static bool operator !=(DataLink dataLink1, DataLink dataLink2) { return !(dataLink1 == dataLink2); } public bool Equals(DataLink other) { return this.Kind == other.Kind; } public override bool Equals(object obj) { if (obj is DataLink) return this.Equals((DataLink) obj); return false; } public override int GetHashCode() { return this._kind.GetHashCode(); } public override string ToString() { return this.Kind.ToString(); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IpV4OptionTimestampType // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.IpV4 { public enum IpV4OptionTimestampType : byte { TimestampOnly = (byte) 0, AddressAndTimestamp = (byte) 1, AddressPrespecified = (byte) 3, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpTraceRouteLayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Icmp { public sealed class IcmpTraceRouteLayer : IcmpLayer { public IcmpCodeTraceRoute Code { get; set; } public ushort Identification { get; set; } public ushort OutboundHopCount { get; set; } public ushort ReturnHopCount { get; set; } public uint OutputLinkSpeed { get; set; } public uint OutputLinkMaximumTransmissionUnit { get; set; } public override IcmpMessageType MessageType { get { return IcmpMessageType.TraceRoute; } } protected override int PayloadLength { get { return 12; } } public override byte CodeValue { get { return (byte) this.Code; } } protected override uint Variable { get { return (uint) this.Identification << 16; } } protected override void WritePayload(byte[] buffer, int offset) { IcmpTraceRouteDatagram.WriteHeaderAdditional(buffer, offset, this.OutboundHopCount, this.ReturnHopCount, this.OutputLinkSpeed, this.OutputLinkMaximumTransmissionUnit); } protected override bool EqualPayload(IcmpLayer other) { return this.EqualPayload(other as IcmpTraceRouteLayer); } private bool EqualPayload(IcmpTraceRouteLayer other) { if (other != null && (int) this.OutboundHopCount == (int) other.OutboundHopCount && ((int) this.ReturnHopCount == (int) other.ReturnHopCount && (int) this.OutputLinkSpeed == (int) other.OutputLinkSpeed)) return (int) this.OutputLinkMaximumTransmissionUnit == (int) other.OutputLinkMaximumTransmissionUnit; return false; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Base.UInt24 // Assembly: PcapDotNet.Base, Version=0.10.0.20668, Culture=neutral, PublicKeyToken=<KEY> // MVID: E9656A63-0145-422C-B8C8-79FDD7FB4270 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Base.dll using System; using System.Globalization; using System.Runtime.InteropServices; namespace PcapDotNet.Base { [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct UInt24 { public static readonly UInt24 MaxValue = (UInt24) 16777215; public const int SizeOf = 3; private readonly ushort _leastSignificant; private readonly byte _mostSignificant; private UInt24(int value) { this._mostSignificant = (byte) (value >> 16); this._leastSignificant = (ushort) value; } public static explicit operator UInt24(int value) { return new UInt24(value); } public static explicit operator UInt24(uint value) { return new UInt24((int) value); } public static implicit operator int(UInt24 value) { return value.ToInt(); } public static bool operator ==(UInt24 value1, UInt24 value2) { return value1.Equals(value2); } public static bool operator !=(UInt24 value1, UInt24 value2) { return !(value1 == value2); } public bool Equals(UInt24 other) { if ((int) this._mostSignificant == (int) other._mostSignificant) return (int) this._leastSignificant == (int) other._leastSignificant; return false; } public override bool Equals(object obj) { if (obj is UInt24) return this.Equals((UInt24) obj); return false; } public override int GetHashCode() { return (int) this; } public override string ToString() { return (int) this.ToString((IFormatProvider) CultureInfo.InvariantCulture); } private int ToInt() { return ((int) this._mostSignificant << 16) + (int) this._leastSignificant; } } } <file_sep>// Copyright 2015 <NAME> // // 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. using Grib.Api.Interop.SWIG; using System; namespace Grib.Api.Interop { public class GribApiException: Exception { protected GribApiException (string msg) : base(msg) { } /// <summary> /// Initializes a new instance of the <see cref="GribApiException"/> class. /// </summary> /// <param name="msg">The MSG.</param> /// <param name="innerException">The inner exception.</param> public GribApiException (string msg, Exception innerException = null) : base(msg, innerException) { } /// <summary> /// Creates a GribApiException instance using an error code returned by grib_api. /// </summary> /// <param name="errCode">The error code.</param> /// <returns></returns> public static GribApiException Create(int errCode) { string msg = GribApiProxy.GribGetErrorMessage(errCode); return new GribApiException(msg); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.OfflinePacketCommunicator // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using System; using System.Runtime.InteropServices; namespace PcapDotNet.Core { public sealed class OfflinePacketCommunicator : PacketCommunicator { public override PacketTotalStatistics TotalStatistics { get { throw new InvalidOperationException("Can't get " + typeof (PacketTotalStatistics).Name + " for offline devices"); } } internal unsafe OfflinePacketCommunicator(string fileName) : base(OfflinePacketCommunicator.OpenFile(fileName), (SocketAddress) null) { } public override sealed void Transmit(PacketSendBuffer sendBuffer, [MarshalAs(UnmanagedType.U1)] bool isSync) { throw new InvalidOperationException("Can't transmit queue to an offline device"); } private static pcap* OpenFile(string filename) { // ISSUE: unable to decompile the method. } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.TcpOptionSimple // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Transport { public sealed class TcpOptionSimple : TcpOption { public const int OptionLength = 1; public override int Length { get { return 1; } } public override bool IsAppearsAtMostOnce { get { return false; } } internal TcpOptionSimple(TcpOptionType optionType) : base(optionType) { } } } <file_sep>// Decompiled with JetBrains decompiler // Type: AcuLink_Bridge_Reader_CSharp.Program // Assembly: AcuLink_Bridge_Reader_CS, Version=2014.9.18.2041, Culture=neutral, PublicKeyToken=null // MVID: 2DF0938E-D9D0-414E-AB5D-7B9A655FB464 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\AcuLink_Bridge_Reader_CS.exe using System; using System.Windows.Forms; namespace AcuLink_Bridge_Reader_CSharp { internal static class Program { [STAThread] private static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run((Form) new frmMain()); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.TcpOptionMaximumSegmentSize // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Transport { [OptionTypeRegistration(typeof (TcpOptionType), TcpOptionType.MaximumSegmentSize)] public sealed class TcpOptionMaximumSegmentSize : TcpOptionComplex, IOptionComplexFactory, IEquatable<TcpOptionMaximumSegmentSize> { public const int OptionLength = 4; public const int OptionValueLength = 2; public ushort MaximumSegmentSize { get; private set; } public override int Length { get { return 4; } } public override bool IsAppearsAtMostOnce { get { return true; } } public TcpOptionMaximumSegmentSize(ushort maximumSegmentSize) : base(TcpOptionType.MaximumSegmentSize) { this.MaximumSegmentSize = maximumSegmentSize; } public TcpOptionMaximumSegmentSize() : this((ushort) 0) { } public bool Equals(TcpOptionMaximumSegmentSize other) { if (other == null) return false; return (int) this.MaximumSegmentSize == (int) other.MaximumSegmentSize; } public override bool Equals(TcpOption other) { return this.Equals(other as TcpOptionMaximumSegmentSize); } public override int GetHashCode() { return base.GetHashCode() ^ this.MaximumSegmentSize.GetHashCode(); } Option IOptionComplexFactory.CreateInstance(byte[] buffer, ref int offset, byte valueLength) { if ((int) valueLength != 2) return (Option) null; return (Option) new TcpOptionMaximumSegmentSize(ByteArrayExtensions.ReadUShort(buffer, ref offset, Endianity.Big)); } internal override void Write(byte[] buffer, ref int offset) { base.Write(buffer, ref offset); ByteArrayExtensions.Write(buffer, ref offset, this.MaximumSegmentSize, Endianity.Big); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsCertificationAuthorityAuthorizationFlags // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using System; using System.Diagnostics.CodeAnalysis; namespace PcapDotNet.Packets.Dns { [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Flags")] [Flags] public enum DnsCertificationAuthorityAuthorizationFlags : byte { Critical = (byte) 128, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Igmp.IgmpQueryVersion3Layer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets.IpV4; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Linq; namespace PcapDotNet.Packets.Igmp { public sealed class IgmpQueryVersion3Layer : IgmpLayer, IIgmpLayerWithGroupAddress { public TimeSpan MaxResponseTime { get; set; } public IpV4Address GroupAddress { get; set; } public bool IsSuppressRouterSideProcessing { get; set; } public byte QueryRobustnessVariable { get; set; } public TimeSpan QueryInterval { get; set; } [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ReadOnlyCollection<IpV4Address> SourceAddresses { get; set; } public override int Length { get { return IgmpDatagram.GetQueryVersion3Length(this.SourceAddresses.Count); } } public override IgmpMessageType MessageType { get { return IgmpMessageType.MembershipQuery; } } public override IgmpQueryVersion QueryVersion { get { return IgmpQueryVersion.Version3; } } public override TimeSpan MaxResponseTimeValue { get { return this.MaxResponseTime; } } public IgmpQueryVersion3Layer() { this.SourceAddresses = IListExtensions.AsReadOnly<IpV4Address>((IList<IpV4Address>) new IpV4Address[0]); } protected override void Write(byte[] buffer, int offset) { IgmpDatagram.WriteQueryVersion3(buffer, offset, this.MaxResponseTime, this.GroupAddress, this.IsSuppressRouterSideProcessing, this.QueryRobustnessVariable, this.QueryInterval, (IEnumerable<IpV4Address>) this.SourceAddresses); } public override int GetHashCode() { return base.GetHashCode() ^ Sequence.GetHashCode((object) this.GroupAddress, (object) BitSequence.Merge(BitSequence.ToByte(this.IsSuppressRouterSideProcessing), this.QueryRobustnessVariable)) ^ IEnumerableExtensions.SequenceGetHashCode<IpV4Address>((IEnumerable<IpV4Address>) this.SourceAddresses); } protected override bool EqualFields(IgmpLayer other) { return this.EqualFields(other as IgmpQueryVersion3Layer); } private bool EqualFields(IgmpQueryVersion3Layer other) { if (other != null && this.GroupAddress == other.GroupAddress && (this.IsSuppressRouterSideProcessing == other.IsSuppressRouterSideProcessing && (int) this.QueryRobustnessVariable == (int) other.QueryRobustnessVariable) && (TimeSpanExtensions.Divide(this.QueryInterval, 2.0) <= other.QueryInterval && TimeSpanExtensions.Multiply(this.QueryInterval, 2.0) >= other.QueryInterval)) return Enumerable.SequenceEqual<IpV4Address>((IEnumerable<IpV4Address>) this.SourceAddresses, (IEnumerable<IpV4Address>) other.SourceAddresses); return false; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpIdentifiedDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; namespace PcapDotNet.Packets.Icmp { public abstract class IcmpIdentifiedDatagram : IcmpDatagram { public ushort Identifier { get { return this.ReadUShort(4, Endianity.Big); } } public ushort SequenceNumber { get { return this.ReadUShort(6, Endianity.Big); } } internal IcmpIdentifiedDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } private static class Offset { public const int Identifier = 4; public const int SequenceNumber = 6; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.PacketDeviceOpenAttributes // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using System; namespace PcapDotNet.Core { [Flags] public enum PacketDeviceOpenAttributes { MaximumResponsiveness = 16, NoCaptureLocal = 8, NoCaptureRemote = 4, DataTransferUdpRemote = 2, Promiscuous = 1, None = 0, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.SamplingMethodNone // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll namespace PcapDotNet.Core { public sealed class SamplingMethodNone : SamplingMethod { internal override int Value { get { return 0; } } internal override int Method { get { return 0; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Xml; using System.IO; namespace Wunderground_API_Test { class Program { static void Main(string[] args) { //Start program Console.WriteLine("Starting C# Weather Undeground Web API Test..."); string wunderground_key = "<KEY>"; // You'll need to goto http://www.wunderground.com/weather/api/, and get a key to use the API. parse("http://api.wunderground.com/api/" + wunderground_key + "/conditions/q/VA/Springfield.xml"); parse("http://api.wunderground.com/api/" + wunderground_key + "/conditions/q/NY/New_York.xml"); parse("http://api.wunderground.com/api/" + wunderground_key + "/conditions/q/CA/Oceanside.xml"); parse("http://api.wunderground.com/api/" + wunderground_key + "/conditions/q/CA/Mission_Beach.xml"); parse("http://api.wunderground.com/api/" + wunderground_key + "/conditions/q/VA/Lorton.xml"); // End. Console.WriteLine("Press any key to exit."); Console.ReadKey(); } //Takes a url request to wunderground, parses it, and displays the data. private static void parse(string input_xml) { //Variables string place = ""; string obs_time = ""; string weather1 = ""; string temperature_string = ""; string relative_humidity = ""; string wind_string = ""; string pressure_mb = ""; string dewpoint_string = ""; string visibility_km = ""; string latitude = ""; string longitude = ""; var cli = new WebClient(); string weather = cli.DownloadString(input_xml); using (XmlReader reader = XmlReader.Create(new StringReader(weather))) { // Parse the file and display each of the nodes. while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: if (reader.Name.Equals("full")) { reader.Read(); place = reader.Value; } else if (reader.Name.Equals("observation_time")) { reader.Read(); obs_time = reader.Value; } else if (reader.Name.Equals("weather")) { reader.Read(); weather1 = reader.Value; } else if (reader.Name.Equals("temperature_string")) { reader.Read(); temperature_string = reader.Value; } else if (reader.Name.Equals("relative_humidity")) { reader.Read(); relative_humidity = reader.Value; } else if (reader.Name.Equals("wind_string")) { reader.Read(); wind_string = reader.Value; } else if (reader.Name.Equals("pressure_mb")) { reader.Read(); pressure_mb = reader.Value; } else if (reader.Name.Equals("dewpoint_string")) { reader.Read(); dewpoint_string = reader.Value; } else if (reader.Name.Equals("visibility_km")) { reader.Read(); visibility_km = reader.Value; } else if (reader.Name.Equals("latitude")) { reader.Read(); latitude = reader.Value; } else if (reader.Name.Equals("longitude")) { reader.Read(); longitude = reader.Value; } break; } } } Console.WriteLine("********************"); Console.WriteLine("Place: " + place); Console.WriteLine("Observation Time: " + obs_time); Console.WriteLine("Weather: " + weather1); Console.WriteLine("Temperature: " + temperature_string); Console.WriteLine("Relative Humidity: " + relative_humidity); Console.WriteLine("Wind: " + wind_string); Console.WriteLine("Pressure (mb): " + pressure_mb); Console.WriteLine("Dewpoint: " + dewpoint_string); Console.WriteLine("Visibility (km): " + visibility_km); Console.WriteLine("Location: " + longitude + ", " + latitude); } } } <file_sep>// Copyright 2015 <NAME> // // 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. using Grib.Api.Interop.SWIG; namespace Grib.Api.Interop { /// <summary> /// Values returned by grib_api to indicate the type associated with a key. /// </summary> /// <remarks> /// /* Types */ /// /* undefined */ /// #define GRIB_TYPE_UNDEFINED 0 /// /* long integer */ /// #define GRIB_TYPE_LONG 1 /// /* double */ /// #define GRIB_TYPE_DOUBLE 2 /// /* char* */ /// #define GRIB_TYPE_STRING 3 /// /* bytes */ /// #define GRIB_TYPE_BYTES 4 /// /* section */ /// #define GRIB_TYPE_SECTION 5 /// /* label */ /// #define GRIB_TYPE_LABEL 6 /// /* missing */ /// #define GRIB_TYPE_MISSING 7 /// </remarks> public enum GribValueType { Undefined = 0, Int = 1, Double = 2, String = 3, Bytes = 4, Section = 5, Label = 6, Missing = 7, // uninque to GribApi.NET IntArray = 1000, DoubleArray = 1001 } public static class GribValueTypeExtension { /// <summary> /// Retrieves the GRIB key's type name. /// </summary> /// <param name="vt">The vt.</param> /// <returns></returns> public static string AsString(this GribValueType vt) { if ((int)vt >= (int)GribValueType.IntArray) { return vt.ToString(); } return GribApiProxy.GribGetTypeName((int) vt); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IpV4OptionQuickStart // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.IpV4 { [OptionTypeRegistration(typeof (IpV4OptionType), IpV4OptionType.QuickStart)] public sealed class IpV4OptionQuickStart : IpV4OptionComplex, IOptionComplexFactory, IEquatable<IpV4OptionQuickStart> { public const int OptionLength = 8; public const int OptionValueLength = 6; public const byte RateMaximumValue = (byte) 15; private readonly IpV4OptionQuickStartFunction _function; private readonly byte _rate; private readonly byte _ttl; private readonly uint _nonce; public IpV4OptionQuickStartFunction Function { get { return this._function; } } public byte Rate { get { return this._rate; } } public int RateKbps { get { if ((int) this.Rate == 0) return 0; return 40 * (1 << (int) this.Rate); } } public byte Ttl { get { return this._ttl; } } public uint Nonce { get { return this._nonce; } } public override int Length { get { return 8; } } public override bool IsAppearsAtMostOnce { get { return true; } } public IpV4OptionQuickStart(IpV4OptionQuickStartFunction function, byte rate, byte ttl, uint nonce) : base(IpV4OptionType.QuickStart) { if (function != IpV4OptionQuickStartFunction.RateRequest && function != IpV4OptionQuickStartFunction.RateReport) throw new ArgumentException("Illegal function " + (object) function, "function"); if ((int) rate > 15) throw new ArgumentOutOfRangeException("rate", (object) rate, "Rate maximum value is " + (object) 15); if (((int) nonce & 3) != 0) throw new ArgumentException("nonce last two bits are reserved and must be zero", "nonce"); this._function = function; this._rate = rate; this._ttl = ttl; this._nonce = nonce; } public IpV4OptionQuickStart() : this(IpV4OptionQuickStartFunction.RateRequest, (byte) 0, (byte) 0, 0U) { } public bool Equals(IpV4OptionQuickStart other) { if (other == null || this.Function != other.Function || ((int) this.Rate != (int) other.Rate || (int) this.Ttl != (int) other.Ttl)) return false; return (int) this.Nonce == (int) other.Nonce; } public override bool Equals(IpV4Option other) { return this.Equals(other as IpV4OptionQuickStart); } public override int GetHashCode() { return base.GetHashCode() ^ Sequence.GetHashCode((object) BitSequence.Merge((byte) (this.Function | (IpV4OptionQuickStartFunction) this.Rate), this.Ttl), (object) this.Nonce); } Option IOptionComplexFactory.CreateInstance(byte[] buffer, ref int offset, byte valueLength) { if ((int) valueLength != 6) return (Option) null; byte num = buffer[offset++]; return (Option) new IpV4OptionQuickStart((IpV4OptionQuickStartFunction) ((uint) num & 240U), (byte) ((uint) num & 15U), buffer[offset++], ByteArrayExtensions.ReadUInt(buffer, ref offset, Endianity.Big)); } internal override void Write(byte[] buffer, ref int offset) { base.Write(buffer, ref offset); buffer[offset++] = (byte) (this.Function | (IpV4OptionQuickStartFunction) this.Rate); buffer[offset++] = this.Ttl; ByteArrayExtensions.Write(buffer, ref offset, this.Nonce, Endianity.Big); } } } <file_sep>// Copyright 2015 <NAME> // // 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. namespace Grib.Api { /// <summary> /// A GRIB grid value with coordinates. /// </summary> public struct GeoSpatialValue : IGeoCoordinate { public double Latitude { get; set; } public double Longitude { get; set; } public double Value { get; set; } public bool IsMissing { get; private set; } public GeoSpatialValue(double lat, double lon, double val, bool isMissing) :this() { this.Latitude = lat; this.Longitude = lon; this.Value = val; this.IsMissing = isMissing; } /// <summary> /// Equals the specified value. /// </summary> /// <param name="that">The that.</param> /// <returns></returns> public bool Equals (GeoSpatialValue that) { return (this.Latitude == that.Latitude) && (this.Longitude == that.Longitude) && (this.Value == that.Value); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="a">a.</param> /// <param name="b">The b.</param> /// <returns> /// The result of the operator. /// </returns> public static bool operator ==(GeoSpatialValue a, GeoSpatialValue b) { if (System.Object.ReferenceEquals(a, b)) { return true; } return a.Equals(b); } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="a">a.</param> /// <param name="b">The b.</param> /// <returns> /// The result of the operator. /// </returns> public static bool operator !=(GeoSpatialValue a, GeoSpatialValue b) { return !(a.Equals(b)); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpUnknownDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Icmp { public sealed class IcmpUnknownDatagram : IcmpDatagram { internal IcmpUnknownDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public override ILayer ExtractLayer() { IcmpUnknownLayer icmpUnknownLayer = new IcmpUnknownLayer(); icmpUnknownLayer.LayerMessageType = (byte) this.MessageType; icmpUnknownLayer.LayerCode = this.Code; icmpUnknownLayer.Checksum = new ushort?(this.Checksum); icmpUnknownLayer.LayerVariable = this.Variable; icmpUnknownLayer.Payload = this.Payload; return (ILayer) icmpUnknownLayer; } protected override bool CalculateIsValid() { return false; } internal override IcmpDatagram CreateInstance(byte[] buffer, int offset, int length) { throw new InvalidOperationException("Unknown Icmp Datagram can't be a prototype"); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpTimeExceededDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System.Linq; namespace PcapDotNet.Packets.Icmp { [IcmpDatagramRegistration(IcmpMessageType.TimeExceeded)] public sealed class IcmpTimeExceededDatagram : IcmpIpV4HeaderPlus64BitsPayloadDatagram { private static readonly byte _minCode = (byte) Enumerable.Min<IcmpCodeTimeExceeded>(TypeExtensions.GetEnumValues<IcmpCodeTimeExceeded>(typeof (IcmpCodeTimeExceeded))); private static readonly byte _maxCode = (byte) Enumerable.Max<IcmpCodeTimeExceeded>(TypeExtensions.GetEnumValues<IcmpCodeTimeExceeded>(typeof (IcmpCodeTimeExceeded))); protected override byte MinCodeValue { get { return IcmpTimeExceededDatagram._minCode; } } protected override byte MaxCodeValue { get { return IcmpTimeExceededDatagram._maxCode; } } private IcmpTimeExceededDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public override ILayer ExtractLayer() { IcmpTimeExceededLayer timeExceededLayer = new IcmpTimeExceededLayer(); timeExceededLayer.Code = (IcmpCodeTimeExceeded) this.Code; timeExceededLayer.Checksum = new ushort?(this.Checksum); return (ILayer) timeExceededLayer; } internal override IcmpDatagram CreateInstance(byte[] buffer, int offset, int length) { return (IcmpDatagram) new IcmpTimeExceededDatagram(buffer, offset, length); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataNetworkServiceAccessPoint // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Globalization; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.NetworkServiceAccessPoint)] public sealed class DnsResourceDataNetworkServiceAccessPoint : DnsResourceDataSimple, IEquatable<DnsResourceDataNetworkServiceAccessPoint> { private const int MinAreaAddressLength = 1; private const int ConstantPartLength = 8; public byte AuthorityAndFormatIdentifier { get { return this.AreaAddress[0]; } } public DataSegment AreaAddress { get; private set; } public UInt48 SystemIdentifier { get; private set; } public byte Selector { get; private set; } public DnsResourceDataNetworkServiceAccessPoint(DataSegment areaAddress, UInt48 systemIdentifier, byte selector) { if (areaAddress == null) throw new ArgumentNullException("areaAddress"); if (areaAddress.Length < 1) throw new ArgumentOutOfRangeException("areaAddress", (object) areaAddress.Length, string.Format((IFormatProvider) CultureInfo.InvariantCulture, "Area Address length must be at least {0}.", new object[1] { (object) 1 })); this.AreaAddress = areaAddress; this.SystemIdentifier = systemIdentifier; this.Selector = selector; } internal DnsResourceDataNetworkServiceAccessPoint() : this(new DataSegment(new byte[1]), (UInt48) 0U, (byte) 0) { } public bool Equals(DnsResourceDataNetworkServiceAccessPoint other) { if (other != null && this.AreaAddress.Equals(other.AreaAddress) && this.SystemIdentifier.Equals(other.SystemIdentifier)) return this.Selector.Equals(other.Selector); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataNetworkServiceAccessPoint); } public override int GetHashCode() { return Sequence.GetHashCode((object) this.AreaAddress, (object) this.SystemIdentifier, (object) this.Selector); } internal override int GetLength() { return 8 + this.AreaAddress.Length - 1; } internal override void WriteDataSimple(byte[] buffer, int offset) { this.AreaAddress.Write(buffer, offset); int offset1 = offset + this.AreaAddress.Length; ByteArrayExtensions.Write(buffer, offset1, this.SystemIdentifier, Endianity.Big); ByteArrayExtensions.Write(buffer, offset1 + 6, this.Selector); } internal override DnsResourceData CreateInstance(DataSegment data) { if (data.Length < 8) return (DnsResourceData) null; DataSegment areaAddress = data.Subsegment(0, 1 + data.Length - 8); int length = areaAddress.Length; UInt48 systemIdentifier = data.ReadUInt48(length, Endianity.Big); byte selector = data[length + 6]; return (DnsResourceData) new DnsResourceDataNetworkServiceAccessPoint(areaAddress, systemIdentifier, selector); } private static class Offset { public const int AreaAddress = 0; } private static class OffsetAfterArea { public const int SystemIdentifier = 0; public const int Selector = 6; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.TcpOptionAlternateChecksumType // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Transport { public enum TcpOptionAlternateChecksumType : byte { TcpChecksum, FletchersAlgorithm8Bit, FletchersAlgorithm16Bit, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IpV4OptionRouterAlert // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.IpV4 { [OptionTypeRegistration(typeof (IpV4OptionType), IpV4OptionType.RouterAlert)] public sealed class IpV4OptionRouterAlert : IpV4OptionComplex, IOptionComplexFactory, IEquatable<IpV4OptionRouterAlert> { public const int OptionLength = 4; public const int OptionValueLength = 2; private readonly ushort _value; public ushort Value { get { return this._value; } } public override int Length { get { return 4; } } public override bool IsAppearsAtMostOnce { get { return true; } } public IpV4OptionRouterAlert(ushort value) : base(IpV4OptionType.RouterAlert) { this._value = value; } public IpV4OptionRouterAlert() : this((ushort) 0) { } public bool Equals(IpV4OptionRouterAlert other) { if (other == null) return false; return (int) this.Value == (int) other.Value; } public override bool Equals(IpV4Option other) { return this.Equals(other as IpV4OptionRouterAlert); } public override int GetHashCode() { return base.GetHashCode() ^ this.Value.GetHashCode(); } Option IOptionComplexFactory.CreateInstance(byte[] buffer, ref int offset, byte valueLength) { if ((int) valueLength != 2) return (Option) null; return (Option) new IpV4OptionRouterAlert(ByteArrayExtensions.ReadUShort(buffer, ref offset, Endianity.Big)); } internal override void Write(byte[] buffer, ref int offset) { base.Write(buffer, ref offset); ByteArrayExtensions.Write(buffer, ref offset, this.Value, Endianity.Big); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Arp.ArpHardwareType // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Arp { public enum ArpHardwareType : ushort { None = (ushort) 0, Ethernet = (ushort) 1, ExperimentalEthernet = (ushort) 2, AmateurRadioAx25 = (ushort) 3, ProteonProNetTokenRing = (ushort) 4, Chaos = (ushort) 5, Ieee802Networks = (ushort) 6, AttachedResourceComputerNetwork = (ushort) 7, HyperChannel = (ushort) 8, LanStar = (ushort) 9, AutonetShortAddress = (ushort) 10, LocalTalk = (ushort) 11, LocalNet = (ushort) 12, UltraLink = (ushort) 13, SwitchedMultimegabitDataService = (ushort) 14, FrameRelay = (ushort) 15, AsynchronousTransmissionMode16 = (ushort) 16, HighLevelDataLinkControl = (ushort) 17, FibreChannel = (ushort) 18, AsynchronousTransmissionMode19 = (ushort) 19, SerialLine = (ushort) 20, AsynchronousTransmissionMode21 = (ushort) 21, MilStd188Hyphen220 = (ushort) 22, Metricom = (ushort) 23, Ieee1394Dot1995 = (ushort) 24, MultipleAccessOverSynchronousOpticalNetworkingOrSynchronousDigitalHierarchy = (ushort) 25, Twinaxial = (ushort) 26, ExtendedUniqueIdentifier64 = (ushort) 27, Hiparp = (ushort) 28, IpAndArpOverIso7816Hyphen3 = (ushort) 29, ArpSec = (ushort) 30, IpSecTunnel = (ushort) 31, InfiniBand = (ushort) 32, Tia102Project25CommonAirInterface = (ushort) 33, WiegandInterface = (ushort) 34, PureIp = (ushort) 35, Experimental1 = (ushort) 36, Experimental2 = (ushort) 256, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Base.SerialNumber32 // Assembly: PcapDotNet.Base, Version=0.10.0.20668, Culture=neutral, PublicKeyToken=<KEY> // MVID: E9656A63-0145-422C-B8C8-79FDD7FB4270 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Base.dll using System; using System.Globalization; namespace PcapDotNet.Base { public struct SerialNumber32 : IEquatable<SerialNumber32>, IComparable<SerialNumber32> { public const int SizeOf = 4; public const int SerialBits = 32; public const uint MaxAdditiveNumber = 2147483647U; private readonly uint _value; public uint Value { get { return this._value; } } public SerialNumber32(uint value) { this._value = value; } public static implicit operator SerialNumber32(uint value) { return new SerialNumber32(value); } public static bool operator ==(SerialNumber32 value1, SerialNumber32 value2) { return value1.Equals(value2); } public static bool operator !=(SerialNumber32 value1, SerialNumber32 value2) { return !(value1 == value2); } public static bool operator <(SerialNumber32 value1, SerialNumber32 value2) { return value1.CompareTo(value2) < 0; } public static bool operator >(SerialNumber32 value1, SerialNumber32 value2) { return value1.CompareTo(value2) > 0; } public SerialNumber32 Add(uint value) { if (value > (uint) int.MaxValue) throw new ArgumentOutOfRangeException("value", (object) value, string.Format((IFormatProvider) CultureInfo.InvariantCulture, "Cannot add a number bigger than {0}", new object[1] { (object) (uint) int.MaxValue })); return (SerialNumber32) (this._value + value); } public bool Equals(SerialNumber32 other) { return (int) this.Value == (int) other.Value; } public override bool Equals(object obj) { if (obj is SerialNumber32) return this.Equals((SerialNumber32) obj); return false; } public override int GetHashCode() { return this.Value.GetHashCode(); } public int CompareTo(SerialNumber32 other) { if (this.Equals(other)) return 0; if (this.Value < other.Value) return other.Value - this.Value >= (uint) int.MinValue ? 1 : -1; return this.Value - other.Value >= (uint) int.MinValue ? -1 : 1; } public override string ToString() { return this.ToString((IFormatProvider) CultureInfo.InvariantCulture); } public string ToString(IFormatProvider provider) { return this.Value.ToString(provider); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpUnknownLayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; namespace PcapDotNet.Packets.Icmp { public sealed class IcmpUnknownLayer : IcmpLayer { public byte LayerMessageType { get; set; } public byte LayerCode { get; set; } public uint LayerVariable { get; set; } public Datagram Payload { get; set; } public override IcmpMessageType MessageType { get { return (IcmpMessageType) this.LayerMessageType; } } public override byte CodeValue { get { return this.LayerCode; } } protected override int PayloadLength { get { return this.Payload.Length; } } protected override uint Variable { get { return this.LayerVariable; } } protected override void WritePayload(byte[] buffer, int offset) { this.Payload.Write(buffer, offset); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.ILayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets { public interface ILayer { int Length { get; } DataLinkKind? DataLink { get; } void Write(byte[] buffer, int offset, int payloadLength, ILayer previousLayer, ILayer nextLayer); void Finalize(byte[] buffer, int offset, int payloadLength, ILayer nextLayer); } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.TcpOptionEchoReply // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Transport { [OptionTypeRegistration(typeof (TcpOptionType), TcpOptionType.EchoReply)] public sealed class TcpOptionEchoReply : TcpOptionComplex, IOptionComplexFactory, IEquatable<TcpOptionEchoReply> { public const int OptionLength = 6; public const int OptionValueLength = 4; public uint Info { get; private set; } public override int Length { get { return 6; } } public override bool IsAppearsAtMostOnce { get { return true; } } public TcpOptionEchoReply(uint info) : base(TcpOptionType.EchoReply) { this.Info = info; } public TcpOptionEchoReply() : this(0U) { } public bool Equals(TcpOptionEchoReply other) { if (other == null) return false; return (int) this.Info == (int) other.Info; } public override bool Equals(TcpOption other) { return this.Equals(other as TcpOptionEchoReply); } public override int GetHashCode() { return base.GetHashCode() ^ this.Info.GetHashCode(); } Option IOptionComplexFactory.CreateInstance(byte[] buffer, ref int offset, byte valueLength) { if ((int) valueLength != 4) return (Option) null; return (Option) new TcpOptionEchoReply(ByteArrayExtensions.ReadUInt(buffer, ref offset, Endianity.Big)); } internal override void Write(byte[] buffer, ref int offset) { base.Write(buffer, ref offset); ByteArrayExtensions.Write(buffer, ref offset, this.Info, Endianity.Big); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.PcapLibrary // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using System.Diagnostics; namespace PcapDotNet.Core { public sealed class PcapLibrary { public static unsafe string Version { get { return new string(\u003CModule\u003E.pcap_lib_version()); } } [DebuggerNonUserCode] private PcapLibrary() { } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResponseCode // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Dns { public enum DnsResponseCode : ushort { NoError = (ushort) 0, FormatError = (ushort) 1, ServerFailure = (ushort) 2, NotExistentDomain = (ushort) 3, NotImplemented = (ushort) 4, Refused = (ushort) 5, YxDomain = (ushort) 6, YxResourceRecordSet = (ushort) 7, NotExistResourceRecordSet = (ushort) 8, NotAuth = (ushort) 9, NotZone = (ushort) 10, BadVersionOrBadSignature = (ushort) 16, BadKey = (ushort) 17, BadTime = (ushort) 18, BadMode = (ushort) 19, BadName = (ushort) 20, BadAlgorithm = (ushort) 21, BadTruncation = (ushort) 22, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataStartOfAuthority // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.StartOfAuthority)] public sealed class DnsResourceDataStartOfAuthority : DnsResourceData, IEquatable<DnsResourceDataStartOfAuthority> { private const int ConstantPartLength = 20; public DnsDomainName MainNameServer { get; private set; } public DnsDomainName ResponsibleMailbox { get; private set; } public SerialNumber32 Serial { get; private set; } public uint Refresh { get; private set; } public uint Retry { get; private set; } public uint Expire { get; private set; } public uint MinimumTtl { get; private set; } public DnsResourceDataStartOfAuthority(DnsDomainName mainNameServer, DnsDomainName responsibleMailbox, SerialNumber32 serial, uint refresh, uint retry, uint expire, uint minimumTtl) { this.MainNameServer = mainNameServer; this.ResponsibleMailbox = responsibleMailbox; this.Serial = serial; this.Refresh = refresh; this.Retry = retry; this.Expire = expire; this.MinimumTtl = minimumTtl; } internal DnsResourceDataStartOfAuthority() : this(DnsDomainName.Root, DnsDomainName.Root, (SerialNumber32) 0U, 0U, 0U, 0U, 0U) { } public bool Equals(DnsResourceDataStartOfAuthority other) { if (other != null && this.MainNameServer.Equals(other.MainNameServer) && this.ResponsibleMailbox.Equals(other.ResponsibleMailbox) && this.Serial.Equals(other.Serial) && (this.Refresh.Equals(other.Refresh) && this.Retry.Equals(other.Retry)) && this.Expire.Equals(other.Expire)) return this.MinimumTtl.Equals(other.MinimumTtl); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataStartOfAuthority); } public override int GetHashCode() { return Sequence.GetHashCode((object) this.MainNameServer, (object) this.ResponsibleMailbox, (object) this.Serial, (object) this.Refresh, (object) this.Retry, (object) this.Expire, (object) this.MinimumTtl); } internal override int GetLength(DnsDomainNameCompressionData compressionData, int offsetInDns) { return this.MainNameServer.GetLength(compressionData, offsetInDns) + this.ResponsibleMailbox.GetLength(compressionData, offsetInDns) + 20; } internal override int WriteData(byte[] buffer, int dnsOffset, int offsetInDns, DnsDomainNameCompressionData compressionData) { int num1 = this.MainNameServer.Write(buffer, dnsOffset, compressionData, offsetInDns); int num2 = num1 + this.ResponsibleMailbox.Write(buffer, dnsOffset, compressionData, offsetInDns + num1); ByteArrayExtensions.Write(buffer, dnsOffset + offsetInDns + num2, this.Serial.Value, Endianity.Big); ByteArrayExtensions.Write(buffer, dnsOffset + offsetInDns + num2 + 4, this.Refresh, Endianity.Big); ByteArrayExtensions.Write(buffer, dnsOffset + offsetInDns + num2 + 8, this.Retry, Endianity.Big); ByteArrayExtensions.Write(buffer, dnsOffset + offsetInDns + num2 + 12, this.Expire, Endianity.Big); ByteArrayExtensions.Write(buffer, dnsOffset + offsetInDns + num2 + 16, this.MinimumTtl, Endianity.Big); return num2 + 20; } internal override DnsResourceData CreateInstance(DnsDatagram dns, int offsetInDns, int length) { DnsDomainName domainName1; int numBytesRead; if (!DnsDomainName.TryParse(dns, offsetInDns, length, out domainName1, out numBytesRead)) return (DnsResourceData) null; offsetInDns += numBytesRead; length -= numBytesRead; DnsDomainName domainName2; if (!DnsDomainName.TryParse(dns, offsetInDns, length, out domainName2, out numBytesRead)) return (DnsResourceData) null; offsetInDns += numBytesRead; length -= numBytesRead; if (length != 20) return (DnsResourceData) null; uint num = dns.ReadUInt(offsetInDns, Endianity.Big); uint refresh = dns.ReadUInt(offsetInDns + 4, Endianity.Big); uint retry = dns.ReadUInt(offsetInDns + 8, Endianity.Big); uint expire = dns.ReadUInt(offsetInDns + 12, Endianity.Big); uint minimumTtl = dns.ReadUInt(offsetInDns + 16, Endianity.Big); return (DnsResourceData) new DnsResourceDataStartOfAuthority(domainName1, domainName2, (SerialNumber32) num, refresh, retry, expire, minimumTtl); } private static class Offset { public const int Serial = 0; public const int Refresh = 4; public const int Retry = 8; public const int Expire = 12; public const int MinimumTtl = 16; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataIpSecKey // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.IpSecKey)] public sealed class DnsResourceDataIpSecKey : DnsResourceDataNoCompression, IEquatable<DnsResourceDataIpSecKey> { private const int ConstPartLength = 3; public byte Precedence { get; private set; } public DnsGatewayType GatewayType { get { return this.Gateway.GatewayType; } } public DnsGateway Gateway { get; private set; } public DnsPublicKeyAlgorithm Algorithm { get; private set; } public DataSegment PublicKey { get; private set; } public DnsResourceDataIpSecKey(byte precedence, DnsGateway gateway, DnsPublicKeyAlgorithm algorithm, DataSegment publicKey) { this.Precedence = precedence; this.Gateway = gateway; this.Algorithm = algorithm; this.PublicKey = publicKey; } internal DnsResourceDataIpSecKey() : this((byte) 0, (DnsGateway) DnsGateway.None, DnsPublicKeyAlgorithm.None, DataSegment.Empty) { } public bool Equals(DnsResourceDataIpSecKey other) { if (other != null && (this.Precedence.Equals(other.Precedence) && this.Gateway.Equals(other.Gateway) && this.Algorithm.Equals((object) other.Algorithm))) return this.PublicKey.Equals(other.PublicKey); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataIpSecKey); } public override int GetHashCode() { return Sequence.GetHashCode((object) BitSequence.Merge(this.Precedence, (byte) this.Algorithm), (object) this.Gateway, (object) this.PublicKey); } internal override int GetLength() { return 3 + this.Gateway.Length + this.PublicKey.Length; } internal override int WriteData(byte[] buffer, int offset) { ByteArrayExtensions.Write(buffer, offset, this.Precedence); ByteArrayExtensions.Write(buffer, offset + 1, (byte) this.GatewayType); ByteArrayExtensions.Write(buffer, offset + 2, (byte) this.Algorithm); this.Gateway.Write(buffer, offset + 3); this.PublicKey.Write(buffer, offset + 3 + this.Gateway.Length); return this.GetLength(); } internal override DnsResourceData CreateInstance(DnsDatagram dns, int offsetInDns, int length) { if (length < 3) return (DnsResourceData) null; byte precedence = dns[offsetInDns]; DnsGatewayType gatewayType = (DnsGatewayType) dns[offsetInDns + 1]; DnsPublicKeyAlgorithm algorithm = (DnsPublicKeyAlgorithm) dns[offsetInDns + 2]; DnsGateway instance = DnsGateway.CreateInstance(gatewayType, dns, offsetInDns + 3, length - 3); if (instance == null) return (DnsResourceData) null; DataSegment publicKey = dns.Subsegment(offsetInDns + 3 + instance.Length, length - 3 - instance.Length); return (DnsResourceData) new DnsResourceDataIpSecKey(precedence, instance, algorithm, publicKey); } private static class Offset { public const int Precedence = 0; public const int GatewayType = 1; public const int Algorithm = 2; public const int Gateway = 3; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.PacketCommunicatorReceiveResult // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll namespace PcapDotNet.Core { public enum PacketCommunicatorReceiveResult { Ok, Timeout, Eof, BreakLoop, None, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.PcapDataLink // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using PcapDotNet.Packets; using System; using System.Globalization; using System.Runtime.InteropServices; namespace PcapDotNet.Core { public struct PcapDataLink : IDataLink, IEquatable<PcapDataLink> { private int _value; public unsafe string Description { get { sbyte* numPtr = \u003CModule\u003E.pcap_datalink_val_to_description(this._value); if ((IntPtr) numPtr == IntPtr.Zero) throw new InvalidOperationException(typeof (PcapDataLink).Name + " " + this._value.ToString((IFormatProvider) CultureInfo.InvariantCulture) + " has no description"); return new string(numPtr); } } public unsafe string Name { get { sbyte* numPtr = \u003CModule\u003E.pcap_datalink_val_to_name(this._value); if ((IntPtr) numPtr == IntPtr.Zero) throw new InvalidOperationException(typeof (PcapDataLink).Name + " " + this._value.ToString((IFormatProvider) CultureInfo.InvariantCulture) + " has no name"); return new string(numPtr); } } public int Value { get { return this._value; } } public DataLinkKind Kind { get { int num = this._value; switch (num) { case 1: return DataLinkKind.Ethernet; case 12: return DataLinkKind.IpV4; case 143: return DataLinkKind.Docsis; default: throw new NotSupportedException(typeof (PcapDataLink).Name + " " + num.ToString((IFormatProvider) CultureInfo.InvariantCulture) + " - " + this.ToString() + " is unsupported"); } } } public PcapDataLink(string name) { // ISSUE: unable to decompile the method. } public PcapDataLink(int value) { this._value = value; } public PcapDataLink(DataLinkKind kind) { this._value = PcapDataLink.KindToValue(kind); } public static bool operator ==(PcapDataLink dataLink1, PcapDataLink dataLink2) { PcapDataLink pcapDataLink = dataLink2; return dataLink1._value == pcapDataLink._value; } public static bool operator !=(PcapDataLink dataLink1, PcapDataLink dataLink2) { PcapDataLink pcapDataLink = dataLink2; return dataLink1._value != pcapDataLink._value; } public override sealed string ToString() { return this.Name + " (" + this.Description + ")"; } [return: MarshalAs(UnmanagedType.U1)] public override sealed bool Equals(object obj) { ValueType valueType = (ValueType) (obj as PcapDataLink); if (valueType == null) return false; return this._value == ((PcapDataLink) valueType)._value; } [return: MarshalAs(UnmanagedType.U1)] public bool Equals(PcapDataLink other) { return this._value == other._value; } public override sealed int GetHashCode() { return this._value.GetHashCode(); } private static int KindToValue(DataLinkKind kind) { if (kind == DataLinkKind.Ethernet) return 1; if (kind == DataLinkKind.IpV4) return 12; if (kind != DataLinkKind.Docsis) throw new NotSupportedException(typeof (PcapDataLink).Name + " kind " + kind.ToString() + " is unsupported"); return 143; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IpV4OptionTimestampOnly // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace PcapDotNet.Packets.IpV4 { public sealed class IpV4OptionTimestampOnly : IpV4OptionTimestamp { private readonly ReadOnlyCollection<IpV4TimeOfDay> _timestamps; public override int CountTimestamps { get { return Enumerable.Count<IpV4TimeOfDay>((IEnumerable<IpV4TimeOfDay>) this.Timestamps); } } public ReadOnlyCollection<IpV4TimeOfDay> Timestamps { get { return this._timestamps; } } protected override int ValuesLength { get { return this.Timestamps.Count * 4; } } public IpV4OptionTimestampOnly(byte overflow, byte pointedIndex, IList<IpV4TimeOfDay> timestamps) : base(IpV4OptionTimestampType.TimestampOnly, overflow, pointedIndex) { this._timestamps = IListExtensions.AsReadOnly<IpV4TimeOfDay>(timestamps); } public IpV4OptionTimestampOnly(byte overflow, byte pointedIndex, params IpV4TimeOfDay[] timestamps) : this(overflow, pointedIndex, (IList<IpV4TimeOfDay>) timestamps) { } public override int GetHashCode() { return base.GetHashCode() ^ IEnumerableExtensions.SequenceGetHashCode<IpV4TimeOfDay>((IEnumerable<IpV4TimeOfDay>) this.Timestamps); } internal static IpV4OptionTimestampOnly Read(byte overflow, byte pointedIndex, byte[] buffer, ref int offset, int numValues) { IpV4TimeOfDay[] ipV4TimeOfDayArray = new IpV4TimeOfDay[numValues]; for (int index = 0; index != numValues; ++index) ipV4TimeOfDayArray[index] = ByteArrayExtensions.ReadIpV4TimeOfDay(buffer, ref offset, Endianity.Big); return new IpV4OptionTimestampOnly(overflow, pointedIndex, ipV4TimeOfDayArray); } protected override bool EqualValues(IpV4OptionTimestamp other) { return Enumerable.SequenceEqual<IpV4TimeOfDay>((IEnumerable<IpV4TimeOfDay>) this.Timestamps, (IEnumerable<IpV4TimeOfDay>) ((IpV4OptionTimestampOnly) other).Timestamps); } protected override void WriteValues(byte[] buffer, ref int offset) { foreach (IpV4TimeOfDay ipV4TimeOfDay in this.Timestamps) ByteArrayExtensions.Write(buffer, ref offset, ipV4TimeOfDay.MillisecondsSinceMidnightUniversalTime, Endianity.Big); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IpV4Options // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System.Collections.Generic; namespace PcapDotNet.Packets.IpV4 { public class IpV4Options : Options<IpV4Option> { private static readonly IpV4Options _none = new IpV4Options(new IpV4Option[0]); public const int MaximumBytesLength = 40; public static IpV4Options None { get { return IpV4Options._none; } } public IpV4Options(IList<IpV4Option> options) : base(options, (IpV4Option) IpV4Option.End, 40) { } public IpV4Options(params IpV4Option[] options) : this((IList<IpV4Option>) options) { } internal IpV4Options(byte[] buffer, int offset, int length) : base(buffer, offset, length, (IpV4Option) IpV4Option.End) { } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpCodeConversionFailed // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Icmp { public enum IcmpCodeConversionFailed : byte { UnknownOrUnspecifiedError, DoNotConvertOptionPresent, UnknownMandatoryOptionPresent, KnownUnsupportedOptionPresent, UnsupportedTransportProtocol, OverallLengthExceeded, IpHeaderLengthExceeded, TransportProtocolIsBiggerThan255, PortConversionOutOfRange, TransportHeaderLengthExceeded, Code32BitRolloverMissingAndAckSet, UnknownMandatoryTransportOptionPresent, } } <file_sep>// Copyright 2015 <NAME> // // 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. using Grib.Api.Interop; using Grib.Api.Interop.SWIG; using Grib.Api.Interop.Util; using System; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Reflection; namespace Grib.Api { /// <summary> /// Interface for configuring GribApi.NET's runtime environment. /// </summary> /// <remarks> /// See also https://software.ecmwf.int/wiki/display/GRIB/Environment+variables. /// </remarks> public static class GribEnvironment { private static AutoRef _libHandle; private static object _initLock = new object(); /// <summary> /// Initializes GribApi.NET. In very rare cases, you may need to call this method directly /// to ensure the native libraries are bootstrapped and the environment setup correctly. /// </summary> /// <exception cref="System.ComponentModel.Win32Exception"></exception> public static void Init() { lock(_initLock) { if (Initialized) { return; } Initialized = true; string definitions = ""; if (String.IsNullOrWhiteSpace(DefinitionsPath) && GribEnvironmentLoadHelper.TryFindDefinitions(out definitions)) { DefinitionsPath = definitions; } _libHandle = GribEnvironmentLoadHelper.BootStrapLibrary(); AssertValidEnvironment(); } } /// <summary> /// Asserts the valid environment. /// </summary> /// <exception cref="GribApiException"> /// GribEnvironment::DefinitionsPath must be a valid path. If you're using ASP.NET or NUnit, this exception is usually caused by shadow copying. Please see GribApi.NET's documentation for help. /// or /// Could not locate 'definitions/boot.def'. /// </exception> private static void AssertValidEnvironment () { string[] paths = GribEnvironment.DefinitionsPath.Split(new [] { ';' }); string existingPath = ""; bool exists = false; foreach(string path in paths) { existingPath = path; exists = Directory.Exists(path); if (exists) { break; } } if (!exists) { throw new GribApiException("GribEnvironment::DefinitionsPath must be a valid path. If you're using ASP.NET or NUnit, this exception is usually caused by shadow copying. Please see GribApi.NET's documentation for help."); } if (!File.Exists(Path.Combine(existingPath, "boot.def"))) { throw new GribApiException("Could not locate 'definitions/boot.def'."); } } /// <summary> /// Sets an env variable and notifies the C runtime to update its values. /// </summary> /// <param name="name">The name.</param> /// <param name="val">The value.</param> private static void PutEnvVar (string name, string val) { Environment.SetEnvironmentVariable(name, val, EnvironmentVariableTarget.Process); Win32._putenv_s(name, val); Debug.Assert(Environment.GetEnvironmentVariable(name) == val); } /// <summary> /// Gets or sets the JPEG dump path. This is primarily useful during debugging /// </summary> /// <value> /// The JPEG dump path. /// </value> public static string JpegDumpPath { get { return Environment.GetEnvironmentVariable("GRIB_DUMP_JPG_FILE"); } set { PutEnvVar("GRIB_DUMP_JPG_FILE", value); } } /// <summary> /// Gets or sets a value indicating whether or not grib_api should abort on an assertion failure or error log. /// </summary> /// <value> /// <c>true</c> if [no abort]; otherwise, <c>false</c>. /// </value> public static bool NoAbort { get { return Environment.GetEnvironmentVariable("GRIB_API_NO_ABORT") == "1"; } set { string val = value ? "1" : "0"; PutEnvVar("GRIB_API_NO_ABORT", val); val = value ? "0" : "1"; PutEnvVar("GRIB_API_FAIL_IF_LOG_MESSAGE", val); } } /// <summary> /// Gets or sets the location of grib_api's definitions directory. By default, it is located at Grib.Api/definitions. /// </summary> /// <value> /// The definitions path. /// </value> public static string DefinitionsPath { get { return Environment.GetEnvironmentVariable("GRIB_DEFINITION_PATH"); } set { PutEnvVar("GRIB_DEFINITION_PATH", value); } } /// <summary> /// Gets the grib_api version wrapped by this library. /// </summary> /// <value> /// The grib API version. /// </value> public static string GribApiVersion { get { string version = GribApiProxy.GribGetApiVersion().ToString(); string major = version[0].ToString(); string minor = Int32.Parse(version.Substring(1, 2)).ToString(); string patch = Int32.Parse(version.Substring(3, 2)).ToString(); return String.Join(".", major, minor, patch); } } /// <summary> /// Gets or sets a value indicating whether this <see cref="GribEnvironment"/> is initialized. /// </summary> /// <value> /// <c>true</c> if initialized; otherwise, <c>false</c>. /// </value> private static bool Initialized { get; set; } } } <file_sep>namespace ForecastPCL.Test { using System; using System.Configuration; using ForecastIOPortable; using NUnit.Framework; [TestFixture] public class LanguageTests { // These coordinates came from the Forecast API documentation, // and should return forecasts with all blocks. private const double AlcatrazLatitude = 37.8267; private const double AlcatrazLongitude = -122.423; private const double MumbaiLatitude = 18.975; private const double MumbaiLongitude = 72.825833; /// <summary> /// API key to be used for testing. This should be specified in the /// test project's app.config file. /// </summary> private string apiKey; /// <summary> /// Sets up all tests by retrieving the API key from app.config. /// </summary> [TestFixtureSetUp] public void SetUp() { this.apiKey = ConfigurationManager.AppSettings["ApiKey"]; } [Test] public void AllLanguagesHaveValues() { foreach (Language language in Enum.GetValues(typeof(Language))) { Assert.That(() => language.ToValue(), Throws.Nothing); } } [Test] public async void UnicodeLanguageIsSupported() { var client = new ForecastApi(this.apiKey); var result = await client.GetWeatherDataAsync(AlcatrazLatitude, AlcatrazLongitude, Unit.Auto, Language.Chinese); Assert.That(result, Is.Not.Null); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataHostInformation // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System.Collections.Generic; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.HInfo)] public sealed class DnsResourceDataHostInformation : DnsResourceDataStrings { private const int NumStrings = 2; public DataSegment Cpu { get { return this.Strings[0]; } } public DataSegment Os { get { return this.Strings[1]; } } public DnsResourceDataHostInformation(DataSegment cpu, DataSegment os) : base(cpu, os) { } internal DnsResourceDataHostInformation() : this(DataSegment.Empty, DataSegment.Empty) { } internal override DnsResourceData CreateInstance(DataSegment data) { List<DataSegment> list = DnsResourceDataStrings.ReadStrings(data, 2); if (list == null || list.Count != 2) return (DnsResourceData) null; return (DnsResourceData) new DnsResourceDataHostInformation(list[0], list[1]); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsAddressPrefix // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Collections.Generic; namespace PcapDotNet.Packets.Dns { public sealed class DnsAddressPrefix : IEquatable<DnsAddressPrefix> { private const int MinimumLength = 4; private const int AddressFamilyDependentPartMaxLength = 127; public AddressFamily AddressFamily { get; private set; } public byte PrefixLength { get; private set; } public bool Negation { get; private set; } public DataSegment AddressFamilyDependentPart { get; private set; } public int Length { get { return 4 + this.AddressFamilyDependentPart.Length; } } public DnsAddressPrefix(AddressFamily addressFamily, byte prefixLength, bool negation, DataSegment addressFamilyDependentPart) { if (addressFamilyDependentPart == null) throw new ArgumentNullException("addressFamilyDependentPart"); if (addressFamilyDependentPart.Length > (int) sbyte.MaxValue) throw new ArgumentOutOfRangeException("addressFamilyDependentPart", (object) addressFamilyDependentPart, "Cannot be longer than " + (object) (int) sbyte.MaxValue); this.AddressFamily = addressFamily; this.PrefixLength = prefixLength; this.Negation = negation; this.AddressFamilyDependentPart = addressFamilyDependentPart; } public bool Equals(DnsAddressPrefix other) { if (other != null && this.AddressFamily.Equals((object) other.AddressFamily) && this.PrefixLength.Equals(other.PrefixLength) && this.Negation.Equals(other.Negation)) return this.AddressFamilyDependentPart.Equals(other.AddressFamilyDependentPart); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsAddressPrefix); } public override int GetHashCode() { return BitSequence.Merge((ushort) this.AddressFamily, this.PrefixLength, (byte) ((this.Negation ? 1 : 0) << 7 | this.AddressFamilyDependentPart.Length)).GetHashCode() ^ IEnumerableExtensions.BytesSequenceGetHashCode((IEnumerable<byte>) this.AddressFamilyDependentPart); } internal static DnsAddressPrefix Read(DataSegment data) { if (data == null) throw new ArgumentNullException("data"); if (data.Length < 4) return (DnsAddressPrefix) null; AddressFamily addressFamily = (AddressFamily) data.ReadUShort(0, Endianity.Big); byte prefixLength = data[2]; bool negation = data.ReadBool(3, (byte) sbyte.MinValue); byte num = (byte) ((uint) data[3] & (uint) sbyte.MaxValue); if (data.Length < 4 + (int) num) return (DnsAddressPrefix) null; DataSegment addressFamilyDependentPart = data.Subsegment(4, (int) num); return new DnsAddressPrefix(addressFamily, prefixLength, negation, addressFamilyDependentPart); } internal void Write(byte[] buffer, ref int offset) { ByteArrayExtensions.Write(buffer, offset, (ushort) this.AddressFamily, Endianity.Big); ByteArrayExtensions.Write(buffer, offset + 2, this.PrefixLength); ByteArrayExtensions.Write(buffer, offset + 3, (byte) ((this.Negation ? 128 : 0) | this.AddressFamilyDependentPart.Length)); this.AddressFamilyDependentPart.Write(buffer, offset + 4); offset += 4 + this.AddressFamilyDependentPart.Length; } private static class Offset { public const int AddressFamily = 0; public const int PrefixLength = 2; public const int Negation = 3; public const int AddressFamilyDependentPartLength = 3; public const int AddressFamilyDependentPart = 4; } private static class Mask { public const byte Negation = (byte) 128; public const byte AddressFamilyDependentPartLength = (byte) 127; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Ethernet.EthernetBaseLayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using PcapDotNet.Packets.Arp; using System; namespace PcapDotNet.Packets.Ethernet { public abstract class EthernetBaseLayer : Layer, IArpPreviousLayer, ILayer { public EthernetType EtherType { get; set; } public ArpHardwareType PreviousLayerHardwareType { get { return ArpHardwareType.Ethernet; } } protected EthernetBaseLayer() { this.EtherType = EthernetType.None; } internal static EthernetType GetEthernetType(EthernetType ethernetType, ILayer nextLayer) { if (ethernetType != EthernetType.None) return ethernetType; if (nextLayer == null) throw new ArgumentException("Can't determine ether type automatically from next layer because there is not next layer"); IEthernetNextLayer ethernetNextLayer = nextLayer as IEthernetNextLayer; if (ethernetNextLayer == null) throw new ArgumentException("Can't determine ether type automatically from next layer (" + (object) nextLayer.GetType() + ")"); return ethernetNextLayer.PreviousLayerEtherType; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.TcpOptionAlternateChecksumData // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace PcapDotNet.Packets.Transport { [OptionTypeRegistration(typeof (TcpOptionType), TcpOptionType.AlternateChecksumData)] public sealed class TcpOptionAlternateChecksumData : TcpOptionComplex, IOptionComplexFactory, IEquatable<TcpOptionAlternateChecksumData> { public const int OptionMinimumLength = 2; public const int OptionValueMinimumLength = 0; public ReadOnlyCollection<byte> Data { get; private set; } public override int Length { get { return 2 + this.Data.Count; } } public override bool IsAppearsAtMostOnce { get { return true; } } public TcpOptionAlternateChecksumData(IList<byte> data) : base(TcpOptionType.AlternateChecksumData) { this.Data = new ReadOnlyCollection<byte>(data); } public TcpOptionAlternateChecksumData() : this((IList<byte>) new byte[0]) { } public bool Equals(TcpOptionAlternateChecksumData other) { if (other == null) return false; return Enumerable.SequenceEqual<byte>((IEnumerable<byte>) this.Data, (IEnumerable<byte>) other.Data); } public override bool Equals(TcpOption other) { return this.Equals(other as TcpOptionAlternateChecksumData); } public override int GetHashCode() { return base.GetHashCode() ^ IEnumerableExtensions.BytesSequenceGetHashCode((IEnumerable<byte>) this.Data); } Option IOptionComplexFactory.CreateInstance(byte[] buffer, ref int offset, byte valueLength) { if ((int) valueLength < 0) return (Option) null; return (Option) new TcpOptionAlternateChecksumData((IList<byte>) ByteArrayExtensions.ReadBytes(buffer, ref offset, (int) valueLength)); } internal override void Write(byte[] buffer, ref int offset) { base.Write(buffer, ref offset); ByteArrayExtensions.Write(buffer, ref offset, (IEnumerable<byte>) this.Data); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataTransactionSignature // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Globalization; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.TransactionSignature)] public sealed class DnsResourceDataTransactionSignature : DnsResourceData, IEquatable<DnsResourceDataTransactionSignature> { private const int ConstantPartLength = 16; public DnsDomainName Algorithm { get; private set; } public UInt48 TimeSigned { get; private set; } public ushort Fudge { get; private set; } public DataSegment MessageAuthenticationCode { get; private set; } public ushort OriginalId { get; private set; } public DnsResponseCode Error { get; private set; } public DataSegment Other { get; private set; } public DnsResourceDataTransactionSignature(DnsDomainName algorithm, UInt48 timeSigned, ushort fudge, DataSegment messageAuthenticationCode, ushort originalId, DnsResponseCode error, DataSegment other) { if (messageAuthenticationCode == null) throw new ArgumentNullException("messageAuthenticationCode"); if (other == null) throw new ArgumentNullException("other"); if (messageAuthenticationCode.Length > (int) ushort.MaxValue) throw new ArgumentOutOfRangeException("messageAuthenticationCode", (object) messageAuthenticationCode.Length, string.Format((IFormatProvider) CultureInfo.InvariantCulture, "Cannot be longer than {0}", new object[1] { (object) ushort.MaxValue })); if (other.Length > (int) ushort.MaxValue) throw new ArgumentOutOfRangeException("other", (object) other.Length, string.Format((IFormatProvider) CultureInfo.InvariantCulture, "Cannot be longer than {0}", new object[1] { (object) ushort.MaxValue })); this.Algorithm = algorithm; this.TimeSigned = timeSigned; this.Fudge = fudge; this.MessageAuthenticationCode = messageAuthenticationCode; this.OriginalId = originalId; this.Error = error; this.Other = other; } internal DnsResourceDataTransactionSignature() : this(DnsDomainName.Root, (UInt48) 0U, (ushort) 0, DataSegment.Empty, (ushort) 0, DnsResponseCode.NoError, DataSegment.Empty) { } public bool Equals(DnsResourceDataTransactionSignature other) { if (other != null && this.Algorithm.Equals(other.Algorithm) && this.TimeSigned.Equals(other.TimeSigned) && (this.Fudge.Equals(other.Fudge) && this.MessageAuthenticationCode.Equals(other.MessageAuthenticationCode) && (this.OriginalId.Equals(other.OriginalId) && this.Error.Equals((object) other.Error)))) return this.Other.Equals(other.Other); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataTransactionSignature); } public override int GetHashCode() { return Sequence.GetHashCode((object) this.Algorithm, (object) this.TimeSigned, (object) BitSequence.Merge(this.Fudge, this.OriginalId), (object) this.MessageAuthenticationCode, (object) this.Error, (object) this.Other); } internal override int GetLength(DnsDomainNameCompressionData compressionData, int offsetInDns) { return this.Algorithm.GetLength(compressionData, offsetInDns) + 16 + this.MessageAuthenticationCode.Length + this.Other.Length; } internal override int WriteData(byte[] buffer, int dnsOffset, int offsetInDns, DnsDomainNameCompressionData compressionData) { int num = this.Algorithm.Write(buffer, dnsOffset, compressionData, offsetInDns); int offset1 = dnsOffset + offsetInDns + num; ByteArrayExtensions.Write(buffer, offset1, this.TimeSigned, Endianity.Big); ByteArrayExtensions.Write(buffer, offset1 + 6, this.Fudge, Endianity.Big); ByteArrayExtensions.Write(buffer, offset1 + 8, (ushort) this.MessageAuthenticationCode.Length, Endianity.Big); this.MessageAuthenticationCode.Write(buffer, offset1 + 10); int offset2 = offset1 + (10 + this.MessageAuthenticationCode.Length); ByteArrayExtensions.Write(buffer, offset2, this.OriginalId, Endianity.Big); ByteArrayExtensions.Write(buffer, offset2 + 2, (ushort) this.Error, Endianity.Big); ByteArrayExtensions.Write(buffer, offset2 + 4, (ushort) this.Other.Length, Endianity.Big); this.Other.Write(buffer, offset2 + 6); return num + 16 + this.MessageAuthenticationCode.Length + this.Other.Length; } internal override DnsResourceData CreateInstance(DnsDatagram dns, int offsetInDns, int length) { if (length < 17) return (DnsResourceData) null; DnsDomainName domainName; int numBytesRead; if (!DnsDomainName.TryParse(dns, offsetInDns, length - 16, out domainName, out numBytesRead)) return (DnsResourceData) null; offsetInDns += numBytesRead; length -= numBytesRead; if (length < 16) return (DnsResourceData) null; UInt48 timeSigned = dns.ReadUInt48(offsetInDns, Endianity.Big); ushort fudge = dns.ReadUShort(offsetInDns + 6, Endianity.Big); int length1 = (int) dns.ReadUShort(offsetInDns + 8, Endianity.Big); if (length < 16 + length1) return (DnsResourceData) null; DataSegment messageAuthenticationCode = dns.Subsegment(offsetInDns + 10, length1); int num = 10 + length1; offsetInDns += num; length -= num; ushort originalId = dns.ReadUShort(offsetInDns, Endianity.Big); DnsResponseCode error = (DnsResponseCode) dns.ReadUShort(offsetInDns + 2, Endianity.Big); int length2 = (int) dns.ReadUShort(offsetInDns + 4, Endianity.Big); if (length != 6 + length2) return (DnsResourceData) null; DataSegment other = dns.Subsegment(offsetInDns + 6, length2); return (DnsResourceData) new DnsResourceDataTransactionSignature(domainName, timeSigned, fudge, messageAuthenticationCode, originalId, error, other); } private static class OffsetAfterAlgorithm { public const int TimeSigned = 0; public const int Fudge = 6; public const int MessageAuthenticationCodeSize = 8; public const int MessageAuthenticationCode = 10; } private static class OffsetAfterMessageAuthenticationCode { public const int OriginalId = 0; public const int Error = 2; public const int OtherLength = 4; public const int OtherData = 6; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Base.DateTimeExtensions // Assembly: PcapDotNet.Base, Version=0.10.0.20668, Culture=neutral, PublicKeyToken=<KEY> // MVID: E9656A63-0145-422C-B8C8-79FDD7FB4270 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Base.dll using System; using System.Globalization; namespace PcapDotNet.Base { public static class DateTimeExtensions { public static DateTime AddMicroseconds(this DateTime dateTime, double value) { if (value > 9.22337203685478E+17) throw new ArgumentOutOfRangeException("value", (object) value, string.Format((IFormatProvider) CultureInfo.InvariantCulture, "Value cannot be bigger than {0}", new object[1] { (object) 922337203685477580 })); if (value < -9.22337203685478E+17) throw new ArgumentOutOfRangeException("value", (object) value, string.Format((IFormatProvider) CultureInfo.InvariantCulture, "Value cannot be smaller than {0}", new object[1] { (object) -922337203685477580 })); long num = (long) Math.Round(value) * 10L; return dateTime.AddTicks(num); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Http.HttpParser // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PcapDotNet.Packets.Http { internal class HttpParser { private static readonly byte[] _httpSlash = Encoding.ASCII.GetBytes("HTTP/"); private readonly byte[] _buffer; private int _offset; private readonly int _totalLength; public bool Success { get; private set; } public int Offset { get { return this._offset; } } private IEnumerable<byte> Range { get { return IListExtensions.Range<byte>((IList<byte>) this._buffer, this._offset, this._totalLength - this._offset); } } public HttpParser(byte[] buffer) : this(buffer, 0, buffer.Length) { } public HttpParser(byte[] buffer, int offset, int length) { this._buffer = buffer; this._offset = offset; this._totalLength = offset + length; this.Success = offset >= 0 && length >= 0 && offset + length <= buffer.Length; } public HttpParser Token(out Datagram token) { if (!this.Success) { token = (Datagram) null; return this; } int length = Enumerable.Count<byte>(Enumerable.TakeWhile<byte>(this.Range, (Func<byte, bool>) (value => ByteExtensions.IsToken(value)))); if (length == 0) { token = (Datagram) null; return this.Fail(); } token = new Datagram(this._buffer, this._offset, length); this._offset += token.Length; return this; } public HttpParser Token(out string token) { Datagram token1; this.Token(out token1); token = this.Success ? token1.Decode(Encoding.ASCII) : (string) null; return this; } public HttpParser Colon() { return this.Bytes((byte) 58); } public HttpParser Dot() { return this.Bytes((byte) 46); } public HttpParser Space() { return this.Bytes((byte) 32); } public HttpParser SkipSpaces() { while (this.IsNext((byte) 32)) this.Skip(1); return this; } public HttpParser SkipLws() { while (true) { IEnumerable<byte> range = this.Range; byte num = Enumerable.FirstOrDefault<byte>(range); if (ByteExtensions.IsSpaceOrHorizontalTab(num)) ++this._offset; else if ((int) num == 13) { IEnumerable<byte> source = Enumerable.Skip<byte>(range, 1); if ((int) Enumerable.FirstOrDefault<byte>(source) == 10 && ByteExtensions.IsSpaceOrHorizontalTab(Enumerable.FirstOrDefault<byte>(Enumerable.Skip<byte>(source, 1)))) this._offset += 3; else break; } else break; } return this; } public HttpParser FieldContent(out IEnumerable<byte> fieldContent) { int offset = this.Offset; fieldContent = (IEnumerable<byte>) null; while (this.Success) { fieldContent = (IEnumerable<byte>) new Datagram(this._buffer, offset, this.Offset - offset); if (!this.IsNext((byte) 32) && !this.IsNext((byte) 13) && (!this.IsNext((byte) 9) && !this.IsNext((byte) 10))) { if (this.IsNext((byte) 34)) { Datagram quotedString; this.QuotedString(out quotedString); } else { IEnumerable<byte> source = Enumerable.TakeWhile<byte>(this.Range, (Func<byte, bool>) (value => { if ((int) value > 32) return (int) value != 34; return false; })); if (!Enumerable.Any<byte>(source)) return this.Fail(); this._offset += Enumerable.Count<byte>(source); } } else break; } return this; } public HttpParser FieldValue(out IEnumerable<byte> fieldValue) { if (!this.Success) { fieldValue = (IEnumerable<byte>) null; return this; } this.SkipLws(); this.FieldContent(out fieldValue); if (!Enumerable.Any<byte>(fieldValue)) return this; while (this.Success) { this.SkipLws(); IEnumerable<byte> fieldContent; this.FieldContent(out fieldContent); if (Enumerable.Any<byte>(fieldContent)) fieldValue = Enumerable.Concat<byte>(IEnumerableExtensions.Concat<byte>(fieldValue, (byte) 32), fieldContent); else break; } return this; } public HttpParser RequestUri(out string uri) { if (!this.Success) { uri = (string) null; return this; } int count = Enumerable.Count<byte>(Enumerable.TakeWhile<byte>(this.Range, (Func<byte, bool>) (value => (int) value > 32))); uri = EncodingExtensions.Iso88591.GetString(this._buffer, this._offset, count); this._offset += count; return this; } public HttpParser Version(out HttpVersion version) { uint? number1; uint? number2; this.Bytes(HttpParser._httpSlash).DecimalNumber(out number1).Dot().DecimalNumber(out number2); version = !number1.HasValue || !number2.HasValue ? (HttpVersion) null : new HttpVersion(number1.Value, number2.Value); return this; } public HttpParser CarriageReturnLineFeed() { return this.Bytes((byte) 13, (byte) 10); } public bool IsCarriageReturnLineFeed() { if (this.IsNext((byte) 13)) return this.IsNextNext((byte) 10); return false; } public HttpParser DecimalNumber(int numDigits, out uint? number) { if (numDigits > 8 || numDigits < 0) throw new ArgumentOutOfRangeException("numDigits", (object) numDigits, "Only between 0 and 8 digits are supported"); if (!this.Success) { number = new uint?(); return this; } IEnumerable<byte> source = Enumerable.TakeWhile<byte>(Enumerable.Take<byte>(this.Range, numDigits), (Func<byte, bool>) (value => ByteExtensions.IsDigit(value))); if (Enumerable.Count<byte>(source) != numDigits) { number = new uint?(); return this.Fail(); } number = new uint?(Enumerable.Aggregate<uint, uint>(Enumerable.Select<byte, uint>(source, (Func<byte, uint>) (value => (uint) value - 48U)), 0U, (Func<uint, uint, uint>) ((accumulated, value) => 10U * accumulated + value))); this._offset += numDigits; return this; } public HttpParser DecimalNumber(out uint? number) { if (!this.Success) { number = new uint?(); return this; } IEnumerable<byte> source = Enumerable.TakeWhile<byte>(this.Range, (Func<byte, bool>) (value => ByteExtensions.IsDigit(value))); if (!Enumerable.Any<byte>(source)) { number = new uint?(); return this.Fail(); } int num1 = Enumerable.Count<byte>(source); int num2 = Enumerable.Count<byte>(Enumerable.TakeWhile<byte>(source, (Func<byte, bool>) (value => (int) value == 48))); if (num1 - num2 > 9) { number = new uint?(); return this.Fail(); } uint num3 = Enumerable.Aggregate<uint, uint>(Enumerable.Select<byte, uint>(source, (Func<byte, uint>) (value => (uint) value - 48U)), 0U, (Func<uint, uint, uint>) ((accumulated, value) => 10U * accumulated + value)); number = new uint?(num3); this._offset += num1; return this; } public HttpParser HexadecimalNumber(out uint? number) { if (!this.Success) { number = new uint?(); return this; } IEnumerable<byte> source = Enumerable.TakeWhile<byte>(this.Range, (Func<byte, bool>) (value => ByteExtensions.IsHexadecimalDigit(value))); if (!Enumerable.Any<byte>(source)) { number = new uint?(); return this.Fail(); } int num1 = Enumerable.Count<byte>(source); int num2 = Enumerable.Count<byte>(Enumerable.TakeWhile<byte>(source, (Func<byte, bool>) (value => (int) value == 48))); if (num1 - num2 > 8) { number = new uint?(); return this.Fail(); } uint num3 = Enumerable.Aggregate<uint, uint>(Enumerable.Select<byte, uint>(source, (Func<byte, uint>) (value => (uint) ByteExtensions.ToHexadecimalValue(value))), 0U, (Func<uint, uint, uint>) ((accumulated, value) => 16U * accumulated + value)); number = new uint?(num3); this._offset += num1; return this; } public HttpParser ReasonPhrase(out Datagram reasonPhrase) { if (!this.Success) { reasonPhrase = (Datagram) null; return this; } int num1 = 0; foreach (byte num2 in this.Range) { if (ByteExtensions.IsControl(num2)) { if ((int) num2 != 9) break; } ++num1; } int length = Enumerable.Count<byte>(Enumerable.TakeWhile<byte>(this.Range, (Func<byte, bool>) (value => { if (ByteExtensions.IsControl(value)) return (int) value == 9; return true; }))); reasonPhrase = new Datagram(this._buffer, this._offset, length); this._offset += length; return this; } public HttpParser QuotedString(out Datagram quotedString) { quotedString = (Datagram) null; int offset = this._offset; if (!this.Bytes((byte) 34).Success) return this; while (this.IsNext()) { byte num1 = this.Next(); switch (num1) { case (byte) 34: ++this._offset; quotedString = new Datagram(this._buffer, offset, this._offset - offset); return this; case (byte) 92: if (this.IsNextNext() && ByteExtensions.IsChar(this.NextNext())) { this._offset += 2; continue; } break; } int num2 = this._offset; this.SkipLws(); if (num2 == this._offset) { if (ByteExtensions.IsControl(num1)) return this.Fail(); ++this._offset; } } return this.Fail(); } public HttpParser SkipChunkExtensions() { while (this.Success && this.IsNext((byte) 59)) { this.Bytes((byte) 59); string token; this.Token(out token); if (this.IsNext((byte) 61)) { this.Bytes((byte) 61); Datagram datagram; if (this.IsNext((byte) 34)) this.QuotedString(out datagram); else this.Token(out datagram); } } return this; } private bool IsNext() { return this._offset < this._totalLength; } private bool IsNext(byte next) { if (this.IsNext()) return (int) this.Next() == (int) next; return false; } private bool IsNextNext() { return this._offset + 1 < this._totalLength; } private bool IsNextNext(byte nextNext) { if (this.IsNextNext()) return (int) this.NextNext() == (int) nextNext; return false; } private byte Next() { return this._buffer[this._offset]; } private byte NextNext() { return this._buffer[this._offset + 1]; } private HttpParser Fail() { this.Success = false; return this; } private HttpParser Bytes(byte value) { if (!this.Success) return this; IEnumerable<byte> range = this.Range; if (!Enumerable.Any<byte>(range) || (int) Enumerable.First<byte>(range) != (int) value) return this.Fail(); ++this._offset; return this; } private HttpParser Bytes(params byte[] values) { if (!this.Success) return this; if (!Enumerable.SequenceEqual<byte>(Enumerable.Take<byte>(this.Range, values.Length), (IEnumerable<byte>) values)) return this.Fail(); this._offset += values.Length; return this; } public HttpParser Skip(int count) { this._offset += count; if (this._offset > this._totalLength) return this.Fail(); return this; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.IpV4SocketAddress // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using PcapDotNet.Packets.IpV4; using System; using System.Net; using System.Text; namespace PcapDotNet.Core { public sealed class IpV4SocketAddress : SocketAddress { private IpV4Address _address; public IpV4Address Address { get { return this._address; } } internal unsafe IpV4SocketAddress(sockaddr* address) : base(*(ushort*) address) { this._address = new IpV4Address((uint) IPAddress.HostToNetworkOrder(*(int*) ((IntPtr) address + 4L))); } public override sealed string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(base.ToString()); stringBuilder.Append(" "); IpV4Address ipV4Address = this._address; stringBuilder.Append((object) ipV4Address); return stringBuilder.ToString(); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Ethernet.ClassOfService // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Ethernet { public enum ClassOfService : byte { BestEffort, Background, ExcellentEffort, CriticalApplications, Video, Voice, InternetworkControl, NetworkControl, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Igmp.IgmpVersion2Layer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using System; namespace PcapDotNet.Packets.Igmp { public abstract class IgmpVersion2Layer : IgmpSimpleLayer { public TimeSpan MaxResponseTime { get; set; } public override sealed TimeSpan MaxResponseTimeValue { get { return this.MaxResponseTime; } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.SocketAddressFamily // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll namespace PcapDotNet.Core { public enum SocketAddressFamily : ushort { Unspecified = (ushort) 0, Unix = (ushort) 1, Internet = (ushort) 2, ImpLink = (ushort) 3, Pup = (ushort) 4, Chaos = (ushort) 5, Ipx = (ushort) 6, NS = (ushort) 6, Iso = (ushort) 7, Osi = (ushort) 7, EuropeanComputerManufactures = (ushort) 8, Datakit = (ushort) 9, Ccitt = (ushort) 10, Sna = (ushort) 11, DECnet = (ushort) 12, DirectDataLinkInterface = (ushort) 13, Lat = (ushort) 14, HyperChannel = (ushort) 15, AppleTalk = (ushort) 16, NetBios = (ushort) 17, VoiceView = (ushort) 18, Firefox = (ushort) 19, Unknown1 = (ushort) 20, Ban = (ushort) 21, Atm = (ushort) 22, Internet6 = (ushort) 23, Cluster = (ushort) 24, Ieee12844 = (ushort) 25, Irda = (ushort) 26, NetworkDesigners = (ushort) 28, TcnProcess = (ushort) 29, TcnMessage = (ushort) 30, Iclfxbm = (ushort) 31, Bluetooth = (ushort) 32, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Base.PropertyInfoExtensions // Assembly: PcapDotNet.Base, Version=0.10.0.20668, Culture=neutral, PublicKeyToken=<KEY> // MVID: E9656A63-0145-422C-B8C8-79FDD7FB4270 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Base.dll using System; using System.Reflection; namespace PcapDotNet.Base { public static class PropertyInfoExtensions { public static object GetValue(this PropertyInfo propertyInfo, object instanceWithProperty) { if (propertyInfo == (PropertyInfo) null) throw new ArgumentNullException("propertyInfo"); return propertyInfo.GetValue(instanceWithProperty, (object[]) null); } } } <file_sep>using Newtonsoft.Json; using System; using System.Net.Http; using System.Threading.Tasks; using WUnderground.Client.Models; namespace WUnderground.Client { /// <summary> /// The client object to access the WUnderground API /// </summary> public class WUndergroundClient { private const string GeolookupAndCurrentConditionsUri = "http://api.wunderground.com/api/{0}/geolookup/conditions/q/{1},{2}.json"; private const string GeolookupCurrentConditionsAndForecastUri = "http://api.wunderground.com/api/{0}/geolookup/conditions/forecast/q/{1},{2}.json"; private const string GeolookupHourlyForecastUri = "http://api.wunderground.com/api/27d9503963b27155/geolookup/hourly/q/{1},{2}.json"; /// <summary> /// Gets the current conditions for the specified coordinates /// </summary> /// <param name="lat">The latitude</param> /// <param name="lng">The longitude</param> /// <returns>The response object</returns> public static async Task<WeatherResponse> GetConditionsForLocationAsync(double lat, double lng) { string uri = string.Format(GeolookupAndCurrentConditionsUri, Config.ApiKey, lat, lng); using (var client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync(uri); if (response.IsSuccessStatusCode) { var content = response.Content.ReadAsStringAsync().Result; WeatherResponse weatherResponse = JsonConvert.DeserializeObject<WeatherResponse>(content); if (weatherResponse.response.error != null) throw new WUndergroundException(weatherResponse.response.error.description); return weatherResponse; } } return null; } /// <summary> /// Gets the current conditions and forecast of the specified coordinates /// </summary> /// <param name="lat">The latitude</param> /// <param name="lng">The longitude</param> /// <returns>The response object</returns> public static async Task<WeatherResponse> GetConditionsAndForecastForLocationAsync(double lat, double lng) { string uri = string.Format(GeolookupCurrentConditionsAndForecastUri, Config.ApiKey, lat, lng); using (var client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync(uri); if (response.IsSuccessStatusCode) { var content = response.Content.ReadAsStringAsync().Result; WeatherResponse weatherResponse = JsonConvert.DeserializeObject<WeatherResponse>(content); return weatherResponse; } } return null; } /// <summary> /// The configuration for the WUnderground Client /// </summary> public static class Config { /// <summary> /// The API Key for the WUnderground API. Get yours at http://www.wunderground.com /// </summary> public static string ApiKey { get; set; } } } /// <summary> /// An exception thrown by the WUnderground service /// </summary> public class WUndergroundException : Exception { /// <summary> /// Creates a new WUnderground exception with the specified message /// </summary> /// <param name="message">The message</param> public WUndergroundException(string message) : base(message) { } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Ethernet.EthernetType // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Ethernet { public enum EthernetType : ushort { None = (ushort) 0, IpV4 = (ushort) 2048, Arp = (ushort) 2054, ReverseArp = (ushort) 32821, AppleTalk = (ushort) 32923, AppleTalkArp = (ushort) 33011, VLanTaggedFrame = (ushort) 33024, NovellInternetworkPacketExchange = (ushort) 33079, Novell = (ushort) 33080, IpV6 = (ushort) 34525, MacControl = (ushort) 34824, PointToPointProtocol = (ushort) 34827, CobraNet = (ushort) 34841, MultiprotocolLabelSwitchingUnicast = (ushort) 34887, MultiprotocolLabelSwitchingMulticast = (ushort) 34888, PointToPointProtocolOverEthernetDiscoveryStage = (ushort) 34915, PointToPointProtocolOverEthernetSessionStage = (ushort) 34916, ExtensibleAuthenticationProtocolOverLan = (ushort) 34958, HyperScsi = (ushort) 34970, AtaOverEthernet = (ushort) 34978, EtherCatProtocol = (ushort) 34980, ProviderBridging = (ushort) 34984, AvbTransportProtocol = (ushort) 34997, SerialRealTimeCommunicationSystemIii = (ushort) 35021, CircuitEmulationServicesOverEthernet = (ushort) 35032, HomePlug = (ushort) 35041, MacSecurity = (ushort) 35045, PrecisionTimeProtocol = (ushort) 35063, ConnectivityFaultManagementOrOperationsAdministrationManagement = (ushort) 35074, FibreChannelOverEthernet = (ushort) 35078, FibreChannelOverEthernetInitializationProtocol = (ushort) 35092, QInQ = (ushort) 37120, VeritasLowLatencyTransport = (ushort) 51966, } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace Grib.Api.Interop.Util { internal static class GribApiNative { [DllImport("Grib.Api.Native.dll", CharSet = CharSet.Ansi)] internal static extern void GetGribKeysIteratorName (StringBuilder name, IntPtr iter); [DllImport("Grib.Api.Native.dll")] internal static extern IntPtr CreateFileHandleProxy ([MarshalAs(UnmanagedType.LPStr)]string filename); [DllImport("Grib.Api.Native.dll")] internal static extern void DestroyFileHandleProxy (IntPtr fileHandleProxy); [DllImport("Grib.Api.Native.dll")] internal static extern bool GribKeyIsReadOnly(HandleRef gribHandle, [MarshalAs(UnmanagedType.LPStr)]string keyName); [DllImport("Grib.Api.Native.dll", EntryPoint="DeleteGribBox")] private static extern int _DeleteGribBox(HandleRef box); internal static void DeleteGribBox(HandleRef box) { int ret = _DeleteGribBox(box); if (ret != 0) { throw GribApiException.Create(ret); } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.TcpOptionMd5Signature // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace PcapDotNet.Packets.Transport { [OptionTypeRegistration(typeof (TcpOptionType), TcpOptionType.Md5Signature)] public sealed class TcpOptionMd5Signature : TcpOptionComplex, IOptionComplexFactory, IEquatable<TcpOptionMd5Signature> { public const int OptionLength = 18; public const int OptionValueLength = 16; public ReadOnlyCollection<byte> Data { get; private set; } public override int Length { get { return 18; } } public override bool IsAppearsAtMostOnce { get { return true; } } public TcpOptionMd5Signature(IList<byte> data) : base(TcpOptionType.Md5Signature) { if (data == null) throw new ArgumentNullException("data"); if (data.Count != 16) throw new ArgumentException("data must be " + (object) 16 + " bytes and not " + (string) (object) data.Count + " bytes", "data"); this.Data = new ReadOnlyCollection<byte>(data); } public TcpOptionMd5Signature() : this((IList<byte>) new byte[16]) { } public bool Equals(TcpOptionMd5Signature other) { if (other == null) return false; return Enumerable.SequenceEqual<byte>((IEnumerable<byte>) this.Data, (IEnumerable<byte>) other.Data); } public override bool Equals(TcpOption other) { return this.Equals(other as TcpOptionMd5Signature); } public override int GetHashCode() { return base.GetHashCode() ^ IEnumerableExtensions.BytesSequenceGetHashCode((IEnumerable<byte>) this.Data); } Option IOptionComplexFactory.CreateInstance(byte[] buffer, ref int offset, byte valueLength) { if ((int) valueLength != 16) return (Option) null; return (Option) new TcpOptionMd5Signature((IList<byte>) ByteArrayExtensions.ReadBytes(buffer, ref offset, 16)); } internal override void Write(byte[] buffer, ref int offset) { base.Write(buffer, ref offset); ByteArrayExtensions.Write(buffer, ref offset, (IEnumerable<byte>) this.Data); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpIpV4PayloadDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets.IpV4; namespace PcapDotNet.Packets.Icmp { public abstract class IcmpIpV4PayloadDatagram : IcmpDatagram { private IpV4Datagram _ipV4; public IpV4Datagram IpV4 { get { if (this._ipV4 == null && this.Length >= 8) this._ipV4 = new IpV4Datagram(this.Buffer, this.StartOffset + 8, this.Length - 8); return this._ipV4; } } internal IcmpIpV4PayloadDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } protected override bool CalculateIsValid() { if (!base.CalculateIsValid()) return false; IpV4Datagram ipV4 = this.IpV4; if (ipV4.Length >= 20) return ipV4.Length >= ipV4.HeaderLength; return false; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.OptionTypeRegistrationAttribute // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using System; namespace PcapDotNet.Packets { internal sealed class OptionTypeRegistrationAttribute : Attribute { public object OptionType { get; private set; } public Type OptionTypeType { get; private set; } public OptionTypeRegistrationAttribute(Type optionTypeType, object optionType) { this.OptionTypeType = optionTypeType; this.OptionType = optionType; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IpV4OptionSecurityClassificationLevel // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.IpV4 { public enum IpV4OptionSecurityClassificationLevel : byte { None = (byte) 0, TopSecret = (byte) 61, Secret = (byte) 90, Confidential = (byte) 150, Unclassified = (byte) 171, } } <file_sep>using System; using CGurus.Weather.WundergroundAPI; namespace TestConsole { //todo: http://research.microsoft.com/en-us/projects/fetchclimate/ //todo: extract from wu update local sql: http://decisivefigures.com/2013/04/01/extracting-data-from-the-weather-underground-api/ // to check: in vb: https://social.msdn.microsoft.com/Forums/vstudio/en-US/10c8d7a3-b749-40e9-8253-966d5e8d6c42/weather-underground-some-help-getting-the-information-from-their-api?forum=vbgeneral class Program { // Replace station id with your wunderground station id // Replace [password] with your wunderground password public const string WU_STATION_ID = "IYUCATNM14"; public const string WU_STATION_PWD = <PASSWORD>$"; public const string WU_API = "<KEY>"; static void Main(string[] args) { // api account: <EMAIL> // api key: <KEY> WUApi wuApi = new WUApi(WU_API); CGurus.Weather.WundergroundAPI.Models.AlertData alerts = wuApi.GetAlertsUS("CA", "San Francisco"); CGurus.Weather.WundergroundAPI.Models.ForecastData forecast = wuApi.GetForecastUS("CA", "San Francisco"); CGurus.Weather.WundergroundAPI.Models.ForecastData forecast10Day = wuApi.GetForecast10DayUS("CA", "San Francisco"); CGurus.Weather.WundergroundAPI.Models.ForecastHourlyData forecastHourlyUS = wuApi.GetForecastHourlyUS("CA", "San Francisco"); WUConditionsXml.GetWeather(WU_API, "CA", "San Francisco"); WUUpdateWeatherStationDto wuuwsdto = new WUUpdateWeatherStationDto { DateUtc = DateTime.UtcNow, WindDir = 92.1f, WindSpeedMph = 12.3f, WindGustMph = 14.4f, Tempf = 87.4f, DewPtF = 78.4f, RainIn = 0.4f, DailyRainIn = 1.7f, BaromIn = 29.96f, Humidity = 55.5F }; WUUpdateWeatherStation wuuws = new WUUpdateWeatherStation(WU_STATION_ID, WU_STATION_PWD); wuuws.Update(wuuwsdto); Console.ReadLine(); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsSinkCoding // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Dns { public enum DnsSinkCoding : byte { None = (byte) 0, Asn1Snmp = (byte) 1, Asn1Osi1990 = (byte) 2, Asn1Osi1994 = (byte) 3, AsnPrivate = (byte) 63, DnsResourceRecords = (byte) 64, Mime = (byte) 65, TextTaggedData = (byte) 66, PrivateByUrl = (byte) 254, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.TcpLayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using PcapDotNet.Packets.IpV4; namespace PcapDotNet.Packets.Transport { public sealed class TcpLayer : TransportLayer { public uint SequenceNumber { get; set; } public uint AcknowledgmentNumber { get; set; } public TcpControlBits ControlBits { get; set; } public ushort Window { get; set; } public ushort UrgentPointer { get; set; } public TcpOptions Options { get; set; } public override IpV4Protocol PreviousLayerProtocol { get { return IpV4Protocol.Tcp; } } public override int ChecksumOffset { get { return 16; } } public override bool IsChecksumOptional { get { return false; } } public override int Length { get { return 20 + this.Options.BytesLength; } } public TcpLayer() { this.Options = TcpOptions.None; } public override void Write(byte[] buffer, int offset, int payloadLength, ILayer previousLayer, ILayer nextLayer) { TcpDatagram.WriteHeader(buffer, offset, this.SourcePort, this.DestinationPort, this.SequenceNumber, this.AcknowledgmentNumber, this.ControlBits, this.Window, this.UrgentPointer, this.Options); } protected override bool EqualFields(TransportLayer other) { return this.EqualFields(other as TcpLayer); } private bool EqualFields(TcpLayer other) { if (other != null && (int) this.SequenceNumber == (int) other.SequenceNumber && ((int) this.AcknowledgmentNumber == (int) other.AcknowledgmentNumber && this.ControlBits == other.ControlBits) && ((int) this.Window == (int) other.Window && (int) this.UrgentPointer == (int) other.UrgentPointer)) return this.Options.Equals((PcapDotNet.Packets.Options<TcpOption>) other.Options); return false; } } } <file_sep> namespace CGurus.Weather.WundergroundAPI.Models { public class Wind { public double? Degrees { get; set; } public string Dir { get; set; } public double? Kph { get; set; } public double? Mph { get; set; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataNamingAuthorityPointer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Text; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.NaPtr)] public sealed class DnsResourceDataNamingAuthorityPointer : DnsResourceDataNoCompression, IEquatable<DnsResourceDataNamingAuthorityPointer> { private const int ConstantPartLength = 4; private const int MinimumLength = 8; public ushort Order { get; private set; } public ushort Preference { get; private set; } [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Flags")] public DataSegment Flags { get; private set; } public DataSegment Services { get; private set; } public DataSegment RegularExpression { get; private set; } public DnsDomainName Replacement { get; private set; } [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "flags")] public DnsResourceDataNamingAuthorityPointer(ushort order, ushort preference, DataSegment flags, DataSegment services, DataSegment regularExpression, DnsDomainName replacement) { if (flags == null) throw new ArgumentNullException("flags"); if (!DnsResourceDataNamingAuthorityPointer.IsLegalFlags(flags)) throw new ArgumentException(string.Format((IFormatProvider) CultureInfo.InvariantCulture, "Flags ({0}) contain a non [a-zA-Z0-9] character.", new object[1] { (object) Encoding.ASCII.GetString(flags.Buffer, flags.StartOffset, flags.Length) }), "flags"); this.Order = order; this.Preference = preference; this.Flags = !Enumerable.All<byte>((IEnumerable<byte>) flags, (Func<byte, bool>) (flag => { if ((int) flag >= 97) return (int) flag > 122; return true; })) || !IEnumerableExtensions.IsStrictOrdered<byte>((IEnumerable<byte>) flags) ? new DataSegment(Enumerable.ToArray<byte>((IEnumerable<byte>) Enumerable.OrderBy<byte, byte>(Enumerable.Distinct<byte>(Enumerable.Select<byte, byte>((IEnumerable<byte>) flags, (Func<byte, byte>) (flag => { if ((int) flag < 97 || (int) flag > 122) return flag; return (byte) ((int) flag + 65 - 97); }))), (Func<byte, byte>) (flag => flag)))) : flags; this.Services = services; this.RegularExpression = regularExpression; this.Replacement = replacement; } internal DnsResourceDataNamingAuthorityPointer() : this((ushort) 0, (ushort) 0, DataSegment.Empty, DataSegment.Empty, DataSegment.Empty, DnsDomainName.Root) { } public bool Equals(DnsResourceDataNamingAuthorityPointer other) { if (other != null && this.Order.Equals(other.Order) && (this.Preference.Equals(other.Preference) && this.Flags.Equals(other.Flags) && (this.Services.Equals(other.Services) && this.RegularExpression.Equals(other.RegularExpression)))) return this.Replacement.Equals(other.Replacement); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataNamingAuthorityPointer); } public override int GetHashCode() { return Sequence.GetHashCode((object) BitSequence.Merge(this.Order, this.Preference), (object) this.Flags, (object) this.Services, (object) this.RegularExpression, (object) this.Replacement); } internal override int GetLength() { return 4 + DnsResourceData.GetStringLength(this.Flags) + DnsResourceData.GetStringLength(this.Services) + DnsResourceData.GetStringLength(this.RegularExpression) + this.Replacement.NonCompressedLength; } internal override int WriteData(byte[] buffer, int offset) { ByteArrayExtensions.Write(buffer, offset, this.Order, Endianity.Big); ByteArrayExtensions.Write(buffer, offset + 2, this.Preference, Endianity.Big); offset += 4; DnsResourceData.WriteString(buffer, ref offset, this.Flags); DnsResourceData.WriteString(buffer, ref offset, this.Services); DnsResourceData.WriteString(buffer, ref offset, this.RegularExpression); this.Replacement.WriteUncompressed(buffer, offset); return this.GetLength(); } internal override DnsResourceData CreateInstance(DnsDatagram dns, int offsetInDns, int length) { if (length < 8) return (DnsResourceData) null; ushort order = dns.ReadUShort(offsetInDns, Endianity.Big); ushort preference = dns.ReadUShort(offsetInDns + 2, Endianity.Big); DataSegment data = dns.Subsegment(offsetInDns + 4, length - 4); int offset = 0; DataSegment flags = DnsResourceData.ReadString(data, ref offset); if (flags == null || !DnsResourceDataNamingAuthorityPointer.IsLegalFlags(flags)) return (DnsResourceData) null; DataSegment services = DnsResourceData.ReadString(data, ref offset); if (services == null) return (DnsResourceData) null; DataSegment regularExpression = DnsResourceData.ReadString(data, ref offset); if (regularExpression == null) return (DnsResourceData) null; DnsDomainName domainName; int numBytesRead; if (!DnsDomainName.TryParse(dns, offsetInDns + 4 + offset, length - 4 - offset, out domainName, out numBytesRead)) return (DnsResourceData) null; if (4 + offset + numBytesRead != length) return (DnsResourceData) null; return (DnsResourceData) new DnsResourceDataNamingAuthorityPointer(order, preference, flags, services, regularExpression, domainName); } private static bool IsLegalFlags(DataSegment flags) { return Enumerable.All<byte>((IEnumerable<byte>) flags, (Func<byte, bool>) (flag => { if ((int) flag >= 48 && (int) flag <= 57 || (int) flag >= 65 && (int) flag <= 90) return true; if ((int) flag >= 97) return (int) flag <= 122; return false; })); } private static class Offset { public const int Order = 0; public const int Preference = 2; public const int Flags = 4; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.PacketDevice // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using System.Collections.ObjectModel; namespace PcapDotNet.Core { public abstract class PacketDevice : IPacketDevice { public const int DefaultSnapshotLength = 65536; public abstract ReadOnlyCollection<DeviceAddress> Addresses { get; } public abstract DeviceAttributes Attributes { get; } public abstract string Description { get; } public abstract string Name { get; } public virtual PacketCommunicator Open() { return this.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000); } public abstract PacketCommunicator Open(int snapshotLength, PacketDeviceOpenAttributes attributes, int readTimeout); } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataDomainName // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using System; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.MailForwarder)] [DnsTypeRegistration(Type = DnsType.Mailbox)] [DnsTypeRegistration(Type = DnsType.MailGroup)] [DnsTypeRegistration(Type = DnsType.DName)] [DnsTypeRegistration(Type = DnsType.NetworkServiceAccessPointPointer)] [DnsTypeRegistration(Type = DnsType.Ns)] [DnsTypeRegistration(Type = DnsType.Md)] [DnsTypeRegistration(Type = DnsType.CName)] [DnsTypeRegistration(Type = DnsType.MailRename)] [DnsTypeRegistration(Type = DnsType.Ptr)] public sealed class DnsResourceDataDomainName : DnsResourceData, IEquatable<DnsResourceDataDomainName> { public DnsDomainName Data { get; private set; } public DnsResourceDataDomainName(DnsDomainName data) { this.Data = data; } internal DnsResourceDataDomainName() : this(DnsDomainName.Root) { } public bool Equals(DnsResourceDataDomainName other) { if (other != null) return this.Data.Equals(other.Data); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataDomainName); } public override int GetHashCode() { return this.Data.GetHashCode(); } internal override int GetLength(DnsDomainNameCompressionData compressionData, int offsetInDns) { return this.Data.GetLength(compressionData, offsetInDns); } internal override int WriteData(byte[] buffer, int dnsOffset, int offsetInDns, DnsDomainNameCompressionData compressionData) { return this.Data.Write(buffer, dnsOffset, compressionData, offsetInDns); } internal override DnsResourceData CreateInstance(DnsDatagram dns, int offsetInDns, int length) { DnsDomainName domainName; int numBytesRead; if (!DnsDomainName.TryParse(dns, offsetInDns, length, out domainName, out numBytesRead)) return (DnsResourceData) null; length -= numBytesRead; if (length != 0) return (DnsResourceData) null; return (DnsResourceData) new DnsResourceDataDomainName(domainName); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.ByteArrayExtensions // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets.Ethernet; using PcapDotNet.Packets.IpV4; using PcapDotNet.Packets.IpV6; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Net; using System.Numerics; using System.Text; namespace PcapDotNet.Packets { public static class ByteArrayExtensions { public static int Compare(this byte[] array, int offset, byte[] other, int otherOffset, int count) { if (array == null) throw new ArgumentNullException("array"); if (other == null) throw new ArgumentNullException("other"); for (int index = 0; index != count; ++index) { int num = array[offset + index].CompareTo(other[otherOffset + index]); if (num != 0) return num; } return 0; } public static bool SequenceEqual(this byte[] array, int offset, byte[] other, int otherOffset, int count) { if (array == null) throw new ArgumentNullException("array"); return ByteArrayExtensions.Compare(array, offset, other, otherOffset, count) == 0; } public static int Find(this byte[] array, int offset, int count, byte[] other, int otherOffset, int otherCount) { if (array == null) throw new ArgumentNullException("array"); if (otherCount > count) return array.Length; for (int index = offset + count - otherCount; offset < index; ++offset) { if (ByteArrayExtensions.SequenceEqual(array, offset, other, otherOffset, otherCount)) return offset; } return array.Length; } public static int Find(this byte[] array, int offset, int count, byte[] other) { if (other == null) throw new ArgumentNullException("other"); return ByteArrayExtensions.Find(array, offset, count, other, 0, other.Length); } public static void BlockCopy(this byte[] source, int sourceOffset, byte[] destination, int destinationOffset, int count) { Buffer.BlockCopy((Array) source, sourceOffset, (Array) destination, destinationOffset, count); } public static byte ReadByte(this byte[] buffer, int offset) { if (buffer == null) throw new ArgumentNullException("buffer"); return buffer[offset]; } public static byte ReadByte(this byte[] buffer, ref int offset) { byte num = ByteArrayExtensions.ReadByte(buffer, offset); ++offset; return num; } public static byte[] ReadBytes(this byte[] buffer, int offset, int length) { byte[] destination = new byte[length]; ByteArrayExtensions.BlockCopy(buffer, offset, destination, 0, length); return destination; } public static byte[] ReadBytes(this byte[] buffer, ref int offset, int length) { byte[] numArray = ByteArrayExtensions.ReadBytes(buffer, offset, length); offset += length; return numArray; } [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "short")] public static short ReadShort(this byte[] buffer, int offset, Endianity endianity) { short num = ByteArrayExtensions.ReadShort(buffer, offset); if (ByteArrayExtensions.IsWrongEndianity(endianity)) num = ShortExtensions.ReverseEndianity(num); return num; } [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "ushort")] public static ushort ReadUShort(this byte[] buffer, int offset, Endianity endianity) { return (ushort) ByteArrayExtensions.ReadShort(buffer, offset, endianity); } [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "ushort")] public static ushort ReadUShort(this byte[] buffer, ref int offset, Endianity endianity) { ushort num = ByteArrayExtensions.ReadUShort(buffer, offset, endianity); offset += 2; return num; } public static UInt24 ReadUInt24(this byte[] buffer, int offset, Endianity endianity) { UInt24 uint24 = ByteArrayExtensions.ReadUInt24(buffer, offset); if (ByteArrayExtensions.IsWrongEndianity(endianity)) uint24 = ByteArrayExtensions.HostToNetworkOrder(uint24); return uint24; } public static UInt24 ReadUInt24(this byte[] buffer, ref int offset, Endianity endianity) { UInt24 uint24 = ByteArrayExtensions.ReadUInt24(buffer, offset, endianity); offset += 3; return uint24; } [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "int")] public static int ReadInt(this byte[] buffer, int offset, Endianity endianity) { int host = ByteArrayExtensions.ReadInt(buffer, offset); if (ByteArrayExtensions.IsWrongEndianity(endianity)) host = IPAddress.HostToNetworkOrder(host); return host; } [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "uint")] public static uint ReadUInt(this byte[] buffer, int offset, Endianity endianity) { return (uint) ByteArrayExtensions.ReadInt(buffer, offset, endianity); } [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "uint")] public static uint ReadUInt(this byte[] buffer, ref int offset, Endianity endianity) { uint num = ByteArrayExtensions.ReadUInt(buffer, offset, endianity); offset += 4; return num; } public static UInt48 ReadUInt48(this byte[] buffer, int offset, Endianity endianity) { UInt48 uint48 = ByteArrayExtensions.ReadUInt48(buffer, offset); if (ByteArrayExtensions.IsWrongEndianity(endianity)) uint48 = ByteArrayExtensions.HostToNetworkOrder(uint48); return uint48; } public static UInt48 ReadUInt48(this byte[] buffer, ref int offset, Endianity endianity) { UInt48 uint48 = ByteArrayExtensions.ReadUInt48(buffer, offset, endianity); offset += 6; return uint48; } [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "long")] public static long ReadLong(this byte[] buffer, int offset, Endianity endianity) { long host = ByteArrayExtensions.ReadLong(buffer, offset); if (ByteArrayExtensions.IsWrongEndianity(endianity)) host = IPAddress.HostToNetworkOrder(host); return host; } [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "ulong")] public static ulong ReadULong(this byte[] buffer, int offset, Endianity endianity) { return (ulong) ByteArrayExtensions.ReadLong(buffer, offset, endianity); } public static UInt128 ReadUInt128(this byte[] buffer, int offset, Endianity endianity) { UInt128 uint128 = ByteArrayExtensions.ReadUInt128(buffer, offset); if (ByteArrayExtensions.IsWrongEndianity(endianity)) uint128 = ByteArrayExtensions.HostToNetworkOrder(uint128); return uint128; } public static BigInteger ReadUnsignedBigInteger(this byte[] buffer, int offset, int length, Endianity endianity) { if (buffer == null) throw new ArgumentNullException("buffer"); BigInteger bigInteger1 = BigInteger.Zero; for (int index = 0; index != length; ++index) { BigInteger bigInteger2 = bigInteger1 << 8; bigInteger1 = endianity != Endianity.Big ? bigInteger2 + (BigInteger) buffer[offset + length - index - 1] : bigInteger2 + (BigInteger) buffer[offset + index]; } return bigInteger1; } public static MacAddress ReadMacAddress(this byte[] buffer, int offset, Endianity endianity) { return new MacAddress(ByteArrayExtensions.ReadUInt48(buffer, offset, endianity)); } public static MacAddress ReadMacAddress(this byte[] buffer, ref int offset, Endianity endianity) { return new MacAddress(ByteArrayExtensions.ReadUInt48(buffer, ref offset, endianity)); } public static IpV4Address ReadIpV4Address(this byte[] buffer, int offset, Endianity endianity) { return new IpV4Address(ByteArrayExtensions.ReadUInt(buffer, offset, endianity)); } public static IpV4Address ReadIpV4Address(this byte[] buffer, ref int offset, Endianity endianity) { return new IpV4Address(ByteArrayExtensions.ReadUInt(buffer, ref offset, endianity)); } public static IpV4TimeOfDay ReadIpV4TimeOfDay(this byte[] buffer, int offset, Endianity endianity) { return new IpV4TimeOfDay(ByteArrayExtensions.ReadUInt(buffer, offset, endianity)); } public static IpV4TimeOfDay ReadIpV4TimeOfDay(this byte[] buffer, ref int offset, Endianity endianity) { return new IpV4TimeOfDay(ByteArrayExtensions.ReadUInt(buffer, ref offset, endianity)); } public static IpV6Address ReadIpV6Address(this byte[] buffer, int offset, Endianity endianity) { return new IpV6Address(ByteArrayExtensions.ReadUInt128(buffer, offset, endianity)); } public static void Write(this byte[] buffer, int offset, byte value) { if (buffer == null) throw new ArgumentNullException("buffer"); buffer[offset] = value; } public static void Write(this byte[] buffer, ref int offset, byte value) { ByteArrayExtensions.Write(buffer, offset, value); ++offset; } public static void Write(this byte[] buffer, ref int offset, IEnumerable<byte> value) { if (buffer == null) throw new ArgumentNullException("buffer"); if (value == null) throw new ArgumentNullException("value"); foreach (byte num in value) ByteArrayExtensions.Write(buffer, offset++, num); } public static void Write(this byte[] buffer, int offset, short value, Endianity endianity) { if (ByteArrayExtensions.IsWrongEndianity(endianity)) value = ShortExtensions.ReverseEndianity(value); ByteArrayExtensions.Write(buffer, offset, value); } public static void Write(this byte[] buffer, int offset, ushort value, Endianity endianity) { ByteArrayExtensions.Write(buffer, offset, (short) value, endianity); } public static void Write(this byte[] buffer, ref int offset, ushort value, Endianity endianity) { ByteArrayExtensions.Write(buffer, offset, value, endianity); offset += 2; } public static void Write(this byte[] buffer, int offset, UInt24 value, Endianity endianity) { if (ByteArrayExtensions.IsWrongEndianity(endianity)) value = ByteArrayExtensions.HostToNetworkOrder(value); ByteArrayExtensions.Write(buffer, offset, value); } public static void Write(this byte[] buffer, ref int offset, UInt24 value, Endianity endianity) { ByteArrayExtensions.Write(buffer, offset, value, endianity); offset += 3; } public static void Write(this byte[] buffer, int offset, int value, Endianity endianity) { if (ByteArrayExtensions.IsWrongEndianity(endianity)) value = IPAddress.HostToNetworkOrder(value); ByteArrayExtensions.Write(buffer, offset, value); } public static void Write(this byte[] buffer, ref int offset, int value, Endianity endianity) { ByteArrayExtensions.Write(buffer, offset, value, endianity); offset += 4; } public static void Write(this byte[] buffer, int offset, uint value, Endianity endianity) { ByteArrayExtensions.Write(buffer, offset, (int) value, endianity); } public static void Write(this byte[] buffer, ref int offset, uint value, Endianity endianity) { ByteArrayExtensions.Write(buffer, offset, value, endianity); offset += 4; } public static void Write(this byte[] buffer, int offset, UInt48 value, Endianity endianity) { if (ByteArrayExtensions.IsWrongEndianity(endianity)) value = ByteArrayExtensions.HostToNetworkOrder(value); ByteArrayExtensions.Write(buffer, offset, value); } public static void Write(this byte[] buffer, ref int offset, UInt48 value, Endianity endianity) { ByteArrayExtensions.Write(buffer, offset, value, endianity); offset += 6; } public static void Write(this byte[] buffer, int offset, long value, Endianity endianity) { if (ByteArrayExtensions.IsWrongEndianity(endianity)) value = IPAddress.HostToNetworkOrder(value); ByteArrayExtensions.Write(buffer, offset, value); } public static void Write(this byte[] buffer, int offset, ulong value, Endianity endianity) { ByteArrayExtensions.Write(buffer, offset, (long) value, endianity); } public static void Write(this byte[] buffer, int offset, UInt128 value, Endianity endianity) { if (ByteArrayExtensions.IsWrongEndianity(endianity)) value = ByteArrayExtensions.HostToNetworkOrder(value); ByteArrayExtensions.Write(buffer, offset, value); } public static void WriteUnsigned(this byte[] buffer, int offset, BigInteger value, int length, Endianity endianity) { if (buffer == null) throw new ArgumentNullException("buffer"); if (value.Sign < 0) throw new ArgumentOutOfRangeException("value", (object) value, "Must be non-negative."); int num1 = 0; while (num1 != length && value != BigInteger.Zero) { byte num2 = (byte) (value & (BigInteger) ((int) byte.MaxValue)); if (endianity == Endianity.Small) buffer[offset + num1] = num2; else buffer[offset + length - num1 - 1] = num2; ++num1; value >>= 8; } } public static void Write(this byte[] buffer, ref int offset, string value, Encoding encoding) { if (encoding == null) throw new ArgumentNullException("encoding"); ByteArrayExtensions.Write(buffer, ref offset, (IEnumerable<byte>) encoding.GetBytes(value)); } public static void Write(this byte[] buffer, int offset, DataSegment value) { ByteArrayExtensions.Write(buffer, ref offset, value); } public static void Write(this byte[] buffer, ref int offset, DataSegment value) { if (value == null) throw new ArgumentNullException("value"); value.Write(buffer, offset); offset += value.Length; } public static void Write(this byte[] buffer, int offset, MacAddress value, Endianity endianity) { ByteArrayExtensions.Write(buffer, offset, value.ToValue(), endianity); } public static void Write(this byte[] buffer, ref int offset, MacAddress value, Endianity endianity) { ByteArrayExtensions.Write(buffer, ref offset, value.ToValue(), endianity); } public static void Write(this byte[] buffer, int offset, IpV4Address value, Endianity endianity) { ByteArrayExtensions.Write(buffer, offset, value.ToValue(), endianity); } public static void Write(this byte[] buffer, ref int offset, IpV4Address value, Endianity endianity) { ByteArrayExtensions.Write(buffer, ref offset, value.ToValue(), endianity); } public static void Write(this byte[] buffer, int offset, IpV4TimeOfDay value, Endianity endianity) { ByteArrayExtensions.Write(buffer, offset, value.MillisecondsSinceMidnightUniversalTime, endianity); } public static void Write(this byte[] buffer, ref int offset, IpV4TimeOfDay value, Endianity endianity) { ByteArrayExtensions.Write(buffer, ref offset, value.MillisecondsSinceMidnightUniversalTime, endianity); } public static void Write(this byte[] buffer, int offset, IpV6Address value, Endianity endianity) { ByteArrayExtensions.Write(buffer, offset, value.ToValue(), endianity); } public static void WriteCarriageReturnLinefeed(this byte[] buffer, ref int offset) { ByteArrayExtensions.Write(buffer, ref offset, (byte) 13); ByteArrayExtensions.Write(buffer, ref offset, (byte) 10); } public static void WriteDecimal(this byte[] buffer, ref int offset, uint value) { ByteArrayExtensions.Write(buffer, ref offset, value.ToString((IFormatProvider) CultureInfo.InvariantCulture), Encoding.ASCII); } private static bool IsWrongEndianity(Endianity endianity) { return BitConverter.IsLittleEndian == (endianity == Endianity.Big); } private static unsafe UInt24 HostToNetworkOrder(UInt24 value) { UInt24 uint24; byte* numPtr1 = (byte*) &uint24; byte* numPtr2 = (byte*) &value; *numPtr1 = numPtr2[2]; numPtr1[1] = numPtr2[1]; numPtr1[2] = *numPtr2; return uint24; } private static unsafe UInt48 HostToNetworkOrder(UInt48 value) { UInt48 uint48; byte* numPtr1 = (byte*) &uint48; byte* numPtr2 = (byte*) &value; *numPtr1 = numPtr2[5]; numPtr1[1] = numPtr2[4]; numPtr1[2] = numPtr2[3]; numPtr1[3] = numPtr2[2]; numPtr1[4] = numPtr2[1]; numPtr1[5] = *numPtr2; return uint48; } private static unsafe UInt128 HostToNetworkOrder(UInt128 value) { UInt128 uint128; byte* numPtr1 = (byte*) &uint128; byte* numPtr2 = (byte*) &value; for (int index = 0; index != 16; ++index) numPtr1[index] = numPtr2[16 - index - 1]; return uint128; } private static unsafe short ReadShort(byte[] buffer, int offset) { fixed (byte* numPtr = &buffer[offset]) return *(short*) numPtr; } private static unsafe UInt24 ReadUInt24(byte[] buffer, int offset) { fixed (byte* numPtr = &buffer[offset]) return *(UInt24*) numPtr; } private static unsafe int ReadInt(byte[] buffer, int offset) { fixed (byte* numPtr = &buffer[offset]) return *(int*) numPtr; } private static unsafe UInt48 ReadUInt48(byte[] buffer, int offset) { fixed (byte* numPtr = &buffer[offset]) return *(UInt48*) numPtr; } private static unsafe long ReadLong(byte[] buffer, int offset) { fixed (byte* numPtr = &buffer[offset]) return *(long*) numPtr; } private static unsafe UInt128 ReadUInt128(byte[] buffer, int offset) { fixed (byte* numPtr = &buffer[offset]) return *(UInt128*) numPtr; } private static unsafe void Write(byte[] buffer, int offset, short value) { fixed (byte* numPtr = &buffer[offset]) *(short*) numPtr = value; } private static unsafe void Write(byte[] buffer, int offset, UInt24 value) { fixed (byte* numPtr = &buffer[offset]) *(UInt24*) numPtr = value; } private static unsafe void Write(byte[] buffer, int offset, int value) { fixed (byte* numPtr = &buffer[offset]) *(int*) numPtr = value; } private static unsafe void Write(byte[] buffer, int offset, UInt48 value) { fixed (byte* numPtr = &buffer[offset]) *(UInt48*) numPtr = value; } private static unsafe void Write(byte[] buffer, int offset, long value) { fixed (byte* numPtr = &buffer[offset]) *(long*) numPtr = value; } private static unsafe void Write(byte[] buffer, int offset, UInt128 value) { fixed (byte* numPtr = &buffer[offset]) *(UInt128*) numPtr = value; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.PacketTotalStatistics // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using System; using System.Runtime.InteropServices; using System.Text; namespace PcapDotNet.Core { public sealed class PacketTotalStatistics : IEquatable<PacketTotalStatistics> { private uint _packetsReceived; private uint _packetsDroppedByDriver; private uint _packetsDroppedByInterface; private uint _packetsCaptured; public uint PacketsCaptured { get { return this._packetsCaptured; } } public uint PacketsDroppedByInterface { get { return this._packetsDroppedByInterface; } } public uint PacketsDroppedByDriver { get { return this._packetsDroppedByDriver; } } public uint PacketsReceived { get { return this._packetsReceived; } } internal unsafe PacketTotalStatistics(pcap_stat* statistics, int statisticsSize) { this._packetsReceived = (uint) *(int*) statistics; this._packetsDroppedByDriver = (uint) *(int*) ((IntPtr) statistics + 4L); this._packetsDroppedByInterface = (uint) *(int*) ((IntPtr) statistics + 8L); this._packetsCaptured = statisticsSize < 16 ? 0U : (uint) *(int*) ((IntPtr) statistics + 12L); } [return: MarshalAs(UnmanagedType.U1)] public override sealed bool Equals(object obj) { return this.Equals(obj as PacketTotalStatistics); } [return: MarshalAs(UnmanagedType.U1)] public bool Equals(PacketTotalStatistics other) { if (other == null) return false; return (int) this._packetsReceived == (int) other._packetsReceived && (int) this._packetsDroppedByDriver == (int) other._packetsDroppedByDriver && ((int) this._packetsDroppedByInterface == (int) other._packetsDroppedByInterface && (int) this._packetsCaptured == (int) other._packetsCaptured); } public override sealed int GetHashCode() { return (int) this._packetsCaptured ^ (int) this._packetsDroppedByInterface ^ (int) this._packetsDroppedByDriver ^ (int) this._packetsReceived; } public override sealed string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("Packets Received: "); stringBuilder.Append(this._packetsReceived); stringBuilder.Append(". "); stringBuilder.Append("Packets Dropped By Driver: "); stringBuilder.Append(this._packetsDroppedByDriver); stringBuilder.Append(". "); stringBuilder.Append("Packets Dropped By Interface: "); stringBuilder.Append(this._packetsDroppedByInterface); stringBuilder.Append(". "); stringBuilder.Append("Packets Captured: "); stringBuilder.Append(this._packetsCaptured); stringBuilder.Append("."); return stringBuilder.ToString(); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpTimestampReplyDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; namespace PcapDotNet.Packets.Icmp { [IcmpDatagramRegistration(IcmpMessageType.TimestampReply)] public sealed class IcmpTimestampReplyDatagram : IcmpTimestampDatagram { private IcmpTimestampReplyDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public override ILayer ExtractLayer() { IcmpTimestampReplyLayer timestampReplyLayer = new IcmpTimestampReplyLayer(); timestampReplyLayer.Checksum = new ushort?(this.Checksum); timestampReplyLayer.Identifier = this.Identifier; timestampReplyLayer.SequenceNumber = this.SequenceNumber; timestampReplyLayer.OriginateTimestamp = this.OriginateTimestamp; timestampReplyLayer.ReceiveTimestamp = this.ReceiveTimestamp; timestampReplyLayer.TransmitTimestamp = this.TransmitTimestamp; return (ILayer) timestampReplyLayer; } internal override IcmpDatagram CreateInstance(byte[] buffer, int offset, int length) { return (IcmpDatagram) new IcmpTimestampReplyDatagram(buffer, offset, length); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpRedirectLayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets.IpV4; namespace PcapDotNet.Packets.Icmp { public sealed class IcmpRedirectLayer : IcmpLayer { public IcmpCodeRedirect Code { get; set; } public IpV4Address GatewayInternetAddress { get; set; } public override IcmpMessageType MessageType { get { return IcmpMessageType.Redirect; } } public override byte CodeValue { get { return (byte) this.Code; } } protected override uint Variable { get { return this.GatewayInternetAddress.ToValue(); } } } } <file_sep>using System; namespace CGurus.Weather.WundergroundAPI.Models { public class ForecastHourly { public string Condition { get; set; } public TemperatureEM Dewpoint { get; set; } public Int16? FctCode { get; set; } public FctTime FctTime { get; set; } public TemperatureEM FeelsLike { get; set; } public TemperatureEM HeatIndex { get; set; } public double? Humidity { get; set; } public string Icon { get; set; } public string Icon_Url { get; set; } public TemperatureEM Mslp { get; set; } public Int16? Pop { get; set; } public TemperatureEM Qpf { get; set; } public double? Sky { get; set; } public TemperatureEM Snow { get; set; } public TemperatureEM Temp { get; set; } public Int16? Uvi { get; set; } public Wind WDir { get; set; } public TemperatureEM WindChill { get; set; } public TemperatureEM WSpd { get; set; } public string Wx { get; set; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.TcpOptionTimestamp // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Transport { [OptionTypeRegistration(typeof (TcpOptionType), TcpOptionType.Timestamp)] public sealed class TcpOptionTimestamp : TcpOptionComplex, IOptionComplexFactory, IEquatable<TcpOptionTimestamp> { public const int OptionLength = 10; public const int OptionValueLength = 8; public uint TimestampValue { get; private set; } public uint TimestampEchoReply { get; private set; } public override int Length { get { return 10; } } public override bool IsAppearsAtMostOnce { get { return true; } } public TcpOptionTimestamp(uint timestampValue, uint timestampEchoReply) : base(TcpOptionType.Timestamp) { this.TimestampValue = timestampValue; this.TimestampEchoReply = timestampEchoReply; } public TcpOptionTimestamp() : this(0U, 0U) { } public bool Equals(TcpOptionTimestamp other) { if (other == null || (int) this.TimestampValue != (int) other.TimestampValue) return false; return (int) this.TimestampEchoReply == (int) other.TimestampEchoReply; } public override bool Equals(TcpOption other) { return this.Equals(other as TcpOptionTimestamp); } public override int GetHashCode() { return base.GetHashCode() ^ this.TimestampEchoReply.GetHashCode(); } Option IOptionComplexFactory.CreateInstance(byte[] buffer, ref int offset, byte valueLength) { if ((int) valueLength != 8) return (Option) null; return (Option) new TcpOptionTimestamp(ByteArrayExtensions.ReadUInt(buffer, ref offset, Endianity.Big), ByteArrayExtensions.ReadUInt(buffer, ref offset, Endianity.Big)); } internal override void Write(byte[] buffer, ref int offset) { base.Write(buffer, ref offset); ByteArrayExtensions.Write(buffer, ref offset, this.TimestampValue, Endianity.Big); ByteArrayExtensions.Write(buffer, ref offset, this.TimestampEchoReply, Endianity.Big); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataIpV4 // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using PcapDotNet.Packets.IpV4; using System; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.A)] public sealed class DnsResourceDataIpV4 : DnsResourceDataSimple, IEquatable<DnsResourceDataIpV4> { public IpV4Address Data { get; private set; } public DnsResourceDataIpV4(IpV4Address data) { this.Data = data; } internal DnsResourceDataIpV4() : this(IpV4Address.Zero) { } public bool Equals(DnsResourceDataIpV4 other) { if (other != null) return this.Data.Equals(other.Data); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataIpV4); } public override int GetHashCode() { return this.Data.GetHashCode(); } internal override int GetLength() { return 4; } internal override void WriteDataSimple(byte[] buffer, int offset) { ByteArrayExtensions.Write(buffer, offset, this.Data, Endianity.Big); } internal override DnsResourceData CreateInstance(DataSegment data) { if (data.Length != 4) return (DnsResourceData) null; return (DnsResourceData) new DnsResourceDataIpV4(data.ReadIpV4Address(0, Endianity.Big)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CGurus.Weather.WundergroundAPI.Models { public class AlertData { public Alert[] Alerts { get; set; } public Response Response { get; set; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Http.HttpRequestDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System.Collections.Generic; namespace PcapDotNet.Packets.Http { public sealed class HttpRequestDatagram : HttpDatagram { public override bool IsRequest { get { return true; } } public HttpRequestMethod Method { get; private set; } public string Uri { get; private set; } internal HttpRequestDatagram(byte[] buffer, int offset, int length) : this(buffer, offset, HttpRequestDatagram.Parse(buffer, offset, length)) { } private HttpRequestDatagram(byte[] buffer, int offset, HttpRequestDatagram.ParseInfo parseInfo) : base(buffer, offset, parseInfo.Length, parseInfo.Version, parseInfo.Header, parseInfo.Body) { this.Method = parseInfo.Method; this.Uri = parseInfo.Uri; } public override ILayer ExtractLayer() { HttpRequestLayer httpRequestLayer = new HttpRequestLayer(); httpRequestLayer.Version = this.Version; httpRequestLayer.Method = this.Method; httpRequestLayer.Uri = this.Uri; httpRequestLayer.Header = this.Header; httpRequestLayer.Body = this.Body; return (ILayer) httpRequestLayer; } private static HttpRequestDatagram.ParseInfo Parse(byte[] buffer, int offset, int length) { HttpParser httpParser = new HttpParser(buffer, offset, length); string token; string uri; HttpVersion version; httpParser.Token(out token).Space().RequestUri(out uri).Space().Version(out version).CarriageReturnLineFeed(); HttpRequestDatagram.ParseInfo parseInfo1 = new HttpRequestDatagram.ParseInfo(); parseInfo1.Length = length; parseInfo1.Version = version; parseInfo1.Method = token == null ? (HttpRequestMethod) null : new HttpRequestMethod(token); parseInfo1.Uri = uri; HttpRequestDatagram.ParseInfo parseInfo2 = parseInfo1; if (!httpParser.Success) return parseInfo2; int num1 = httpParser.Offset - offset; int? endOffset; HttpHeader header = new HttpHeader((IEnumerable<KeyValuePair<string, IEnumerable<byte>>>) HttpDatagram.GetHeaderFields(out endOffset, buffer, offset + num1, length - num1)); parseInfo2.Header = header; if (!endOffset.HasValue) return parseInfo2; int num2 = endOffset.Value - offset - num1; Datagram datagram = HttpDatagram.ParseBody(buffer, offset + num1 + num2, length - num1 - num2, HttpRequestDatagram.IsBodyPossible(header), header); parseInfo2.Body = datagram; parseInfo2.Length = num1 + num2 + datagram.Length; return parseInfo2; } private static bool IsBodyPossible(HttpHeader header) { return header.ContentLength != null; } private class ParseInfo : HttpDatagram.ParseInfoBase { public HttpRequestMethod Method { get; set; } public string Uri { get; set; } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataWellKnownService // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using PcapDotNet.Packets.IpV4; using System; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.Wks)] public sealed class DnsResourceDataWellKnownService : DnsResourceDataSimple, IEquatable<DnsResourceDataWellKnownService> { private const int ConstantPartLength = 5; public IpV4Address Address { get; private set; } public IpV4Protocol Protocol { get; private set; } public DataSegment Bitmap { get; private set; } public DnsResourceDataWellKnownService(IpV4Address address, IpV4Protocol protocol, DataSegment bitmap) { this.Address = address; this.Protocol = protocol; this.Bitmap = bitmap; } internal DnsResourceDataWellKnownService() : this(IpV4Address.Zero, IpV4Protocol.Ip, DataSegment.Empty) { } public bool Equals(DnsResourceDataWellKnownService other) { if (other != null && (this.Address.Equals(other.Address) && this.Protocol.Equals((object) other.Protocol))) return this.Bitmap.Equals(other.Bitmap); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataWellKnownService); } public override int GetHashCode() { return Sequence.GetHashCode((object) this.Address, (object) this.Protocol, (object) this.Bitmap); } internal override int GetLength() { return 5 + this.Bitmap.Length; } internal override void WriteDataSimple(byte[] buffer, int offset) { ByteArrayExtensions.Write(buffer, offset, this.Address, Endianity.Big); ByteArrayExtensions.Write(buffer, offset + 4, (byte) this.Protocol); this.Bitmap.Write(buffer, offset + 5); } internal override DnsResourceData CreateInstance(DataSegment data) { if (data.Length < 5) return (DnsResourceData) null; return (DnsResourceData) new DnsResourceDataWellKnownService(data.ReadIpV4Address(0, Endianity.Big), (IpV4Protocol) data[4], data.Subsegment(5, data.Length - 5)); } private static class Offset { public const int Address = 0; public const int Protocol = 4; public const int Bitmap = 5; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Base.UInt48 // Assembly: PcapDotNet.Base, Version=0.10.0.20668, Culture=neutral, PublicKeyToken=<KEY> // MVID: E9656A63-0145-422C-B8C8-79FDD7FB4270 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Base.dll using System; using System.Globalization; using System.Runtime.InteropServices; namespace PcapDotNet.Base { [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct UInt48 { public static readonly UInt48 MinValue = (UInt48) 0U; public static readonly UInt48 MaxValue = (UInt48) 281474976710655L; public const int SizeOf = 6; private readonly uint _leastSignificant; private readonly ushort _mostSignificant; private UInt48(long value) { this._mostSignificant = (ushort) (value >> 32); this._leastSignificant = (uint) value; } public static implicit operator UInt48(uint value) { return new UInt48((long) value); } public static explicit operator UInt48(long value) { return new UInt48(value); } public static explicit operator UInt48(ulong value) { return new UInt48((long) value); } public static implicit operator long(UInt48 value) { return value.ToLong(); } public static implicit operator ulong(UInt48 value) { return (ulong) value.ToLong(); } public static explicit operator byte(UInt48 value) { return value.ToByte(); } public static bool operator ==(UInt48 value1, UInt48 value2) { return value1.Equals(value2); } public static bool operator !=(UInt48 value1, UInt48 value2) { return !(value1 == value2); } public static UInt48 Parse(string value) { return UInt48.Parse(value, NumberStyles.Integer, (IFormatProvider) CultureInfo.CurrentCulture); } public static UInt48 Parse(string value, IFormatProvider provider) { return UInt48.Parse(value, NumberStyles.Integer, provider); } public static UInt48 Parse(string value, NumberStyles style) { return UInt48.Parse(value, style, (IFormatProvider) CultureInfo.CurrentCulture.NumberFormat); } public static UInt48 Parse(string value, NumberStyles style, IFormatProvider provider) { ulong num; try { num = ulong.Parse(value, style, provider); } catch (OverflowException ex) { throw new OverflowException("Value was either too large or too small for a UInt48"); } if (num > (ulong) UInt48.MaxValue) throw new OverflowException("Value was too large for a UInt48"); return (UInt48) num; } public bool Equals(UInt48 other) { if ((int) this._mostSignificant == (int) other._mostSignificant) return (int) this._leastSignificant == (int) other._leastSignificant; return false; } public override bool Equals(object obj) { if (obj is UInt48) return this.Equals((UInt48) obj); return false; } public override int GetHashCode() { return (long) this.GetHashCode(); } public override string ToString() { return (long) this.ToString((IFormatProvider) CultureInfo.InvariantCulture); } public string ToString(string format) { return this.ToString(format, (IFormatProvider) CultureInfo.InvariantCulture); } public string ToString(string format, IFormatProvider provider) { return (long) this.ToString(format, provider); } private long ToLong() { return ((long) this._mostSignificant << 32) + (long) this._leastSignificant; } private byte ToByte() { return (byte) this._leastSignificant; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Ethernet.IEthernetNextLayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; namespace PcapDotNet.Packets.Ethernet { public interface IEthernetNextLayer : ILayer { EthernetType PreviousLayerEtherType { get; } MacAddress? PreviousLayerDefaultDestination { get; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsKeyProtocol // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Dns { public enum DnsKeyProtocol : byte { None = (byte) 0, Tls = (byte) 1, Email = (byte) 2, DnsSec = (byte) 3, IpSec = (byte) 4, All = (byte) 255, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.PayloadLayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using System; namespace PcapDotNet.Packets { public sealed class PayloadLayer : SimpleLayer, IEquatable<PayloadLayer> { public Datagram Data { get; set; } public override int Length { get { return this.Data.Length; } } public PayloadLayer() { this.Data = Datagram.Empty; } public bool Equals(PayloadLayer other) { if (other != null) return this.Data.Equals((DataSegment) other.Data); return false; } public override bool Equals(Layer other) { return this.Equals(other as PayloadLayer); } protected override void Write(byte[] buffer, int offset) { this.Data.Write(buffer, offset); } } } <file_sep>namespace ForecastIOPortable.Models { using System.Collections.Generic; using System.Runtime.Serialization; /// <summary> /// Metadata associated with a forecast. /// </summary> [DataContract] public class Flags { /// <summary> /// Gets or sets the IDs for each data source used to provide info for this forecast. /// </summary> [DataMember(Name = "sources")] public IList<string> Sources { get; set; } /// <summary> /// Gets or sets the IDs for each radar station used to provide info for this forecast. /// </summary> [DataMember(Name = "darksky-stations")] public IList<string> DarkSkyStations { get; set; } /// <summary> /// Gets or sets the IDs for each DataPoint station used to provide info for this forecast. /// </summary> [DataMember(Name = "datapoint-stations")] public IList<string> DataPointStations { get; set; } /// <summary> /// Gets or sets the IDs for each ISD station used to provide info for this forecast. /// </summary> [DataMember(Name = "isd-stations")] public IList<string> IsdStations { get; set; } /// <summary> /// Gets or sets the IDs for each LAMP station used to provide info for this forecast. /// </summary> [DataMember(Name = "lamp-stations")] public IList<string> LampStations { get; set; } /// <summary> /// Gets or sets the IDs for each METAR station used to provide info for this forecast. /// </summary> [DataMember(Name = "metar-stations")] public IList<string> MetarStations { get; set; } /// <summary> /// Gets or sets the IDs for each MADIS station used to provide info for this forecast. /// </summary> [DataMember(Name = "madis-stations")] public IList<string> MadisStations { get; set; } /// <summary> /// Gets or sets the met.no license. If this is present, data from api.met.no was used to provide info for this forecast. /// </summary> [DataMember(Name = "metno-license")] public string MetnoLicense { get; set; } /// <summary> /// Gets or sets the type of units that are used for the data in this forecast. /// </summary> [DataMember(Name = "units")] public string Units { get; set; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.IPacketDevice // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using System.Collections.ObjectModel; namespace PcapDotNet.Core { public interface IPacketDevice { ReadOnlyCollection<DeviceAddress> Addresses { get; } DeviceAttributes Attributes { get; } string Description { get; } string Name { get; } PacketCommunicator Open(); PacketCommunicator Open(int snapshotLength, PacketDeviceOpenAttributes attributes, int readTimeout); } } <file_sep>using Grib.Api.Interop.SWIG; using System; namespace Grib.Api.Interop { /// <summary> /// Wraps grib_context struct. /// </summary> public class GribContext : AutoRef { /// <summary> /// Initializes a new instance of the <see cref="GribContext"/> class. /// </summary> /// <param name="h">The h.</param> public GribContext (IntPtr h) : base(h) { } /// <summary> /// Called when [dispose]. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected override void OnDispose (bool disposing) { // This causes AccessViolation when disposing // GribApiProxy.GribContextDelete(this); } /// <summary> /// Gets or sets a value indicating whether [enable multiple field messages]. /// </summary> /// <value> /// <c>true</c> if [enable multiple field messages]; otherwise, <c>false</c>. /// </value> public bool EnableMultipleFieldMessages { get { return _enableMultipleFieldMessages; } set { if (value) { GribApiProxy.GribMultiSupportOn(this); } else { GribApiProxy.GribMultiSupportOff(this); } _enableMultipleFieldMessages = value; } } private bool _enableMultipleFieldMessages = false; } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.SimpleLayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets { public abstract class SimpleLayer : Layer { public override sealed void Write(byte[] buffer, int offset, int payloadLength, ILayer previousLayer, ILayer nextLayer) { this.Write(buffer, offset); } protected abstract void Write(byte[] buffer, int offset); } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsType // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using System.Diagnostics.CodeAnalysis; namespace PcapDotNet.Packets.Dns { public enum DnsType : ushort { None = (ushort) 0, [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "A")] A = (ushort) 1, Ns = (ushort) 2, Md = (ushort) 3, MailForwarder = (ushort) 4, CName = (ushort) 5, StartOfAuthority = (ushort) 6, Mailbox = (ushort) 7, MailGroup = (ushort) 8, MailRename = (ushort) 9, Null = (ushort) 10, Wks = (ushort) 11, Ptr = (ushort) 12, HInfo = (ushort) 13, MInfo = (ushort) 14, MailExchange = (ushort) 15, Txt = (ushort) 16, ResponsiblePerson = (ushort) 17, AfsDatabase = (ushort) 18, X25 = (ushort) 19, Isdn = (ushort) 20, RouteThrough = (ushort) 21, NetworkServiceAccessPoint = (ushort) 22, NetworkServiceAccessPointPointer = (ushort) 23, Signature = (ushort) 24, Key = (ushort) 25, PointerX400 = (ushort) 26, GPos = (ushort) 27, Aaaa = (ushort) 28, Loc = (ushort) 29, NextDomain = (ushort) 30, EId = (ushort) 31, NimrodLocator = (ushort) 32, ServerSelection = (ushort) 33, AtmA = (ushort) 34, NaPtr = (ushort) 35, KeyExchanger = (ushort) 36, Cert = (ushort) 37, A6 = (ushort) 38, DName = (ushort) 39, Sink = (ushort) 40, Opt = (ushort) 41, Apl = (ushort) 42, DelegationSigner = (ushort) 43, SshFingerprint = (ushort) 44, IpSecKey = (ushort) 45, ResourceRecordSignature = (ushort) 46, NSec = (ushort) 47, DnsKey = (ushort) 48, DynamicHostConfigurationId = (ushort) 49, NSec3 = (ushort) 50, NSec3Parameters = (ushort) 51, Hip = (ushort) 55, NInfo = (ushort) 56, RKey = (ushort) 57, TrustAnchorLink = (ushort) 58, Cds = (ushort) 59, Spf = (ushort) 99, UInfo = (ushort) 100, Uid = (ushort) 101, Gid = (ushort) 102, Unspecified = (ushort) 103, TKey = (ushort) 249, TransactionSignature = (ushort) 250, Ixfr = (ushort) 251, Axfr = (ushort) 252, MailB = (ushort) 253, MailA = (ushort) 254, Any = (ushort) 255, Uri = (ushort) 256, CertificationAuthorityAuthorization = (ushort) 257, TrustAnchor = (ushort) 32768, DnsSecLookAsideValidation = (ushort) 32769, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IpV4Layer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using PcapDotNet.Packets.Ethernet; using System; namespace PcapDotNet.Packets.IpV4 { public sealed class IpV4Layer : Layer, IEthernetNextLayer, IIpV4NextLayer, ILayer { public byte TypeOfService { get; set; } public ushort Identification { get; set; } public IpV4Fragmentation Fragmentation { get; set; } public byte Ttl { get; set; } public IpV4Protocol? Protocol { get; set; } public ushort? HeaderChecksum { get; set; } public IpV4Address Source { get; set; } public IpV4Address CurrentDestination { get; set; } public IpV4Address Destination { get { return IpV4Datagram.CalculateDestination(this.CurrentDestination, this.Options); } } public IpV4Options Options { get; set; } public EthernetType PreviousLayerEtherType { get { return EthernetType.IpV4; } } public IpV4Protocol PreviousLayerProtocol { get { return IpV4Protocol.Ip; } } public MacAddress? PreviousLayerDefaultDestination { get { return new MacAddress?(); } } public override int Length { get { return 20 + this.Options.BytesLength; } } public override DataLinkKind? DataLink { get { return new DataLinkKind?(DataLinkKind.IpV4); } } public IpV4Layer() { this.TypeOfService = (byte) 0; this.Identification = (ushort) 0; this.Fragmentation = IpV4Fragmentation.None; this.Ttl = (byte) 0; this.Protocol = new IpV4Protocol?(); this.HeaderChecksum = new ushort?(); this.Source = IpV4Address.Zero; this.CurrentDestination = IpV4Address.Zero; this.Options = IpV4Options.None; } public override void Write(byte[] buffer, int offset, int payloadLength, ILayer previousLayer, ILayer nextLayer) { IpV4Protocol previousLayerProtocol; if (!this.Protocol.HasValue) { if (nextLayer == null) throw new ArgumentException("Can't determine protocol automatically from next layer because there is no next layer"); IIpV4NextLayer ipV4NextLayer = nextLayer as IIpV4NextLayer; if (ipV4NextLayer == null) throw new ArgumentException("Can't determine protocol automatically from next layer (" + (object) nextLayer.GetType() + ")"); previousLayerProtocol = ipV4NextLayer.PreviousLayerProtocol; } else previousLayerProtocol = this.Protocol.Value; IpV4Datagram.WriteHeader(buffer, offset, this.TypeOfService, this.Identification, this.Fragmentation, this.Ttl, previousLayerProtocol, this.HeaderChecksum, this.Source, this.CurrentDestination, this.Options, payloadLength); } public override void Finalize(byte[] buffer, int offset, int payloadLength, ILayer nextLayer) { IIpV4NextTransportLayer nextTransportLayer = nextLayer as IIpV4NextTransportLayer; if (nextTransportLayer == null || !nextTransportLayer.CalculateChecksum) return; IpV4Datagram.WriteTransportChecksum(buffer, offset, this.Length, (ushort) payloadLength, nextTransportLayer.ChecksumOffset, nextTransportLayer.IsChecksumOptional, nextTransportLayer.Checksum, this.Destination); } public bool Equals(IpV4Layer other) { if (other != null && (int) this.TypeOfService == (int) other.TypeOfService && ((int) this.Identification == (int) other.Identification && this.Fragmentation == other.Fragmentation) && (int) this.Ttl == (int) other.Ttl) { IpV4Protocol? protocol1 = this.Protocol; IpV4Protocol? protocol2 = other.Protocol; if ((protocol1.GetValueOrDefault() != protocol2.GetValueOrDefault() ? 0 : (protocol1.HasValue == protocol2.HasValue ? 1 : 0)) != 0) { ushort? headerChecksum1 = this.HeaderChecksum; ushort? headerChecksum2 = other.HeaderChecksum; if (((int) headerChecksum1.GetValueOrDefault() != (int) headerChecksum2.GetValueOrDefault() ? 0 : (headerChecksum1.HasValue == headerChecksum2.HasValue ? 1 : 0)) != 0 && this.Source == other.Source && this.CurrentDestination == other.CurrentDestination) return this.Options.Equals((PcapDotNet.Packets.Options<IpV4Option>) other.Options); } } return false; } public override bool Equals(Layer other) { return this.Equals(other as IpV4Layer); } public override int GetHashCode() { return base.GetHashCode() ^ Sequence.GetHashCode((object) BitSequence.Merge(this.TypeOfService, this.Identification, this.Ttl), (object) this.Fragmentation, (object) this.Source, (object) this.CurrentDestination, (object) this.Options) ^ this.Protocol.GetHashCode() ^ this.HeaderChecksum.GetHashCode(); } public override string ToString() { return (string) (object) this.Source + (object) " -> " + (string) (object) this.Destination + " (" + (string) (object) this.Protocol + ")"; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsDomainNameCompressionData // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace PcapDotNet.Packets.Dns { internal class DnsDomainNameCompressionData { private static readonly InlineEqualityComparer<ListSegment<DataSegment>> _labelsComparer = new InlineEqualityComparer<ListSegment<DataSegment>>((Func<ListSegment<DataSegment>, ListSegment<DataSegment>, bool>) ((x, y) => Enumerable.SequenceEqual<DataSegment>((IEnumerable<DataSegment>) x, (IEnumerable<DataSegment>) y)), (Func<ListSegment<DataSegment>, int>) (obj => IEnumerableExtensions.SequenceGetHashCode<DataSegment>((IEnumerable<DataSegment>) obj))); private readonly Dictionary<ListSegment<DataSegment>, int> _data = new Dictionary<ListSegment<DataSegment>, int>((IEqualityComparer<ListSegment<DataSegment>>) DnsDomainNameCompressionData._labelsComparer); public DnsDomainNameCompressionMode DomainNameCompressionMode { get; private set; } public DnsDomainNameCompressionData(DnsDomainNameCompressionMode domainNameCompressionMode) { this.DomainNameCompressionMode = domainNameCompressionMode; } public bool IsAvailable(ListSegment<DataSegment> labels) { int offsetInDns; return this.TryGetOffset(labels, out offsetInDns); } public bool TryGetOffset(ListSegment<DataSegment> labels, out int offsetInDns) { switch (this.DomainNameCompressionMode) { case DnsDomainNameCompressionMode.All: return this._data.TryGetValue(labels, out offsetInDns); case DnsDomainNameCompressionMode.Nothing: offsetInDns = 0; return false; default: throw new InvalidOperationException(string.Format((IFormatProvider) CultureInfo.InvariantCulture, "Invalid Domain Name Compression Mode {0}", new object[1] { (object) this.DomainNameCompressionMode })); } } public void AddCompressionData(ListSegment<DataSegment> labels, int dnsOffset) { if (dnsOffset > 16383) return; switch (this.DomainNameCompressionMode) { case DnsDomainNameCompressionMode.All: if (this._data.ContainsKey(labels)) break; this._data.Add(labels, dnsOffset); break; case DnsDomainNameCompressionMode.Nothing: break; default: throw new InvalidOperationException(string.Format((IFormatProvider) CultureInfo.InvariantCulture, "Invalid Domain Name Compression Mode {0}", new object[1] { (object) this.DomainNameCompressionMode })); } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsKeySignatoryAttributes // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using System; namespace PcapDotNet.Packets.Dns { [Flags] public enum DnsKeySignatoryAttributes : byte { General = (byte) 1, Unique = (byte) 2, Strong = (byte) 4, Zone = (byte) 8, } } <file_sep>using Grib.Api.Interop; using Grib.Api.Interop.SWIG; namespace Grib.Api { /// <summary> /// A subdomain of field measurements. /// </summary> public class GribBox { private GribPoints _points; /// <summary> /// Initializes a new instance of the <see cref="GribBox"/> class. /// </summary> /// <param name="msgHandle">The MSG handle.</param> /// <param name="nw">The nw.</param> /// <param name="se">The se.</param> public GribBox (GribHandle msgHandle, GeoCoordinate nw, GeoCoordinate se) { int err; var box = GribApiProxy.GribBoxNew(msgHandle, out err); if (err != 0) { throw GribApiException.Create(err); } var pts = GribApiProxy.GribBoxGetPoints(box, nw.Latitude, nw.Longitude, se.Latitude, se.Longitude, out err); if (err != 0) { throw GribApiException.Create(err); } _points = new GribPoints(SWIGTYPE_p_grib_points.getCPtr(pts).Handle, false); } /// <summary> /// Gets or sets the latitudes. /// </summary> /// <value> /// The latitudes. /// </value> public double[] Latitudes { set { _points.latitudes = value; } get { return _points.latitudes; } } /// <summary> /// Gets or sets the longitudes. /// </summary> /// <value> /// The longitudes. /// </value> public double[] Longitudes { set { _points.longitudes = value; } get { return _points.longitudes; } } /// <summary> /// Gets or sets the indexes. /// </summary> /// <value> /// The indexes. /// </value> public uint Indexes { set { _points.indexes = value; } get { return _points.indexes; } } /// <summary> /// Gets or sets the group start. /// </summary> /// <value> /// The group start. /// </value> public uint GroupStart { set { _points.groupStart = value; } get { return _points.groupStart; } } /// <summary> /// Gets or sets the length of the group. /// </summary> /// <value> /// The length of the group. /// </value> public uint GroupLength { set { _points.groupLen = value; } get { return _points.groupLen; } } /// <summary> /// Gets or sets the group count. /// </summary> /// <value> /// The group count. /// </value> public uint GroupCount { set { _points.nGroups = value; } get { return _points.nGroups; } } /// <summary> /// Gets or sets the count. /// </summary> /// <value> /// The count. /// </value> public uint Count { set { _points.n = value; } get { return _points.n; } } /// <summary> /// Gets or sets the size. /// </summary> /// <value> /// The size. /// </value> public uint Size { set { _points.size = value; } get { return _points.size; } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpDatagramRegistrationAttribute // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using System; namespace PcapDotNet.Packets.Icmp { internal sealed class IcmpDatagramRegistrationAttribute : Attribute { public IcmpMessageType MessageType { get; private set; } public IcmpDatagramRegistrationAttribute(IcmpMessageType messageType) { this.MessageType = messageType; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpCodeTraceRoute // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Icmp { public enum IcmpCodeTraceRoute : byte { OutboundPacketSuccessfullyForwarded, NoRouteForOutboundPacketDiscarded, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpCodeDestinationUnreachable // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Icmp { public enum IcmpCodeDestinationUnreachable : byte { NetUnreachable, HostUnreachable, ProtocolUnreachable, PortUnreachable, FragmentationNeededAndDoNotFragmentSet, SourceRouteFailed, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsClass // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Dns { public enum DnsClass : ushort { None = (ushort) 0, Internet = (ushort) 1, Chaos = (ushort) 3, Hesiod = (ushort) 4, NoneExistent = (ushort) 254, Any = (ushort) 255, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Base.UShortExtensions // Assembly: PcapDotNet.Base, Version=0.10.0.20668, Culture=neutral, PublicKeyToken=<KEY> // MVID: E9656A63-0145-422C-B8C8-79FDD7FB4270 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Base.dll namespace PcapDotNet.Base { public static class UShortExtensions { public static ushort ReverseEndianity(this ushort value) { return (ushort) ShortExtensions.ReverseEndianity((short) value); } } } <file_sep>using System; using System.IO; using System.Net; using System.Xml; namespace CGurus.Weather.WundergroundAPI { // WU XML // Request syntaxe: "http://api.wunderground.com/api/" + wunderground_key + "/conditions/q/VA/Springfield.xml" // Returns public static class WUConditionsXml { public static string GetWeather(string wu_apikey, string usastate, string usatown) { string request = "http://api.wunderground.com/api/" + wu_apikey + "/conditions/q/" + usastate + "/" + usatown +".xml"; var cli = new WebClient(); string weatherxml = cli.DownloadString(request); #if DEBUG Parse(weatherxml); #endif return weatherxml; } public static string GetNodeValue(this XmlReader xmlreader) { xmlreader.Read(); return xmlreader.Value; } //Takes a url request to wunderground, parses it, and displays the data. public static void Parse(string weatherxml) { //Variables string place = ""; string obs_time = ""; string weather1 = ""; string temperature_string = ""; string relative_humidity = ""; string wind_string = ""; string pressure_mb = ""; string dewpoint_string = ""; string visibility_km = ""; string latitude = ""; string longitude = ""; string node = ""; using (XmlReader reader = XmlReader.Create(new StringReader(weatherxml))) { // Parse the file and display each of the nodes. while (reader.Read()) { node = reader.Name; switch (reader.NodeType) { case XmlNodeType.Element: if (node.Equals("full")) { place = reader.GetNodeValue(); } else if (node.Equals("observation_time")) { obs_time = reader.GetNodeValue(); } else if (node.Equals("weather")) { weather1 = reader.GetNodeValue(); } else if (node.Equals("temperature_string")) { temperature_string = reader.GetNodeValue(); } else if (node.Equals("relative_humidity")) { relative_humidity = reader.GetNodeValue(); } else if (node.Equals("wind_string")) { wind_string = reader.GetNodeValue(); } else if (node.Equals("pressure_mb")) { pressure_mb = reader.GetNodeValue(); } else if (node.Equals("dewpoint_string")) { dewpoint_string = reader.GetNodeValue(); } else if (node.Equals("visibility_km")) { visibility_km = reader.GetNodeValue(); } else if (node.Equals("latitude")) { latitude = reader.GetNodeValue(); } else if (node.Equals("longitude")) { longitude = reader.GetNodeValue(); } break; } } } Console.WriteLine("********************"); Console.WriteLine("Place: " + place); Console.WriteLine("Observation Time: " + obs_time); Console.WriteLine("Weather: " + weather1); Console.WriteLine("Temperature: " + temperature_string); Console.WriteLine("Relative Humidity: " + relative_humidity); Console.WriteLine("Wind: " + wind_string); Console.WriteLine("Pressure (mb): " + pressure_mb); Console.WriteLine("Dewpoint: " + dewpoint_string); Console.WriteLine("Visibility (km): " + visibility_km); Console.WriteLine("Location: " + longitude + ", " + latitude); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsQueryResourceRecord // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using System; namespace PcapDotNet.Packets.Dns { public sealed class DnsQueryResourceRecord : DnsResourceRecord, IEquatable<DnsQueryResourceRecord> { public override int Ttl { get { throw new InvalidOperationException("No TTL in queries"); } protected set { throw new InvalidOperationException("No TTL in queries"); } } public override DnsResourceData Data { get { throw new InvalidOperationException("No Resource Data in queries"); } protected set { throw new InvalidOperationException("No Resource Data in queries"); } } public DnsQueryResourceRecord(DnsDomainName domainName, DnsType type, DnsClass dnsClass) : base(domainName, type, dnsClass) { } public bool Equals(DnsQueryResourceRecord other) { return this.EqualsBase((DnsResourceRecord) other); } public override bool Equals(object obj) { return this.Equals(obj as DnsQueryResourceRecord); } public override int GetHashCode() { return this.GetHashCodeBase(); } internal static DnsQueryResourceRecord Parse(DnsDatagram dns, int offsetInDns, out int numBytesRead) { DnsDomainName domainName; DnsType type; DnsClass dnsClass; if (!DnsResourceRecord.TryParseBase(dns, offsetInDns, out domainName, out type, out dnsClass, out numBytesRead)) return (DnsQueryResourceRecord) null; return new DnsQueryResourceRecord(domainName, type, dnsClass); } internal override int GetLengthAfterBase(DnsDomainNameCompressionData compressionData, int offsetInDns) { return 0; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Grib.Api.Templates { class RegularLatLon { //public static double iDirectionIncrement(GribMessage msg) //{ // return msg["iDirectionIncrementInDegrees"].AsDouble(); //} //public static double jDirectionIncrement (GribMessage msg) //{ // return msg["jDirectionIncrementInDegrees"].AsDouble(); //} //public static double LongitudeFirstGridPt (GribMessage msg) //{ // return msg["longitudeOfFirstGridPointInDegrees"].AsDouble(); //} //public static double LongitudeLastGridPt (GribMessage msg) //{ // return msg["longitudeOfLastGridPointInDegrees"].AsDouble(); //} //public static double LatitudeFirstGridPt (GribMessage msg) //{ // return msg["latitudeOfFirstGridPointInDegrees"].AsDouble(); //} //public static double LatitudeLastGridPt (GribMessage msg) //{ // return msg["latitudeOfLastGridPointInDegrees"].AsDouble(); //} //public static double LatitudeSouthernPole (GribMessage msg) //{ // return msg["latitudeOfSouthernPoleInDegrees"].AsDouble(); //} //public static double LongitudeSouthernPole (GribMessage msg) //{ // return msg["longitudeOfSouthernPoleInDegrees"].AsDouble(); //} //public static int uvRelativeToGrid (GribMessage msg) //{ // return msg["uvRelativeToGrid"].AsInt(); //} //public static int iScansNegatively (GribMessage msg) //{ // return msg["iScansNegatively"].AsInt(); //} //public static int jScansPositively (GribMessage msg) //{ // return msg["jScansPositively"].AsInt(); //} //public static int N (GribMessage msg) //{ // return msg["jScansPositively"].AsInt(); //} //public static int[] pl (GribMessage msg) //{ // return msg["pl"].AsIntArray(); //} //public static int truncation (GribMessage msg) //{ // return msg["truncation"].AsInt(); //} //public static int orientationOfTheGrid (GribMessage msg) //{ // return msg["orientationOfTheGridInDegrees"].AsInt(); //} //public static int DyInMetres (GribMessage msg) //{ // return msg["DyInMetres"].AsInt(); //} //public static int DxInMetres (GribMessage msg) //{ // return msg["DxInMetres"].AsInt(); //} } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.LivePacketCommunicator // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using \u003CCppImplementationDetails\u003E; using System; using System.Globalization; using System.Runtime.InteropServices; namespace PcapDotNet.Core { public sealed class LivePacketCommunicator : PacketCommunicator { public override unsafe PacketTotalStatistics TotalStatistics { get { int statisticsSize; pcap_stat* statistics = \u003CModule\u003E.pcap_stats_ex(this.PcapDescriptor, &statisticsSize); if ((IntPtr) statistics == IntPtr.Zero) throw this.BuildInvalidOperation("Failed getting total statistics"); return new PacketTotalStatistics(statistics, statisticsSize); } } internal unsafe LivePacketCommunicator(sbyte* source, int snapshotLength, PacketDeviceOpenAttributes attributes, int readTimeout, pcap_rmtauth* auth, SocketAddress netmask) : base(LivePacketCommunicator.PcapOpen(source, snapshotLength, attributes, readTimeout, auth), netmask) { } public override sealed unsafe void Transmit(PacketSendBuffer sendBuffer, [MarshalAs(UnmanagedType.U1)] bool isSync) { if (sendBuffer == null) throw new ArgumentNullException("sendBuffer"); sendBuffer.Transmit(this.PcapDescriptor, isSync); } private static unsafe pcap* PcapOpen(sbyte* source, int snapshotLength, PacketDeviceOpenAttributes attributes, int readTimeout, pcap_rmtauth* auth) { \u0024ArrayType\u0024\u0024\u0024BY0BAA\u0040D arrayTypeBy0BaAD; pcap* pcapPtr = \u003CModule\u003E.pcap_open(source, snapshotLength, (int) attributes, readTimeout, auth, (sbyte*) &arrayTypeBy0BaAD); if ((IntPtr) pcapPtr == IntPtr.Zero) throw new InvalidOperationException(string.Format((IFormatProvider) CultureInfo.InvariantCulture, "Unable to open the adapter. Adapter name: {0}. Error: {1}", new object[2] { (object) new string(source), (object) new string((sbyte*) &arrayTypeBy0BaAD) })); return pcapPtr; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataServerSelection // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.ServerSelection)] public sealed class DnsResourceDataServerSelection : DnsResourceDataNoCompression, IEquatable<DnsResourceDataServerSelection> { private const int ConstantPartLength = 6; public ushort Priority { get; private set; } public ushort Weight { get; private set; } public ushort Port { get; private set; } public DnsDomainName Target { get; private set; } public DnsResourceDataServerSelection(ushort priority, ushort weight, ushort port, DnsDomainName target) { this.Priority = priority; this.Weight = weight; this.Port = port; this.Target = target; } internal DnsResourceDataServerSelection() : this((ushort) 0, (ushort) 0, (ushort) 0, DnsDomainName.Root) { } public bool Equals(DnsResourceDataServerSelection other) { if (other != null && this.Priority.Equals(other.Priority) && (this.Weight.Equals(other.Weight) && this.Port.Equals(other.Port))) return this.Target.Equals(other.Target); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataServerSelection); } public override int GetHashCode() { return Sequence.GetHashCode((object) BitSequence.Merge(this.Priority, this.Weight), (object) this.Port, (object) this.Target); } internal override int GetLength() { return 6 + this.Target.NonCompressedLength; } internal override int WriteData(byte[] buffer, int offset) { ByteArrayExtensions.Write(buffer, offset, this.Priority, Endianity.Big); ByteArrayExtensions.Write(buffer, offset + 2, this.Weight, Endianity.Big); ByteArrayExtensions.Write(buffer, offset + 4, this.Port, Endianity.Big); this.Target.WriteUncompressed(buffer, offset + 6); return this.GetLength(); } internal override DnsResourceData CreateInstance(DnsDatagram dns, int offsetInDns, int length) { if (length < 6) return (DnsResourceData) null; ushort priority = dns.ReadUShort(offsetInDns, Endianity.Big); ushort weight = dns.ReadUShort(offsetInDns + 2, Endianity.Big); ushort port = dns.ReadUShort(offsetInDns + 4, Endianity.Big); DnsDomainName domainName; int numBytesRead; if (!DnsDomainName.TryParse(dns, offsetInDns + 6, length - 6, out domainName, out numBytesRead)) return (DnsResourceData) null; if (6 + numBytesRead != length) return (DnsResourceData) null; return (DnsResourceData) new DnsResourceDataServerSelection(priority, weight, port, domainName); } private static class Offset { public const int Priority = 0; public const int Weight = 2; public const int Port = 4; public const int Target = 6; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.TcpOptionSelectiveAcknowledgmentBlock // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using System; namespace PcapDotNet.Packets.Transport { public struct TcpOptionSelectiveAcknowledgmentBlock : IEquatable<TcpOptionSelectiveAcknowledgmentBlock> { public const int SizeOf = 8; public uint LeftEdge { get; private set; } public uint RightEdge { get; private set; } public TcpOptionSelectiveAcknowledgmentBlock(uint leftEdge, uint rightEdge) { this = new TcpOptionSelectiveAcknowledgmentBlock(); this.LeftEdge = leftEdge; this.RightEdge = rightEdge; } public static bool operator ==(TcpOptionSelectiveAcknowledgmentBlock value1, TcpOptionSelectiveAcknowledgmentBlock value2) { return value1.Equals(value2); } public static bool operator !=(TcpOptionSelectiveAcknowledgmentBlock value1, TcpOptionSelectiveAcknowledgmentBlock value2) { return !(value1 == value2); } public override string ToString() { return (string) (object) this.LeftEdge + (object) "-" + (string) (object) this.RightEdge; } public bool Equals(TcpOptionSelectiveAcknowledgmentBlock other) { if ((int) this.LeftEdge == (int) other.LeftEdge) return (int) this.RightEdge == (int) other.RightEdge; return false; } public override bool Equals(object obj) { if (obj is TcpOptionSelectiveAcknowledgmentBlock) return this.Equals((TcpOptionSelectiveAcknowledgmentBlock) obj); return false; } public override int GetHashCode() { return Sequence.GetHashCode((object) this.LeftEdge, (object) this.RightEdge); } } } <file_sep>using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Permissions; [assembly: ComVisible(false)] [assembly: AssemblyTrademark("Pcap.Net")] [assembly: AssemblyCopyright("Copyright © Pcap.Net 2010")] [assembly: AssemblyProduct("Packets")] [assembly: AssemblyFileVersion("0.10.0.0")] [assembly: CLSCompliant(false)] [assembly: Guid("662a51ed-d89d-4f59-9a62-612706ee3eb2")] [assembly: AssemblyTitle("Packets")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Pcap.Net")] [assembly: AssemblyVersion("0.10.0.20671")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.PacketHeader // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using PcapDotNet.Packets; using System; using System.Diagnostics; namespace PcapDotNet.Core { internal class PacketHeader { [DebuggerNonUserCode] private PacketHeader() { } public static unsafe void GetPcapHeader(pcap_pkthdr* header, Packet packet) { PacketTimestamp.DateTimeToPcapTimestamp(packet.Timestamp, (timeval*) header); *(int*) ((IntPtr) header + 12L) = packet.Length; *(int*) ((IntPtr) header + 8L) = packet.Length; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataDnsKey // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.DnsKey)] public sealed class DnsResourceDataDnsKey : DnsResourceDataSimple, IEquatable<DnsResourceDataDnsKey> { public const byte ProtocolValue = (byte) 3; private const int ConstantPartLength = 4; public bool ZoneKey { get; private set; } public bool Revoke { get; private set; } public bool SecureEntryPoint { get; private set; } public byte Protocol { get; private set; } public DnsAlgorithm Algorithm { get; private set; } public DataSegment PublicKey { get; private set; } public DnsResourceDataDnsKey(bool zoneKey, bool revoke, bool secureEntryPoint, byte protocol, DnsAlgorithm algorithm, DataSegment publicKey) { this.ZoneKey = zoneKey; this.Revoke = revoke; this.SecureEntryPoint = secureEntryPoint; this.Protocol = protocol; this.Algorithm = algorithm; this.PublicKey = publicKey; } internal DnsResourceDataDnsKey() : this(false, false, false, (byte) 3, DnsAlgorithm.None, DataSegment.Empty) { } public bool Equals(DnsResourceDataDnsKey other) { if (other != null && this.ZoneKey.Equals(other.ZoneKey) && (this.Revoke.Equals(other.Revoke) && this.SecureEntryPoint.Equals(other.SecureEntryPoint)) && (this.Protocol.Equals(other.Protocol) && this.Algorithm.Equals((object) other.Algorithm))) return this.PublicKey.Equals(other.PublicKey); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataDnsKey); } public override int GetHashCode() { return BitSequence.Merge(BitSequence.Merge(this.ZoneKey, this.Revoke, this.SecureEntryPoint), this.Protocol, (byte) this.Algorithm).GetHashCode(); } internal override int GetLength() { return 4 + this.PublicKey.Length; } internal override void WriteDataSimple(byte[] buffer, int offset) { byte num1 = (byte) 0; if (this.ZoneKey) num1 |= (byte) 1; ByteArrayExtensions.Write(buffer, offset, num1); byte num2 = (byte) 0; if (this.Revoke) num2 |= (byte) sbyte.MinValue; if (this.SecureEntryPoint) num2 |= (byte) 1; ByteArrayExtensions.Write(buffer, offset + 1, num2); ByteArrayExtensions.Write(buffer, offset + 2, this.Protocol); ByteArrayExtensions.Write(buffer, offset + 3, (byte) this.Algorithm); this.PublicKey.Write(buffer, offset + 4); } internal override DnsResourceData CreateInstance(DataSegment data) { if (data.Length < 4) return (DnsResourceData) null; return (DnsResourceData) new DnsResourceDataDnsKey(data.ReadBool(0, (byte) 1), data.ReadBool(1, (byte) sbyte.MinValue), data.ReadBool(1, (byte) 1), data[2], (DnsAlgorithm) data[3], data.Subsegment(4, data.Length - 4)); } private static class Offset { public const int ZoneKey = 0; public const int Revoke = 1; public const int SecureEntryPoint = 1; public const int Protocol = 2; public const int Algorithm = 3; public const int PublicKey = 4; } private static class Mask { public const byte ZoneKey = (byte) 1; public const byte Revoke = (byte) 128; public const byte SecureEntryPoint = (byte) 1; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IpV4Address // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using System; using System.Globalization; using System.Text; namespace PcapDotNet.Packets.IpV4 { public struct IpV4Address { private static readonly IpV4Address _zero = new IpV4Address(0U); private static readonly IpV4Address _allHostsGroupAddress = new IpV4Address("172.16.17.32"); public const int SizeOf = 4; private readonly uint _value; public static IpV4Address Zero { get { return IpV4Address._zero; } } public static IpV4Address AllHostsGroupAddress { get { return IpV4Address._allHostsGroupAddress; } } public IpV4Address(uint value) { this._value = value; } public IpV4Address(string value) { if (value == null) throw new ArgumentNullException("value"); string[] strArray = value.Split('.'); this._value = BitSequence.Merge(byte.Parse(strArray[0], (IFormatProvider) CultureInfo.InvariantCulture), byte.Parse(strArray[1], (IFormatProvider) CultureInfo.InvariantCulture), byte.Parse(strArray[2], (IFormatProvider) CultureInfo.InvariantCulture), byte.Parse(strArray[3], (IFormatProvider) CultureInfo.InvariantCulture)); } public static bool operator ==(IpV4Address value1, IpV4Address value2) { return value1.Equals(value2); } public static bool operator !=(IpV4Address value1, IpV4Address value2) { return !(value1 == value2); } public uint ToValue() { return this._value; } public bool Equals(IpV4Address other) { return (int) this.ToValue() == (int) other.ToValue(); } public override bool Equals(object obj) { if (obj is IpV4Address) return this.Equals((IpV4Address) obj); return false; } public override int GetHashCode() { return this._value.GetHashCode(); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(15); stringBuilder.Append(this._value >> 24); stringBuilder.Append('.'); stringBuilder.Append((this._value >> 16) % 256U); stringBuilder.Append('.'); stringBuilder.Append((this._value >> 8) % 256U); stringBuilder.Append('.'); stringBuilder.Append(this._value % 256U); return stringBuilder.ToString(); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Http.HttpRequestLayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Http { public sealed class HttpRequestLayer : HttpLayer, IEquatable<HttpRequestLayer> { public override bool IsRequest { get { return true; } } public HttpRequestMethod Method { get; set; } public string Uri { get; set; } internal override int FirstLineLength { get { int num1 = 0; if (this.Method == null) return num1; int num2 = num1 + (this.Method.Length + 1); if (this.Uri == null) return num2; int num3 = num2 + (this.Uri.Length + 1); if (this.Version == null) return num3; return num3 + this.Version.Length + 2; } } public override bool Equals(HttpLayer other) { return this.Equals(other as HttpRequestLayer); } public bool Equals(HttpRequestLayer other) { if (!base.Equals((HttpLayer) other) || !object.ReferenceEquals((object) this.Method, (object) other.Method) && !this.Method.Equals(other.Method)) return false; if (!object.ReferenceEquals((object) this.Uri, (object) other.Uri)) return this.Uri.Equals(other.Uri); return true; } internal override void WriteFirstLine(byte[] buffer, ref int offset) { if (this.Method == null) return; this.Method.Write(buffer, ref offset); ByteArrayExtensions.Write(buffer, ref offset, (byte) 32); if (this.Uri == null) return; ByteArrayExtensions.Write(buffer, ref offset, this.Uri, EncodingExtensions.Iso88591); ByteArrayExtensions.Write(buffer, ref offset, (byte) 32); if (this.Version == null) return; this.Version.Write(buffer, ref offset); ByteArrayExtensions.WriteCarriageReturnLinefeed(buffer, ref offset); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataLocationInformation // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.Loc)] public sealed class DnsResourceDataLocationInformation : DnsResourceDataSimple, IEquatable<DnsResourceDataLocationInformation> { public const ulong MaxSizeValue = 9000000000UL; public const int Length = 16; public byte Version { get; private set; } public ulong Size { get; private set; } public ulong HorizontalPrecision { get; private set; } public ulong VerticalPrecision { get; private set; } public uint Latitude { get; private set; } public uint Longitude { get; private set; } public uint Altitude { get; private set; } public DnsResourceDataLocationInformation(byte version, ulong size, ulong horizontalPrecision, ulong verticalPrecision, uint latitude, uint longitude, uint altitude) { if (!DnsResourceDataLocationInformation.IsValidSize(size)) throw new ArgumentOutOfRangeException("size", (object) size, "Must be in the form <digit> * 10^<digit>."); if (!DnsResourceDataLocationInformation.IsValidSize(horizontalPrecision)) throw new ArgumentOutOfRangeException("horizontalPrecision", (object) horizontalPrecision, "Must be in the form <digit> * 10^<digit>."); if (!DnsResourceDataLocationInformation.IsValidSize(verticalPrecision)) throw new ArgumentOutOfRangeException("verticalPrecision", (object) verticalPrecision, "Must be in the form <digit> * 10^<digit>."); this.Version = version; this.Size = size; this.HorizontalPrecision = horizontalPrecision; this.VerticalPrecision = verticalPrecision; this.Latitude = latitude; this.Longitude = longitude; this.Altitude = altitude; } internal DnsResourceDataLocationInformation() : this((byte) 0, 0UL, 0UL, 0UL, 0U, 0U, 0U) { } public bool Equals(DnsResourceDataLocationInformation other) { if (other != null && this.Version.Equals(other.Version) && (this.Size.Equals(other.Size) && this.HorizontalPrecision.Equals(other.HorizontalPrecision)) && (this.VerticalPrecision.Equals(other.VerticalPrecision) && this.Latitude.Equals(other.Latitude) && this.Longitude.Equals(other.Longitude))) return this.Altitude.Equals(other.Altitude); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataLocationInformation); } public override int GetHashCode() { return Sequence.GetHashCode((object) this.Version, (object) this.Size, (object) this.HorizontalPrecision, (object) this.VerticalPrecision, (object) this.Latitude, (object) this.Longitude, (object) this.Altitude); } internal override int GetLength() { return 16; } internal override void WriteDataSimple(byte[] buffer, int offset) { ByteArrayExtensions.Write(buffer, offset, this.Version); DnsResourceDataLocationInformation.WriteSize(buffer, offset + 1, this.Size); DnsResourceDataLocationInformation.WriteSize(buffer, offset + 2, this.HorizontalPrecision); DnsResourceDataLocationInformation.WriteSize(buffer, offset + 3, this.VerticalPrecision); ByteArrayExtensions.Write(buffer, offset + 4, this.Latitude, Endianity.Big); ByteArrayExtensions.Write(buffer, offset + 8, this.Longitude, Endianity.Big); ByteArrayExtensions.Write(buffer, offset + 12, this.Altitude, Endianity.Big); } internal override DnsResourceData CreateInstance(DataSegment data) { if (data.Length != 16) return (DnsResourceData) null; byte version = data[0]; ulong size = DnsResourceDataLocationInformation.ReadSize(data[1]); if (size > 9000000000UL) return (DnsResourceData) null; ulong horizontalPrecision = DnsResourceDataLocationInformation.ReadSize(data[2]); if (horizontalPrecision > 9000000000UL) return (DnsResourceData) null; ulong verticalPrecision = DnsResourceDataLocationInformation.ReadSize(data[3]); if (verticalPrecision > 9000000000UL) return (DnsResourceData) null; uint latitude = data.ReadUInt(4, Endianity.Big); uint longitude = data.ReadUInt(8, Endianity.Big); uint altitude = data.ReadUInt(12, Endianity.Big); return (DnsResourceData) new DnsResourceDataLocationInformation(version, size, horizontalPrecision, verticalPrecision, latitude, longitude, altitude); } private static bool IsValidSize(ulong size) { if ((long) size == 0L) return true; if (size > 9000000000UL) return false; while ((long) (size % 10UL) == 0L) size /= 10UL; return size <= 9UL; } private static void WriteSize(byte[] buffer, int offset, ulong size) { byte num1; byte num2; if ((long) size == 0L) { num1 = (byte) 0; num2 = (byte) 0; } else { num2 = (byte) Math.Log10((double) size); num1 = (byte) ((double) size / Math.Pow(10.0, (double) num2)); } byte num3 = (byte) ((uint) num1 << 4 | (uint) num2); ByteArrayExtensions.Write(buffer, offset, num3); } private static ulong ReadSize(byte value) { return (ulong) ((double) ((int) value >> 4) * Math.Pow(10.0, (double) ((int) value & 15))); } private static class Offset { public const int Version = 0; public const int Size = 1; public const int HorizontalPrecision = 2; public const int VerticalPrecision = 3; public const int Latitude = 4; public const int Longitude = 8; public const int Altitude = 12; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IOptionUnknownFactory`1 // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets { public interface IOptionUnknownFactory<in TOptionType> { Option CreateInstance(TOptionType optionType, byte[] buffer, ref int offset, byte valueLength); } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpRouterSolicitationDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; namespace PcapDotNet.Packets.Icmp { [IcmpDatagramRegistration(IcmpMessageType.RouterSolicitation)] public sealed class IcmpRouterSolicitationDatagram : IcmpDatagram { private IcmpRouterSolicitationDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public override ILayer ExtractLayer() { return (ILayer) new IcmpRouterSolicitationLayer(); } internal override IcmpDatagram CreateInstance(byte[] buffer, int offset, int length) { return (IcmpDatagram) new IcmpRouterSolicitationDatagram(buffer, offset, length); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataKeyExchanger // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.KeyExchanger)] public sealed class DnsResourceDataKeyExchanger : DnsResourceDataUShortDomainName { public ushort Preference { get { return this.Value; } } public DnsDomainName KeyExchangeHost { get { return this.DomainName; } } public DnsResourceDataKeyExchanger(ushort preference, DnsDomainName keyExchanger) : base(preference, keyExchanger) { } internal DnsResourceDataKeyExchanger() : this((ushort) 0, DnsDomainName.Root) { } internal override DnsResourceData CreateInstance(DnsDatagram dns, int offsetInDns, int length) { ushort preference; DnsDomainName domainName; if (!DnsResourceDataUShortDomainName.TryRead(out preference, out domainName, dns, offsetInDns, length)) return (DnsResourceData) null; return (DnsResourceData) new DnsResourceDataKeyExchanger(preference, domainName); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Http.HttpLayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Http { public abstract class HttpLayer : SimpleLayer, IEquatable<HttpLayer> { public abstract bool IsRequest { get; } public bool IsResponse { get { return !this.IsRequest; } } public HttpVersion Version { get; set; } public HttpHeader Header { get; set; } public Datagram Body { get; set; } public override sealed int Length { get { return this.FirstLineLength + (this.Header == null ? 0 : this.Header.BytesLength) + (this.Body == null ? 0 : this.Body.Length); } } internal abstract int FirstLineLength { get; } public override sealed bool Equals(Layer other) { return this.Equals(other as HttpLayer); } public virtual bool Equals(HttpLayer other) { if (other == null || !object.ReferenceEquals((object) this.Version, (object) other.Version) && !this.Version.Equals(other.Version) || !object.ReferenceEquals((object) this.Header, (object) other.Header) && !this.Header.Equals(other.Header)) return false; if (!object.ReferenceEquals((object) this.Body, (object) other.Body)) return this.Body.Equals((DataSegment) other.Body); return true; } protected override sealed void Write(byte[] buffer, int offset) { this.WriteFirstLine(buffer, ref offset); if (this.Header != null) this.Header.Write(buffer, ref offset); if (this.Body == null) return; ByteArrayExtensions.Write(buffer, offset, (DataSegment) this.Body); } internal abstract void WriteFirstLine(byte[] buffer, ref int offset); } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.PacketSendBuffer // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using PcapDotNet.Packets; using System; using System.Runtime.InteropServices; namespace PcapDotNet.Core { public class PacketSendBuffer : IDisposable { private unsafe pcap_send_queue* _pcapSendQueue; private int _length; public int Length { get { return this._length; } } public unsafe PacketSendBuffer(uint capacity) { this._pcapSendQueue = \u003CModule\u003E.pcap_sendqueue_alloc(capacity); } public unsafe void Enqueue(Packet packet) { if (packet == null) throw new ArgumentNullException("packet"); pcap_pkthdr pcapPkthdr; PacketHeader.GetPcapHeader(&pcapPkthdr, packet); fixed (byte* numPtr = &packet.Buffer[0]) { if (\u003CModule\u003E.pcap_sendqueue_queue(this._pcapSendQueue, &pcapPkthdr, numPtr) != 0) throw new InvalidOperationException("Failed enqueueing to queue"); ++this._length; } } private unsafe void \u007EPacketSendBuffer() { \u003CModule\u003E.pcap_sendqueue_destroy(this._pcapSendQueue); } internal unsafe void Transmit(pcap* pcapDescriptor, [MarshalAs(UnmanagedType.U1)] bool isSync) { if (\u003CModule\u003E.pcap_sendqueue_transmit(pcapDescriptor, this._pcapSendQueue, isSync ? 1 : 0) < (uint) *(int*) ((IntPtr) this._pcapSendQueue + 4L)) throw PcapError.BuildInvalidOperation("Failed transmiting packets from queue", pcapDescriptor); } protected virtual void Dispose([MarshalAs(UnmanagedType.U1)] bool _param1) { if (param0) { this.\u007EPacketSendBuffer(); } else { // ISSUE: explicit finalizer call this.Finalize(); } } public virtual void Dispose() { this.Dispose(true); GC.SuppressFinalize((object) this); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.SamplingMethodOneEveryCount // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using System; namespace PcapDotNet.Core { public sealed class SamplingMethodOneEveryCount : SamplingMethod { private int _count; internal override int Value { get { return this._count; } } internal override int Method { get { return 1; } } public SamplingMethodOneEveryCount(int count) { if (count <= 0) throw new ArgumentOutOfRangeException("count", (object) count, "Must be positive"); this._count = count; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Icmp { public abstract class IcmpDatagram : Datagram { public const int HeaderLength = 8; private bool? _isChecksumCorrect; private Datagram _payload; public IcmpMessageType MessageType { get { return (IcmpMessageType) this[0]; } } public byte Code { get { return this[1]; } } public IcmpMessageTypeAndCode MessageTypeAndCode { get { return (IcmpMessageTypeAndCode) this.ReadUShort(0, Endianity.Big); } } public ushort Checksum { get { return this.ReadUShort(2, Endianity.Big); } } public uint Variable { get { return this.ReadUInt(4, Endianity.Big); } } public bool IsChecksumCorrect { get { if (!this._isChecksumCorrect.HasValue) this._isChecksumCorrect = new bool?((int) this.CalculateChecksum() == (int) this.Checksum); return this._isChecksumCorrect.Value; } } public Datagram Payload { get { if (this._payload == null && this.Length >= 8) this._payload = new Datagram(this.Buffer, this.StartOffset + 8, this.Length - 8); return this._payload; } } protected virtual byte MinCodeValue { get { return (byte) 0; } } protected virtual byte MaxCodeValue { get { return (byte) 0; } } internal IcmpDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public abstract override ILayer ExtractLayer(); internal static void WriteHeader(byte[] buffer, int offset, IcmpMessageType messageType, byte code, uint valueAccordingToType) { ByteArrayExtensions.Write(buffer, offset, (byte) messageType); ByteArrayExtensions.Write(buffer, offset + 1, code); ByteArrayExtensions.Write(buffer, offset + 4, valueAccordingToType, Endianity.Big); } internal static void WriteChecksum(byte[] buffer, int offset, int length, ushort? checksum) { ushort? nullable = checksum; ushort num = !(nullable.HasValue ? new int?((int) nullable.GetValueOrDefault()) : new int?()).HasValue ? IcmpDatagram.CalculateChecksum(buffer, offset, length) : checksum.Value; ByteArrayExtensions.Write(buffer, offset + 2, num, Endianity.Big); } protected override bool CalculateIsValid() { if (this.Length >= 8 && this.IsChecksumCorrect && (int) this.Code >= (int) this.MinCodeValue) return (int) this.Code <= (int) this.MaxCodeValue; return false; } private ushort CalculateChecksum() { return IcmpDatagram.CalculateChecksum(this.Buffer, this.StartOffset, this.Length); } private static ushort CalculateChecksum(byte[] buffer, int offset, int length) { return DataSegment.Sum16BitsToChecksum(DataSegment.Sum16Bits(buffer, offset, Math.Min(2, length)) + DataSegment.Sum16Bits(buffer, offset + 2 + 2, length - 2 - 2)); } public static IcmpDatagram CreateDatagram(byte[] buffer, int offset, int length) { if (buffer == null) throw new ArgumentNullException("buffer"); if (length <= 0) return (IcmpDatagram) new IcmpUnknownDatagram(buffer, offset, length); return IcmpDatagramFactory.CreateInstance((IcmpMessageType) buffer[offset], buffer, offset, length); } internal abstract IcmpDatagram CreateInstance(byte[] buffer, int offset, int length); private static class Offset { public const int Type = 0; public const int Code = 1; public const int Checksum = 2; public const int Variable = 4; public const int Payload = 8; } } } <file_sep>using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Grib.Api.Tests { [TestFixture] public class Write { public Write() { } [Test] public void TestWrite() { if (File.Exists(Settings.OUT_GRIB)) { File.Delete(Settings.OUT_GRIB); } int count = 0; int valCount = 0; using (var readFile = new GribFile(Settings.PACIFIC_WIND)) { var msg = readFile.First(); Assert.AreNotEqual(33, msg["latitudeOfFirstGridPoint"].AsDouble()); msg["latitudeOfFirstGridPoint"].AsDouble(33); valCount = msg.ValuesCount; GribFile.Write(Settings.OUT_GRIB, msg); } using (var readFile = new GribFile(Settings.OUT_GRIB)) { var msg = readFile.First(); count = readFile.MessageCount; Assert.AreEqual(valCount, msg.ValuesCount); Assert.AreEqual(count, readFile.MessageCount); Assert.AreEqual(33, msg["latitudeOfFirstGridPoint"].AsDouble()); } using (var readFile = new GribFile(Settings.PACIFIC_WIND)) { GribFile.Write(Settings.OUT_GRIB, readFile as IEnumerable<GribMessage>, FileMode.Append); count += readFile.MessageCount; } using (var readFile = new GribFile(Settings.OUT_GRIB)) { Assert.AreEqual(count, readFile.MessageCount); Assert.AreEqual(33, readFile.First()["latitudeOfFirstGridPoint"].AsDouble()); } } public void TestCompression (string grid) { if (File.Exists(Settings.OUT_GRIB)) { File.Delete(Settings.OUT_GRIB); } int count = 0; double val = Double.NaN; Dictionary<int, GeoSpatialValue> orig = new Dictionary<int, GeoSpatialValue>(); using (var readFile = new GribFile(Settings.REDUCED_LATLON_GRB2)) { var msg = readFile.First(); count = msg.ValuesCount; val = msg["latitudeOfFirstGridPoint"].AsDouble(); Assert.AreNotEqual(val, Double.NaN); Assert.AreNotEqual(msg["packingType"].AsString(), grid); { for (int j = 0; j < 50; j++) { int k = 0; do { // over 200k values, so only pick from a subset k = GetRandomNumber(0, (count - 2) / 20); } while (orig.ContainsKey(k)); orig.Add(k, new GeoSpatialValue()); } int x = 0; int y = 0; foreach(var gsv in msg.GeoSpatialValues) { if (orig.ContainsKey(x)) { orig[x] = gsv; y++; if (y == orig.Count) break; } x++; } Assert.IsTrue(y == orig.Count); Assert.IsTrue(x > 0); } msg["packingType"].AsString(grid); Assert.AreEqual(msg["packingType"].AsString(), grid); Assert.AreEqual(count - 2, msg.ValuesCount); Assert.AreEqual(val, msg["latitudeOfFirstGridPoint"].AsDouble()); GribFile.Write(Settings.OUT_GRIB, msg); var newGsv = msg.GeoSpatialValues.ToArray(); Assert.IsTrue(newGsv.Any()); foreach (var kvp in orig) { var nv = newGsv[kvp.Key]; Assert.AreEqual(kvp.Value.Value, nv.Value, 0.01); } } using (var readFile = new GribFile(Settings.OUT_GRIB)) { var msg = readFile.First(); Assert.AreEqual(count - 2, msg.ValuesCount); Assert.AreEqual(val, msg["latitudeOfFirstGridPoint"].AsDouble()); Assert.AreEqual(msg["packingType"].AsString(), grid); var newGsv = msg.GeoSpatialValues.ToArray(); Assert.IsTrue(newGsv.Any()); foreach (var kvp in orig) { var nv = newGsv[kvp.Key]; Assert.AreEqual(kvp.Value.Value, nv.Value, 0.01); } } } [Test] public void TestPng () { TestCompression("grid_png"); } [Test] public void TestJpeg () { TestCompression("grid_jpeg"); } //Function to get random number private static readonly Random getrandom = new Random(); public static int GetRandomNumber (int min, int max) { return getrandom.Next(min, max); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpEchoDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; namespace PcapDotNet.Packets.Icmp { [IcmpDatagramRegistration(IcmpMessageType.Echo)] public sealed class IcmpEchoDatagram : IcmpIdentifiedDatagram { private IcmpEchoDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public override ILayer ExtractLayer() { IcmpEchoLayer icmpEchoLayer = new IcmpEchoLayer(); icmpEchoLayer.Checksum = new ushort?(this.Checksum); icmpEchoLayer.Identifier = this.Identifier; icmpEchoLayer.SequenceNumber = this.SequenceNumber; return (ILayer) icmpEchoLayer; } internal override IcmpDatagram CreateInstance(byte[] buffer, int offset, int length) { return (IcmpDatagram) new IcmpEchoDatagram(buffer, offset, length); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: <CppImplementationDetails>.$ArrayType$$$BY0A@P6AXXZ // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using Microsoft.VisualC; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace \u003CCppImplementationDetails\u003E { [DebugInfoInPDB] [MiscellaneousBits(65)] [NativeCppClass] [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct \u0024ArrayType\u0024\u0024\u0024BY0A\u0040P6AXXZ { } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsGatewayIpV6 // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using PcapDotNet.Packets.IpV6; using System; namespace PcapDotNet.Packets.Dns { public sealed class DnsGatewayIpV6 : DnsGateway, IEquatable<DnsGatewayIpV6> { public IpV6Address Value { get; private set; } public override DnsGatewayType GatewayType { get { return DnsGatewayType.IpV6; } } public override int Length { get { return 16; } } public DnsGatewayIpV6(IpV6Address value) { this.Value = value; } public bool Equals(DnsGatewayIpV6 other) { if (other != null) return this.Value.Equals(other.Value); return false; } public override bool Equals(DnsGateway other) { return this.Equals(other as DnsGatewayIpV6); } internal override int DataGetHashCode() { return this.Value.GetHashCode(); } internal override void Write(byte[] buffer, int offset) { ByteArrayExtensions.Write(buffer, offset, this.Value, Endianity.Big); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpCodeRedirect // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Icmp { public enum IcmpCodeRedirect : byte { ForTheNetwork, ForTheHost, ForTheTypeOfServiceAndNetwork, ForTheTypeOfServiceAndHost, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.PacketSampleStatistics // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using System; namespace PcapDotNet.Core { public sealed class PacketSampleStatistics { private DateTime _timestamp; private uint _acceptedPackets; private uint _acceptedBytes; public uint AcceptedBytes { get { return this._acceptedBytes; } } public uint AcceptedPackets { get { return this._acceptedPackets; } } public DateTime Timestamp { get { return this._timestamp; } } internal unsafe PacketSampleStatistics(pcap_pkthdr* packetHeader, byte* packetData) { PacketTimestamp.PcapTimestampToDateTime((timeval*) packetHeader, out this._timestamp); this._acceptedPackets = (uint) *(int*) packetData; this._acceptedBytes = (uint) *(int*) (packetData + 8L); } public override sealed string ToString() { return (string) (object) this._timestamp + (object) ": " + (object) this._acceptedPackets + " packets. " + (object) this._acceptedBytes + " bytes."; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Datagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets { public class Datagram : DataSegment { private static readonly Datagram _empty = new Datagram(new byte[0]); private bool? _isValid; public static Datagram Empty { get { return Datagram._empty; } } public bool IsValid { get { if (!this._isValid.HasValue) this._isValid = new bool?(this.CalculateIsValid()); return this._isValid.Value; } } public Datagram(byte[] buffer) : base(buffer) { } public Datagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public virtual ILayer ExtractLayer() { return (ILayer) new PayloadLayer() { Data = this }; } protected virtual bool CalculateIsValid() { return true; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: std.allocator<wchar_t> // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using Microsoft.VisualC; using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace std { [MiscellaneousBits(64)] [DebugInfoInPDB] [NativeCppClass] [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct allocator\u003Cwchar_t\u003E { [SpecialName] public static unsafe void \u003CMarshalCopy\u003E(allocator\u003Cwchar_t\u003E* _param1, allocator\u003Cwchar_t\u003E* _param2) { } [MiscellaneousBits(65)] [DebugInfoInPDB] [CLSCompliant(false)] [NativeCppClass] [StructLayout(LayoutKind.Sequential, Size = 1)] public struct rebind\u003Cwchar_t\u003E { } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Gre.GreVersion // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Gre { public enum GreVersion : byte { Gre, EnhancedGre, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.TcpOptionSelectiveAcknowledgment // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace PcapDotNet.Packets.Transport { [OptionTypeRegistration(typeof (TcpOptionType), TcpOptionType.SelectiveAcknowledgment)] public sealed class TcpOptionSelectiveAcknowledgment : TcpOptionComplex, IOptionComplexFactory, IEquatable<TcpOptionSelectiveAcknowledgment> { public const int OptionMinimumLength = 2; public const int OptionValueMinimumLength = 0; private readonly ReadOnlyCollection<TcpOptionSelectiveAcknowledgmentBlock> _blocks; public ReadOnlyCollection<TcpOptionSelectiveAcknowledgmentBlock> Blocks { get { return this._blocks; } } public override int Length { get { return 2 + 8 * this.Blocks.Count; } } public override bool IsAppearsAtMostOnce { get { return true; } } public TcpOptionSelectiveAcknowledgment(IList<TcpOptionSelectiveAcknowledgmentBlock> blocks) : base(TcpOptionType.SelectiveAcknowledgment) { this._blocks = new ReadOnlyCollection<TcpOptionSelectiveAcknowledgmentBlock>(blocks); } public TcpOptionSelectiveAcknowledgment() : this((IList<TcpOptionSelectiveAcknowledgmentBlock>) new TcpOptionSelectiveAcknowledgmentBlock[0]) { } public bool Equals(TcpOptionSelectiveAcknowledgment other) { if (other == null) return false; return Enumerable.SequenceEqual<TcpOptionSelectiveAcknowledgmentBlock>((IEnumerable<TcpOptionSelectiveAcknowledgmentBlock>) this.Blocks, (IEnumerable<TcpOptionSelectiveAcknowledgmentBlock>) other.Blocks); } public override bool Equals(TcpOption other) { return this.Equals(other as TcpOptionSelectiveAcknowledgment); } public override int GetHashCode() { return base.GetHashCode() ^ IEnumerableExtensions.SequenceGetHashCode<TcpOptionSelectiveAcknowledgmentBlock>((IEnumerable<TcpOptionSelectiveAcknowledgmentBlock>) this.Blocks); } Option IOptionComplexFactory.CreateInstance(byte[] buffer, ref int offset, byte valueLength) { if ((int) valueLength < 0 || (int) valueLength % 8 != 0) return (Option) null; int length = (int) valueLength / 8; TcpOptionSelectiveAcknowledgmentBlock[] acknowledgmentBlockArray = new TcpOptionSelectiveAcknowledgmentBlock[length]; for (int index = 0; index != length; ++index) acknowledgmentBlockArray[index] = new TcpOptionSelectiveAcknowledgmentBlock(ByteArrayExtensions.ReadUInt(buffer, ref offset, Endianity.Big), ByteArrayExtensions.ReadUInt(buffer, ref offset, Endianity.Big)); return (Option) new TcpOptionSelectiveAcknowledgment((IList<TcpOptionSelectiveAcknowledgmentBlock>) acknowledgmentBlockArray); } internal override void Write(byte[] buffer, ref int offset) { base.Write(buffer, ref offset); foreach (TcpOptionSelectiveAcknowledgmentBlock acknowledgmentBlock in this.Blocks) { ByteArrayExtensions.Write(buffer, ref offset, acknowledgmentBlock.LeftEdge, Endianity.Big); ByteArrayExtensions.Write(buffer, ref offset, acknowledgmentBlock.RightEdge, Endianity.Big); } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.TcpOptionConnectionCount // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; namespace PcapDotNet.Packets.Transport { [OptionTypeRegistration(typeof (TcpOptionType), TcpOptionType.ConnectionCount)] public class TcpOptionConnectionCount : TcpOptionConnectionCountBase, IOptionComplexFactory { public TcpOptionConnectionCount(uint connectionCount) : base(TcpOptionType.ConnectionCount, connectionCount) { } public TcpOptionConnectionCount() : this(0U) { } Option IOptionComplexFactory.CreateInstance(byte[] buffer, ref int offset, byte valueLength) { uint connectionCount; if (!TcpOptionConnectionCountBase.TryRead(out connectionCount, buffer, ref offset, valueLength)) return (Option) null; return (Option) new TcpOptionConnectionCount(connectionCount); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Igmp.IgmpLayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using PcapDotNet.Packets.IpV4; using System; namespace PcapDotNet.Packets.Igmp { public abstract class IgmpLayer : SimpleLayer, IIpV4NextLayer, ILayer { public abstract IgmpMessageType MessageType { get; } public virtual IgmpQueryVersion QueryVersion { get { return IgmpQueryVersion.None; } } public abstract TimeSpan MaxResponseTimeValue { get; } public IpV4Protocol PreviousLayerProtocol { get { return IpV4Protocol.InternetGroupManagementProtocol; } } public bool Equals(IgmpLayer other) { if (other != null && this.MessageType == other.MessageType && (this.QueryVersion == other.QueryVersion && IgmpLayer.EqualMaxResponseTime(this.MaxResponseTimeValue, other.MaxResponseTimeValue))) return this.EqualFields(other); return false; } public override sealed bool Equals(Layer other) { return this.Equals(other as IgmpLayer); } public override int GetHashCode() { return base.GetHashCode() ^ Sequence.GetHashCode((object) this.MessageType, (object) this.QueryVersion); } protected abstract bool EqualFields(IgmpLayer other); private static bool EqualMaxResponseTime(TimeSpan value1, TimeSpan value2) { if (TimeSpanExtensions.Divide(value1, 2.0) <= value2) return TimeSpanExtensions.Multiply(value1, 2.0) >= value2; return false; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Gre.GreSourceRouteEntryIp // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using PcapDotNet.Packets.IpV4; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace PcapDotNet.Packets.Gre { public sealed class GreSourceRouteEntryIp : GreSourceRouteEntry { private readonly ReadOnlyCollection<IpV4Address> _addresses; private readonly int _nextAddressIndex; public override GreSourceRouteEntryAddressFamily AddressFamily { get { return GreSourceRouteEntryAddressFamily.IpSourceRoute; } } public override byte PayloadLength { get { return (byte) (this.Addresses.Count * 4); } } public override byte PayloadOffset { get { return (byte) (this.NextAddressIndex * 4); } } protected override int PayloadHashCode { get { return IEnumerableExtensions.SequenceGetHashCode<IpV4Address>((IEnumerable<IpV4Address>) this.Addresses); } } public ReadOnlyCollection<IpV4Address> Addresses { get { return this._addresses; } } public int NextAddressIndex { get { return this._nextAddressIndex; } } public IpV4Address NextAddress { get { return this.Addresses[this.NextAddressIndex]; } } public GreSourceRouteEntryIp(ReadOnlyCollection<IpV4Address> addresses, int nextAddressIndex) { this._addresses = addresses; this._nextAddressIndex = nextAddressIndex; } internal GreSourceRouteEntryIp(IpV4Address[] addresses, int nextAddressIndex) : this(IListExtensions.AsReadOnly<IpV4Address>((IList<IpV4Address>) addresses), nextAddressIndex) { } protected override bool EqualsPayloads(GreSourceRouteEntry other) { return Enumerable.SequenceEqual<IpV4Address>((IEnumerable<IpV4Address>) this.Addresses, (IEnumerable<IpV4Address>) ((GreSourceRouteEntryIp) other).Addresses); } protected override void WritePayload(byte[] buffer, int offset) { foreach (IpV4Address ipV4Address in this.Addresses) ByteArrayExtensions.Write(buffer, ref offset, ipV4Address, Endianity.Big); } } } <file_sep>using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Grib.Api.Tests { [TestFixture] public class SetBitmap { [Test] public void TestSetBitmapMissing () { using (GribFile file = new GribFile(Settings.REG_LATLON_GRB1)) { var msg = file.First(); int missing = 3333; // set the value used to represent missing data msg.MissingValue = missing; Assert.AreEqual(msg.MissingValue, missing); Assert.IsFalse(msg.HasBitmap); int numVals = 10; double[] vals = new double[numVals]; for (int i = 0; i < numVals; i++) { vals[i] = missing; } msg.HasBitmap = true; msg.SetValues(vals); double[] vals2; msg.Values(out vals2); for (int i = 0; i < numVals; i++) { Assert.AreEqual(vals[i], vals2[i]); Assert.AreEqual(missing, vals2[i]); } missing = 9898; msg.MissingValue = missing; msg.Values(out vals); for (int i = 0; i < numVals; i++) { Assert.AreEqual(missing, vals[i]); } } } [Test] public void TestSetBitmap() { using (GribFile file = new GribFile(Settings.REG_LATLON_GRB1)) { var msg = file.First(); int numVals = 10; double[] vals = new double[numVals]; double val = 42; for(int i =0; i < numVals; i++) { vals[i] = val; } msg.HasBitmap = true; msg.SetValues(vals); double[] vals2; msg.Values(out vals2); for (int i = 0; i < numVals; i++) { Assert.AreEqual(vals[i], vals2[i]); Assert.AreEqual(val, vals2[i]); } } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IpV4Option // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.IpV4 { public abstract class IpV4Option : Option, IEquatable<IpV4Option> { private static readonly IpV4OptionSimple _end = new IpV4OptionSimple(IpV4OptionType.EndOfOptionList); private static readonly IpV4OptionSimple _nop = new IpV4OptionSimple(IpV4OptionType.NoOperation); private readonly IpV4OptionType _type; public static IpV4OptionSimple End { get { return IpV4Option._end; } } public static IpV4OptionSimple Nop { get { return IpV4Option._nop; } } public IpV4OptionType OptionType { get { return this._type; } } protected IpV4Option(IpV4OptionType type) { this._type = type; } public override sealed bool Equivalent(Option other) { return this.OptionType == ((IpV4Option) other).OptionType; } public virtual bool Equals(IpV4Option other) { if (other == null) return false; return this.Equivalent((Option) other); } public override sealed bool Equals(object obj) { return this.Equals(obj as IpV4Option); } public override int GetHashCode() { return this.OptionType.GetHashCode(); } public override sealed string ToString() { return this.OptionType.ToString(); } internal override sealed Option Read(byte[] buffer, ref int offset, int length) { int num = offset + length; if (offset == num) return (Option) null; IpV4OptionType optionType = (IpV4OptionType) buffer[offset++]; switch (optionType) { case IpV4OptionType.EndOfOptionList: return (Option) IpV4Option.End; case IpV4OptionType.NoOperation: return (Option) IpV4Option.Nop; default: return OptionComplexFactory<IpV4OptionType>.Read(optionType, buffer, ref offset, num - offset); } } internal override void Write(byte[] buffer, ref int offset) { buffer[offset++] = (byte) this.OptionType; } } } <file_sep>namespace ForecastIOPortable.Models { using System.Collections.Generic; using System.Runtime.Serialization; /// <summary> /// An hour-by-hour forecast. /// </summary> [DataContract] public class HourlyForecast { /// <summary> /// Gets or sets a human-readable summary of the forecast. /// </summary> [DataMember(Name = "summary")] public string Summary { get; set; } /// <summary> /// Gets or sets machine-readable text that can be used to select an icon to display. /// </summary> [DataMember(Name = "icon")] public string Icon { get; set; } /// <summary> /// Gets or sets the individual hours that make up this forecast. /// </summary> [DataMember(Name = "data")] public IList<HourDataPoint> Hours { get; set; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IpV4OptionType // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.IpV4 { public enum IpV4OptionType : byte { EndOfOptionList = (byte) 0, NoOperation = (byte) 1, RecordRoute = (byte) 7, QuickStart = (byte) 25, InternetTimestamp = (byte) 68, TraceRoute = (byte) 82, BasicSecurity = (byte) 130, LooseSourceRouting = (byte) 131, StreamIdentifier = (byte) 136, StrictSourceRouting = (byte) 137, RouterAlert = (byte) 148, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.PacketDumpFile // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using PcapDotNet.Packets; using std; using System; using System.Collections.Generic; using System.Runtime.InteropServices; namespace PcapDotNet.Core { public class PacketDumpFile : IDisposable { private unsafe pcap_dumper* _pcapDumper; private string _filename; public unsafe int Position { get { int num = \u003CModule\u003E.pcap_dump_ftell(this._pcapDumper); if (num == -1) throw new InvalidOperationException("Failed getting position"); return num; } } internal PacketDumpFile(pcap* pcapDescriptor, string filename) { // ISSUE: unable to decompile the method. } public unsafe void Dump(Packet packet) { if (packet == null) throw new ArgumentNullException("packet"); pcap_pkthdr pcapPkthdr; PacketHeader.GetPcapHeader(&pcapPkthdr, packet); basic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E stdAllocatorChar; MarshalingServices.ManagedToUnmanagedString(&stdAllocatorChar, this._filename); // ISSUE: fault handler try { fixed (byte* numPtr = &packet.Buffer[0]) \u003CModule\u003E.pcap_dump((byte*) this._pcapDumper, &pcapPkthdr, numPtr); } __fault { // ISSUE: method pointer // ISSUE: cast to a function pointer type \u003CModule\u003E.___CxxCallUnwindDtor((__FnPtr<void (void*)>) __methodptr(std\u002Ebasic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E\u002E\u007Bdtor\u007D), (void*) &stdAllocatorChar); } // ISSUE: cast to a reference type // ISSUE: explicit reference operation if (16UL > (ulong) ^(long&) ((IntPtr) &stdAllocatorChar + 24)) return; // ISSUE: explicit reference operation // ISSUE: cast to a reference type // ISSUE: explicit reference operation \u003CModule\u003E.delete((void*) ^(long&) @stdAllocatorChar); } public static void Dump(string fileName, DataLinkKind dataLink, int snapshotLength, IEnumerable<Packet> packets) { PcapDataLink dataLink1 = new PcapDataLink(dataLink); PacketDumpFile.Dump(fileName, dataLink1, snapshotLength, packets); } public static unsafe void Dump(string fileName, PcapDataLink dataLink, int snapshotLength, IEnumerable<Packet> packets) { if (packets == null) throw new ArgumentNullException("packets"); pcap* pcapDescriptor = \u003CModule\u003E.pcap_open_dead(dataLink.Value, snapshotLength); if ((IntPtr) pcapDescriptor == IntPtr.Zero) throw new InvalidOperationException("Unable to open open a dead capture"); try { using (PacketDumpFile packetDumpFile = new PacketDumpFile(pcapDescriptor, fileName)) { foreach (Packet packet in packets) packetDumpFile.Dump(packet); } } finally { \u003CModule\u003E.pcap_close(pcapDescriptor); } } public unsafe void Flush() { if (\u003CModule\u003E.pcap_dump_flush(this._pcapDumper) != 0) throw new InvalidOperationException("Failed flushing to file " + this._filename); } private unsafe void \u007EPacketDumpFile() { \u003CModule\u003E.pcap_dump_close(this._pcapDumper); } protected virtual void Dispose([MarshalAs(UnmanagedType.U1)] bool _param1) { if (param0) { this.\u007EPacketDumpFile(); } else { // ISSUE: explicit finalizer call this.Finalize(); } } public virtual void Dispose() { this.Dispose(true); GC.SuppressFinalize((object) this); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: <Module> // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using \u003CCppImplementationDetails\u003E; using \u003CCrtImplementationDetails\u003E; using std; using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Threading; internal class \u003CModule\u003E { internal static \u0024ArrayType\u0024\u0024\u0024BY08\u0024\u0024CBD \u003F\u003F_C\u0040_08FFEMNKKP\u0040rpcap\u003F3\u003F1\u003F1\u003F\u0024AA\u0040; internal static \u0024ArrayType\u0024\u0024\u0024BY0BI\u0040\u0024\u0024CBD \u003F\u003F_C\u0040_0BI\u0040CFPLBAOH\u0040invalid\u003F5string\u003F5position\u003F\u0024AA\u0040; internal static \u0024ArrayType\u0024\u0024\u0024BY0BA\u0040\u0024\u0024CBD \u003F\u003F_C\u0040_0BA\u0040JFNIOLAK\u0040string\u003F5too\u003F5long\u003F\u0024AA\u0040; internal static \u0024ArrayType\u0024\u0024\u0024BY02Q6AXXZ \u003F\u003F_7bad_alloc\u0040std\u0040\u00406B\u0040; internal static _s__RTTIBaseClassDescriptor2 \u003F\u003F_R1A\u0040\u003F0A\u0040EA\u0040exception\u0040std\u0040\u00408; internal static \u0024_TypeDescriptor\u0024_extraBytes_20 \u003F\u003F_R0\u003FAVexception\u0040std\u0040\u0040\u00408; internal static _s__CatchableType _CT\u003F\u003F_R0\u003FAVbad_alloc\u0040std\u0040\u0040\u00408\u003F\u003F0bad_alloc\u0040std\u0040\u0040\u0024\u0024FQEAA\u0040AEBV01\u0040\u0040Z24; internal static \u0024_s__RTTIBaseClassArray\u0024_extraBytes_16 \u003F\u003F_R2bad_alloc\u0040std\u0040\u00408; internal static _s__RTTIBaseClassDescriptor2 \u003F\u003F_R1A\u0040\u003F0A\u0040EA\u0040bad_alloc\u0040std\u0040\u00408; internal static _s__RTTIClassHierarchyDescriptor \u003F\u003F_R3bad_alloc\u0040std\u0040\u00408; internal static \u0024_TypeDescriptor\u0024_extraBytes_20 \u003F\u003F_R0\u003FAVbad_alloc\u0040std\u0040\u0040\u00408; internal static \u0024_s__RTTIBaseClassArray\u0024_extraBytes_8 \u003F\u003F_R2exception\u0040std\u0040\u00408; internal static _s__RTTIClassHierarchyDescriptor \u003F\u003F_R3exception\u0040std\u0040\u00408; internal static \u0024_s__CatchableTypeArray\u0024_extraBytes_16 _CTA2\u003FAVbad_alloc\u0040std\u0040\u0040; internal static _s__ThrowInfo _TI2\u003FAVbad_alloc\u0040std\u0040\u0040; internal static _s__RTTICompleteObjectLocator2 \u003F\u003F_R4bad_alloc\u0040std\u0040\u00406B\u0040; internal static _s__CatchableType _CT\u003F\u003F_R0\u003FAVexception\u0040std\u0040\u0040\u00408\u003F\u003F0exception\u0040std\u0040\u0040\u0024\u0024FQEAA\u0040AEBV01\u0040\u0040Z24; public static __FnPtr<void (bad_alloc*)> __m2mep\u0040\u003F\u003F1bad_alloc\u0040std\u0040\u0040\u0024\u0024FUEAA\u0040XZ; public static __FnPtr<void* (bad_alloc*, uint)> __m2mep\u0040\u003F\u003F_Ebad_alloc\u0040std\u0040\u0040\u0024\u0024FUEAAPEAXI\u0040Z; public static __FnPtr<bad_alloc* (bad_alloc*, bad_alloc*)> __m2mep\u0040\u003F\u003F0bad_alloc\u0040std\u0040\u0040\u0024\u0024FQEAA\u0040AEBV01\u0040\u0040Z; internal static \u0024ArrayType\u0024\u0024\u0024BY02\u0024\u0024CB_W \u003F\u003F_C\u0040_15JJPIMNBO\u0040\u003F\u0024AAr\u003F\u0024AAb\u003F\u0024AA\u003F\u0024AA\u0040; internal static __s_GUID _GUID_90f1a06e_7712_4762_86b5_7a5eba6bdb02; internal static __s_GUID _GUID_cb2f6722_ab3a_11d2_9c40_00c04fa30a3e; internal static \u0024ArrayType\u0024\u0024\u0024BY00Q6MPEBXXZ \u003FA0x73b2ab14\u002E__xc_mp_z; internal static \u0024ArrayType\u0024\u0024\u0024BY00Q6MPEBXXZ \u003FA0x73b2ab14\u002E__xi_vt_a; [FixedAddressValueType] internal static Progress.State \u003FInitializedVtables\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2W4State\u0040Progress\u00402\u0040A; internal static __FnPtr<void ()> \u003FA0x73b2ab14\u002E\u003FInitializedVtables\u0024initializer\u0024\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2P6MXXZEA; [FixedAddressValueType] internal static bool \u003FIsDefaultDomain\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2_NA; internal static __FnPtr<void ()> \u003FA0x73b2ab14\u002E\u003FIsDefaultDomain\u0024initializer\u0024\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2P6MXXZEA; internal static \u0024ArrayType\u0024\u0024\u0024BY00Q6MPEBXXZ \u003FA0x73b2ab14\u002E__xc_ma_a; [FixedAddressValueType] internal static Progress.State \u003FInitializedPerAppDomain\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2W4State\u0040Progress\u00402\u0040A; internal static __FnPtr<void ()> \u003FA0x73b2ab14\u002E\u003FInitializedPerAppDomain\u0024initializer\u0024\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2P6MXXZEA; internal static \u0024ArrayType\u0024\u0024\u0024BY00Q6MPEBXXZ \u003FA0x73b2ab14\u002E__xc_ma_z; [FixedAddressValueType] internal static Progress.State \u003FInitializedNative\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2W4State\u0040Progress\u00402\u0040A; internal static __FnPtr<void ()> \u003FA0x73b2ab14\u002E\u003FInitializedNative\u0024initializer\u0024\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2P6MXXZEA; internal static __s_GUID _GUID_cb2f6723_ab3a_11d2_9c40_00c04fa30a3e; internal static \u0024ArrayType\u0024\u0024\u0024BY00Q6MPEBXXZ \u003FA0x73b2ab14\u002E__xi_vt_z; [FixedAddressValueType] internal static int \u003FUninitialized\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2HA; internal static __FnPtr<void ()> \u003FA0x73b2ab14\u002E\u003FUninitialized\u0024initializer\u0024\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2P6MXXZEA; [FixedAddressValueType] internal static int \u003FInitialized\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2HA; internal static __FnPtr<void ()> \u003FA0x73b2ab14\u002E\u003FInitialized\u0024initializer\u0024\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2P6MXXZEA; internal static bool \u003FInitializedPerProcess\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u00402_NA; [FixedAddressValueType] internal static Progress.State \u003FInitializedPerProcess\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2W4State\u0040Progress\u00402\u0040A; internal static bool \u003FEntered\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u00402_NA; internal static bool \u003FInitializedNative\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u00402_NA; internal static int \u003FCount\u0040AllDomains\u0040\u003CCrtImplementationDetails\u003E\u0040\u00402HA; internal static TriBool.State \u003FhasNative\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u00400W4State\u0040TriBool\u00402\u0040A; internal static TriBool.State \u003FhasPerProcess\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u00400W4State\u0040TriBool\u00402\u0040A; internal static bool \u003FInitializedNativeFromCCTOR\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u00402_NA; internal static \u0024ArrayType\u0024\u0024\u0024BY00Q6MPEBXXZ \u003FA0x73b2ab14\u002E__xc_mp_a; internal static __s_GUID _GUID_90f1a06c_7712_4762_86b5_7a5eba6bdb02; internal static __FnPtr<void ()> \u003FA0x73b2ab14\u002E\u003FInitializedPerProcess\u0024initializer\u0024\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2P6MXXZEA; public static __FnPtr<int (void*)> __m2mep\u0040\u003FDoNothing\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024FCAJPEAX\u0040Z; public static __FnPtr<int (void*)> __m2mep\u0040\u003F_UninitializeDefaultDomain\u0040LanguageSupport\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024FCAJPEAX\u0040Z; public static unsafe int** __unep\u0040\u003FDoNothing\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024FCAJPEAX\u0040Z; public static unsafe int** __unep\u0040\u003F_UninitializeDefaultDomain\u0040LanguageSupport\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024FCAJPEAX\u0040Z; [FixedAddressValueType] internal static ulong __exit_list_size_app_domain; [FixedAddressValueType] internal static unsafe __FnPtr<void ()>* __onexitbegin_app_domain; internal static ulong \u003FA0x47cf2733\u002E__exit_list_size; [FixedAddressValueType] internal static unsafe __FnPtr<void ()>* __onexitend_app_domain; internal static unsafe __FnPtr<void ()>* \u003FA0x47cf2733\u002E__onexitbegin_m; internal static unsafe __FnPtr<void ()>* \u003FA0x47cf2733\u002E__onexitend_m; [FixedAddressValueType] internal static int \u003F_ref_count\u0040AtExitLock\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q0HA; [FixedAddressValueType] internal static unsafe void* \u003F_lock\u0040AtExitLock\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q0PEAXEA; internal static \u0024ArrayType\u0024\u0024\u0024BY01Q6AXXZ \u003F\u003F_7type_info\u0040\u00406B\u0040; internal static \u0024ArrayType\u0024\u0024\u0024BY0A\u0040P6AXXZ __xc_z; internal static volatile uint __native_vcclrit_reason; internal static \u0024ArrayType\u0024\u0024\u0024BY0A\u0040P6AXXZ __xc_a; internal static \u0024ArrayType\u0024\u0024\u0024BY0A\u0040P6AHXZ __xi_a; internal static volatile __enative_startup_state __native_startup_state; internal static \u0024ArrayType\u0024\u0024\u0024BY0A\u0040P6AHXZ __xi_z; internal static volatile unsafe void* __native_startup_lock; internal static volatile uint __native_dllmain_reason; [SecurityCritical] [DebuggerStepThrough] static unsafe \u003CModule\u003E() { LanguageSupport languageSupport; \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002E\u007Bctor\u007D(&languageSupport); // ISSUE: fault handler try { \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002EInitialize(&languageSupport); } __fault { // ISSUE: method pointer // ISSUE: cast to a function pointer type \u003CModule\u003E.___CxxCallUnwindDtor((__FnPtr<void (void*)>) __methodptr(\u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002E\u007Bdtor\u007D), (void*) &languageSupport); } \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002E\u007Bdtor\u007D(&languageSupport); } internal static unsafe void std\u002Ebad_alloc\u002E\u007Bdtor\u007D([In] bad_alloc* obj0) { *(long*) obj0 = (long) &\u003CModule\u003E.\u003F\u003F_7bad_alloc\u0040std\u0040\u00406B\u0040; \u003CModule\u003E.std\u002Eexception\u002E\u007Bdtor\u007D((exception*) obj0); } internal static unsafe void* std\u002Ebad_alloc\u002E__vecDelDtor([In] bad_alloc* obj0, uint _param2) { if (((int) param1 & 2) != 0) { bad_alloc* badAllocPtr = (bad_alloc*) ((IntPtr) obj0 - 8L); // ISSUE: method pointer // ISSUE: cast to a function pointer type \u003CModule\u003E.__ehvec_dtor((void*) obj0, 24UL, *(int*) badAllocPtr, (__FnPtr<void (void*)>) __methodptr(std\u002Ebad_alloc\u002E\u007Bdtor\u007D)); if (((int) param1 & 1) != 0) \u003CModule\u003E.delete((void*) badAllocPtr); return (void*) badAllocPtr; } *(long*) obj0 = (long) &\u003CModule\u003E.\u003F\u003F_7bad_alloc\u0040std\u0040\u00406B\u0040; \u003CModule\u003E.std\u002Eexception\u002E\u007Bdtor\u007D((exception*) obj0); if (((int) param1 & 1) != 0) \u003CModule\u003E.delete((void*) obj0); return (void*) obj0; } internal static unsafe void std\u002Ebasic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E\u002E\u007Bdtor\u007D([In] basic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E* obj0) { if (16UL <= (ulong) *(long*) ((IntPtr) obj0 + 24L)) \u003CModule\u003E.delete((void*) *(long*) obj0); *(long*) ((IntPtr) obj0 + 24L) = 15L; *(long*) ((IntPtr) obj0 + 16L) = 0L; *(sbyte*) obj0 = (sbyte) 0; } internal static unsafe sbyte* std\u002Ebasic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E\u002Ec_str([In] basic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E* obj0) { if (16UL <= (ulong) *(long*) ((IntPtr) obj0 + 24L)) return (sbyte*) *(long*) obj0; return (sbyte*) obj0; } internal static unsafe void std\u002Ebasic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E\u002E\u007Bdtor\u007D([In] basic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E* obj0) { if (8UL <= (ulong) *(long*) ((IntPtr) obj0 + 24L)) \u003CModule\u003E.delete((void*) *(long*) obj0); *(long*) ((IntPtr) obj0 + 24L) = 7L; *(long*) ((IntPtr) obj0 + 16L) = 0L; *(short*) obj0 = (short) 0; } internal static unsafe void std\u002Ebasic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E\u002E_Tidy([In] basic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E* obj0, [MarshalAs(UnmanagedType.U1)] bool _Built, ulong _Newsize) { if (_Built && 16UL <= (ulong) *(long*) ((IntPtr) obj0 + 24L)) { sbyte* numPtr = (sbyte*) *(long*) obj0; if (0UL < _Newsize) { // ISSUE: cpblk instruction __memcpy((IntPtr) obj0, (IntPtr) numPtr, (long) _Newsize); } \u003CModule\u003E.delete((void*) numPtr); } *(long*) ((IntPtr) obj0 + 24L) = 15L; *(long*) ((IntPtr) obj0 + 16L) = (long) _Newsize; *(sbyte*) ((long) _Newsize + (IntPtr) obj0) = (sbyte) 0; } internal static unsafe basic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E* std\u002Ebasic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E\u002Eassign([In] basic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E* obj0, basic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E* _Right, ulong _Roff, ulong _Count) { ulong num1 = (ulong) *(long*) ((IntPtr) _Right + 16L); if (num1 < _Roff) \u003CModule\u003E.std\u002E_Xout_of_range((sbyte*) &\u003CModule\u003E.\u003F\u003F_C\u0040_0BI\u0040CFPLBAOH\u0040invalid\u003F5string\u003F5position\u003F\u0024AA\u0040); ulong num2 = num1 - _Roff; ulong _Newsize = _Count < num2 ? _Count : num2; if (obj0 == _Right) { \u003CModule\u003E.std\u002Ebasic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E\u002Eerase(obj0, _Newsize + _Roff, ulong.MaxValue); \u003CModule\u003E.std\u002Ebasic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E\u002Eerase(obj0, 0UL, _Roff); } else { if (9223372036854775806UL < _Newsize) \u003CModule\u003E.std\u002E_Xlength_error((sbyte*) &\u003CModule\u003E.\u003F\u003F_C\u0040_0BA\u0040JFNIOLAK\u0040string\u003F5too\u003F5long\u003F\u0024AA\u0040); ulong num3 = (ulong) *(long*) ((IntPtr) obj0 + 24L); if (num3 < _Newsize) \u003CModule\u003E.std\u002Ebasic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E\u002E_Copy(obj0, _Newsize, (ulong) *(long*) ((IntPtr) obj0 + 16L)); else if ((long) _Newsize == 0L) { *(long*) ((IntPtr) obj0 + 16L) = 0L; *(8UL > num3 ? (short*) (ValueType) (IntPtr) obj0 : (short*) (ValueType) *(long*) obj0) = (short) 0; goto label_12; } int num4; if (0UL < _Newsize) { num4 = 1; goto label_13; } label_12: num4 = 0; label_13: if ((int) (byte) num4 != 0) { char* chPtr1 = 8UL > (ulong) *(long*) ((IntPtr) _Right + 24L) ? (char*) _Right : (char*) *(long*) _Right; ValueType valueType = 8UL > (ulong) *(long*) ((IntPtr) obj0 + 24L) ? (ValueType) (IntPtr) obj0 : (ValueType) *(long*) obj0; ulong num5 = _Newsize * 2UL; IntPtr num6 = (long) _Roff * 2L + (IntPtr) chPtr1; long num7 = (long) num5; // ISSUE: cpblk instruction __memcpy(valueType, num6, num7); *(long*) ((IntPtr) obj0 + 16L) = (long) _Newsize; char* chPtr2 = 8UL > (ulong) *(long*) ((IntPtr) obj0 + 24L) ? (char*) obj0 : (char*) *(long*) obj0; *(short*) ((long) num5 + (IntPtr) chPtr2) = (short) 0; } } return obj0; } internal static unsafe void std\u002Ebasic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E\u002E_Tidy([In] basic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E* obj0, [MarshalAs(UnmanagedType.U1)] bool _Built, ulong _Newsize) { if (_Built && 8UL <= (ulong) *(long*) ((IntPtr) obj0 + 24L)) { char* chPtr = (char*) *(long*) obj0; if (0UL < _Newsize) { // ISSUE: cpblk instruction __memcpy((IntPtr) obj0, (IntPtr) chPtr, (long) _Newsize * 2L); } \u003CModule\u003E.delete((void*) chPtr); } *(long*) ((IntPtr) obj0 + 24L) = 7L; *(long*) ((IntPtr) obj0 + 16L) = (long) _Newsize; *(short*) ((long) _Newsize * 2L + (IntPtr) obj0) = (short) 0; } internal static unsafe basic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E* std\u002Ebasic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E\u002Eerase([In] basic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E* obj0, ulong _Off, ulong _Count) { ulong num1 = (ulong) *(long*) ((IntPtr) obj0 + 16L); if (num1 < _Off) \u003CModule\u003E.std\u002E_Xout_of_range((sbyte*) &\u003CModule\u003E.\u003F\u003F_C\u0040_0BI\u0040CFPLBAOH\u0040invalid\u003F5string\u003F5position\u003F\u0024AA\u0040); ulong num2 = num1 - _Off; _Count = num2 < _Count ? num2 : _Count; if (0UL < _Count) { ulong num3 = (ulong) *(long*) ((IntPtr) obj0 + 24L); char* chPtr1 = 8UL > num3 ? (char*) obj0 : (char*) *(long*) obj0; char* chPtr2 = 8UL > num3 ? (char*) obj0 : (char*) *(long*) obj0; \u003CModule\u003E.memmove((void*) ((long) _Off * 2L + (IntPtr) chPtr2), (void*) (((long) _Off + (long) _Count) * 2L + (IntPtr) chPtr1), (num2 - _Count) * 2UL); ulong num4 = (ulong) *(long*) ((IntPtr) obj0 + 16L) - _Count; *(long*) ((IntPtr) obj0 + 16L) = (long) num4; char* chPtr3 = 8UL > (ulong) *(long*) ((IntPtr) obj0 + 24L) ? (char*) obj0 : (char*) *(long*) obj0; *(short*) ((long) num4 * 2L + (IntPtr) chPtr3) = (short) 0; } return obj0; } internal static unsafe void std\u002Ebasic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E\u002E_Copy([In] basic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E* obj0, ulong _Newsize, ulong _Oldlen) { ulong num1 = (ulong) \u003CModule\u003E.__CxxQueryExceptionSize(); // ISSUE: untyped stack allocation long num2 = (long) __untypedstackalloc((long) num1 * 2L); ulong num3 = _Newsize | 7UL; if (9223372036854775806UL < num3) { num3 = _Newsize; } else { ulong num4 = (ulong) *(long*) ((IntPtr) obj0 + 24L); ulong num5 = num4 >> 1; if (num5 > num3 / 3UL) num3 = num4 > 9223372036854775806UL - num5 ? 9223372036854775806UL : num5 + num4; } long num6; char* chPtr1; try { num6 = num2 + (long) num1; chPtr1 = \u003CModule\u003E.std\u002Eallocator\u003Cwchar_t\u003E\u002Eallocate((allocator\u003Cwchar_t\u003E*) ((IntPtr) obj0 + 32L), num3 + 1UL); } catch (Exception ex1) when ( { // ISSUE: unable to correctly present filter uint num4 = (uint) Marshal.GetExceptionCode(); if (\u003CModule\u003E.__CxxExceptionFilter((void*) Marshal.GetExceptionPointers(), (void*) 0, 0, (void*) 0) != 0) { SuccessfulFiltering; } else throw; } ) { uint num5 = 0U; \u003CModule\u003E.__CxxRegisterExceptionObject((void*) Marshal.GetExceptionPointers(), (void*) num6); try { try { num3 = _Newsize; try { chPtr1 = \u003CModule\u003E.std\u002Eallocator\u003Cwchar_t\u003E\u002Eallocate((allocator\u003Cwchar_t\u003E*) ((IntPtr) obj0 + 32L), _Newsize + 1UL); goto label_23; } catch (Exception ex2) when ( { // ISSUE: unable to correctly present filter uint num7 = (uint) Marshal.GetExceptionCode(); if (\u003CModule\u003E.__CxxExceptionFilter((void*) Marshal.GetExceptionPointers(), (void*) 0, 0, (void*) 0) != 0) { SuccessfulFiltering; } else throw; } ) { uint num8 = 0U; \u003CModule\u003E.__CxxRegisterExceptionObject((void*) Marshal.GetExceptionPointers(), (void*) num2); try { try { \u003CModule\u003E.std\u002Ebasic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E\u002E_Tidy(obj0, true, 0UL); \u003CModule\u003E._CxxThrowException((void*) 0, (_s__ThrowInfo*) 0); } catch (Exception ex3) when ( { // ISSUE: unable to correctly present filter num8 = (uint) \u003CModule\u003E.__CxxDetectRethrow((void*) Marshal.GetExceptionPointers()); if ((int) num8 != 0) { SuccessfulFiltering; } else throw; } ) { } if ((int) num8 != 0) throw; else goto label_23; } finally { \u003CModule\u003E.__CxxUnregisterExceptionObject((void*) num2, (int) num8); } } } catch (Exception ex2) when ( { // ISSUE: unable to correctly present filter num5 = (uint) \u003CModule\u003E.__CxxDetectRethrow((void*) Marshal.GetExceptionPointers()); if ((int) num5 != 0) { SuccessfulFiltering; } else throw; } ) { } if ((int) num5 != 0) throw; } finally { \u003CModule\u003E.__CxxUnregisterExceptionObject((void*) num6, (int) num5); } } label_23: if (0UL < _Oldlen) { char* chPtr2 = 8UL > (ulong) *(long*) ((IntPtr) obj0 + 24L) ? (char*) obj0 : (char*) *(long*) obj0; // ISSUE: cpblk instruction __memcpy((IntPtr) chPtr1, (IntPtr) chPtr2, (long) _Oldlen * 2L); } if (8UL <= (ulong) *(long*) ((IntPtr) obj0 + 24L)) \u003CModule\u003E.delete((void*) *(long*) obj0); *(short*) obj0 = (short) 0; *(long*) obj0 = (long) chPtr1; *(long*) ((IntPtr) obj0 + 24L) = (long) num3; *(long*) ((IntPtr) obj0 + 16L) = (long) _Oldlen; char* chPtr3 = 8UL <= num3 ? chPtr1 : (char*) obj0; *(short*) ((long) _Oldlen * 2L + (IntPtr) chPtr3) = (short) 0; } internal static unsafe char* std\u002Eallocator\u003Cwchar_t\u003E\u002Eallocate([In] allocator\u003Cwchar_t\u003E* obj0, ulong _Count) { void* voidPtr = (void*) 0; if (_Count > 0UL) { if (9223372036854775807UL >= _Count) { voidPtr = \u003CModule\u003E.@new(_Count * 2UL); if ((IntPtr) voidPtr != IntPtr.Zero) goto label_3; } sbyte* numPtr = (sbyte*) 0; bad_alloc badAlloc; \u003CModule\u003E.std\u002Eexception\u002E\u007Bctor\u007D((exception*) &badAlloc, &numPtr); // ISSUE: fault handler try { // ISSUE: explicit reference operation // ISSUE: cast to a reference type // ISSUE: explicit reference operation ^(long&) @badAlloc = (long) &\u003CModule\u003E.\u003F\u003F_7bad_alloc\u0040std\u0040\u00406B\u0040; } __fault { // ISSUE: method pointer // ISSUE: cast to a function pointer type \u003CModule\u003E.___CxxCallUnwindDtor((__FnPtr<void (void*)>) __methodptr(std\u002Eexception\u002E\u007Bdtor\u007D), (void*) &badAlloc); } \u003CModule\u003E._CxxThrowException((void*) &badAlloc, &\u003CModule\u003E._TI2\u003FAVbad_alloc\u0040std\u0040\u0040); return (char*) 0; } label_3: return (char*) voidPtr; } [SpecialName] internal static unsafe bad_alloc* std\u002Ebad_alloc\u002E\u007Bctor\u007D([In] bad_alloc* obj0, bad_alloc* _param2) { \u003CModule\u003E.std\u002Eexception\u002E\u007Bctor\u007D((exception*) obj0, (exception*) param1); // ISSUE: fault handler try { *(long*) obj0 = (long) &\u003CModule\u003E.\u003F\u003F_7bad_alloc\u0040std\u0040\u00406B\u0040; } __fault { // ISSUE: method pointer // ISSUE: cast to a function pointer type \u003CModule\u003E.___CxxCallUnwindDtor((__FnPtr<void (void*)>) __methodptr(std\u002Eexception\u002E\u007Bdtor\u007D), (void*) obj0); } return obj0; } internal static unsafe basic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E* std\u002Ebasic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E\u002Eassign([In] basic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E* obj0, basic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E* _Right) { if (obj0 != _Right) { if (16UL <= (ulong) *(long*) ((IntPtr) obj0 + 24L)) \u003CModule\u003E.delete((void*) *(long*) obj0); *(long*) ((IntPtr) obj0 + 24L) = 15L; *(long*) ((IntPtr) obj0 + 16L) = 0L; *(sbyte*) obj0 = (sbyte) 0; if ((ulong) *(long*) ((IntPtr) _Right + 24L) < 16UL) { basic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E* stdAllocatorCharPtr1 = obj0; basic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E* stdAllocatorCharPtr2 = _Right; long num1 = 16L; long num2 = *(long*) ((IntPtr) stdAllocatorCharPtr2 + num1) + 1L; \u003CModule\u003E.memmove((void*) stdAllocatorCharPtr1, (void*) stdAllocatorCharPtr2, (ulong) num2); } else { *(long*) obj0 = *(long*) _Right; *(long*) _Right = 0L; } *(long*) ((IntPtr) obj0 + 16L) = *(long*) ((IntPtr) _Right + 16L); *(long*) ((IntPtr) obj0 + 24L) = *(long*) ((IntPtr) _Right + 24L); *(long*) ((IntPtr) _Right + 24L) = 15L; *(long*) ((IntPtr) _Right + 16L) = 0L; *(sbyte*) _Right = (sbyte) 0; } return obj0; } internal static unsafe basic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E* std\u002Ebasic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E\u002Eassign([In] basic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E* obj0, basic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E* _Right) { if (obj0 != _Right) { if (8UL <= (ulong) *(long*) ((IntPtr) obj0 + 24L)) \u003CModule\u003E.delete((void*) *(long*) obj0); *(long*) ((IntPtr) obj0 + 24L) = 7L; *(long*) ((IntPtr) obj0 + 16L) = 0L; *(short*) obj0 = (short) 0; if ((ulong) *(long*) ((IntPtr) _Right + 24L) < 8UL) { basic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E* stdAllocatorWcharTPtr1 = obj0; basic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E* stdAllocatorWcharTPtr2 = _Right; long num1 = 16L; long num2 = (*(long*) ((IntPtr) stdAllocatorWcharTPtr2 + num1) + 1L) * 2L; \u003CModule\u003E.memmove((void*) stdAllocatorWcharTPtr1, (void*) stdAllocatorWcharTPtr2, (ulong) num2); } else { *(long*) obj0 = *(long*) _Right; *(long*) _Right = 0L; } *(long*) ((IntPtr) obj0 + 16L) = *(long*) ((IntPtr) _Right + 16L); *(long*) ((IntPtr) obj0 + 24L) = *(long*) ((IntPtr) _Right + 24L); *(long*) ((IntPtr) _Right + 24L) = 7L; *(long*) ((IntPtr) _Right + 16L) = 0L; *(short*) _Right = (short) 0; } return obj0; } internal static basic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E* std\u002Ebasic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E\u002Eassign([In] basic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E* obj0, sbyte* _Ptr, ulong _Count) { // ISSUE: unable to decompile the method. } internal static unsafe basic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E* std\u002Ebasic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E\u002Eassign([In] basic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E* obj0, char* _Ptr, ulong _Count) { if (\u003CModule\u003E.std\u002Ebasic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E\u002E_Inside(obj0, _Ptr)) { char* chPtr = 8UL > (ulong) *(long*) ((IntPtr) obj0 + 24L) ? (char*) obj0 : (char*) *(long*) obj0; basic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E* _Right = obj0; IntPtr num1 = (IntPtr) _Ptr - (IntPtr) chPtr >> 1; long num2 = (long) _Count; return \u003CModule\u003E.std\u002Ebasic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E\u002Eassign(_Right, _Right, (ulong) num1, (ulong) num2); } if (9223372036854775806UL < _Count) \u003CModule\u003E.std\u002E_Xlength_error((sbyte*) &\u003CModule\u003E.\u003F\u003F_C\u0040_0BA\u0040JFNIOLAK\u0040string\u003F5too\u003F5long\u003F\u0024AA\u0040); ulong num3 = (ulong) *(long*) ((IntPtr) obj0 + 24L); if (num3 < _Count) \u003CModule\u003E.std\u002Ebasic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E\u002E_Copy(obj0, _Count, (ulong) *(long*) ((IntPtr) obj0 + 16L)); else if ((long) _Count == 0L) { *(long*) ((IntPtr) obj0 + 16L) = 0L; *(8UL > num3 ? (short*) (ValueType) (IntPtr) obj0 : (short*) (ValueType) *(long*) obj0) = (short) 0; goto label_10; } int num4; if (0UL < _Count) { num4 = 1; goto label_11; } label_10: num4 = 0; label_11: if ((int) (byte) num4 != 0) { ValueType valueType = 8UL > (ulong) *(long*) ((IntPtr) obj0 + 24L) ? (ValueType) (IntPtr) obj0 : (ValueType) *(long*) obj0; ulong num1 = _Count * 2UL; char* chPtr1 = _Ptr; long num2 = (long) num1; // ISSUE: cpblk instruction __memcpy(valueType, (IntPtr) chPtr1, num2); *(long*) ((IntPtr) obj0 + 16L) = (long) _Count; char* chPtr2 = 8UL > (ulong) *(long*) ((IntPtr) obj0 + 24L) ? (char*) obj0 : (char*) *(long*) obj0; *(short*) ((long) num1 + (IntPtr) chPtr2) = (short) 0; } return obj0; } internal static basic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E* std\u002Ebasic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E\u002Eassign([In] basic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E* obj0, basic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E* _Right, ulong _Roff, ulong _Count) { // ISSUE: unable to decompile the method. } [return: MarshalAs(UnmanagedType.U1)] internal static unsafe bool std\u002Ebasic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E\u002E_Inside([In] basic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E* obj0, sbyte* _Ptr) { if ((IntPtr) _Ptr != IntPtr.Zero) { ulong num = (ulong) *(long*) ((IntPtr) obj0 + 24L); sbyte* numPtr1 = 16UL > num ? (sbyte*) obj0 : (sbyte*) *(long*) obj0; if (_Ptr >= numPtr1) { sbyte* numPtr2 = 16UL > num ? (sbyte*) obj0 : (sbyte*) *(long*) obj0; if ((UIntPtr) *(long*) ((IntPtr) obj0 + 16L) + (UIntPtr) numPtr2 > (UIntPtr) _Ptr) return true; } } return false; } [return: MarshalAs(UnmanagedType.U1)] internal static unsafe bool std\u002Ebasic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E\u002E_Inside([In] basic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E* obj0, char* _Ptr) { if ((IntPtr) _Ptr != IntPtr.Zero) { ulong num = (ulong) *(long*) ((IntPtr) obj0 + 24L); char* chPtr1 = 8UL > num ? (char*) obj0 : (char*) *(long*) obj0; if (_Ptr >= chPtr1) { char* chPtr2 = 8UL > num ? (char*) obj0 : (char*) *(long*) obj0; if ((UIntPtr) (*(long*) ((IntPtr) obj0 + 16L) * 2L) + (UIntPtr) chPtr2 > (UIntPtr) _Ptr) return true; } } return false; } internal static basic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E* std\u002Ebasic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E\u002Eerase([In] basic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E* obj0, ulong _Off, ulong _Count) { // ISSUE: unable to decompile the method. } internal static unsafe void std\u002Ebasic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E\u002E_Copy([In] basic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E* obj0, ulong _Newsize, ulong _Oldlen) { ulong num1 = (ulong) \u003CModule\u003E.__CxxQueryExceptionSize(); // ISSUE: untyped stack allocation long num2 = (long) __untypedstackalloc((long) num1 * 2L); ulong num3 = _Newsize | 15UL; if (18446744073709551614UL < num3) { num3 = _Newsize; } else { ulong num4 = (ulong) *(long*) ((IntPtr) obj0 + 24L); ulong num5 = num4 >> 1; if (num5 > num3 / 3UL) num3 = num4 > 18446744073709551614UL - num5 ? 18446744073709551614UL : num5 + num4; } long num6; sbyte* numPtr1; try { num6 = num2 + (long) num1; numPtr1 = \u003CModule\u003E.std\u002Eallocator\u003Cchar\u003E\u002Eallocate((allocator\u003Cchar\u003E*) ((IntPtr) obj0 + 32L), num3 + 1UL); } catch (Exception ex1) when ( { // ISSUE: unable to correctly present filter uint num4 = (uint) Marshal.GetExceptionCode(); if (\u003CModule\u003E.__CxxExceptionFilter((void*) Marshal.GetExceptionPointers(), (void*) 0, 0, (void*) 0) != 0) { SuccessfulFiltering; } else throw; } ) { uint num5 = 0U; \u003CModule\u003E.__CxxRegisterExceptionObject((void*) Marshal.GetExceptionPointers(), (void*) num6); try { try { num3 = _Newsize; try { numPtr1 = \u003CModule\u003E.std\u002Eallocator\u003Cchar\u003E\u002Eallocate((allocator\u003Cchar\u003E*) ((IntPtr) obj0 + 32L), _Newsize + 1UL); goto label_23; } catch (Exception ex2) when ( { // ISSUE: unable to correctly present filter uint num7 = (uint) Marshal.GetExceptionCode(); if (\u003CModule\u003E.__CxxExceptionFilter((void*) Marshal.GetExceptionPointers(), (void*) 0, 0, (void*) 0) != 0) { SuccessfulFiltering; } else throw; } ) { uint num8 = 0U; \u003CModule\u003E.__CxxRegisterExceptionObject((void*) Marshal.GetExceptionPointers(), (void*) num2); try { try { \u003CModule\u003E.std\u002Ebasic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E\u002E_Tidy(obj0, true, 0UL); \u003CModule\u003E._CxxThrowException((void*) 0, (_s__ThrowInfo*) 0); } catch (Exception ex3) when ( { // ISSUE: unable to correctly present filter num8 = (uint) \u003CModule\u003E.__CxxDetectRethrow((void*) Marshal.GetExceptionPointers()); if ((int) num8 != 0) { SuccessfulFiltering; } else throw; } ) { } if ((int) num8 != 0) throw; else goto label_23; } finally { \u003CModule\u003E.__CxxUnregisterExceptionObject((void*) num2, (int) num8); } } } catch (Exception ex2) when ( { // ISSUE: unable to correctly present filter num5 = (uint) \u003CModule\u003E.__CxxDetectRethrow((void*) Marshal.GetExceptionPointers()); if ((int) num5 != 0) { SuccessfulFiltering; } else throw; } ) { } if ((int) num5 != 0) throw; } finally { \u003CModule\u003E.__CxxUnregisterExceptionObject((void*) num6, (int) num5); } } label_23: if (0UL < _Oldlen) { sbyte* numPtr2 = 16UL > (ulong) *(long*) ((IntPtr) obj0 + 24L) ? (sbyte*) obj0 : (sbyte*) *(long*) obj0; // ISSUE: cpblk instruction __memcpy((IntPtr) numPtr1, (IntPtr) numPtr2, (long) _Oldlen); } if (16UL <= (ulong) *(long*) ((IntPtr) obj0 + 24L)) \u003CModule\u003E.delete((void*) *(long*) obj0); *(sbyte*) obj0 = (sbyte) 0; *(long*) obj0 = (long) numPtr1; *(long*) ((IntPtr) obj0 + 24L) = (long) num3; *(long*) ((IntPtr) obj0 + 16L) = (long) _Oldlen; *(sbyte*) ((16UL <= num3 ? (IntPtr) numPtr1 : (IntPtr) obj0) + (long) _Oldlen) = (sbyte) 0; } internal static unsafe sbyte* std\u002Eallocator\u003Cchar\u003E\u002Eallocate([In] allocator\u003Cchar\u003E* obj0, ulong _Count) { void* voidPtr = (void*) 0; if (_Count > 0UL) { if (ulong.MaxValue >= _Count) { voidPtr = \u003CModule\u003E.@new(_Count); if ((IntPtr) voidPtr != IntPtr.Zero) goto label_3; } sbyte* numPtr = (sbyte*) 0; bad_alloc badAlloc; \u003CModule\u003E.std\u002Eexception\u002E\u007Bctor\u007D((exception*) &badAlloc, &numPtr); // ISSUE: fault handler try { // ISSUE: explicit reference operation // ISSUE: cast to a reference type // ISSUE: explicit reference operation ^(long&) @badAlloc = (long) &\u003CModule\u003E.\u003F\u003F_7bad_alloc\u0040std\u0040\u00406B\u0040; } __fault { // ISSUE: method pointer // ISSUE: cast to a function pointer type \u003CModule\u003E.___CxxCallUnwindDtor((__FnPtr<void (void*)>) __methodptr(std\u002Eexception\u002E\u007Bdtor\u007D), (void*) &badAlloc); } \u003CModule\u003E._CxxThrowException((void*) &badAlloc, &\u003CModule\u003E._TI2\u003FAVbad_alloc\u0040std\u0040\u0040); return (sbyte*) 0; } label_3: return (sbyte*) voidPtr; } [return: MarshalAs(UnmanagedType.U1)] internal static bool \u003CCrtImplementationDetails\u003E\u002ENativeDll\u002EIsSafeForManagedCode() { if (((int) \u003CModule\u003E.__native_dllmain_reason != -1 ? 1 : 0) == 0 || ((int) \u003CModule\u003E.__native_vcclrit_reason != -1 ? 1 : 0) != 0) return true; return (int) \u003CModule\u003E.__native_dllmain_reason != 1 && (int) \u003CModule\u003E.__native_dllmain_reason != 0; } internal static void \u003CCrtImplementationDetails\u003E\u002EThrowNestedModuleLoadException(Exception innerException, Exception nestedException) { throw new ModuleLoadExceptionHandlerException("A nested exception occurred after the primary exception that caused the C++ module to fail to load.\n", innerException, nestedException); } internal static void \u003CCrtImplementationDetails\u003E\u002EThrowModuleLoadException(string errorMessage) { throw new ModuleLoadException(errorMessage); } internal static void \u003CCrtImplementationDetails\u003E\u002EThrowModuleLoadException(string errorMessage, Exception innerException) { throw new ModuleLoadException(errorMessage, innerException); } internal static void \u003CCrtImplementationDetails\u003E\u002ERegisterModuleUninitializer(EventHandler handler) { ModuleUninitializer._ModuleUninitializer.AddHandler(handler); } [SecuritySafeCritical] internal static unsafe Guid \u003CCrtImplementationDetails\u003E\u002EFromGUID(_GUID* guid) { return new Guid((uint) *(int*) guid, *(ushort*) ((IntPtr) guid + 4L), *(ushort*) ((IntPtr) guid + 6L), *(byte*) ((IntPtr) guid + 8L), *(byte*) ((IntPtr) guid + 9L), *(byte*) ((IntPtr) guid + 10L), *(byte*) ((IntPtr) guid + 11L), *(byte*) ((IntPtr) guid + 12L), *(byte*) ((IntPtr) guid + 13L), *(byte*) ((IntPtr) guid + 14L), *(byte*) ((IntPtr) guid + 15L)); } [SecurityCritical] internal static unsafe int __get_default_appdomain(IUnknown** ppUnk) { ICorRuntimeHost* icorRuntimeHostPtr1 = (ICorRuntimeHost*) 0; int num1; try { Guid riid = \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EFromGUID((_GUID*) &\u003CModule\u003E._GUID_cb2f6722_ab3a_11d2_9c40_00c04fa30a3e); icorRuntimeHostPtr1 = (ICorRuntimeHost*) RuntimeEnvironment.GetRuntimeInterfaceAsIntPtr(\u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EFromGUID((_GUID*) &\u003CModule\u003E._GUID_cb2f6723_ab3a_11d2_9c40_00c04fa30a3e), riid).ToPointer(); goto label_4; } catch (Exception ex) { num1 = Marshal.GetHRForException(ex); } if (num1 < 0) goto label_5; label_4: ICorRuntimeHost* icorRuntimeHostPtr2 = icorRuntimeHostPtr1; IUnknown** iunknownPtr = ppUnk; // ISSUE: cast to a function pointer type // ISSUE: function pointer call num1 = __calli((__FnPtr<int (IntPtr, IUnknown**)>) *(long*) (*(long*) icorRuntimeHostPtr1 + 104L))((IUnknown**) icorRuntimeHostPtr2, (IntPtr) iunknownPtr); ICorRuntimeHost* icorRuntimeHostPtr3 = icorRuntimeHostPtr1; // ISSUE: cast to a function pointer type // ISSUE: function pointer call int num2 = (int) __calli((__FnPtr<uint (IntPtr)>) *(long*) (*(long*) icorRuntimeHostPtr3 + 16L))((IntPtr) icorRuntimeHostPtr3); label_5: return num1; } internal static unsafe void __release_appdomain(IUnknown* ppUnk) { IUnknown* iunknownPtr = ppUnk; // ISSUE: cast to a function pointer type // ISSUE: function pointer call int num = (int) __calli((__FnPtr<uint (IntPtr)>) *(long*) (*(long*) iunknownPtr + 16L))((IntPtr) iunknownPtr); } [SecurityCritical] internal static unsafe AppDomain \u003CCrtImplementationDetails\u003E\u002EGetDefaultDomain() { IUnknown* ppUnk = (IUnknown*) 0; int defaultAppdomain = \u003CModule\u003E.__get_default_appdomain(&ppUnk); if (defaultAppdomain >= 0) { try { return (AppDomain) Marshal.GetObjectForIUnknown(new IntPtr((void*) ppUnk)); } finally { \u003CModule\u003E.__release_appdomain(ppUnk); } } else { Marshal.ThrowExceptionForHR(defaultAppdomain); return (AppDomain) null; } } [SecurityCritical] internal static unsafe void \u003CCrtImplementationDetails\u003E\u002EDoCallBackInDefaultDomain(__FnPtr<int (void*)> function, void* cookie) { Guid riid = \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EFromGUID((_GUID*) &\u003CModule\u003E._GUID_90f1a06c_7712_4762_86b5_7a5eba6bdb02); ICLRRuntimeHost* iclrRuntimeHostPtr1 = (ICLRRuntimeHost*) RuntimeEnvironment.GetRuntimeInterfaceAsIntPtr(\u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EFromGUID((_GUID*) &\u003CModule\u003E._GUID_90f1a06e_7712_4762_86b5_7a5eba6bdb02), riid).ToPointer(); try { AppDomain defaultDomain = \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EGetDefaultDomain(); // ISSUE: cast to a function pointer type // ISSUE: cast to a function pointer type // ISSUE: function pointer call int errorCode = __calli((__FnPtr<int (IntPtr, uint, __FnPtr<int (void*)>, void*)>) *(long*) (*(long*) iclrRuntimeHostPtr1 + 64L))((void*) iclrRuntimeHostPtr1, (__FnPtr<int (void*)>) defaultDomain.Id, (uint) function, (IntPtr) cookie); if (errorCode >= 0) return; Marshal.ThrowExceptionForHR(errorCode); } finally { ICLRRuntimeHost* iclrRuntimeHostPtr2 = iclrRuntimeHostPtr1; // ISSUE: cast to a function pointer type // ISSUE: function pointer call int num = (int) __calli((__FnPtr<uint (IntPtr)>) *(long*) (*(long*) iclrRuntimeHostPtr2 + 16L))((IntPtr) iclrRuntimeHostPtr2); } } [SecuritySafeCritical] internal static unsafe int \u003CCrtImplementationDetails\u003E\u002EDefaultDomain\u002EDoNothing(void* cookie) { GC.KeepAlive((object) int.MaxValue); return 0; } [SecuritySafeCritical] [return: MarshalAs(UnmanagedType.U1)] internal static unsafe bool \u003CCrtImplementationDetails\u003E\u002EDefaultDomain\u002EHasPerProcess() { if (\u003CModule\u003E.\u003FhasPerProcess\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u00400W4State\u0040TriBool\u00402\u0040A != (TriBool.State) 2) return \u003CModule\u003E.\u003FhasPerProcess\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u00400W4State\u0040TriBool\u00402\u0040A == (TriBool.State) -1; void** voidPtr = (void**) &\u003CModule\u003E.\u003FA0x73b2ab14\u002E__xc_mp_a; // ISSUE: explicit reference operation // ISSUE: explicit reference operation if (@\u003CModule\u003E.\u003FA0x73b2ab14\u002E__xc_mp_a < @\u003CModule\u003E.\u003FA0x73b2ab14\u002E__xc_mp_z) { while (*(long*) voidPtr == 0L) { voidPtr += 8L; // ISSUE: explicit reference operation if ((IntPtr) voidPtr >= @\u003CModule\u003E.\u003FA0x73b2ab14\u002E__xc_mp_z) goto label_5; } \u003CModule\u003E.\u003FhasPerProcess\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u00400W4State\u0040TriBool\u00402\u0040A = (TriBool.State) -1; return true; } label_5: \u003CModule\u003E.\u003FhasPerProcess\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u00400W4State\u0040TriBool\u00402\u0040A = (TriBool.State) 0; return false; } [SecuritySafeCritical] [return: MarshalAs(UnmanagedType.U1)] internal static unsafe bool \u003CCrtImplementationDetails\u003E\u002EDefaultDomain\u002EHasNative() { if (\u003CModule\u003E.\u003FhasNative\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u00400W4State\u0040TriBool\u00402\u0040A != (TriBool.State) 2) return \u003CModule\u003E.\u003FhasNative\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u00400W4State\u0040TriBool\u00402\u0040A == (TriBool.State) -1; void** voidPtr1 = (void**) &\u003CModule\u003E.__xi_a; // ISSUE: explicit reference operation // ISSUE: explicit reference operation if (@\u003CModule\u003E.__xi_a < @\u003CModule\u003E.__xi_z) { while (*(long*) voidPtr1 == 0L) { voidPtr1 += 8L; // ISSUE: explicit reference operation if ((IntPtr) voidPtr1 >= @\u003CModule\u003E.__xi_z) goto label_5; } \u003CModule\u003E.\u003FhasNative\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u00400W4State\u0040TriBool\u00402\u0040A = (TriBool.State) -1; return true; } label_5: void** voidPtr2 = (void**) &\u003CModule\u003E.__xc_a; // ISSUE: explicit reference operation // ISSUE: explicit reference operation if (@\u003CModule\u003E.__xc_a < @\u003CModule\u003E.__xc_z) { while (*(long*) voidPtr2 == 0L) { voidPtr2 += 8L; // ISSUE: explicit reference operation if ((IntPtr) voidPtr2 >= @\u003CModule\u003E.__xc_z) goto label_9; } \u003CModule\u003E.\u003FhasNative\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u00400W4State\u0040TriBool\u00402\u0040A = (TriBool.State) -1; return true; } label_9: \u003CModule\u003E.\u003FhasNative\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u00400W4State\u0040TriBool\u00402\u0040A = (TriBool.State) 0; return false; } [SecuritySafeCritical] [return: MarshalAs(UnmanagedType.U1)] internal static bool \u003CCrtImplementationDetails\u003E\u002EDefaultDomain\u002ENeedsInitialization() { return \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EDefaultDomain\u002EHasPerProcess() && !\u003CModule\u003E.\u003FInitializedPerProcess\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u00402_NA || \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EDefaultDomain\u002EHasNative() && !\u003CModule\u003E.\u003FInitializedNative\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u00402_NA && \u003CModule\u003E.__native_startup_state == (__enative_startup_state) 0; } [return: MarshalAs(UnmanagedType.U1)] internal static bool \u003CCrtImplementationDetails\u003E\u002EDefaultDomain\u002ENeedsUninitialization() { return \u003CModule\u003E.\u003FEntered\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u00402_NA; } [SecurityCritical] internal static unsafe void \u003CCrtImplementationDetails\u003E\u002EDefaultDomain\u002EInitialize() { // ISSUE: cast to a function pointer type \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EDoCallBackInDefaultDomain((__FnPtr<int (void*)>) (IntPtr) \u003CModule\u003E.__unep\u0040\u003FDoNothing\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024FCAJPEAX\u0040Z, (void*) 0); } internal static void \u003FA0x73b2ab14\u002E\u003F\u003F__E\u003FInitialized\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2HA\u0040\u0040YMXXZ() { \u003CModule\u003E.\u003FInitialized\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2HA = 0; } internal static void \u003FA0x73b2ab14\u002E\u003F\u003F__E\u003FUninitialized\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2HA\u0040\u0040YMXXZ() { \u003CModule\u003E.\u003FUninitialized\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2HA = 0; } internal static void \u003FA0x73b2ab14\u002E\u003F\u003F__E\u003FIsDefaultDomain\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2_NA\u0040\u0040YMXXZ() { \u003CModule\u003E.\u003FIsDefaultDomain\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2_NA = false; } internal static void \u003FA0x73b2ab14\u002E\u003F\u003F__E\u003FInitializedVtables\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2W4State\u0040Progress\u00402\u0040A\u0040\u0040YMXXZ() { \u003CModule\u003E.\u003FInitializedVtables\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2W4State\u0040Progress\u00402\u0040A = (Progress.State) 0; } internal static void \u003FA0x73b2ab14\u002E\u003F\u003F__E\u003FInitializedNative\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2W4State\u0040Progress\u00402\u0040A\u0040\u0040YMXXZ() { \u003CModule\u003E.\u003FInitializedNative\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2W4State\u0040Progress\u00402\u0040A = (Progress.State) 0; } internal static void \u003FA0x73b2ab14\u002E\u003F\u003F__E\u003FInitializedPerProcess\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2W4State\u0040Progress\u00402\u0040A\u0040\u0040YMXXZ() { \u003CModule\u003E.\u003FInitializedPerProcess\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2W4State\u0040Progress\u00402\u0040A = (Progress.State) 0; } internal static void \u003FA0x73b2ab14\u002E\u003F\u003F__E\u003FInitializedPerAppDomain\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2W4State\u0040Progress\u00402\u0040A\u0040\u0040YMXXZ() { \u003CModule\u003E.\u003FInitializedPerAppDomain\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2W4State\u0040Progress\u00402\u0040A = (Progress.State) 0; } [SecurityCritical] [DebuggerStepThrough] internal static unsafe void \u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002EInitializeVtables([In] LanguageSupport* obj0) { \u003CModule\u003E.gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E\u002E\u003D((gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E*) obj0, "The C++ module failed to load during vtable initialization.\n"); \u003CModule\u003E.\u003FInitializedVtables\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2W4State\u0040Progress\u00402\u0040A = (Progress.State) 1; \u003CModule\u003E._initterm_m((__FnPtr<void* ()>*) &\u003CModule\u003E.\u003FA0x73b2ab14\u002E__xi_vt_a, (__FnPtr<void* ()>*) &\u003CModule\u003E.\u003FA0x73b2ab14\u002E__xi_vt_z); \u003CModule\u003E.\u003FInitializedVtables\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2W4State\u0040Progress\u00402\u0040A = (Progress.State) 2; } [SecurityCritical] internal static unsafe void \u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002EInitializeDefaultAppDomain([In] LanguageSupport* obj0) { \u003CModule\u003E.gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E\u002E\u003D((gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E*) obj0, "The C++ module failed to load while attempting to initialize the default appdomain.\n"); \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EDefaultDomain\u002EInitialize(); } [DebuggerStepThrough] [SecurityCritical] internal static unsafe void \u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002EInitializeNative([In] LanguageSupport* obj0) { \u003CModule\u003E.gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E\u002E\u003D((gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E*) obj0, "The C++ module failed to load during native initialization.\n"); \u003CModule\u003E.__security_init_cookie(); \u003CModule\u003E.\u003FInitializedNative\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u00402_NA = true; if (!\u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002ENativeDll\u002EIsSafeForManagedCode()) \u003CModule\u003E._amsg_exit(33); if (\u003CModule\u003E.__native_startup_state == (__enative_startup_state) 1) { \u003CModule\u003E._amsg_exit(33); } else { if (\u003CModule\u003E.__native_startup_state != (__enative_startup_state) 0) return; \u003CModule\u003E.\u003FInitializedNative\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2W4State\u0040Progress\u00402\u0040A = (Progress.State) 1; \u003CModule\u003E.__native_startup_state = (__enative_startup_state) 1; if (\u003CModule\u003E._initterm_e((__FnPtr<int ()>*) &\u003CModule\u003E.__xi_a, (__FnPtr<int ()>*) &\u003CModule\u003E.__xi_z) != 0) \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EThrowModuleLoadException(\u003CModule\u003E.gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E\u002E\u002EPE\u0024AAVString\u0040System\u0040\u0040((gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E*) obj0)); \u003CModule\u003E._initterm((__FnPtr<void ()>*) &\u003CModule\u003E.__xc_a, (__FnPtr<void ()>*) &\u003CModule\u003E.__xc_z); \u003CModule\u003E.__native_startup_state = (__enative_startup_state) 2; \u003CModule\u003E.\u003FInitializedNativeFromCCTOR\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u00402_NA = true; \u003CModule\u003E.\u003FInitializedNative\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2W4State\u0040Progress\u00402\u0040A = (Progress.State) 2; } } [SecurityCritical] [DebuggerStepThrough] internal static unsafe void \u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002EInitializePerProcess([In] LanguageSupport* obj0) { \u003CModule\u003E.gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E\u002E\u003D((gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E*) obj0, "The C++ module failed to load during process initialization.\n"); \u003CModule\u003E.\u003FInitializedPerProcess\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2W4State\u0040Progress\u00402\u0040A = (Progress.State) 1; \u003CModule\u003E._initatexit_m(); \u003CModule\u003E._initterm_m((__FnPtr<void* ()>*) &\u003CModule\u003E.\u003FA0x73b2ab14\u002E__xc_mp_a, (__FnPtr<void* ()>*) &\u003CModule\u003E.\u003FA0x73b2ab14\u002E__xc_mp_z); \u003CModule\u003E.\u003FInitializedPerProcess\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2W4State\u0040Progress\u00402\u0040A = (Progress.State) 2; \u003CModule\u003E.\u003FInitializedPerProcess\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u00402_NA = true; } [DebuggerStepThrough] [SecurityCritical] internal static unsafe void \u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002EInitializePerAppDomain([In] LanguageSupport* obj0) { \u003CModule\u003E.gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E\u002E\u003D((gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E*) obj0, "The C++ module failed to load during appdomain initialization.\n"); \u003CModule\u003E.\u003FInitializedPerAppDomain\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2W4State\u0040Progress\u00402\u0040A = (Progress.State) 1; \u003CModule\u003E._initatexit_app_domain(); \u003CModule\u003E._initterm_m((__FnPtr<void* ()>*) &\u003CModule\u003E.\u003FA0x73b2ab14\u002E__xc_ma_a, (__FnPtr<void* ()>*) &\u003CModule\u003E.\u003FA0x73b2ab14\u002E__xc_ma_z); \u003CModule\u003E.\u003FInitializedPerAppDomain\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2W4State\u0040Progress\u00402\u0040A = (Progress.State) 2; } [DebuggerStepThrough] [SecurityCritical] internal static unsafe void \u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002EInitializeUninitializer([In] LanguageSupport* obj0) { \u003CModule\u003E.gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E\u002E\u003D((gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E*) obj0, "The C++ module failed to load during registration for the unload events.\n"); \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002ERegisterModuleUninitializer(new EventHandler(\u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002EDomainUnload)); } [DebuggerStepThrough] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [SecurityCritical] internal static unsafe void \u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002E_Initialize([In] LanguageSupport* obj0) { \u003CModule\u003E.\u003FIsDefaultDomain\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2_NA = AppDomain.CurrentDomain.IsDefaultAppDomain(); \u003CModule\u003E.\u003FEntered\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u00402_NA = \u003CModule\u003E.\u003FIsDefaultDomain\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2_NA || \u003CModule\u003E.\u003FEntered\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u00402_NA; void* fiberPtrId = \u003CModule\u003E._getFiberPtrId(); int num1 = 0; int num2 = 0; int num3 = 0; RuntimeHelpers.PrepareConstrainedRegions(); try { while (num2 == 0) { try { } finally { // ISSUE: explicit reference operation // ISSUE: cast to a reference type void* voidPtr = (void*) Interlocked.CompareExchange((long&) @\u003CModule\u003E.__native_startup_lock, (long) fiberPtrId, 0L); if ((IntPtr) voidPtr == IntPtr.Zero) num2 = 1; else if (voidPtr == fiberPtrId) { num1 = 1; num2 = 1; } } if (num2 == 0) \u003CModule\u003E.Sleep(1000U); } \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002EInitializeVtables(obj0); if (\u003CModule\u003E.\u003FIsDefaultDomain\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2_NA) { \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002EInitializeNative(obj0); \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002EInitializePerProcess(obj0); } else num3 = \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EDefaultDomain\u002ENeedsInitialization() ? 1 : num3; } finally { if (num1 == 0) { // ISSUE: explicit reference operation // ISSUE: cast to a reference type Interlocked.Exchange((long&) @\u003CModule\u003E.__native_startup_lock, 0L); } } if (num3 != 0) \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002EInitializeDefaultAppDomain(obj0); \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002EInitializePerAppDomain(obj0); \u003CModule\u003E.\u003FInitialized\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2HA = 1; \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002EInitializeUninitializer(obj0); } [SecurityCritical] internal static void \u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002EUninitializeAppDomain() { \u003CModule\u003E._app_exit_callback(); } [SecurityCritical] internal static unsafe int \u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002E_UninitializeDefaultDomain(void* cookie) { \u003CModule\u003E._exit_callback(); \u003CModule\u003E.\u003FInitializedPerProcess\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u00402_NA = false; if (\u003CModule\u003E.\u003FInitializedNativeFromCCTOR\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u00402_NA) { \u003CModule\u003E._cexit(); \u003CModule\u003E.__native_startup_state = (__enative_startup_state) 0; \u003CModule\u003E.\u003FInitializedNativeFromCCTOR\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u00402_NA = false; } \u003CModule\u003E.\u003FInitializedNative\u0040DefaultDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u00402_NA = false; return 0; } [SecurityCritical] internal static unsafe void \u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002EUninitializeDefaultDomain() { if (!\u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EDefaultDomain\u002ENeedsUninitialization()) return; if (AppDomain.CurrentDomain.IsDefaultAppDomain()) { \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002E_UninitializeDefaultDomain((void*) 0); } else { // ISSUE: cast to a function pointer type \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EDoCallBackInDefaultDomain((__FnPtr<int (void*)>) (IntPtr) \u003CModule\u003E.__unep\u0040\u003F_UninitializeDefaultDomain\u0040LanguageSupport\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024FCAJPEAX\u0040Z, (void*) 0); } } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [PrePrepareMethod] [SecurityCritical] internal static void \u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002EDomainUnload(object source, EventArgs arguments) { if (\u003CModule\u003E.\u003FInitialized\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2HA == 0 || Interlocked.Exchange(ref \u003CModule\u003E.\u003FUninitialized\u0040CurrentDomain\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q2HA, 1) != 0) return; int num = Interlocked.Decrement(ref \u003CModule\u003E.\u003FCount\u0040AllDomains\u0040\u003CCrtImplementationDetails\u003E\u0040\u00402HA) == 0 ? 1 : 0; \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002EUninitializeAppDomain(); if ((int) (byte) num == 0) return; \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002EUninitializeDefaultDomain(); } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [DebuggerStepThrough] [SecurityCritical] internal static unsafe void \u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002ECleanup([In] LanguageSupport* obj0, Exception innerException) { try { bool flag = Interlocked.Decrement(ref \u003CModule\u003E.\u003FCount\u0040AllDomains\u0040\u003CCrtImplementationDetails\u003E\u0040\u00402HA) == 0; \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002EUninitializeAppDomain(); if (!flag) return; \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002EUninitializeDefaultDomain(); } catch (Exception ex) { \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EThrowNestedModuleLoadException(innerException, ex); } catch { \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EThrowNestedModuleLoadException(innerException, (Exception) null); } } [SecurityCritical] internal static unsafe LanguageSupport* \u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002E\u007Bctor\u007D([In] LanguageSupport* obj0) { \u003CModule\u003E.gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E\u002E\u007Bctor\u007D((gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E*) obj0); return obj0; } [SecurityCritical] internal static unsafe void \u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002E\u007Bdtor\u007D([In] LanguageSupport* obj0) { \u003CModule\u003E.gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E\u002E\u007Bdtor\u007D((gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E*) obj0); } [SecurityCritical] [DebuggerStepThrough] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal static unsafe void \u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002EInitialize([In] LanguageSupport* obj0) { bool flag = false; RuntimeHelpers.PrepareConstrainedRegions(); try { \u003CModule\u003E.gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E\u002E\u003D((gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E*) obj0, "The C++ module failed to load.\n"); RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { Interlocked.Increment(ref \u003CModule\u003E.\u003FCount\u0040AllDomains\u0040\u003CCrtImplementationDetails\u003E\u0040\u00402HA); flag = true; } \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002E_Initialize(obj0); } catch (Exception ex) { if (flag) \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002ECleanup(obj0, ex); \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EThrowModuleLoadException(\u003CModule\u003E.gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E\u002E\u002EPE\u0024AAVString\u0040System\u0040\u0040((gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E*) obj0), ex); } catch { if (flag) \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002ELanguageSupport\u002ECleanup(obj0, (Exception) null); \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EThrowModuleLoadException(\u003CModule\u003E.gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E\u002E\u002EPE\u0024AAVString\u0040System\u0040\u0040((gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E*) obj0), (Exception) null); } } [SecuritySafeCritical] [DebuggerStepThrough] internal static unsafe gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E* gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E\u002E\u007Bctor\u007D([In] gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E* obj0) { IntPtr num = (IntPtr) GCHandle.Alloc((object) null); *(long*) obj0 = (long) num.ToPointer(); return obj0; } [DebuggerStepThrough] [SecurityCritical] internal static unsafe void gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E\u002E\u007Bdtor\u007D([In] gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E* obj0) { (GCHandle) new IntPtr((void*) *(long*) obj0).Free(); *(long*) obj0 = 0L; } [SecurityCritical] [DebuggerStepThrough] internal static unsafe gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E* gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E\u002E\u003D([In] gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E* obj0, string t) { (GCHandle) new IntPtr((void*) *(long*) obj0).Target = (object) t; return obj0; } [SecuritySafeCritical] internal static unsafe string gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E\u002E\u002EPE\u0024AAVString\u0040System\u0040\u0040([In] gcroot\u003CSystem\u003A\u003AString\u0020\u005E\u003E* obj0) { return (string) (GCHandle) new IntPtr((void*) *(long*) obj0).Target; } [SecurityCritical] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [HandleProcessCorruptedStateExceptions] [SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)] internal static unsafe void ___CxxCallUnwindDtor(__FnPtr<void (void*)> pDtor, void* pThis) { try { void* voidPtr = pThis; // ISSUE: function pointer call __calli(pDtor)(voidPtr); } catch (Exception ex) when (\u003CModule\u003E.__FrameUnwindFilter((_EXCEPTION_POINTERS*) Marshal.GetExceptionPointers()) != 0) { } } [SecurityCritical] [HandleProcessCorruptedStateExceptions] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal static unsafe void __ehvec_dtor(void* ptr, ulong size, int count, __FnPtr<void (void*)> pDtor) { int num = 0; ptr = (void*) ((long) count * (long) size + (IntPtr) ptr); try { while (true) { count += -1; if (count >= 0) { ptr -= (long) size; void* voidPtr = ptr; // ISSUE: function pointer call __calli(pDtor)(voidPtr); } else break; } num = 1; } finally { if (num == 0) \u003CModule\u003E.__ArrayUnwind(ptr, size, count, pDtor); } } [SecurityCritical] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)] internal static unsafe int \u003FA0xb49558ae\u002EArrayUnwindFilter(_EXCEPTION_POINTERS* pExPtrs) { if (*(int*) *(long*) pExPtrs != -529697949) return 0; \u003CModule\u003E.terminate(); return 0; } [HandleProcessCorruptedStateExceptions] [SecurityCritical] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal static unsafe void __ArrayUnwind(void* ptr, ulong size, int count, __FnPtr<void (void*)> pDtor) { try { while (true) { count += -1; if (count >= 0) { ptr -= (long) size; void* voidPtr = ptr; // ISSUE: function pointer call __calli(pDtor)(voidPtr); } else break; } } catch (Exception ex) when (\u003CModule\u003E.\u003FA0xb49558ae\u002EArrayUnwindFilter((_EXCEPTION_POINTERS*) Marshal.GetExceptionPointers()) != 0) { } } [DebuggerStepThrough] [SecurityCritical] internal static unsafe ValueType \u003CCrtImplementationDetails\u003E\u002EAtExitLock\u002E_handle() { if ((IntPtr) \u003CModule\u003E.\u003F_lock\u0040AtExitLock\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q0PEAXEA != IntPtr.Zero) return (ValueType) GCHandle.FromIntPtr(new IntPtr(\u003CModule\u003E.\u003F_lock\u0040AtExitLock\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q0PEAXEA)); return (ValueType) null; } [SecurityCritical] [DebuggerStepThrough] internal static unsafe void \u003CCrtImplementationDetails\u003E\u002EAtExitLock\u002E_lock_Construct(object value) { \u003CModule\u003E.\u003F_lock\u0040AtExitLock\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q0PEAXEA = (void*) 0; \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EAtExitLock\u002E_lock_Set(value); } [SecurityCritical] [DebuggerStepThrough] internal static unsafe void \u003CCrtImplementationDetails\u003E\u002EAtExitLock\u002E_lock_Set(object value) { ValueType valueType = \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EAtExitLock\u002E_handle(); if (valueType == null) \u003CModule\u003E.\u003F_lock\u0040AtExitLock\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q0PEAXEA = GCHandle.ToIntPtr(GCHandle.Alloc(value)).ToPointer(); else ((GCHandle) valueType).Target = value; } [DebuggerStepThrough] [SecurityCritical] internal static object \u003CCrtImplementationDetails\u003E\u002EAtExitLock\u002E_lock_Get() { ValueType valueType = \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EAtExitLock\u002E_handle(); if (valueType != null) return ((GCHandle) valueType).Target; return (object) null; } [SecurityCritical] [DebuggerStepThrough] internal static unsafe void \u003CCrtImplementationDetails\u003E\u002EAtExitLock\u002E_lock_Destruct() { ValueType valueType = \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EAtExitLock\u002E_handle(); if (valueType == null) return; ((GCHandle) valueType).Free(); \u003CModule\u003E.\u003F_lock\u0040AtExitLock\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q0PEAXEA = (void*) 0; } [SecuritySafeCritical] [DebuggerStepThrough] [return: MarshalAs(UnmanagedType.U1)] internal static bool \u003CCrtImplementationDetails\u003E\u002EAtExitLock\u002EIsInitialized() { return \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EAtExitLock\u002E_lock_Get() != null; } [SecurityCritical] [DebuggerStepThrough] internal static void \u003CCrtImplementationDetails\u003E\u002EAtExitLock\u002EAddRef() { if (!\u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EAtExitLock\u002EIsInitialized()) { \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EAtExitLock\u002E_lock_Construct(new object()); \u003CModule\u003E.\u003F_ref_count\u0040AtExitLock\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q0HA = 0; } ++\u003CModule\u003E.\u003F_ref_count\u0040AtExitLock\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q0HA; } [SecurityCritical] [DebuggerStepThrough] internal static void \u003CCrtImplementationDetails\u003E\u002EAtExitLock\u002ERemoveRef() { \u003CModule\u003E.\u003F_ref_count\u0040AtExitLock\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q0HA += -1; if (\u003CModule\u003E.\u003F_ref_count\u0040AtExitLock\u0040\u003CCrtImplementationDetails\u003E\u0040\u0040\u0024\u0024Q0HA != 0) return; \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EAtExitLock\u002E_lock_Destruct(); } [DebuggerStepThrough] [SecurityCritical] [return: MarshalAs(UnmanagedType.U1)] internal static bool \u003FA0x47cf2733\u002E__alloc_global_lock() { \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EAtExitLock\u002EAddRef(); return \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EAtExitLock\u002EIsInitialized(); } [SecurityCritical] [DebuggerStepThrough] internal static void \u003FA0x47cf2733\u002E__dealloc_global_lock() { \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EAtExitLock\u002ERemoveRef(); } [SecurityCritical] internal static unsafe void _exit_callback() { if ((long) \u003CModule\u003E.\u003FA0x47cf2733\u002E__exit_list_size == 0L) return; __FnPtr<void ()>* local1 = (__FnPtr<void ()>*) \u003CModule\u003E.DecodePointer((void*) \u003CModule\u003E.\u003FA0x47cf2733\u002E__onexitbegin_m); __FnPtr<void ()>* local2 = (__FnPtr<void ()>*) \u003CModule\u003E.DecodePointer((void*) \u003CModule\u003E.\u003FA0x47cf2733\u002E__onexitend_m); if ((IntPtr) local1 != -1L && (IntPtr) local1 != IntPtr.Zero && (IntPtr) local2 != IntPtr.Zero) { __FnPtr<void ()>* local3 = local1; __FnPtr<void ()>* local4 = local2; while (true) { __FnPtr<void ()>* local5; __FnPtr<void ()>* local6; do { do { local2 -= 8L; if (local2 < local1) goto label_7; } while (*(long*) local2 == (IntPtr) \u003CModule\u003E._encoded_null()); void* voidPtr = \u003CModule\u003E.DecodePointer((void*) *(long*) local2); *(long*) local2 = (long) \u003CModule\u003E._encoded_null(); // ISSUE: cast to a function pointer type // ISSUE: function pointer call __calli((__FnPtr<void ()>) (IntPtr) voidPtr)(); local5 = (__FnPtr<void ()>*) \u003CModule\u003E.DecodePointer((void*) \u003CModule\u003E.\u003FA0x47cf2733\u002E__onexitbegin_m); local6 = (__FnPtr<void ()>*) \u003CModule\u003E.DecodePointer((void*) \u003CModule\u003E.\u003FA0x47cf2733\u002E__onexitend_m); } while (local3 == local5 && local4 == local6); local3 = local5; local1 = local5; local4 = local6; local2 = local6; } label_7: Marshal.FreeHGlobal(new IntPtr((void*) local1)); } \u003CModule\u003E.\u003FA0x47cf2733\u002E__dealloc_global_lock(); } [DebuggerStepThrough] [SecurityCritical] internal static unsafe int _initatexit_m() { int num = 0; if (!\u003CModule\u003E.\u003FA0x47cf2733\u002E__alloc_global_lock()) return num; \u003CModule\u003E.\u003FA0x47cf2733\u002E__onexitbegin_m = (__FnPtr<void ()>*) \u003CModule\u003E.EncodePointer(Marshal.AllocHGlobal(256).ToPointer()); \u003CModule\u003E.\u003FA0x47cf2733\u002E__onexitend_m = \u003CModule\u003E.\u003FA0x47cf2733\u002E__onexitbegin_m; \u003CModule\u003E.\u003FA0x47cf2733\u002E__exit_list_size = 32UL; return 1; } [DebuggerStepThrough] [SecurityCritical] internal static unsafe int _initatexit_app_domain() { if (\u003CModule\u003E.\u003FA0x47cf2733\u002E__alloc_global_lock()) { \u003CModule\u003E.__onexitbegin_app_domain = (__FnPtr<void ()>*) \u003CModule\u003E.EncodePointer(Marshal.AllocHGlobal(256).ToPointer()); \u003CModule\u003E.__onexitend_app_domain = \u003CModule\u003E.__onexitbegin_app_domain; \u003CModule\u003E.__exit_list_size_app_domain = 32UL; } return 1; } [HandleProcessCorruptedStateExceptions] [SecurityCritical] internal static unsafe void _app_exit_callback() { if ((long) \u003CModule\u003E.__exit_list_size_app_domain == 0L) return; __FnPtr<void ()>* local1 = (__FnPtr<void ()>*) \u003CModule\u003E.DecodePointer((void*) \u003CModule\u003E.__onexitbegin_app_domain); __FnPtr<void ()>* local2 = (__FnPtr<void ()>*) \u003CModule\u003E.DecodePointer((void*) \u003CModule\u003E.__onexitend_app_domain); try { if ((IntPtr) local1 == -1L || (IntPtr) local1 == IntPtr.Zero || (IntPtr) local2 == IntPtr.Zero) return; __FnPtr<void ()>* local3 = local1; __FnPtr<void ()>* local4 = local2; while (true) { __FnPtr<void ()>* local5; __FnPtr<void ()>* local6; do { do { local2 -= 8L; } while (local2 >= local1 && *(long*) local2 == (IntPtr) \u003CModule\u003E._encoded_null()); if (local2 >= local1) { // ISSUE: cast to a function pointer type __FnPtr<void ()> local7 = (__FnPtr<void ()>) (IntPtr) \u003CModule\u003E.DecodePointer((void*) *(long*) local2); *(long*) local2 = (long) \u003CModule\u003E._encoded_null(); // ISSUE: function pointer call __calli(local7)(); local5 = (__FnPtr<void ()>*) \u003CModule\u003E.DecodePointer((void*) \u003CModule\u003E.__onexitbegin_app_domain); local6 = (__FnPtr<void ()>*) \u003CModule\u003E.DecodePointer((void*) \u003CModule\u003E.__onexitend_app_domain); } else goto label_12; } while (local3 == local5 && local4 == local6); local3 = local5; local1 = local5; local4 = local6; local2 = local6; } label_12:; } finally { Marshal.FreeHGlobal(new IntPtr((void*) local1)); \u003CModule\u003E.\u003FA0x47cf2733\u002E__dealloc_global_lock(); } } [SecurityCritical] [SuppressUnmanagedCodeSecurity] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [DllImport("KERNEL32.dll")] public static extern unsafe void* DecodePointer(void* Ptr); [SuppressUnmanagedCodeSecurity] [SecurityCritical] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [DllImport("MSVCR100.dll", CallingConvention = CallingConvention.Cdecl)] public static extern unsafe void* _encoded_null(); [SecurityCritical] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [SuppressUnmanagedCodeSecurity] [DllImport("KERNEL32.dll")] public static extern unsafe void* EncodePointer(void* Ptr); [DebuggerStepThrough] [SecurityCritical] internal static unsafe int _initterm_e(__FnPtr<int ()>* pfbegin, __FnPtr<int ()>* pfend) { int num1 = 0; if (pfbegin < pfend) { while (num1 == 0) { ulong num2 = (ulong) *(long*) pfbegin; if ((long) num2 != 0L) { // ISSUE: cast to a function pointer type // ISSUE: function pointer call num1 = __calli((__FnPtr<int ()>) (long) num2)(); } pfbegin += 8L; if (pfbegin >= pfend) break; } } return num1; } [SecurityCritical] [DebuggerStepThrough] internal static unsafe void _initterm(__FnPtr<void ()>* pfbegin, __FnPtr<void ()>* pfend) { if (pfbegin >= pfend) return; do { ulong num = (ulong) *(long*) pfbegin; if ((long) num != 0L) { // ISSUE: cast to a function pointer type // ISSUE: function pointer call __calli((__FnPtr<void ()>) (long) num)(); } pfbegin += 8L; } while (pfbegin < pfend); } [DebuggerStepThrough] internal static ModuleHandle \u003CCrtImplementationDetails\u003E\u002EThisModule\u002EHandle() { return typeof (ThisModule).Module.ModuleHandle; } [SecurityCritical] [DebuggerStepThrough] [SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)] internal static unsafe void _initterm_m(__FnPtr<void* ()>* pfbegin, __FnPtr<void* ()>* pfend) { if (pfbegin >= pfend) return; do { ulong num = (ulong) *(long*) pfbegin; if ((long) num != 0L) { // ISSUE: cast to a function pointer type // ISSUE: function pointer call void* voidPtr = __calli(\u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EThisModule\u002EResolveMethod\u003Cvoid\u0020const\u0020\u002A\u0020__clrcall\u0028void\u0029\u003E((__FnPtr<void* ()>) (long) num))(); } pfbegin += 8L; } while (pfbegin < pfend); } [SecurityCritical] [DebuggerStepThrough] internal static unsafe __FnPtr<void* ()> \u003CCrtImplementationDetails\u003E\u002EThisModule\u002EResolveMethod\u003Cvoid\u0020const\u0020\u002A\u0020__clrcall\u0028void\u0029\u003E(__FnPtr<void* ()> methodToken) { // ISSUE: cast to a function pointer type return (__FnPtr<void* ()>) (IntPtr) \u003CModule\u003E.\u003CCrtImplementationDetails\u003E\u002EThisModule\u002EHandle().ResolveMethodHandle((int) methodToken).GetFunctionPointer().ToPointer(); } [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe void* @new([In] ulong obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern int __CxxQueryExceptionSize(); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int __CxxDetectRethrow([In] void* obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe void pcap_freealldevs([In] pcap_if* obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe void _CxxThrowException([In] void* obj0, [In] _s__ThrowInfo* obj1); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe void __CxxUnregisterExceptionObject([In] void* obj0, [In] int obj1); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe void delete([In] void* obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int __CxxExceptionFilter([In] void* obj0, [In] void* obj1, [In] int obj2, [In] void* obj3); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int pcap_findalldevs_ex([In] sbyte* obj0, [In] pcap_rmtauth* obj1, [In] pcap_if** obj2, [In] sbyte* obj3); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int __CxxRegisterExceptionObject([In] void* obj0, [In] void* obj1); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe void* memmove([In] void* obj0, [In] void* obj1, [In] ulong obj2); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe void std\u002E_Xlength_error([In] sbyte* obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe void std\u002E_Xout_of_range([In] sbyte* obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe exception* std\u002Eexception\u002E\u007Bctor\u007D([In] exception* obj0, [In] exception* obj1); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe exception* std\u002Eexception\u002E\u007Bctor\u007D([In] exception* obj0, [In] sbyte** obj1); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe void std\u002Eexception\u002E\u007Bdtor\u007D([In] exception* obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe pcap_stat* pcap_stats_ex([In] pcap* obj0, [In] int* obj1); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe pcap* pcap_open([In] sbyte* obj0, [In] int obj1, [In] int obj2, [In] int obj3, [In] pcap_rmtauth* obj4, [In] sbyte* obj5); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int fclose([In] _iobuf* obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern long _get_osfhandle([In] int obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int _fileno([In] _iobuf* obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe pcap* pcap_hopen_offline([In] long obj0, [In] sbyte* obj1); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe _iobuf* _wfopen([In] char* obj0, [In] char* obj1); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int pcap_list_datalinks([In] pcap* obj0, [In] int** obj1); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int pcap_loop([In] pcap* obj0, [In] int obj1, [In] __FnPtr<void (byte*, pcap_pkthdr*, byte*)> obj2, [In] byte* obj3); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int pcap_set_datalink([In] pcap* obj0, [In] int obj1); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe void pcap_close([In] pcap* obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe void pcap_free_datalinks([In] int* obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int pcap_next_ex([In] pcap* obj0, [In] pcap_pkthdr** obj1, [In] byte** obj2); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int pcap_sendpacket([In] pcap* obj0, [In] byte* obj1, [In] int obj2); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int pcap_setmode([In] pcap* obj0, [In] int obj1); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int pcap_datalink([In] pcap* obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int pcap_setbuff([In] pcap* obj0, [In] int obj1); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int pcap_major_version([In] pcap* obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int pcap_is_swapped([In] pcap* obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int pcap_getnonblock([In] pcap* obj0, [In] sbyte* obj1); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int pcap_minor_version([In] pcap* obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int pcap_snapshot([In] pcap* obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int pcap_setmintocopy([In] pcap* obj0, [In] int obj1); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int pcap_dispatch([In] pcap* obj0, [In] int obj1, [In] __FnPtr<void (byte*, pcap_pkthdr*, byte*)> obj2, [In] byte* obj3); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int pcap_setnonblock([In] pcap* obj0, [In] int obj1, [In] sbyte* obj2); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe void pcap_breakloop([In] pcap* obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe pcap_samp* pcap_setsampling([In] pcap* obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe pcap* pcap_open_dead([In] int obj0, [In] int obj1); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int pcap_setfilter([In] pcap* obj0, [In] bpf_program* obj1); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int pcap_offline_filter([In] bpf_program* obj0, [In] pcap_pkthdr* obj1, [In] byte* obj2); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int pcap_compile([In] pcap* obj0, [In] bpf_program* obj1, [In] sbyte* obj2, [In] int obj3, [In] uint obj4); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe void pcap_freecode([In] bpf_program* obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int pcap_dump_flush([In] pcap_dumper* obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe void pcap_dump_close([In] pcap_dumper* obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe void pcap_dump([In] byte* obj0, [In] pcap_pkthdr* obj1, [In] byte* obj2); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int pcap_dump_ftell([In] pcap_dumper* obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe pcap_dumper* pcap_dump_open([In] pcap* obj0, [In] sbyte* obj1); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe pcap_send_queue* pcap_sendqueue_alloc([In] uint obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe void pcap_sendqueue_destroy([In] pcap_send_queue* obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe uint pcap_sendqueue_transmit([In] pcap* obj0, [In] pcap_send_queue* obj1, [In] int obj2); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int pcap_sendqueue_queue([In] pcap_send_queue* obj0, [In] pcap_pkthdr* obj1, [In] byte* obj2); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int pcap_datalink_name_to_val([In] sbyte* obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe sbyte* pcap_datalink_val_to_name([In] int obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe sbyte* pcap_datalink_val_to_description([In] int obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe sbyte* pcap_geterr([In] pcap* obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe sbyte* pcap_lib_version(); [SuppressUnmanagedCodeSecurity] [MethodImpl(MethodImplOptions.Unmanaged | MethodImplOptions.PreserveSig, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe void* _getFiberPtrId(); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern void _amsg_exit([In] int obj0); [SuppressUnmanagedCodeSecurity] [MethodImpl(MethodImplOptions.Unmanaged | MethodImplOptions.PreserveSig, MethodCodeType = MethodCodeType.Native)] internal static extern void __security_init_cookie(); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern void Sleep([In] uint obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern void _cexit(); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern unsafe int __FrameUnwindFilter([In] _EXCEPTION_POINTERS* obj0); [SuppressUnmanagedCodeSecurity] [DllImport("", EntryPoint = "", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] [MethodImpl(MethodImplOptions.Unmanaged, MethodCodeType = MethodCodeType.Native)] internal static extern void terminate(); } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsOpCode // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Dns { public enum DnsOpCode : byte { Query = (byte) 0, IQuery = (byte) 1, Status = (byte) 2, Notify = (byte) 4, Update = (byte) 5, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.SocketAddress // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll namespace PcapDotNet.Core { public abstract class SocketAddress { private SocketAddressFamily _family; public SocketAddressFamily Family { get { return this._family; } } protected SocketAddress(ushort family) { this._family = (SocketAddressFamily) family; } public override string ToString() { return this._family.ToString(); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataA6 // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using PcapDotNet.Packets.IpV6; using System; using System.Globalization; using System.Numerics; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.A6)] public sealed class DnsResourceDataA6 : DnsResourceDataNoCompression, IEquatable<DnsResourceDataA6> { public const byte MaxPrefixLength = (byte) 128; private const int ConstantPartLength = 1; private const int MinimumLength = 2; public byte PrefixLength { get; private set; } public IpV6Address AddressSuffix { get; private set; } public int AddressSuffixLength { get { return DnsResourceDataA6.CalculateAddressSuffixLength(this.PrefixLength); } } public DnsDomainName PrefixName { get; private set; } public DnsResourceDataA6(byte prefixLength, IpV6Address addressSuffix, DnsDomainName prefixName) { if (DnsResourceDataA6.IsAddressSuffixTooSmall(prefixLength, addressSuffix)) throw new ArgumentOutOfRangeException("addressSuffix", string.Format((IFormatProvider) CultureInfo.InvariantCulture, "Value is too small for prefix length {0}", new object[1] { (object) prefixLength })); if (DnsResourceDataA6.IsAddressSuffixTooBig(prefixLength, addressSuffix)) throw new ArgumentOutOfRangeException("addressSuffix", string.Format((IFormatProvider) CultureInfo.InvariantCulture, "Value is too big for prefix length {0}", new object[1] { (object) prefixLength })); this.PrefixLength = prefixLength; this.AddressSuffix = addressSuffix; this.PrefixName = prefixName; } internal DnsResourceDataA6() : this((byte) 0, IpV6Address.MaxValue, DnsDomainName.Root) { } public bool Equals(DnsResourceDataA6 other) { if (other != null && this.PrefixLength.Equals(other.PrefixLength) && this.AddressSuffix.Equals(other.AddressSuffix)) return this.PrefixName.Equals(other.PrefixName); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataA6); } public override int GetHashCode() { return Sequence.GetHashCode((object) this.PrefixLength, (object) this.AddressSuffix, (object) this.PrefixName); } internal override int GetLength() { return 1 + this.AddressSuffixLength + this.PrefixName.NonCompressedLength; } internal override int WriteData(byte[] buffer, int offset) { ByteArrayExtensions.Write(buffer, offset, this.PrefixLength); ByteArrayExtensions.WriteUnsigned(buffer, offset + 1, (BigInteger) this.AddressSuffix.ToValue(), this.AddressSuffixLength, Endianity.Big); this.PrefixName.WriteUncompressed(buffer, offset + 1 + this.AddressSuffixLength); return this.GetLength(); } internal override DnsResourceData CreateInstance(DnsDatagram dns, int offsetInDns, int length) { if (length < 2) return (DnsResourceData) null; byte prefixLength = dns[offsetInDns]; if ((int) prefixLength > 128) return (DnsResourceData) null; ++offsetInDns; --length; int length1 = DnsResourceDataA6.CalculateAddressSuffixLength(prefixLength); if (length < length1) return (DnsResourceData) null; IpV6Address addressSuffix = new IpV6Address((UInt128) dns.ReadUnsignedBigInteger(offsetInDns, length1, Endianity.Big)); offsetInDns += length1; length -= length1; if (DnsResourceDataA6.IsAddressSuffixTooSmall(prefixLength, addressSuffix) || DnsResourceDataA6.IsAddressSuffixTooBig(prefixLength, addressSuffix)) return (DnsResourceData) null; DnsDomainName domainName; int numBytesRead; if (!DnsDomainName.TryParse(dns, offsetInDns, length, out domainName, out numBytesRead)) return (DnsResourceData) null; if (numBytesRead != length) return (DnsResourceData) null; return (DnsResourceData) new DnsResourceDataA6(prefixLength, addressSuffix, domainName); } private static bool IsAddressSuffixTooSmall(byte prefixLength, IpV6Address addressSuffix) { if ((int) prefixLength < 128) return addressSuffix.ToValue() < UInt128.One << (int) sbyte.MaxValue - (int) prefixLength; return false; } private static bool IsAddressSuffixTooBig(byte prefixLength, IpV6Address addressSuffix) { if ((int) prefixLength > 0) return addressSuffix.ToValue() >= UInt128.One << 128 - (int) prefixLength; return false; } private static int CalculateAddressSuffixLength(byte prefixLength) { return (128 - (int) prefixLength + 7) / 8; } private static class Offset { public const int PrefixLength = 0; public const int AddressSuffix = 1; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceData2DomainNames // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using System.Collections.Generic; namespace PcapDotNet.Packets.Dns { public abstract class DnsResourceData2DomainNames : DnsResourceDataDomainNames { private const int NumDomains = 2; internal DnsDomainName First { get { return this.DomainNames[0]; } } internal DnsDomainName Second { get { return this.DomainNames[1]; } } internal DnsResourceData2DomainNames(DnsDomainName first, DnsDomainName second) : base(first, second) { } internal static bool TryRead(out DnsDomainName first, out DnsDomainName second, DnsDatagram dns, int offsetInDns, int length) { List<DnsDomainName> list = DnsResourceDataDomainNames.ReadDomainNames(dns, offsetInDns, length, 2); if (list == null || list.Count != 2) { first = (DnsDomainName) null; second = (DnsDomainName) null; return false; } first = list[0]; second = list[1]; return true; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataNextDomainSecure // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using System; using System.Collections.Generic; using System.Collections.ObjectModel; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.NSec)] public sealed class DnsResourceDataNextDomainSecure : DnsResourceDataNoCompression, IEquatable<DnsResourceDataNextDomainSecure> { private readonly DnsTypeBitmaps _typeBitmaps; public DnsDomainName NextDomainName { get; private set; } public ReadOnlyCollection<DnsType> TypesExist { get { return this._typeBitmaps.TypesExist.AsReadOnly(); } } public DnsResourceDataNextDomainSecure(DnsDomainName nextDomainName, IEnumerable<DnsType> typesExist) : this(nextDomainName, new DnsTypeBitmaps(typesExist)) { } internal DnsResourceDataNextDomainSecure() : this(DnsDomainName.Root, (IEnumerable<DnsType>) new DnsType[0]) { } private DnsResourceDataNextDomainSecure(DnsDomainName nextDomainName, DnsTypeBitmaps typeBitmaps) { this.NextDomainName = nextDomainName; this._typeBitmaps = typeBitmaps; } public bool IsTypePresentForOwner(DnsType dnsType) { return this._typeBitmaps.Contains(dnsType); } public bool Equals(DnsResourceDataNextDomainSecure other) { if (other != null && this.NextDomainName.Equals(other.NextDomainName)) return this._typeBitmaps.Equals(other._typeBitmaps); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataNextDomainSecure); } public override int GetHashCode() { return Sequence.GetHashCode((object) this.NextDomainName, (object) this._typeBitmaps); } internal override int GetLength() { return this.NextDomainName.NonCompressedLength + this._typeBitmaps.GetLength(); } internal override int WriteData(byte[] buffer, int offset) { this.NextDomainName.WriteUncompressed(buffer, offset); int compressedLength = this.NextDomainName.NonCompressedLength; return compressedLength + this._typeBitmaps.Write(buffer, offset + compressedLength); } internal override DnsResourceData CreateInstance(DnsDatagram dns, int offsetInDns, int length) { DnsDomainName domainName; int numBytesRead; if (!DnsDomainName.TryParse(dns, offsetInDns, length, out domainName, out numBytesRead)) return (DnsResourceData) null; offsetInDns += numBytesRead; length -= numBytesRead; DnsTypeBitmaps instance = DnsTypeBitmaps.CreateInstance(dns.Buffer, dns.StartOffset + offsetInDns, length); if (instance == null) return (DnsResourceData) null; return (DnsResourceData) new DnsResourceDataNextDomainSecure(domainName, instance); } } } <file_sep>using Grib.Api.Interop; using Grib.Api.Interop.Util; using System; using System.IO; using System.Reflection; namespace Grib.Api { internal static class GribEnvironmentLoadHelper { internal static AutoRef BootStrapLibrary () { string path = ""; if (!TryFindBootstrapLibrary(out path)) { throw new FileNotFoundException("Could not find Grib.Api.Native. If you're using ASP.NET or NUnit, this is usually caused by shadow copying. Please see GribApi.NET's documentation for help."); } return Win32.LoadWin32Library(path); } internal static bool TryFindBootstrapLibrary (out string path) { path = ""; // TODO: make cross platform string binaryType = "dll"; string file = "Grib.Api.Native." + binaryType; const string PATH_TEMPLATE = "Grib.Api\\lib\\win"; string platform = (IntPtr.Size == 8) ? "x64" : "x86"; string gribNativeLibPath = Path.Combine(PATH_TEMPLATE, platform, file); return TryBuildDescriptorPath(gribNativeLibPath, out path); } internal static bool TryFindDefinitions (out string path) { return TryBuildDescriptorPath("Grib.Api\\definitions", out path); } internal static bool TryBuildDescriptorPath (string target, out string path) { path = ""; string varDef = Environment.GetEnvironmentVariable("GRIB_API_DIR_ROOT") + ""; string envDir = Path.Combine(varDef, target); string thisDir = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), target); string exeDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, target); return TryBuildGriApiPath(envDir, out path) || // try using environment variable TryBuildGriApiPath(target, out path) || // try using relative path TryBuildGriApiPath(thisDir, out path) || // try using the directory that contains this binary TryBuildGriApiPath(exeDir, out path); // try using the directory that contains the exe } internal static bool TryBuildGriApiPath (string root, out string path) { path = ""; if (File.Exists(root) || Directory.Exists(root)) { path = Path.GetFullPath(root); } return !String.IsNullOrWhiteSpace(path); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataMailExchange // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.MailExchange)] public sealed class DnsResourceDataMailExchange : DnsResourceDataUShortDomainName { public ushort Preference { get { return this.Value; } } public DnsDomainName MailExchangeHost { get { return this.DomainName; } } public DnsResourceDataMailExchange(ushort preference, DnsDomainName mailExchangeHost) : base(preference, mailExchangeHost) { } internal DnsResourceDataMailExchange() : this((ushort) 0, DnsDomainName.Root) { } internal override DnsResourceData CreateInstance(DnsDatagram dns, int offsetInDns, int length) { ushort preference; DnsDomainName domainName; if (!DnsResourceDataUShortDomainName.TryRead(out preference, out domainName, dns, offsetInDns, length)) return (DnsResourceData) null; return (DnsResourceData) new DnsResourceDataMailExchange(preference, domainName); } } } <file_sep>namespace ForecastIOPortable { using System; /// <summary> /// Various helper methods. /// </summary> public static class Helpers { /// <summary> /// DateTime representing 0 Unix time: January 1, 1970, GMT. /// </summary> private static readonly DateTimeOffset BaseUnixTime = new DateTimeOffset(1970, 1, 1, 0, 0, 0, new TimeSpan()); /// <summary> /// Converts Unix Time (seconds since January 1, 1970 UTC) to a DateTimeOffset object. /// </summary> /// <param name="secondsSince"> /// Seconds since January 1, 1970. /// </param> /// <returns> /// <see cref="DateTime"/> representing the given Unix time. /// </returns> public static DateTimeOffset ToDateTimeOffset(this int secondsSince) { var converted = BaseUnixTime.AddSeconds(secondsSince); return converted; } /// <summary> /// Converts this DateTimeOffset to Unix time (seconds since January 1, 1970 UTC). /// </summary> /// <param name="time"></param> /// <returns>The number of seconds since January 1, 1970 UTC.</returns> public static int ToUnixTime(this DateTimeOffset time) { var seconds = time.Subtract(BaseUnixTime).TotalSeconds; return (int)seconds; } } } <file_sep># GribApi.NET ## What it is GribApi.NET is a C# wrapper around the [European Centre for Medium Range Weather Forecasting's](http://www.ecmwf.int/) powerful [grib_api](https://software.ecmwf.int/wiki/display/GRIB/Home), a C library for reading, writing, and converting GRIB1 and GRIB2 files. GRIB is a format commonly used in meteorology to store weather data. GribApi.NET makes it easy to encode and decode these data by providing access to both GRIB editions through a set of [GRIB API keys](https://software.ecmwf.int/wiki/display/GRIB/GRIB%20API%20keys). GribApi.NET and grib_api are licensed under the friendly [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0). Special thanks to <NAME>, Meteorological Data Analyst at aWhere, Inc., for his contributions as scientific advisor. #### Features * Read and write GRIB 1 and 2 messages * Easy to understand API * Thread safe * JPEG and PNG compression support * Multi-field support -------------------------- ## Docs The documentation is very much a WIP, but you'll find [grib_api's wiki](https://software.ecmwf.int/wiki/display/GRIB/Home), helpful. * [Key Concepts](https://github.com/0x1mason/GribApi.NET/blob/master/docs/KeyConcepts.md) * [Example Key Dump](https://github.com/0x1mason/GribApi.NET/blob/master/docs/TypicalKeyDump.md) -------------------------- ## Usage Make sure you have the [MSVC 2013 redistributables](https://www.microsoft.com/en-us/download/details.aspx?id=40784) installed. Install [GribApi.NET using Nuget](https://www.nuget.org/packages/Grib.Api). From Package Manager Console run ```shell PM> Install-Package Grib.Api ``` #### Shadow Copying **ASP.NET**, **NUnit**, and other frameworks employ a technique called "shadow copying". When Grib.Api.dll is shadow copied, GribApi.NET may have difficulty locating the `Grib.Api` directory, which is required for proper operation. There are several ways to deal with this issue. The simplest is to set the`GRIB_API_DIR_ROOT` before calling GribApi.NET for the first time. The value should be the directory *containing* the `Grib.Api` directory. E.g., for `C:\Some\Path\Grib.Api`, set: ```csharp Environment.SetEnvironmentVariable("GRIB_API_DIR_ROOT", "C:\\Some\\Path", EnvironmentVariableTarget.Process); ``` ### Examples #### Getting grid information from a GRIB message: ```csharp using (GribFile file = new GribFile("mygrib.grb")) { GribMessage msg = file.First(); Console.WriteLine("Grid Type: " + msg.GridType); double latInDegrees = msg["latitudeOfFirstGridPoint"].AsDouble(); // GribApi.NET automatically converts coordinate values to degrees. This follows the best practice // advised by ECMWF and normalizes the values returned by the API. You can opt-out of degree // conversion by calling `AsDouble(false)`, e.g.: // double rawValue = msg["latitudeOfFirstGridPoint"].AsDouble(false); // Only values capable of degree conversion are affected. // all values are also accessible as strings Console.WriteLine("latitudeOfFirstGridPointInDegrees = " + msg["latitudeOfFirstGridPoint"].AsString()); } ``` #### Iterating multiple messages: ```csharp using (GribFile file = new GribFile("mygrib.grb")) { foreach (GribMessage msg in file) { // do something } } ``` #### Iterating lat/lon/value: ```csharp GribMessage msg = gribFile.First(); // the values in GeoSpatialValues are calculated by grid type foreach (GeoSpatialValue val in msg.GeoSpatialValues) { if (val.IsMissing) { continue; } Console.WriteLine("Lat: {0} Lon: {1} Val: {2}", val.Latitude, val.Longitude, val.Value); } ``` #### Cherry-picking messages by parameter name ```csharp using(GribFile file = new GribFile(@".\TestData\Pacific.wind.7days.grb")) { var vComp = file.Where(m => m.Name.Contains("V-component of wind m s**-1")).First(); foreach (var val in vComp.GeoSpatialValues) { Console.WriteLine("Lat: {0} Lon: {1} Val: {2}", val.Latitude, val.Longitude, val.Value); } } ``` #### Getting raw data: ```csharp GribMessage msg = gribFile.First(); double[] rawValues; // a copy of the raw values stored in the message msg.Values(out rawValues); ``` #### Editing a single message and saving to a new file: ```csharp string outPath = "out.grb"; string readPath = "some.grb"; using (GribFile readFile = new GribFile(readPath)) { Console.WriteLine("Writing 1 message from {0} to {1}", readPath, outPath); var msg = readFile.First(); msg["latitudeOfFirstGridPoint"].AsDouble(42); GribFile.Write(outPath, msg); } ``` #### Appending multiple messages to an existing file: ```csharp using (GribFile readFile = new GribFile(readPath)) { Console.WriteLine("Appending {0} messages from {1} to {2}", readFile.MessageCount, readPath, outPath); GribFile.Write(outPath, readFile as IEnumerable<GribMessage>, FileMode.Append); // or, more simply: // GribFile.Write(outPath, readFile, FileMode.Append); } ``` For more examples, checkout the tests. -------------------------- ## Building The current build is only designed for Windows and Visual Studio. I am eager to get it converted to CMake and make it cross-platform. Even a consistent build using make under msys2 would be great. I'd love some help doing this. :) To build, you can use `build/Grib.Api.Master.sln`. The native projects are set to use the v110 (Visual Studio 2012) Cpp build tools. However, you can change these to match your version of VS in the native projects' `Properties > General > Platform Toolset` field. To run a full release build, you'll need `NUnit` and `Nuget` on PATH. Then run: ```shell build/build_gribapi.cmd [build|rebuild] [VS version, 11|12|14] ``` E.g., to build with Visual Studio 2012 (VS version 11): ```shell build/build_gribapi.cmd build 11 ``` ### Running SWIG Most of the interop interfaces are generated using `SWIG` and included in the repository. If you want generate the interfaces yourself, you'll need `SWIG` installed and available on PATH. Then run `build/swig_gen.cmd`. ### Running Tests 1. Install [NUnit](http://www.nunit.org/) and expose it on PATH. 2. Run `build/run_tests <architecture> <configuration> [optional "1" to break the tests on start]`, e.g. ```shell build/run_tests x64 Debug ``` or ```shell build/run_tests x86 Debug 1 ``` <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataGeographicalPosition // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Text; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.GPos)] public sealed class DnsResourceDataGeographicalPosition : DnsResourceDataSimple, IEquatable<DnsResourceDataGeographicalPosition> { public string Longitude { get; private set; } public string Latitude { get; private set; } public string Altitude { get; private set; } public DnsResourceDataGeographicalPosition(string longitude, string latitude, string altitude) { this.Longitude = longitude; this.Latitude = latitude; this.Altitude = altitude; } internal DnsResourceDataGeographicalPosition() : this(string.Empty, string.Empty, string.Empty) { } public bool Equals(DnsResourceDataGeographicalPosition other) { if (other != null && this.Longitude.Equals(other.Longitude) && this.Latitude.Equals(other.Latitude)) return this.Altitude.Equals(other.Altitude); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataGeographicalPosition); } public override int GetHashCode() { return Sequence.GetHashCode((object) this.Longitude, (object) this.Latitude, (object) this.Altitude); } internal override int GetLength() { return Encoding.ASCII.GetByteCount(this.Longitude) + 1 + Encoding.ASCII.GetByteCount(this.Latitude) + 1 + Encoding.ASCII.GetByteCount(this.Altitude) + 1; } internal override void WriteDataSimple(byte[] buffer, int offset) { byte[] bytes1 = Encoding.ASCII.GetBytes(this.Longitude); byte[] bytes2 = Encoding.ASCII.GetBytes(this.Latitude); byte[] bytes3 = Encoding.ASCII.GetBytes(this.Altitude); ByteArrayExtensions.Write(buffer, ref offset, (byte) bytes1.Length); ByteArrayExtensions.Write(buffer, ref offset, (IEnumerable<byte>) bytes1); ByteArrayExtensions.Write(buffer, ref offset, (byte) bytes2.Length); ByteArrayExtensions.Write(buffer, ref offset, (IEnumerable<byte>) bytes2); ByteArrayExtensions.Write(buffer, ref offset, (byte) bytes3.Length); ByteArrayExtensions.Write(buffer, ref offset, (IEnumerable<byte>) bytes3); } internal override DnsResourceData CreateInstance(DataSegment data) { if (data.Length < 3) return (DnsResourceData) null; int length1 = (int) data[0]; if (data.Length < length1 + 3) return (DnsResourceData) null; string longitude = data.Subsegment(1, length1).Decode(Encoding.ASCII); data = data.Subsegment(length1 + 1, data.Length - length1 - 1); int length2 = (int) data[0]; if (data.Length < length2 + 2) return (DnsResourceData) null; string latitude = data.Subsegment(1, length2).Decode(Encoding.ASCII); data = data.Subsegment(length2 + 1, data.Length - length2 - 1); int length3 = (int) data[0]; if (data.Length != length3 + 1) return (DnsResourceData) null; string altitude = data.Subsegment(1, length3).Decode(Encoding.ASCII); return (DnsResourceData) new DnsResourceDataGeographicalPosition(longitude, latitude, altitude); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpAddressMaskRequestLayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets.IpV4; namespace PcapDotNet.Packets.Icmp { public class IcmpAddressMaskRequestLayer : IcmpIdentifiedLayer { public IpV4Address AddressMask { get; set; } public override IcmpMessageType MessageType { get { return IcmpMessageType.AddressMaskRequest; } } protected override sealed int PayloadLength { get { return 4; } } protected override sealed void WritePayload(byte[] buffer, int offset) { IcmpAddressMaskRequestDatagram.WriteHeaderAdditional(buffer, offset, this.AddressMask); } protected override sealed bool EqualPayload(IcmpLayer other) { return this.EqualPayload(other as IcmpAddressMaskRequestLayer); } private bool EqualPayload(IcmpAddressMaskRequestLayer other) { if (other != null) return this.AddressMask.Equals(other.AddressMask); return false; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Option // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using System.Diagnostics.CodeAnalysis; namespace PcapDotNet.Packets { [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Option")] public abstract class Option { public abstract int Length { get; } public abstract bool IsAppearsAtMostOnce { get; } public abstract bool Equivalent(Option other); internal abstract Option Read(byte[] buffer, ref int offset, int length); internal abstract void Write(byte[] buffer, ref int offset); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CGurus.Weather.WundergroundAPI.Models { public class ForecastData { public Forecast Forecast { get; set; } public Response Response { get; set; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.TcpOptionConnectionCountEcho // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; namespace PcapDotNet.Packets.Transport { [OptionTypeRegistration(typeof (TcpOptionType), TcpOptionType.ConnectionCountEcho)] public class TcpOptionConnectionCountEcho : TcpOptionConnectionCountBase, IOptionComplexFactory { public TcpOptionConnectionCountEcho(uint connectionCount) : base(TcpOptionType.ConnectionCountEcho, connectionCount) { } public TcpOptionConnectionCountEcho() : this(0U) { } Option IOptionComplexFactory.CreateInstance(byte[] buffer, ref int offset, byte valueLength) { uint connectionCount; if (!TcpOptionConnectionCountBase.TryRead(out connectionCount, buffer, ref offset, valueLength)) return (Option) null; return (Option) new TcpOptionConnectionCountEcho(connectionCount); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsTypeRegistrationAttribute // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using System; namespace PcapDotNet.Packets.Dns { [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] internal sealed class DnsTypeRegistrationAttribute : Attribute { public DnsType Type { get; set; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: AcuLink_Bridge_Reader_CSharp.WindData // Assembly: AcuLink_Bridge_Reader_CS, Version=2014.9.18.2041, Culture=neutral, PublicKeyToken=null // MVID: 2DF0938E-D9D0-414E-AB5D-7B9A655FB464 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\AcuLink_Bridge_Reader_CS.exe using System; namespace AcuLink_Bridge_Reader_CSharp { public class WindData { public DateTime time { get; set; } public Decimal windSpeed { get; set; } public WindData(DateTime time, Decimal windSpeed) { this.time = time; this.windSpeed = windSpeed; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpMessageType // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Icmp { public enum IcmpMessageType : byte { EchoReply = (byte) 0, DestinationUnreachable = (byte) 3, SourceQuench = (byte) 4, Redirect = (byte) 5, Echo = (byte) 8, RouterAdvertisement = (byte) 9, RouterSolicitation = (byte) 10, TimeExceeded = (byte) 11, ParameterProblem = (byte) 12, Timestamp = (byte) 13, TimestampReply = (byte) 14, InformationRequest = (byte) 15, InformationReply = (byte) 16, AddressMaskRequest = (byte) 17, AddressMaskReply = (byte) 18, TraceRoute = (byte) 30, ConversionFailed = (byte) 31, DomainNameRequest = (byte) 37, DomainNameReply = (byte) 38, SecurityFailures = (byte) 40, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Http.HttpDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; namespace PcapDotNet.Packets.Http { public abstract class HttpDatagram : Datagram { private static readonly byte[] _httpSlash = Encoding.ASCII.GetBytes("HTTP/"); public abstract bool IsRequest { get; } public bool IsResponse { get { return !this.IsRequest; } } public HttpVersion Version { get; private set; } public HttpHeader Header { get; private set; } public Datagram Body { get; private set; } internal HttpDatagram(byte[] buffer, int offset, int length, HttpVersion version, HttpHeader header, Datagram body) : base(buffer, offset, length) { this.Version = version; this.Header = header; this.Body = body; } internal static HttpDatagram CreateDatagram(byte[] buffer, int offset, int length) { if (length >= HttpDatagram._httpSlash.Length && ByteArrayExtensions.SequenceEqual(buffer, offset, HttpDatagram._httpSlash, 0, HttpDatagram._httpSlash.Length)) return (HttpDatagram) new HttpResponseDatagram(buffer, offset, length); return (HttpDatagram) new HttpRequestDatagram(buffer, offset, length); } internal static Datagram ParseBody(byte[] buffer, int offset, int length, bool isBodyPossible, HttpHeader header) { if (!isBodyPossible) return Datagram.Empty; HttpTransferEncodingField transferEncoding = header.TransferEncoding; if (transferEncoding != null && transferEncoding.TransferCodings != null && Enumerable.Any<string>((IEnumerable<string>) transferEncoding.TransferCodings, (Func<string, bool>) (coding => coding != "identity"))) return HttpDatagram.ParseChunkedBody(buffer, offset, length); HttpContentLengthField contentLength1 = header.ContentLength; if (contentLength1 != null) { uint? contentLength2 = contentLength1.ContentLength; if (contentLength2.HasValue) return new Datagram(buffer, offset, Math.Min((int) contentLength2.Value, length)); } HttpContentTypeField contentType = header.ContentType; if (contentType != null && contentType.MediaType == "multipart" && contentType.MediaSubtype == "byteranges") { string str = contentType.Parameters["boundary"]; if (str != null) { byte[] bytes = Encoding.ASCII.GetBytes(string.Format((IFormatProvider) CultureInfo.InvariantCulture, "\r\n--{0}--", new object[1] { (object) str })); int num = ByteArrayExtensions.Find(buffer, offset, length, bytes) + bytes.Length; return new Datagram(buffer, offset, Math.Min(num - offset, length)); } } return new Datagram(buffer, offset, length); } private static Datagram ParseChunkedBody(byte[] buffer, int offset, int length) { List<Datagram> list = new List<Datagram>(); HttpParser httpParser = new HttpParser(buffer, offset, length); uint? number; while (httpParser.HexadecimalNumber(out number).SkipChunkExtensions().CarriageReturnLineFeed().Success) { uint num1 = number.Value; if ((int) num1 == 0) { int? endOffset; HttpDatagram.GetHeaderFields(out endOffset, buffer, httpParser.Offset, offset + length - httpParser.Offset); if (endOffset.HasValue) { httpParser.Skip(endOffset.Value - httpParser.Offset); break; } break; } int num2 = (int) Math.Min((long) num1, (long) (offset + length - httpParser.Offset)); list.Add(new Datagram(buffer, httpParser.Offset, num2)); httpParser.Skip(num2); httpParser.CarriageReturnLineFeed(); } byte[] buffer1 = new byte[Enumerable.Sum<Datagram>((IEnumerable<Datagram>) list, (Func<Datagram, int>) (datagram => datagram.Length))]; int offset1 = 0; foreach (Datagram datagram in list) { datagram.Write(buffer1, offset1); offset1 += datagram.Length; } return new Datagram(buffer, offset, httpParser.Offset - offset); } internal static List<KeyValuePair<string, IEnumerable<byte>>> GetHeaderFields(out int? endOffset, byte[] buffer, int offset, int length) { endOffset = new int?(); List<KeyValuePair<string, IEnumerable<byte>>> list = new List<KeyValuePair<string, IEnumerable<byte>>>(); HttpParser httpParser = new HttpParser(buffer, offset, length); while (httpParser.Success) { if (httpParser.IsCarriageReturnLineFeed()) { endOffset = new int?(httpParser.Offset + 2); break; } string token; IEnumerable<byte> fieldValue; httpParser.Token(out token).Colon().FieldValue(out fieldValue).CarriageReturnLineFeed(); if (httpParser.Success) list.Add(new KeyValuePair<string, IEnumerable<byte>>(token, fieldValue)); } return list; } internal class ParseInfoBase { public int Length { get; set; } public HttpVersion Version { get; set; } public HttpHeader Header { get; set; } public Datagram Body { get; set; } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.TcpOptions // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System.Collections.Generic; namespace PcapDotNet.Packets.Transport { public class TcpOptions : Options<TcpOption> { private static readonly TcpOptions _none = new TcpOptions(new TcpOption[0]); public const int MaximumBytesLength = 40; public static TcpOptions None { get { return TcpOptions._none; } } public TcpOptions(IList<TcpOption> options) : base(options, TcpOption.End, 40) { } public TcpOptions(params TcpOption[] options) : this((IList<TcpOption>) options) { } internal TcpOptions(byte[] buffer, int offset, int length) : base(buffer, offset, length, TcpOption.End) { } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.TcpOptionPartialOrderServiceProfile // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Transport { [OptionTypeRegistration(typeof (TcpOptionType), TcpOptionType.PartialOrderServiceProfile)] public sealed class TcpOptionPartialOrderServiceProfile : TcpOptionComplex, IOptionComplexFactory, IEquatable<TcpOptionPartialOrderServiceProfile> { private const byte NoFlags = (byte) 0; private const byte StartFlag = (byte) 128; private const byte EndFlag = (byte) 64; public const int OptionLength = 3; public const int OptionValueLength = 1; public bool IsStart { get; private set; } public bool IsEnd { get; private set; } public override int Length { get { return 3; } } public override bool IsAppearsAtMostOnce { get { return true; } } public TcpOptionPartialOrderServiceProfile(bool isStart, bool isEnd) : base(TcpOptionType.PartialOrderServiceProfile) { this.IsStart = isStart; this.IsEnd = isEnd; } public TcpOptionPartialOrderServiceProfile() : this(true, true) { } public bool Equals(TcpOptionPartialOrderServiceProfile other) { if (other == null || this.IsStart != other.IsStart) return false; return this.IsEnd == other.IsEnd; } public override bool Equals(TcpOption other) { return this.Equals(other as TcpOptionPartialOrderServiceProfile); } public override int GetHashCode() { return base.GetHashCode() ^ BitSequence.Merge(this.IsStart, this.IsEnd).GetHashCode(); } Option IOptionComplexFactory.CreateInstance(byte[] buffer, ref int offset, byte valueLength) { if ((int) valueLength != 1) return (Option) null; byte num = ByteArrayExtensions.ReadByte(buffer, ref offset); return (Option) new TcpOptionPartialOrderServiceProfile(((int) num & 128) == 128, ((int) num & 64) == 64); } internal override void Write(byte[] buffer, ref int offset) { base.Write(buffer, ref offset); byte num = (byte) ((this.IsStart ? 128 : 0) | (this.IsEnd ? 64 : 0)); ByteArrayExtensions.Write(buffer, ref offset, num); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Arp.ArpLayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using PcapDotNet.Packets.Ethernet; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Linq; namespace PcapDotNet.Packets.Arp { public sealed class ArpLayer : Layer, IEthernetNextLayer, ILayer { public EthernetType ProtocolType { get; set; } public ArpOperation Operation { get; set; } [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ReadOnlyCollection<byte> SenderHardwareAddress { get; set; } [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ReadOnlyCollection<byte> SenderProtocolAddress { get; set; } [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ReadOnlyCollection<byte> TargetHardwareAddress { get; set; } [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ReadOnlyCollection<byte> TargetProtocolAddress { get; set; } public EthernetType PreviousLayerEtherType { get { return EthernetType.Arp; } } public MacAddress? PreviousLayerDefaultDestination { get { return new MacAddress?(EthernetDatagram.BroadcastAddress); } } public override int Length { get { return ArpDatagram.GetHeaderLength(this.SenderHardwareAddress.Count, this.SenderProtocolAddress.Count); } } public override void Write(byte[] buffer, int offset, int payloadLength, ILayer previousLayer, ILayer nextLayer) { if (previousLayer == null) throw new ArgumentNullException("previousLayer"); IArpPreviousLayer arpPreviousLayer = previousLayer as IArpPreviousLayer; if (arpPreviousLayer == null) throw new ArgumentException("The layer before the ARP layer must be an ARP previous layer and can't be " + (object) previousLayer.GetType()); if (this.SenderHardwareAddress.Count != this.TargetHardwareAddress.Count) throw new ArgumentException("Sender hardware address length is " + (object) this.SenderHardwareAddress.Count + " bytes while target hardware address length is " + (string) (object) this.TargetHardwareAddress.Count + " bytes"); if (this.SenderProtocolAddress.Count != this.TargetProtocolAddress.Count) throw new ArgumentException("Sender protocol address length is " + (object) this.SenderProtocolAddress.Count + " bytes while target protocol address length is " + (string) (object) this.TargetProtocolAddress.Count + " bytes"); ArpDatagram.WriteHeader(buffer, offset, arpPreviousLayer.PreviousLayerHardwareType, this.ProtocolType, this.Operation, (IList<byte>) this.SenderHardwareAddress, (IList<byte>) this.SenderProtocolAddress, (IList<byte>) this.TargetHardwareAddress, (IList<byte>) this.TargetProtocolAddress); } public bool Equals(ArpLayer other) { if (other != null && this.ProtocolType == other.ProtocolType && (this.Operation == other.Operation && Enumerable.SequenceEqual<byte>((IEnumerable<byte>) this.SenderHardwareAddress, (IEnumerable<byte>) other.SenderHardwareAddress)) && (Enumerable.SequenceEqual<byte>((IEnumerable<byte>) this.SenderProtocolAddress, (IEnumerable<byte>) other.SenderProtocolAddress) && Enumerable.SequenceEqual<byte>((IEnumerable<byte>) this.TargetHardwareAddress, (IEnumerable<byte>) other.TargetHardwareAddress))) return Enumerable.SequenceEqual<byte>((IEnumerable<byte>) this.TargetProtocolAddress, (IEnumerable<byte>) other.TargetProtocolAddress); return false; } public override bool Equals(Layer other) { return this.Equals(other as ArpLayer); } public override int GetHashCode() { return base.GetHashCode() ^ BitSequence.Merge((ushort) this.ProtocolType, (ushort) this.Operation).GetHashCode() ^ IEnumerableExtensions.BytesSequenceGetHashCode((IEnumerable<byte>) this.SenderHardwareAddress) ^ IEnumerableExtensions.BytesSequenceGetHashCode((IEnumerable<byte>) this.SenderProtocolAddress) ^ IEnumerableExtensions.BytesSequenceGetHashCode((IEnumerable<byte>) this.TargetHardwareAddress) ^ IEnumerableExtensions.BytesSequenceGetHashCode((IEnumerable<byte>) this.TargetProtocolAddress); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Base.EncodingExtensions // Assembly: PcapDotNet.Base, Version=0.10.0.20668, Culture=neutral, PublicKeyToken=<KEY> // MVID: E9656A63-0145-422C-B8C8-79FDD7FB4270 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Base.dll using System.Text; namespace PcapDotNet.Base { public static class EncodingExtensions { private static readonly Encoding _iso88591 = Encoding.GetEncoding(28591); public static Encoding Iso88591 { get { return EncodingExtensions._iso88591; } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Base.MemberInfoExtensions // Assembly: PcapDotNet.Base, Version=0.10.0.20668, Culture=neutral, PublicKeyToken=<KEY> // MVID: E9656A63-0145-422C-B8C8-79FDD7FB4270 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Base.dll using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace PcapDotNet.Base { public static class MemberInfoExtensions { public static IEnumerable<T> GetCustomAttributes<T>(this MemberInfo memberInfo, bool inherit) where T : Attribute { if (memberInfo == (MemberInfo) null) throw new ArgumentNullException("memberInfo"); return Enumerable.Cast<T>((IEnumerable) memberInfo.GetCustomAttributes(typeof (T), inherit)); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataNextDomainSecure3 // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.NSec3)] public sealed class DnsResourceDataNextDomainSecure3 : DnsResourceDataNextDomainSecure3Base, IEquatable<DnsResourceDataNextDomainSecure3> { private readonly DnsTypeBitmaps _typeBitmaps; public DataSegment NextHashedOwnerName { get; private set; } public ReadOnlyCollection<DnsType> TypesExist { get { return this._typeBitmaps.TypesExist.AsReadOnly(); } } private int NextHashedOwnerNameLengthOffset { get { return this.ParametersLength; } } private int NextHashedOwnerNameOffset { get { return this.NextHashedOwnerNameLengthOffset + 1; } } private int TypeBitmapsOffset { get { return this.NextHashedOwnerNameOffset + this.NextHashedOwnerName.Length; } } [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "flags")] public DnsResourceDataNextDomainSecure3(DnsSecNSec3HashAlgorithm hashAlgorithm, DnsSecNSec3Flags flags, ushort iterations, DataSegment salt, DataSegment nextHashedOwnerName, IEnumerable<DnsType> typesExist) : this(hashAlgorithm, flags, iterations, salt, nextHashedOwnerName, new DnsTypeBitmaps(typesExist)) { } internal DnsResourceDataNextDomainSecure3() : this(DnsSecNSec3HashAlgorithm.Sha1, DnsSecNSec3Flags.None, (ushort) 0, DataSegment.Empty, DataSegment.Empty, (IEnumerable<DnsType>) new DnsType[0]) { } private DnsResourceDataNextDomainSecure3(DnsSecNSec3HashAlgorithm hashAlgorithm, DnsSecNSec3Flags flags, ushort iterations, DataSegment salt, DataSegment nextHashedOwnerName, DnsTypeBitmaps typeBitmaps) : base(hashAlgorithm, flags, iterations, salt) { if (nextHashedOwnerName.Length > (int) byte.MaxValue) throw new ArgumentOutOfRangeException("nextHashedOwnerName", (object) nextHashedOwnerName.Length, string.Format((IFormatProvider) CultureInfo.InvariantCulture, "Cannot bigger than {0}.", new object[1] { (object) byte.MaxValue })); this.NextHashedOwnerName = nextHashedOwnerName; this._typeBitmaps = typeBitmaps; } [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0")] public bool Equals(DnsResourceDataNextDomainSecure3 other) { if (this.EqualsParameters((DnsResourceDataNextDomainSecure3Base) other) && this.NextHashedOwnerName.Equals(other.NextHashedOwnerName)) return this._typeBitmaps.Equals(other._typeBitmaps); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataNextDomainSecure3); } public override int GetHashCode() { return this.GetHashCodeParameters() ^ Sequence.GetHashCode((object) this.NextHashedOwnerName, (object) this._typeBitmaps); } internal override int GetLength() { return this.ParametersLength + 1 + this.NextHashedOwnerName.Length + this._typeBitmaps.GetLength(); } internal override void WriteDataSimple(byte[] buffer, int offset) { this.WriteParameters(buffer, offset); ByteArrayExtensions.Write(buffer, offset + this.NextHashedOwnerNameLengthOffset, (byte) this.NextHashedOwnerName.Length); this.NextHashedOwnerName.Write(buffer, offset + this.NextHashedOwnerNameOffset); this._typeBitmaps.Write(buffer, offset + this.TypeBitmapsOffset); } internal override DnsResourceData CreateInstance(DataSegment data) { DnsSecNSec3HashAlgorithm hashAlgorithm; DnsSecNSec3Flags flags; ushort iterations; DataSegment salt; if (!DnsResourceDataNextDomainSecure3Base.TryReadParameters(data, out hashAlgorithm, out flags, out iterations, out salt)) return (DnsResourceData) null; int parametersLength = DnsResourceDataNextDomainSecure3Base.GetParametersLength(salt.Length); if (data.Length - parametersLength < 1) return (DnsResourceData) null; int offset = parametersLength + 1; int length = (int) data[parametersLength]; if (data.Length - offset < length) return (DnsResourceData) null; DataSegment nextHashedOwnerName = data.Subsegment(offset, length); int num = offset + length; DnsTypeBitmaps instance = DnsTypeBitmaps.CreateInstance(data.Buffer, data.StartOffset + num, data.Length - num); if (instance == null) return (DnsResourceData) null; return (DnsResourceData) new DnsResourceDataNextDomainSecure3(hashAlgorithm, flags, iterations, salt, nextHashedOwnerName, instance); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.TcpControlBits // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using System; namespace PcapDotNet.Packets.Transport { [Flags] public enum TcpControlBits : ushort { None = (ushort) 0, Fin = (ushort) 1, Synchronize = (ushort) 2, Reset = (ushort) 4, Push = (ushort) 8, Acknowledgment = (ushort) 16, Urgent = (ushort) 32, ExplicitCongestionNotificationEcho = (ushort) 64, CongestionWindowReduced = (ushort) 128, NonceSum = (ushort) 256, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.DataSegment // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets.Ethernet; using PcapDotNet.Packets.IpV4; using PcapDotNet.Packets.IpV6; using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Numerics; using System.Text; namespace PcapDotNet.Packets { public class DataSegment : IEquatable<DataSegment>, IEnumerable<byte>, IEnumerable { private static readonly DataSegment _empty = new DataSegment(new byte[0]); public int Length { get; private set; } public byte this[int offset] { get { return this.Buffer[this.StartOffset + offset]; } } public byte Last { get { return this[this.Length - 1]; } } public static DataSegment Empty { get { return DataSegment._empty; } } [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] internal byte[] Buffer { get; private set; } internal int StartOffset { get; private set; } public DataSegment(byte[] buffer) { if (buffer == null) throw new ArgumentNullException("buffer"); this.Buffer = buffer; this.StartOffset = 0; this.Length = buffer.Length; } public DataSegment(byte[] buffer, int offset, int length) { this.Buffer = buffer; this.StartOffset = offset; this.Length = length; } public DataSegment Subsegment(int offset, int length) { return this.Subsegment(ref offset, length); } public MemoryStream ToMemoryStream() { return new MemoryStream(this.Buffer, this.StartOffset, this.Length, false, false); } public IEnumerator<byte> GetEnumerator() { for (int i = 0; i != this.Length; ++i) yield return this[i]; } IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator) this.GetEnumerator(); } public bool Equals(DataSegment other) { if (other == null || this.Length != other.Length) return false; for (int index = 0; index != this.Length; ++index) { if ((int) this[index] != (int) other[index]) return false; } return true; } public override sealed bool Equals(object obj) { return this.Equals(obj as DataSegment); } public override sealed int GetHashCode() { return this.Length.GetHashCode() ^ IEnumerableExtensions.BytesSequenceGetHashCode((IEnumerable<byte>) this); } public override sealed string ToString() { return string.Format((IFormatProvider) CultureInfo.InvariantCulture, "{0} bytes: {1}{2}", (object) this.Length, (object) IEnumerableExtensions.BytesSequenceToHexadecimalString(IListExtensions.Range<byte>((IList<byte>) this.Buffer, this.StartOffset, Math.Min(this.Length, 10))), this.Length > 10 ? (object) "..." : (object) ""); } public string ToHexadecimalString() { return IEnumerableExtensions.BytesSequenceToHexadecimalString(IListExtensions.Range<byte>((IList<byte>) this.Buffer, this.StartOffset, this.Length)); } public string Decode(Encoding encoding) { if (encoding == null) throw new ArgumentNullException("encoding"); return encoding.GetString(this.Buffer, this.StartOffset, this.Length); } internal void Write(byte[] buffer, ref int offset) { ByteArrayExtensions.BlockCopy(this.Buffer, this.StartOffset, buffer, offset, this.Length); offset += this.Length; } internal void Write(byte[] buffer, int offset) { this.Write(buffer, ref offset); } internal byte[] ReadBytes(int offset, int length) { return ByteArrayExtensions.ReadBytes(this.Buffer, this.StartOffset + offset, length); } internal DataSegment Subsegment(ref int offset, int length) { DataSegment dataSegment = new DataSegment(this.Buffer, this.StartOffset + offset, length); offset += length; return dataSegment; } internal bool ReadBool(int offset, byte mask) { return ((int) this[offset] & (int) mask) == (int) mask; } [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "ushort")] internal ushort ReadUShort(int offset, Endianity endianity) { return ByteArrayExtensions.ReadUShort(this.Buffer, this.StartOffset + offset, endianity); } [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "int")] internal int ReadInt(int offset, Endianity endianity) { return ByteArrayExtensions.ReadInt(this.Buffer, this.StartOffset + offset, endianity); } [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "uint")] internal uint ReadUInt(int offset, Endianity endianity) { return ByteArrayExtensions.ReadUInt(this.Buffer, this.StartOffset + offset, endianity); } internal UInt48 ReadUInt48(int offset, Endianity endianity) { return ByteArrayExtensions.ReadUInt48(this.Buffer, this.StartOffset + offset, endianity); } internal ulong ReadULong(int offset, Endianity endianity) { return ByteArrayExtensions.ReadULong(this.Buffer, this.StartOffset + offset, endianity); } internal BigInteger ReadUnsignedBigInteger(int offset, int length, Endianity endianity) { return ByteArrayExtensions.ReadUnsignedBigInteger(this.Buffer, this.StartOffset + offset, length, endianity); } protected MacAddress ReadMacAddress(int offset, Endianity endianity) { return ByteArrayExtensions.ReadMacAddress(this.Buffer, this.StartOffset + offset, endianity); } internal IpV4Address ReadIpV4Address(int offset, Endianity endianity) { return ByteArrayExtensions.ReadIpV4Address(this.Buffer, this.StartOffset + offset, endianity); } protected IpV4TimeOfDay ReadIpV4TimeOfDay(int offset, Endianity endianity) { return ByteArrayExtensions.ReadIpV4TimeOfDay(this.Buffer, this.StartOffset + offset, endianity); } internal IpV6Address ReadIpV6Address(int offset, Endianity endianity) { return ByteArrayExtensions.ReadIpV6Address(this.Buffer, this.StartOffset + offset, endianity); } protected static ushort Sum16BitsToChecksum(uint sum) { while (sum > (uint) ushort.MaxValue) sum = (sum & (uint) ushort.MaxValue) + (sum >> 16); sum = ~sum; return (ushort) sum; } protected static uint Sum16Bits(byte[] buffer, int offset, int length) { if (buffer == null) throw new ArgumentNullException("buffer"); int num1 = offset + length; uint num2 = 0U; while (offset < num1 - 1) num2 += (uint) ByteArrayExtensions.ReadUShort(buffer, ref offset, Endianity.Big); if (offset < num1) num2 += (uint) (ushort) ((uint) buffer[offset] << 8); return num2; } internal static uint Sum16Bits(IpV4Address address) { uint num = address.ToValue(); return (num >> 16) + (num & (uint) ushort.MaxValue); } } } <file_sep> namespace CGurus.Weather.WundergroundAPI.Models { public class ForecastHourlyData { public ForecastHourly[] Hourly_Forecast { get; set; } public Response Response { get; set; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Igmp.IgmpSimpleLayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets.IpV4; namespace PcapDotNet.Packets.Igmp { public abstract class IgmpSimpleLayer : IgmpLayer, IIgmpLayerWithGroupAddress { public IpV4Address GroupAddress { get; set; } public override sealed int Length { get { return 8; } } protected override sealed void Write(byte[] buffer, int offset) { IgmpDatagram.WriteHeader(buffer, offset, this.MessageType, this.MaxResponseTimeValue, this.GroupAddress); } public override sealed int GetHashCode() { return base.GetHashCode() ^ this.GroupAddress.GetHashCode(); } protected override sealed bool EqualFields(IgmpLayer other) { return this.EqualFields(other as IgmpSimpleLayer); } private bool EqualFields(IgmpSimpleLayer other) { if (other != null) return this.GroupAddress == other.GroupAddress; return false; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpConversionFailedDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using PcapDotNet.Packets.IpV4; using PcapDotNet.Packets.Transport; using System.Linq; namespace PcapDotNet.Packets.Icmp { [IcmpDatagramRegistration(IcmpMessageType.ConversionFailed)] public sealed class IcmpConversionFailedDatagram : IcmpIpV4PayloadDatagram { private static readonly byte _minCode = (byte) Enumerable.Min<IcmpCodeConversionFailed>(TypeExtensions.GetEnumValues<IcmpCodeConversionFailed>(typeof (IcmpCodeConversionFailed))); private static readonly byte _maxCode = (byte) Enumerable.Max<IcmpCodeConversionFailed>(TypeExtensions.GetEnumValues<IcmpCodeConversionFailed>(typeof (IcmpCodeConversionFailed))); public const int OriginalDatagramLengthForUnsupportedTransportProtocol = 256; public uint Pointer { get { return this.ReadUInt(4, Endianity.Big); } } protected override byte MinCodeValue { get { return IcmpConversionFailedDatagram._minCode; } } protected override byte MaxCodeValue { get { return IcmpConversionFailedDatagram._maxCode; } } private IcmpConversionFailedDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public override ILayer ExtractLayer() { IcmpConversionFailedLayer conversionFailedLayer = new IcmpConversionFailedLayer(); conversionFailedLayer.Checksum = new ushort?(this.Checksum); conversionFailedLayer.Code = (IcmpCodeConversionFailed) this.Code; conversionFailedLayer.Pointer = this.Pointer; return (ILayer) conversionFailedLayer; } protected override bool CalculateIsValid() { if (!base.CalculateIsValid()) return false; IpV4Datagram ipV4 = this.IpV4; if ((int) this.Code == 4) return ipV4.Length == 256; switch (ipV4.Protocol) { case IpV4Protocol.Tcp: TcpDatagram tcp = ipV4.Tcp; if (tcp.Length >= 20) return tcp.Length >= tcp.HeaderLength; return false; case IpV4Protocol.Udp: return ipV4.Udp.Length >= 8; default: return true; } } internal override IcmpDatagram CreateInstance(byte[] buffer, int offset, int length) { return (IcmpDatagram) new IcmpConversionFailedDatagram(buffer, offset, length); } private static class Offset { public const int Pointer = 4; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV6.IpV6Address // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets.IpV4; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; namespace PcapDotNet.Packets.IpV6 { public struct IpV6Address { private static readonly IpV6Address _zero = new IpV6Address((UInt128) 0UL); private static readonly IpV6Address _maxValue = new IpV6Address(UInt128.MaxValue); public const int SizeOf = 16; private readonly UInt128 _value; public static IpV6Address Zero { get { return IpV6Address._zero; } } public static IpV6Address MaxValue { get { return IpV6Address._maxValue; } } public IpV6Address(UInt128 value) { this._value = value; } public IpV6Address(string value) { if (value == null) throw new ArgumentNullException("value"); string str1 = value; int num1 = str1.LastIndexOf(':'); if (num1 == -1) throw new ArgumentException("Invalid IPv6 address format " + value); string str2 = value.Substring(num1 + 1, str1.Length - num1 - 1); if (str2.IndexOf('.') != -1) { uint num2 = new IpV4Address(str2).ToValue(); str1 = str1.Substring(0, num1 + 1) + (num2 >> 16).ToString("x", (IFormatProvider) CultureInfo.InvariantCulture) + ":" + (num2 & (uint) ushort.MaxValue).ToString("x", (IFormatProvider) CultureInfo.InvariantCulture); } int num3 = str1.IndexOf("::", StringComparison.Ordinal); if (num3 != -1) { int count = 7 - IEnumerableExtensions.Count<char>((IEnumerable<char>) str1, ':'); if (count < 0) throw new ArgumentException("Invalid IPv6 address format " + value); str1 = str1.Substring(0, num3 + 2) + new string(':', count) + str1.Substring(num3 + 2); } IEnumerable<ushort> source = Enumerable.Select<string, ushort>((IEnumerable<string>) str1.Split(':'), (Func<string, ushort>) (part => { if (!string.IsNullOrEmpty(part)) return ushort.Parse(part, NumberStyles.HexNumber, (IFormatProvider) CultureInfo.InvariantCulture); return (ushort) 0; })); this._value = new UInt128(Enumerable.Aggregate<ushort, ulong>(Enumerable.Take<ushort>(source, 4), 0UL, (Func<ulong, ushort, ulong>) ((sum, element) => (sum << 16) + (ulong) element)), Enumerable.Aggregate<ushort, ulong>(Enumerable.Take<ushort>(Enumerable.Skip<ushort>(source, 4), 4), 0UL, (Func<ulong, ushort, ulong>) ((sum, element) => (sum << 16) + (ulong) element))); } public static bool operator ==(IpV6Address value1, IpV6Address value2) { return value1.Equals(value2); } public static bool operator !=(IpV6Address value1, IpV6Address value2) { return !(value1 == value2); } public UInt128 ToValue() { return this._value; } public bool Equals(IpV6Address other) { return this._value == other._value; } public override bool Equals(object obj) { if (obj is IpV6Address) return this.Equals((IpV6Address) obj); return false; } public override int GetHashCode() { return this._value.GetHashCode(); } public override string ToString() { string str = this._value.ToString("X33", (IFormatProvider) CultureInfo.InvariantCulture).Substring(1); StringBuilder stringBuilder = new StringBuilder(39); for (int index = 0; index != 8; ++index) { if (index != 0) stringBuilder.Append(':'); stringBuilder.Append(str.Substring(index * 4, 4)); } return stringBuilder.ToString(); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.OfflinePacketDevice // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using System.Collections.Generic; using System.Collections.ObjectModel; namespace PcapDotNet.Core { public sealed class OfflinePacketDevice : PacketDevice { private string _fileName; public override ReadOnlyCollection<DeviceAddress> Addresses { get { return new ReadOnlyCollection<DeviceAddress>((IList<DeviceAddress>) new List<DeviceAddress>()); } } public override DeviceAttributes Attributes { get { return DeviceAttributes.None; } } public override string Description { get { return string.Empty; } } public override string Name { get { return this._fileName; } } public OfflinePacketDevice(string fileName) { this._fileName = fileName; } public override sealed PacketCommunicator Open(int snapshotLength, PacketDeviceOpenAttributes attributes, int readTimeout) { return (PacketCommunicator) new OfflinePacketCommunicator(this._fileName); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.BerkeleyPacketFilter // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using PcapDotNet.Packets; using std; using System; using System.Runtime.InteropServices; namespace PcapDotNet.Core { public class BerkeleyPacketFilter : IDisposable { private unsafe bpf_program* _bpf; internal unsafe BerkeleyPacketFilter(pcap* pcapDescriptor, string filterString, IpV4SocketAddress netmask) { this.Initialize(pcapDescriptor, filterString, netmask); } public BerkeleyPacketFilter(string filterValue, int snapshotLength, DataLinkKind kind) { this.Initialize(filterValue, snapshotLength, kind, (IpV4SocketAddress) null); } public BerkeleyPacketFilter(string filterValue, int snapshotLength, DataLinkKind kind, IpV4SocketAddress netmask) { this.Initialize(filterValue, snapshotLength, kind, netmask); } [return: MarshalAs(UnmanagedType.U1)] public bool Test(Packet packet) { int snapshotLength; return this.Test(out snapshotLength, packet); } [return: MarshalAs(UnmanagedType.U1)] public unsafe bool Test(out int snapshotLength, Packet packet) { if (packet == null) throw new ArgumentNullException("packet"); pcap_pkthdr pcapPkthdr; PacketHeader.GetPcapHeader(&pcapPkthdr, packet); fixed (byte* numPtr = &packet.Buffer[0]) { int num = \u003CModule\u003E.pcap_offline_filter(this._bpf, &pcapPkthdr, numPtr); snapshotLength = num; return num != 0; } } private unsafe void \u007EBerkeleyPacketFilter() { \u003CModule\u003E.pcap_freecode(this._bpf); \u003CModule\u003E.delete((void*) this._bpf); } internal unsafe void SetFilter(pcap* pcapDescriptor) { if (\u003CModule\u003E.pcap_setfilter(pcapDescriptor, this._bpf) != 0) throw PcapError.BuildInvalidOperation("Failed setting bpf filter", pcapDescriptor); } private unsafe void Initialize(pcap* pcapDescriptor, string filterString, IpV4SocketAddress netmask) { // ISSUE: untyped stack allocation long num1 = (long) __untypedstackalloc(\u003CModule\u003E.__CxxQueryExceptionSize()); basic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E stdAllocatorChar; MarshalingServices.ManagedToUnmanagedString(&stdAllocatorChar, filterString); // ISSUE: fault handler try { uint num2 = 0U; if (netmask != null) num2 = netmask.Address.ToValue(); bpf_program* bpfProgramPtr1 = (bpf_program*) \u003CModule\u003E.@new(16UL); bpf_program* bpfProgramPtr2; if ((IntPtr) bpfProgramPtr1 != IntPtr.Zero) { // ISSUE: initblk instruction __memset((IntPtr) bpfProgramPtr1, 0, 16L); bpfProgramPtr2 = bpfProgramPtr1; } else bpfProgramPtr2 = (bpf_program*) 0; this._bpf = bpfProgramPtr2; try { if (\u003CModule\u003E.pcap_compile(pcapDescriptor, this._bpf, \u003CModule\u003E.std\u002Ebasic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E\u002Ec_str(&stdAllocatorChar), 1, num2) < 0) throw new ArgumentException("An error has occured when compiling the filter <" + filterString + ">: " + PcapError.GetErrorMessage(pcapDescriptor)); } catch (Exception ex1) when ( { // ISSUE: unable to correctly present filter uint num3 = (uint) Marshal.GetExceptionCode(); if (\u003CModule\u003E.__CxxExceptionFilter((void*) Marshal.GetExceptionPointers(), (void*) 0, 0, (void*) 0) != 0) { SuccessfulFiltering; } else throw; } ) { uint num4 = 0U; \u003CModule\u003E.__CxxRegisterExceptionObject((void*) Marshal.GetExceptionPointers(), (void*) num1); try { try { \u003CModule\u003E.delete((void*) this._bpf); \u003CModule\u003E._CxxThrowException((void*) 0, (_s__ThrowInfo*) 0); } catch (Exception ex2) when ( { // ISSUE: unable to correctly present filter num4 = (uint) \u003CModule\u003E.__CxxDetectRethrow((void*) Marshal.GetExceptionPointers()); if ((int) num4 != 0) { SuccessfulFiltering; } else throw; } ) { } if ((int) num4 != 0) throw; } finally { \u003CModule\u003E.__CxxUnregisterExceptionObject((void*) num1, (int) num4); } } } __fault { // ISSUE: method pointer // ISSUE: cast to a function pointer type \u003CModule\u003E.___CxxCallUnwindDtor((__FnPtr<void (void*)>) __methodptr(std\u002Ebasic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E\u002E\u007Bdtor\u007D), (void*) &stdAllocatorChar); } // ISSUE: cast to a reference type // ISSUE: explicit reference operation if (16UL <= (ulong) ^(long&) ((IntPtr) &stdAllocatorChar + 24)) { // ISSUE: explicit reference operation // ISSUE: cast to a reference type // ISSUE: explicit reference operation \u003CModule\u003E.delete((void*) ^(long&) @stdAllocatorChar); } // ISSUE: fault handler try { } __fault { // ISSUE: method pointer // ISSUE: cast to a function pointer type \u003CModule\u003E.___CxxCallUnwindDtor((__FnPtr<void (void*)>) __methodptr(std\u002Ebasic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E\u002E\u007Bdtor\u007D), (void*) &stdAllocatorChar); } } private unsafe void Initialize(string filterString, int snapshotLength, DataLinkKind kind, IpV4SocketAddress netmask) { pcap* pcapDescriptor = \u003CModule\u003E.pcap_open_dead(new PcapDataLink(kind).Value, snapshotLength); try { this.Initialize(pcapDescriptor, filterString, netmask); } finally { \u003CModule\u003E.pcap_close(pcapDescriptor); } } protected virtual void Dispose([MarshalAs(UnmanagedType.U1)] bool _param1) { if (param0) { this.\u007EBerkeleyPacketFilter(); } else { // ISSUE: explicit finalizer call this.Finalize(); } } public virtual void Dispose() { this.Dispose(true); GC.SuppressFinalize((object) this); } } } <file_sep>using System; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; [assembly: AssemblyProduct("PcapDotNet.Core")] [assembly: AssemblyTitle("PcapDotNet.Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCompany("Pcap.Net")] [assembly: AssemblyCopyright("Copyright (c) 2010")] [assembly: AssemblyConfiguration("")] [assembly: SuppressMessage("Microsoft.Design", "CA2210:AssembliesShouldHaveValidStrongNames")] [assembly: SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "<Module>.__CxxRegisterExceptionObject(System.Void*,System.Void*)", Scope = "member", Target = "PcapDotNet.Core.BerkeleyPacketFilter.#Initialize(pcap*,System.String,PcapDotNet.Core.IpV4SocketAddress)")] [assembly: SecurityRules(SecurityRuleSet.Level1)] [assembly: CLSCompliant(true)] [assembly: ComVisible(false)] [assembly: AssemblyFileVersion("0.10.0.0")] [assembly: AssemblyVersion("0.10.0.20693")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.TransportDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; namespace PcapDotNet.Packets.Transport { public abstract class TransportDatagram : Datagram { public ushort SourcePort { get { return this.ReadUShort(0, Endianity.Big); } } public ushort DestinationPort { get { return this.ReadUShort(2, Endianity.Big); } } public abstract ushort Checksum { get; } public abstract bool IsChecksumOptional { get; } public abstract Datagram Payload { get; } internal abstract int ChecksumOffset { get; } internal TransportDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } internal static void WriteHeader(byte[] buffer, int offset, ushort sourcePort, ushort destinationPort) { ByteArrayExtensions.Write(buffer, offset, sourcePort, Endianity.Big); ByteArrayExtensions.Write(buffer, offset + 2, destinationPort, Endianity.Big); } private static class Offset { public const int SourcePort = 0; public const int DestinationPort = 2; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Http.AsciiBytes // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Http { internal static class AsciiBytes { public const byte UpperA = (byte) 65; public const byte UpperF = (byte) 70; public const byte UpperZ = (byte) 90; public const byte LowerA = (byte) 97; public const byte LowerF = (byte) 102; public const byte LowerZ = (byte) 122; public const byte Zero = (byte) 48; public const byte Nine = (byte) 57; public const byte Delete = (byte) 127; public const byte CarriageReturn = (byte) 13; public const byte Linefeed = (byte) 10; public const byte Space = (byte) 32; public const byte HorizontalTab = (byte) 9; public const byte DoubleQuotationMark = (byte) 34; public const byte LeftRoundBracket = (byte) 40; public const byte RightRoundBracket = (byte) 41; public const byte LowerThan = (byte) 60; public const byte BiggerThan = (byte) 62; public const byte AtSign = (byte) 64; public const byte Comma = (byte) 44; public const byte Semicolon = (byte) 59; public const byte Colon = (byte) 58; public const byte BackSlash = (byte) 92; public const byte Slash = (byte) 47; public const byte LeftSquareBracket = (byte) 91; public const byte RightSquareBracket = (byte) 93; public const byte QuestionMark = (byte) 63; public const byte EqualsSign = (byte) 61; public const byte LeftCurlyBracket = (byte) 123; public const byte RightCurlyBracket = (byte) 125; public const byte Asterisk = (byte) 42; public const byte Dot = (byte) 46; } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Http.HttpVersion // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Globalization; using System.Text; namespace PcapDotNet.Packets.Http { public sealed class HttpVersion : IEquatable<HttpVersion> { private static readonly HttpVersion _version10 = new HttpVersion(1U, 0U); private static readonly HttpVersion _version11 = new HttpVersion(1U, 1U); private static readonly byte[] _httpSlashBytes = Encoding.ASCII.GetBytes("HTTP/"); public static HttpVersion Version10 { get { return HttpVersion._version10; } } public static HttpVersion Version11 { get { return HttpVersion._version11; } } public uint Major { get; private set; } public uint Minor { get; private set; } public int Length { get { return HttpVersion._httpSlashBytes.Length + UIntExtensions.DigitsCount(this.Major, 10.0) + 1 + UIntExtensions.DigitsCount(this.Minor, 10.0); } } public HttpVersion(uint major, uint minor) { this.Major = major; this.Minor = minor; } public override string ToString() { return string.Format((IFormatProvider) CultureInfo.InvariantCulture, "HTTP/{0}.{1}", new object[2] { (object) this.Major, (object) this.Minor }); } public bool Equals(HttpVersion other) { if (other != null && (int) this.Major == (int) other.Major) return (int) this.Minor == (int) other.Minor; return false; } public override bool Equals(object obj) { return this.Equals(obj as HttpVersion); } public override int GetHashCode() { return Sequence.GetHashCode((object) this.Minor, (object) this.Major); } internal void Write(byte[] buffer, ref int offset) { ByteArrayExtensions.Write(buffer, ref offset, (IEnumerable<byte>) HttpVersion._httpSlashBytes); ByteArrayExtensions.WriteDecimal(buffer, ref offset, this.Major); ByteArrayExtensions.Write(buffer, ref offset, (byte) 46); ByteArrayExtensions.WriteDecimal(buffer, ref offset, this.Minor); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpInformationReplyDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; namespace PcapDotNet.Packets.Icmp { [IcmpDatagramRegistration(IcmpMessageType.InformationReply)] public sealed class IcmpInformationReplyDatagram : IcmpIdentifiedDatagram { private IcmpInformationReplyDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public override ILayer ExtractLayer() { IcmpInformationReplyLayer informationReplyLayer = new IcmpInformationReplyLayer(); informationReplyLayer.Checksum = new ushort?(this.Checksum); informationReplyLayer.Identifier = this.Identifier; informationReplyLayer.SequenceNumber = this.SequenceNumber; return (ILayer) informationReplyLayer; } internal override IcmpDatagram CreateInstance(byte[] buffer, int offset, int length) { return (IcmpDatagram) new IcmpInformationReplyDatagram(buffer, offset, length); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpTimeExceededLayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Icmp { public sealed class IcmpTimeExceededLayer : IcmpLayer { public IcmpCodeTimeExceeded Code { get; set; } public override IcmpMessageType MessageType { get { return IcmpMessageType.TimeExceeded; } } public override byte CodeValue { get { return (byte) this.Code; } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsGatewayDomainName // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using System; namespace PcapDotNet.Packets.Dns { public sealed class DnsGatewayDomainName : DnsGateway, IEquatable<DnsGatewayDomainName> { public DnsDomainName Value { get; private set; } public override DnsGatewayType GatewayType { get { return DnsGatewayType.DomainName; } } public override int Length { get { return this.Value.NonCompressedLength; } } public DnsGatewayDomainName(DnsDomainName value) { this.Value = value; } public bool Equals(DnsGatewayDomainName other) { if (other != null) return this.Value.Equals(other.Value); return false; } public override bool Equals(DnsGateway other) { return this.Equals(other as DnsGatewayDomainName); } internal override int DataGetHashCode() { return this.Value.GetHashCode(); } internal override void Write(byte[] buffer, int offset) { this.Value.WriteUncompressed(buffer, offset); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Base.TypeExtensions // Assembly: PcapDotNet.Base, Version=0.10.0.20668, Culture=neutral, PublicKeyToken=<KEY> // MVID: E9656A63-0145-422C-B8C8-79FDD7FB4270 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Base.dll using System; using System.Collections.Generic; namespace PcapDotNet.Base { public static class TypeExtensions { public static IEnumerable<T> GetEnumValues<T>(this Type type) { return (IEnumerable<T>) Enum.GetValues(type); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; using System.IO; using System.Reflection; using System.Threading; namespace Grib.Api.Tests { [SetUpFixture] public class Setup { [SetUp] public void OnSetup() { if (Environment.GetEnvironmentVariable("_GRIB_BREAK") == "1") { Console.WriteLine("Breaking on start..."); var mre = new ManualResetEvent(false); // after attaching nunit-agent, put a breakpoint here while (!mre.WaitOne(250)) ; } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsOptions // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace PcapDotNet.Packets.Dns { public sealed class DnsOptions : IEquatable<DnsOptions> { private static readonly DnsOptions _none = new DnsOptions(new DnsOption[0]); public static DnsOptions None { get { return DnsOptions._none; } } public ReadOnlyCollection<DnsOption> Options { get; private set; } public int BytesLength { get; private set; } public DnsOptions(IList<DnsOption> options) { this.Options = IListExtensions.AsReadOnly<DnsOption>(options); this.BytesLength = Enumerable.Sum<DnsOption>((IEnumerable<DnsOption>) options, (Func<DnsOption, int>) (option => option.Length)); } public DnsOptions(params DnsOption[] options) : this((IList<DnsOption>) options) { } public bool Equals(DnsOptions other) { if (other != null) return Enumerable.SequenceEqual<DnsOption>((IEnumerable<DnsOption>) this.Options, (IEnumerable<DnsOption>) other.Options); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsOptions); } public override int GetHashCode() { return IEnumerableExtensions.SequenceGetHashCode<DnsOption>((IEnumerable<DnsOption>) this.Options); } internal static DnsOptions Read(DataSegment data) { List<DnsOption> list = new List<DnsOption>(); int offset; for (; data.Length != 0; data = data.Subsegment(offset, data.Length - offset)) { if (data.Length < 4) return (DnsOptions) null; DnsOptionCode code = (DnsOptionCode) data.ReadUShort(0, Endianity.Big); ushort num = data.ReadUShort(2, Endianity.Big); offset = 4 + (int) num; if (data.Length < offset) return (DnsOptions) null; DnsOption instance = DnsOption.CreateInstance(code, data.Subsegment(4, (int) num)); if (instance == null) return (DnsOptions) null; list.Add(instance); } return new DnsOptions((IList<DnsOption>) list); } internal void Write(byte[] buffer, int offset) { foreach (DnsOption dnsOption in this.Options) dnsOption.Write(buffer, ref offset); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpDatagramFactory // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace PcapDotNet.Packets.Icmp { internal static class IcmpDatagramFactory { private static readonly Dictionary<IcmpMessageType, IcmpDatagram> _prototypes = IcmpDatagramFactory.InitializeComplexOptions(); internal static IcmpDatagram CreateInstance(IcmpMessageType messageType, byte[] buffer, int offset, int length) { IcmpDatagram icmpDatagram; if (!IcmpDatagramFactory._prototypes.TryGetValue(messageType, out icmpDatagram)) return (IcmpDatagram) new IcmpUnknownDatagram(buffer, offset, length); return icmpDatagram.CreateInstance(buffer, offset, length); } private static Dictionary<IcmpMessageType, IcmpDatagram> InitializeComplexOptions() { return Enumerable.ToDictionary(Enumerable.Select(Enumerable.Select(Enumerable.Where<Type>((IEnumerable<Type>) Assembly.GetExecutingAssembly().GetTypes(), (Func<Type, bool>) (type => { if (typeof (IcmpDatagram).IsAssignableFrom(type)) return IcmpDatagramFactory.GetRegistrationAttribute(type) != null; return false; })), type => new { type = type, constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, (Binder) null, new Type[3] { typeof (byte[]), typeof (int), typeof (int) }, (ParameterModifier[]) null) }), param0 => new { MessageType = IcmpDatagramFactory.GetRegistrationAttribute(param0.type).MessageType, Datagram = (IcmpDatagram) param0.constructor.Invoke(new object[3] { null, (object) 0, (object) 0 }) }), prototype => prototype.MessageType, prototype => prototype.Datagram); } private static IcmpDatagramRegistrationAttribute GetRegistrationAttribute(Type type) { IEnumerable<IcmpDatagramRegistrationAttribute> source = Enumerable.Select<IcmpDatagramRegistrationAttribute, IcmpDatagramRegistrationAttribute>(MemberInfoExtensions.GetCustomAttributes<IcmpDatagramRegistrationAttribute>((MemberInfo) type, false), (Func<IcmpDatagramRegistrationAttribute, IcmpDatagramRegistrationAttribute>) (attribute => attribute)); if (!Enumerable.Any<IcmpDatagramRegistrationAttribute>(source)) return (IcmpDatagramRegistrationAttribute) null; return Enumerable.First<IcmpDatagramRegistrationAttribute>(source); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Gre.GreSourceRouteEntry // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using PcapDotNet.Packets.IpV4; using System; namespace PcapDotNet.Packets.Gre { public abstract class GreSourceRouteEntry : IEquatable<GreSourceRouteEntry> { public const int HeaderLength = 4; public abstract GreSourceRouteEntryAddressFamily AddressFamily { get; } public int Length { get { return 4 + (int) this.PayloadLength; } } public abstract byte PayloadOffset { get; } public abstract byte PayloadLength { get; } protected abstract int PayloadHashCode { get; } public bool Equals(GreSourceRouteEntry other) { if (other != null && this.AddressFamily == other.AddressFamily && (this.Length == other.Length && (int) this.PayloadOffset == (int) other.PayloadOffset)) return this.EqualsPayloads(other); return false; } public override sealed bool Equals(object obj) { return this.Equals(obj as GreSourceRouteEntry); } public override sealed int GetHashCode() { return Sequence.GetHashCode((object) this.AddressFamily, (object) this.Length, (object) this.PayloadOffset) ^ this.PayloadHashCode; } protected abstract bool EqualsPayloads(GreSourceRouteEntry other); protected abstract void WritePayload(byte[] buffer, int offset); internal static bool TryReadEntry(byte[] buffer, ref int offset, int length, out GreSourceRouteEntry entry) { entry = (GreSourceRouteEntry) null; if (length < 4) return false; GreSourceRouteEntryAddressFamily addressFamily = (GreSourceRouteEntryAddressFamily) ByteArrayExtensions.ReadUShort(buffer, offset, Endianity.Big); byte num1 = buffer[offset + 3]; if ((int) num1 == 0) return addressFamily == GreSourceRouteEntryAddressFamily.None; if (4 + (int) num1 > length) return false; byte num2 = buffer[offset + 2]; if ((int) num2 > (int) num1 || !GreSourceRouteEntry.TryReadEntry(buffer, offset + 4, (int) num1, addressFamily, (int) num2, out entry)) return false; offset += entry.Length; return true; } internal void Write(byte[] buffer, ref int offset) { ByteArrayExtensions.Write(buffer, offset, (ushort) this.AddressFamily, Endianity.Big); ByteArrayExtensions.Write(buffer, offset + 2, this.PayloadOffset); ByteArrayExtensions.Write(buffer, offset + 3, this.PayloadLength); this.WritePayload(buffer, offset + 4); offset += this.Length; } private static bool TryReadEntry(byte[] buffer, int payloadOffset, int payloadLength, GreSourceRouteEntryAddressFamily addressFamily, int offsetInPayload, out GreSourceRouteEntry entry) { entry = (GreSourceRouteEntry) null; switch (addressFamily) { case GreSourceRouteEntryAddressFamily.IpSourceRoute: if (offsetInPayload % 4 != 0 || payloadLength % 4 != 0) return false; int length1 = payloadLength / 4; IpV4Address[] addresses = new IpV4Address[length1]; for (int index = 0; index != length1; ++index) addresses[index] = ByteArrayExtensions.ReadIpV4Address(buffer, payloadOffset + index * 4, Endianity.Big); entry = (GreSourceRouteEntry) new GreSourceRouteEntryIp(addresses, offsetInPayload / 4); return true; case GreSourceRouteEntryAddressFamily.AsSourceRoute: if (offsetInPayload % 2 != 0 || payloadLength % 2 != 0) return false; int length2 = payloadLength / 2; ushort[] asNumbers = new ushort[length2]; for (int index = 0; index != length2; ++index) asNumbers[index] = ByteArrayExtensions.ReadUShort(buffer, payloadOffset + index * 2, Endianity.Big); entry = (GreSourceRouteEntry) new GreSourceRouteEntryAs(asNumbers, offsetInPayload / 2); return true; default: Datagram data = new Datagram(buffer, payloadOffset, payloadLength); entry = (GreSourceRouteEntry) new GreSourceRouteEntryUnknown(addressFamily, data, offsetInPayload); return true; } } private static class Offset { public const int AddressFamily = 0; public const int SreOffset = 2; public const int SreLength = 3; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataAfsDatabase // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.AfsDatabase)] public sealed class DnsResourceDataAfsDatabase : DnsResourceDataUShortDomainName { public DnsAfsDatabaseSubtype Subtype { get { return (DnsAfsDatabaseSubtype) this.Value; } } public DnsDomainName HostName { get { return this.DomainName; } } public DnsResourceDataAfsDatabase(DnsAfsDatabaseSubtype subtype, DnsDomainName hostName) : base((ushort) subtype, hostName) { } internal DnsResourceDataAfsDatabase() : this(DnsAfsDatabaseSubtype.None, DnsDomainName.Root) { } internal override DnsResourceData CreateInstance(DnsDatagram dns, int offsetInDns, int length) { ushort num; DnsDomainName domainName; if (!DnsResourceDataUShortDomainName.TryRead(out num, out domainName, dns, offsetInDns, length)) return (DnsResourceData) null; return (DnsResourceData) new DnsResourceDataAfsDatabase((DnsAfsDatabaseSubtype) num, domainName); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.MarshalingServices // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using PcapDotNet.Base; using std; using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace PcapDotNet.Core { internal class MarshalingServices { [DebuggerNonUserCode] private MarshalingServices() { } public static unsafe basic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E* ManagedToUnmanagedString([In] basic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E* obj0, string managedString) { uint num1 = 0U; uint num2; if (string.IsNullOrEmpty(managedString)) { *(long*) ((IntPtr) obj0 + 24L) = 15L; *(long*) ((IntPtr) obj0 + 16L) = 0L; *(sbyte*) obj0 = (sbyte) 0; // ISSUE: fault handler try { num1 = 1U; return obj0; } __fault { if (((int) num1 & 1) != 0) { num2 = num1 & 4294967294U; // ISSUE: method pointer // ISSUE: cast to a function pointer type \u003CModule\u003E.___CxxCallUnwindDtor((__FnPtr<void (void*)>) __methodptr(std\u002Ebasic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E\u002E\u007Bdtor\u007D), (void*) obj0); } } } else { fixed (byte* numPtr1 = &EncodingExtensions.Iso88591.GetBytes(managedString)[0]) { basic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E stdAllocatorChar; // ISSUE: cast to a reference type // ISSUE: explicit reference operation ^(long&) ((IntPtr) &stdAllocatorChar + 24) = 15L; // ISSUE: cast to a reference type // ISSUE: explicit reference operation ^(long&) ((IntPtr) &stdAllocatorChar + 16) = 0L; // ISSUE: explicit reference operation // ISSUE: cast to a reference type // ISSUE: explicit reference operation ^(sbyte&) @stdAllocatorChar = (sbyte) 0; byte* numPtr2 = numPtr1; if ((int) (sbyte) *numPtr1 != 0) { do { ++numPtr2; } while ((int) (sbyte) *numPtr2 != 0); } long num3 = (long) ((IntPtr) numPtr2 - (IntPtr) numPtr1); \u003CModule\u003E.std\u002Ebasic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E\u002Eassign(&stdAllocatorChar, (sbyte*) numPtr1, (ulong) num3); // ISSUE: fault handler try { // ISSUE: fault handler try { *(long*) ((IntPtr) obj0 + 24L) = 15L; *(long*) ((IntPtr) obj0 + 16L) = 0L; *(sbyte*) obj0 = (sbyte) 0; \u003CModule\u003E.std\u002Ebasic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E\u002Eassign(obj0, &stdAllocatorChar); num1 = 1U; } __fault { // ISSUE: method pointer // ISSUE: cast to a function pointer type \u003CModule\u003E.___CxxCallUnwindDtor((__FnPtr<void (void*)>) __methodptr(std\u002Ebasic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E\u002E\u007Bdtor\u007D), (void*) &stdAllocatorChar); } // ISSUE: cast to a reference type // ISSUE: explicit reference operation if (16UL <= (ulong) ^(long&) ((IntPtr) &stdAllocatorChar + 24)) { // ISSUE: explicit reference operation // ISSUE: cast to a reference type // ISSUE: explicit reference operation \u003CModule\u003E.delete((void*) ^(long&) @stdAllocatorChar); } // ISSUE: cast to a reference type // ISSUE: explicit reference operation ^(long&) ((IntPtr) &stdAllocatorChar + 24) = 15L; // ISSUE: cast to a reference type // ISSUE: explicit reference operation ^(long&) ((IntPtr) &stdAllocatorChar + 16) = 0L; // ISSUE: explicit reference operation // ISSUE: cast to a reference type // ISSUE: explicit reference operation ^(sbyte&) @stdAllocatorChar = (sbyte) 0; return obj0; } __fault { if (((int) num1 & 1) != 0) { num2 = num1 & 4294967294U; // ISSUE: method pointer // ISSUE: cast to a function pointer type \u003CModule\u003E.___CxxCallUnwindDtor((__FnPtr<void (void*)>) __methodptr(std\u002Ebasic_string\u003Cchar\u002Cstd\u003A\u003Achar_traits\u003Cchar\u003E\u002Cstd\u003A\u003Aallocator\u003Cchar\u003E\u0020\u003E\u002E\u007Bdtor\u007D), (void*) obj0); } } } } } public static unsafe basic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E* ManagedToUnmanagedWideString([In] basic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E* obj0, string managedString) { uint num1 = 0U; uint num2; if (string.IsNullOrEmpty(managedString)) { *(long*) ((IntPtr) obj0 + 24L) = 7L; *(long*) ((IntPtr) obj0 + 16L) = 0L; *(short*) obj0 = (short) 0; // ISSUE: fault handler try { num1 = 1U; return obj0; } __fault { if (((int) num1 & 1) != 0) { num2 = num1 & 4294967294U; // ISSUE: method pointer // ISSUE: cast to a function pointer type \u003CModule\u003E.___CxxCallUnwindDtor((__FnPtr<void (void*)>) __methodptr(std\u002Ebasic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E\u002E\u007Bdtor\u007D), (void*) obj0); } } } else { // ISSUE: cast to a reference type // ISSUE: variable of a reference type byte& local = (byte&) managedString; if (local != null) local = (long) (uint) RuntimeHelpers.OffsetToStringData + local; // ISSUE: explicit reference operation fixed (byte* numPtr = &^local) { basic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E stdAllocatorWcharT; // ISSUE: cast to a reference type // ISSUE: explicit reference operation ^(long&) ((IntPtr) &stdAllocatorWcharT + 24) = 7L; // ISSUE: cast to a reference type // ISSUE: explicit reference operation ^(long&) ((IntPtr) &stdAllocatorWcharT + 16) = 0L; // ISSUE: explicit reference operation // ISSUE: cast to a reference type // ISSUE: explicit reference operation ^(short&) @stdAllocatorWcharT = (short) 0; char* chPtr = (char*) numPtr; if ((int) (short) *(char*) numPtr != 0) { do { chPtr += 2L; } while ((int) (short) *chPtr != 0); } ulong _Count = (ulong) ((IntPtr) chPtr - (IntPtr) numPtr >> 1); \u003CModule\u003E.std\u002Ebasic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E\u002Eassign(&stdAllocatorWcharT, (char*) numPtr, _Count); // ISSUE: fault handler try { // ISSUE: fault handler try { *(long*) ((IntPtr) obj0 + 24L) = 7L; *(long*) ((IntPtr) obj0 + 16L) = 0L; *(short*) obj0 = (short) 0; \u003CModule\u003E.std\u002Ebasic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E\u002Eassign(obj0, &stdAllocatorWcharT); num1 = 1U; } __fault { // ISSUE: method pointer // ISSUE: cast to a function pointer type \u003CModule\u003E.___CxxCallUnwindDtor((__FnPtr<void (void*)>) __methodptr(std\u002Ebasic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E\u002E\u007Bdtor\u007D), (void*) &stdAllocatorWcharT); } // ISSUE: cast to a reference type // ISSUE: explicit reference operation if (8UL <= (ulong) ^(long&) ((IntPtr) &stdAllocatorWcharT + 24)) { // ISSUE: explicit reference operation // ISSUE: cast to a reference type // ISSUE: explicit reference operation \u003CModule\u003E.delete((void*) ^(long&) @stdAllocatorWcharT); } // ISSUE: cast to a reference type // ISSUE: explicit reference operation ^(long&) ((IntPtr) &stdAllocatorWcharT + 24) = 7L; // ISSUE: cast to a reference type // ISSUE: explicit reference operation ^(long&) ((IntPtr) &stdAllocatorWcharT + 16) = 0L; // ISSUE: explicit reference operation // ISSUE: cast to a reference type // ISSUE: explicit reference operation ^(short&) @stdAllocatorWcharT = (short) 0; return obj0; } __fault { if (((int) num1 & 1) != 0) { num2 = num1 & 4294967294U; // ISSUE: method pointer // ISSUE: cast to a function pointer type \u003CModule\u003E.___CxxCallUnwindDtor((__FnPtr<void (void*)>) __methodptr(std\u002Ebasic_string\u003Cwchar_t\u002Cstd\u003A\u003Achar_traits\u003Cwchar_t\u003E\u002Cstd\u003A\u003Aallocator\u003Cwchar_t\u003E\u0020\u003E\u002E\u007Bdtor\u007D), (void*) obj0); } } } } } public static unsafe byte[] UnamangedToManagedByteArray(byte* unmanagedByteArray, int offset, int count) { byte[] destination = new byte[count]; Marshal.Copy((IntPtr) ((void*) unmanagedByteArray), destination, offset, count); return destination; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Base.TimeSpanExtensions // Assembly: PcapDotNet.Base, Version=0.10.0.20668, Culture=neutral, PublicKeyToken=<KEY> // MVID: E9656A63-0145-422C-B8C8-79FDD7FB4270 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Base.dll using System; namespace PcapDotNet.Base { public static class TimeSpanExtensions { public const long TicksPerMicrosecond = 10L; public static TimeSpan Divide(this TimeSpan timeSpan, double value) { return TimeSpan.FromTicks((long) ((double) timeSpan.Ticks / value)); } public static TimeSpan Multiply(this TimeSpan timeSpan, double value) { return TimeSpan.FromTicks((long) ((double) timeSpan.Ticks * value)); } } } <file_sep>using Grib.Api.Interop.SWIG; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Grib.Api.Tests { [TestFixture] public class IterateValues { [Test] public void TestIterateKeyValuePairs () { using(var file = new GribFile(Settings.BIN)) { Assert.IsTrue(file.MessageCount > 0); Assert.IsTrue(file.First().Any()); } } [Test] public void TestIterateLatLong () { Console.WriteLine(); using (var file = new GribFile(Settings.REDUCED_LATLON_GRB2)) { Assert.IsTrue(file.MessageCount > 0); foreach (var msg in file) { int c = msg.Count(); msg.Namespace = "geography"; Assert.AreNotEqual(c, msg.Count()); Assert.IsTrue(msg.GeoSpatialValues.Any()); } } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Ethernet.EthernetLayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; namespace PcapDotNet.Packets.Ethernet { public sealed class EthernetLayer : EthernetBaseLayer { public MacAddress Source { get; set; } public MacAddress Destination { get; set; } public override int Length { get { return 14; } } public override DataLinkKind? DataLink { get { return new DataLinkKind?(DataLinkKind.Ethernet); } } public EthernetLayer() { this.Source = MacAddress.Zero; this.Destination = MacAddress.Zero; } public override void Write(byte[] buffer, int offset, int payloadLength, ILayer previousLayer, ILayer nextLayer) { EthernetType ethernetType = EthernetBaseLayer.GetEthernetType(this.EtherType, nextLayer); MacAddress destination = this.Destination; IEthernetNextLayer ethernetNextLayer = nextLayer as IEthernetNextLayer; if (destination == MacAddress.Zero && ethernetNextLayer != null && ethernetNextLayer.PreviousLayerDefaultDestination.HasValue) destination = ethernetNextLayer.PreviousLayerDefaultDestination.Value; EthernetDatagram.WriteHeader(buffer, offset, this.Source, destination, ethernetType); } public bool Equals(EthernetLayer other) { if (other != null && this.Source == other.Source && this.Destination == other.Destination) return this.EtherType == other.EtherType; return false; } public override bool Equals(Layer other) { return this.Equals(other as EthernetLayer); } public override int GetHashCode() { return base.GetHashCode() ^ Sequence.GetHashCode((object) this.Source, (object) this.Destination, (object) this.EtherType); } public override string ToString() { return (string) (object) this.Source + (object) " -> " + (string) (object) this.Destination + " (" + (string) (object) this.EtherType + ")"; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Igmp.IgmpQueryVersion1Layer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Igmp { public sealed class IgmpQueryVersion1Layer : IgmpVersion1Layer { public override IgmpMessageType MessageType { get { return IgmpMessageType.MembershipQuery; } } public override IgmpQueryVersion QueryVersion { get { return IgmpQueryVersion.Version1; } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataHostIdentityProtocol // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.Hip)] public sealed class DnsResourceDataHostIdentityProtocol : DnsResourceDataNoCompression, IEquatable<DnsResourceDataHostIdentityProtocol> { private const int ConstantPartLength = 4; public DataSegment HostIdentityTag { get; private set; } public DnsPublicKeyAlgorithm PublicKeyAlgorithm { get; private set; } public DataSegment PublicKey { get; private set; } public ReadOnlyCollection<DnsDomainName> RendezvousServers { get; private set; } public DnsResourceDataHostIdentityProtocol(DataSegment hostIdentityTag, DnsPublicKeyAlgorithm publicKeyAlgorithm, DataSegment publicKey, IEnumerable<DnsDomainName> rendezvousServers) { if (hostIdentityTag == null) throw new ArgumentNullException("hostIdentityTag"); if (publicKey == null) throw new ArgumentNullException("publicKey"); if (hostIdentityTag.Length > (int) byte.MaxValue) throw new ArgumentOutOfRangeException("hostIdentityTag", (object) hostIdentityTag.Length, string.Format((IFormatProvider) CultureInfo.InvariantCulture, "Cannot be bigger than {0}.", new object[1] { (object) byte.MaxValue })); if (publicKey.Length > (int) ushort.MaxValue) throw new ArgumentOutOfRangeException("publicKey", (object) publicKey.Length, string.Format((IFormatProvider) CultureInfo.InvariantCulture, "Cannot be bigger than {0}.", new object[1] { (object) ushort.MaxValue })); this.HostIdentityTag = hostIdentityTag; this.PublicKeyAlgorithm = publicKeyAlgorithm; this.PublicKey = publicKey; this.RendezvousServers = IListExtensions.AsReadOnly<DnsDomainName>((IList<DnsDomainName>) Enumerable.ToArray<DnsDomainName>(rendezvousServers)); } internal DnsResourceDataHostIdentityProtocol() : this(DataSegment.Empty, DnsPublicKeyAlgorithm.None, DataSegment.Empty, (IEnumerable<DnsDomainName>) new DnsDomainName[0]) { } public bool Equals(DnsResourceDataHostIdentityProtocol other) { if (other != null && this.HostIdentityTag.Equals(other.HostIdentityTag) && (this.PublicKeyAlgorithm.Equals((object) other.PublicKeyAlgorithm) && this.PublicKey.Equals(other.PublicKey))) return Enumerable.SequenceEqual<DnsDomainName>((IEnumerable<DnsDomainName>) this.RendezvousServers, (IEnumerable<DnsDomainName>) this.RendezvousServers); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataHostIdentityProtocol); } public override int GetHashCode() { return Sequence.GetHashCode((object) this.HostIdentityTag, (object) this.PublicKeyAlgorithm, (object) this.PublicKey) ^ IEnumerableExtensions.SequenceGetHashCode<DnsDomainName>((IEnumerable<DnsDomainName>) this.RendezvousServers); } internal override int GetLength() { return 4 + this.HostIdentityTag.Length + this.PublicKey.Length + Enumerable.Sum<DnsDomainName>((IEnumerable<DnsDomainName>) this.RendezvousServers, (Func<DnsDomainName, int>) (rendezvousServer => rendezvousServer.NonCompressedLength)); } internal override int WriteData(byte[] buffer, int offset) { ByteArrayExtensions.Write(buffer, offset, (byte) this.HostIdentityTag.Length); ByteArrayExtensions.Write(buffer, offset + 1, (byte) this.PublicKeyAlgorithm); ByteArrayExtensions.Write(buffer, offset + 2, (ushort) this.PublicKey.Length, Endianity.Big); this.HostIdentityTag.Write(buffer, offset + 4); int num1 = 4 + this.HostIdentityTag.Length; this.PublicKey.Write(buffer, offset + num1); int num2 = num1 + this.PublicKey.Length; foreach (DnsDomainName dnsDomainName in this.RendezvousServers) { dnsDomainName.WriteUncompressed(buffer, offset + num2); num2 += dnsDomainName.NonCompressedLength; } return num2; } internal override DnsResourceData CreateInstance(DnsDatagram dns, int offsetInDns, int length) { if (length < 4) return (DnsResourceData) null; int length1 = (int) dns[offsetInDns]; DnsPublicKeyAlgorithm publicKeyAlgorithm = (DnsPublicKeyAlgorithm) dns[offsetInDns + 1]; int length2 = (int) dns.ReadUShort(offsetInDns + 2, Endianity.Big); if (length < 4 + length1 + length2) return (DnsResourceData) null; DataSegment hostIdentityTag = dns.Subsegment(offsetInDns + 4, length1); int offset = offsetInDns + 4 + length1; DataSegment publicKey = dns.Subsegment(offset, length2); offsetInDns += 4 + length1 + length2; length -= 4 + length1 + length2; List<DnsDomainName> list = new List<DnsDomainName>(); while (length != 0) { DnsDomainName domainName; int numBytesRead; if (!DnsDomainName.TryParse(dns, offsetInDns, length, out domainName, out numBytesRead)) return (DnsResourceData) null; list.Add(domainName); offsetInDns += numBytesRead; length -= numBytesRead; } return (DnsResourceData) new DnsResourceDataHostIdentityProtocol(hostIdentityTag, publicKeyAlgorithm, publicKey, (IEnumerable<DnsDomainName>) list); } private static class Offset { public const int HostIdentityTagLength = 0; public const int PublicKeyAlgorithm = 1; public const int PublicKeyLength = 2; public const int HostIdentityTag = 4; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace PcapDotNet.Packets.Dns { public sealed class DnsDatagram : Datagram { public const int HeaderLength = 12; private ReadOnlyCollection<DnsQueryResourceRecord> _queries; private ReadOnlyCollection<DnsDataResourceRecord> _answers; private ReadOnlyCollection<DnsDataResourceRecord> _authorities; private ReadOnlyCollection<DnsDataResourceRecord> _additionals; private DnsOptResourceRecord _options; private int _answersOffset; private int _authoritiesOffset; private int _additionalsOffset; private bool? _isValid; public ushort Id { get { return this.ReadUShort(0, Endianity.Big); } } public bool IsResponse { get { return this.ReadBool(2, (byte) sbyte.MinValue); } } public bool IsQuery { get { return !this.IsResponse; } } public DnsOpCode OpCode { get { return (DnsOpCode) (((int) this[2] & 120) >> 3); } } public bool IsAuthoritativeAnswer { get { return this.ReadBool(2, (byte) 4); } } public bool IsTruncated { get { return this.ReadBool(2, (byte) 2); } } public bool IsRecursionDesired { get { return this.ReadBool(2, (byte) 1); } } public bool IsRecursionAvailable { get { return this.ReadBool(3, (byte) sbyte.MinValue); } } public bool FutureUse { get { return this.ReadBool(3, (byte) 64); } } public bool IsAuthenticData { get { return this.ReadBool(3, (byte) 32); } } public bool IsCheckingDisabled { get { return this.ReadBool(3, (byte) 16); } } public DnsResponseCode ResponseCode { get { return (DnsResponseCode) ((uint) this[3] & 15U); } } public ushort QueryCount { get { return this.ReadUShort(4, Endianity.Big); } } public ushort AnswerCount { get { return this.ReadUShort(6, Endianity.Big); } } public ushort AuthorityCount { get { return this.ReadUShort(8, Endianity.Big); } } public ushort AdditionalCount { get { return this.ReadUShort(10, Endianity.Big); } } public ReadOnlyCollection<DnsQueryResourceRecord> Queries { get { this.ParseQueries(); return this._queries; } } public ReadOnlyCollection<DnsDataResourceRecord> Answers { get { this.ParseAnswers(); return this._answers; } } public ReadOnlyCollection<DnsDataResourceRecord> Authorities { get { this.ParseAuthorities(); return this._authorities; } } public ReadOnlyCollection<DnsDataResourceRecord> Additionals { get { this.ParseAdditionals(); return this._additionals; } } public IEnumerable<DnsResourceRecord> ResourceRecords { get { return Enumerable.Concat<DnsResourceRecord>(Enumerable.Cast<DnsResourceRecord>((IEnumerable) this.Queries), (IEnumerable<DnsResourceRecord>) this.DataResourceRecords); } } public IEnumerable<DnsDataResourceRecord> DataResourceRecords { get { return Enumerable.Concat<DnsDataResourceRecord>(Enumerable.Concat<DnsDataResourceRecord>((IEnumerable<DnsDataResourceRecord>) this.Answers, (IEnumerable<DnsDataResourceRecord>) this.Authorities), (IEnumerable<DnsDataResourceRecord>) this.Additionals); } } public DnsOptResourceRecord OptionsRecord { get { this.ParseAdditionals(); return this._options; } } private int AnswersOffset { get { this.ParseQueries(); return this._answersOffset; } } private int AuthoritiesOffset { get { this.ParseAnswers(); return this._authoritiesOffset; } } private int AdditionalsOffset { get { this.ParseAuthorities(); return this._additionalsOffset; } } internal DnsDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public override ILayer ExtractLayer() { return (ILayer) new DnsLayer() { Id = this.Id, IsQuery = this.IsQuery, OpCode = this.OpCode, IsAuthoritativeAnswer = this.IsAuthoritativeAnswer, IsTruncated = this.IsTruncated, IsRecursionDesired = this.IsRecursionDesired, IsRecursionAvailable = this.IsRecursionAvailable, FutureUse = this.FutureUse, IsAuthenticData = this.IsAuthenticData, IsCheckingDisabled = this.IsCheckingDisabled, ResponseCode = this.ResponseCode, Queries = (IList<DnsQueryResourceRecord>) Enumerable.ToList<DnsQueryResourceRecord>((IEnumerable<DnsQueryResourceRecord>) this.Queries), Answers = (IList<DnsDataResourceRecord>) Enumerable.ToList<DnsDataResourceRecord>((IEnumerable<DnsDataResourceRecord>) this.Answers), Authorities = (IList<DnsDataResourceRecord>) Enumerable.ToList<DnsDataResourceRecord>((IEnumerable<DnsDataResourceRecord>) this.Authorities), Additionals = (IList<DnsDataResourceRecord>) Enumerable.ToList<DnsDataResourceRecord>((IEnumerable<DnsDataResourceRecord>) this.Additionals) }; } protected override bool CalculateIsValid() { if (!this._isValid.HasValue) this._isValid = new bool?(this.Length >= 12 && (int) this.QueryCount == this.Queries.Count && ((int) this.AnswerCount == this.Answers.Count && (int) this.AuthorityCount == this.Authorities.Count) && (int) this.AdditionalCount == this.Additionals.Count); return this._isValid.Value; } internal static int GetLength(IEnumerable<DnsResourceRecord> resourceRecords, DnsDomainNameCompressionMode domainNameCompressionMode) { int offsetInDns = 12; DnsDomainNameCompressionData compressionData = new DnsDomainNameCompressionData(domainNameCompressionMode); if (resourceRecords != null) { foreach (DnsResourceRecord dnsResourceRecord in resourceRecords) offsetInDns += dnsResourceRecord.GetLength(compressionData, offsetInDns); } return offsetInDns; } internal static void Write(byte[] buffer, int offset, ushort id, bool isResponse, DnsOpCode opCode, bool isAuthoritiveAnswer, bool isTruncated, bool isRecursionDesired, bool isRecursionAvailable, bool futureUse, bool isAuthenticData, bool isCheckingDisabled, DnsResponseCode responseCode, IList<DnsQueryResourceRecord> queries, IList<DnsDataResourceRecord> answers, IList<DnsDataResourceRecord> authorities, IList<DnsDataResourceRecord> additionals, DnsDomainNameCompressionMode domainNameCompressionMode) { ByteArrayExtensions.Write(buffer, offset, id, Endianity.Big); byte num1 = (byte) 0; if (isResponse) num1 |= (byte) sbyte.MinValue; byte num2 = (byte) ((uint) num1 | (uint) (byte) ((int) opCode << 3 & 120)); if (isAuthoritiveAnswer) num2 |= (byte) 4; if (isTruncated) num2 |= (byte) 2; if (isRecursionDesired) num2 |= (byte) 1; ByteArrayExtensions.Write(buffer, offset + 2, num2); byte num3 = (byte) 0; if (isRecursionAvailable) num3 |= (byte) sbyte.MinValue; if (futureUse) num3 |= (byte) 64; if (isAuthenticData) num3 |= (byte) 32; if (isCheckingDisabled) num3 |= (byte) 16; byte num4 = (byte) ((uint) num3 | (uint) (byte) (responseCode & (DnsResponseCode) 15)); ByteArrayExtensions.Write(buffer, offset + 3, num4); DnsDomainNameCompressionData compressionData = new DnsDomainNameCompressionData(domainNameCompressionMode); int offsetInDns = 12; if (queries != null) { ByteArrayExtensions.Write(buffer, offset + 4, (ushort) queries.Count, Endianity.Big); foreach (DnsQueryResourceRecord queryResourceRecord in (IEnumerable<DnsQueryResourceRecord>) queries) offsetInDns += queryResourceRecord.Write(buffer, offset, compressionData, offsetInDns); } if (answers != null) { ByteArrayExtensions.Write(buffer, offset + 6, (ushort) answers.Count, Endianity.Big); foreach (DnsDataResourceRecord dataResourceRecord in (IEnumerable<DnsDataResourceRecord>) answers) offsetInDns += dataResourceRecord.Write(buffer, offset, compressionData, offsetInDns); } if (authorities != null) { ByteArrayExtensions.Write(buffer, offset + 8, (ushort) authorities.Count, Endianity.Big); foreach (DnsDataResourceRecord dataResourceRecord in (IEnumerable<DnsDataResourceRecord>) authorities) offsetInDns += dataResourceRecord.Write(buffer, offset, compressionData, offsetInDns); } if (additionals == null) return; ByteArrayExtensions.Write(buffer, offset + 10, (ushort) additionals.Count, Endianity.Big); foreach (DnsDataResourceRecord dataResourceRecord in (IEnumerable<DnsDataResourceRecord>) additionals) offsetInDns += dataResourceRecord.Write(buffer, offset, compressionData, offsetInDns); } private void ParseQueries() { this.ParseRecords<DnsQueryResourceRecord>(12, (Func<ushort>) (() => this.QueryCount), new DnsDatagram.ParseRecord<DnsQueryResourceRecord>(DnsQueryResourceRecord.Parse), ref this._queries, ref this._answersOffset); } private void ParseAnswers() { this.ParseRecords<DnsDataResourceRecord>(this.AnswersOffset, (Func<ushort>) (() => this.AnswerCount), new DnsDatagram.ParseRecord<DnsDataResourceRecord>(DnsDataResourceRecord.Parse), ref this._answers, ref this._authoritiesOffset); } private void ParseAuthorities() { this.ParseRecords<DnsDataResourceRecord>(this.AuthoritiesOffset, (Func<ushort>) (() => this.AuthorityCount), new DnsDatagram.ParseRecord<DnsDataResourceRecord>(DnsDataResourceRecord.Parse), ref this._authorities, ref this._additionalsOffset); } private void ParseAdditionals() { int nextOffset = 0; if (!this.ParseRecords<DnsDataResourceRecord>(this.AdditionalsOffset, (Func<ushort>) (() => this.AdditionalCount), new DnsDatagram.ParseRecord<DnsDataResourceRecord>(DnsDataResourceRecord.Parse), ref this._additionals, ref nextOffset) || this._additionals == null) return; this._options = (DnsOptResourceRecord) Enumerable.FirstOrDefault<DnsDataResourceRecord>((IEnumerable<DnsDataResourceRecord>) this._additionals, (Func<DnsDataResourceRecord, bool>) (additional => additional.DnsType == DnsType.Opt)); } private bool ParseRecords<TRecord>(int offset, Func<ushort> countDelegate, DnsDatagram.ParseRecord<TRecord> parseRecord, ref ReadOnlyCollection<TRecord> parsedRecords, ref int nextOffset) where TRecord : DnsResourceRecord { if (parsedRecords != null || this.Length < offset) return false; ushort num = countDelegate(); List<TRecord> list = new List<TRecord>((int) num); for (int index = 0; index != (int) num; ++index) { int numBytesRead; TRecord record = parseRecord(this, offset, out numBytesRead); if ((object) record == null) { offset = 0; break; } list.Add(record); offset += numBytesRead; } parsedRecords = new ReadOnlyCollection<TRecord>((IList<TRecord>) list.ToArray()); nextOffset = offset; return true; } private static class Offset { public const int Id = 0; public const int IsResponse = 2; public const int OpCode = 2; public const int IsAuthoritiveAnswer = 2; public const int IsTruncated = 2; public const int IsRecusionDesired = 2; public const int IsRecusionAvailable = 3; public const int FutureUse = 3; public const int IsAuthenticData = 3; public const int IsCheckingDisabled = 3; public const int ResponseCode = 3; public const int QueryCount = 4; public const int AnswerCount = 6; public const int AuthorityCount = 8; public const int AdditionalCount = 10; public const int Query = 12; } private static class Mask { public const byte IsResponse = (byte) 128; public const byte OpCode = (byte) 120; public const byte IsAuthoritiveAnswer = (byte) 4; public const byte IsTruncated = (byte) 2; public const byte IsRecusionDesired = (byte) 1; public const byte IsRecursionAvailable = (byte) 128; public const byte FutureUse = (byte) 64; public const byte IsAuthenticData = (byte) 32; public const byte IsCheckingDisabled = (byte) 16; public const ushort ResponseCode = (ushort) 15; } private static class Shift { public const int OpCode = 3; } private delegate TRecord ParseRecord<out TRecord>(DnsDatagram dns, int offset, out int numBytesRead); } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IpV4Protocol // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.IpV4 { public enum IpV4Protocol : byte { IpV6HopByHopOption, InternetControlMessageProtocol, InternetGroupManagementProtocol, GatewayToGateway, Ip, Stream, Tcp, Cbt, ExteriorGatewayProtocol, InteriorGatewayProtocol, BbnRccMonitoring, NetworkVoice, Pup, Argus, Emcon, CrossNetDebugger, Chaos, Udp, Multiplexing, DcnMeasurement, HostMonitoringProtocol, PacketRadioMeasurement, XeroxNsInternetDatagramProtocol, Trunk1, Trunk2, Leaf1, Leaf2, ReliableDatagramProtocol, InternetReliableTransactionProtocol, IsoTransportProtocolClass4, BulkDataTransferProtocol, MagneticFusionEnergyNetworkServicesProtocol, MeritInternodalProtocol, DatagramCongestionControlProtocol, ThirdPartyConnect, InterDomainPolicyRoutingProtocol, XpressTransportProtocol, DatagramDeliveryProtocol, InterDomainPolicyRoutingProtocolControlMessageTransportProtocol, TransportProtocolPlusPlus, Il, IpV6, SourceDemandRoutingProtocol, IpV6Route, FragmentHeaderForIpV6, InterDomainRoutingProtocol, Rsvp, Gre, MobileHostRoutingProtocol, Bna, Esp, AuthenticationHeader, IntegratedNetLayerSecurityProtocol, Swipe, NArp, Mobile, TransportLayerSecurityProtocol, Skip, InternetControlMessageProtocolForIpV6, NoNextHeaderForIpV6, IpV6Opts, AnyHostInternal, Cftp, AnyLocalNetwork, SatnetAndBackroomExpak, Kryptolan, RemoteVirtualDiskProtocol, InternetPluribusPacketCore, AnyDistributedFileSystem, SatMon, Visa, InternetPacketCoreUtility, ComputerProtocolNetworkExecutive, ComputerProtocolHeartbeat, WangSpanNetwork, PacketVideoProtocol, BackroomSatMon, SunNd, WidebandMonitoring, WidebandExpak, IsoIp, VersatileMessageTransactionProtocol, SecureVersatileMessageTransactionProtocol, Vines, Ttp, NationalScienceFoundationNetworkInteriorGatewayProtocol, DissimilarGatewayProtocol, Tcf, EnhancedInteriorGatewayRoutingProtocol, OpenShortestPathFirst, SpriteRpc, LArp, MulticastTransportProtocol, Ax25, IpIp, MobileInternetworkingControlProtocol, SemaphoreCommunicationsSecondProtocol, EtherIp, EncapsulationHeader, AnyPrivateEncryptionScheme, Gmtp, IpsilonFlowManagementProtocol, PrivateNetworkToNetworkInterface, Pin, Aris, SpaceCommunicationsProtocolStandards, Qnx, ActiveNetworks, IpComp, SitaraNetworksProtocol, CompaqPeer, InternetworkPacketExchangeInIp, VirtualRouterRedundancyProtocol, PragmaticGeneralMulticastTransportProtocol, Any0HopProtocol, LayerTwoTunnelingProtocol, DiiDataExchange, InteractiveAgentTransferProtocol, ScheduleTransferProtocol, SpectraLinkRadioProtocol, Uti, SimpleMessageProtocol, Sm, PerformanceTransparencyProtocol, IsIsOverIpV4, Fire, CombatRadioTransportProtocol, CombatRadioUserDatagram, ServiceSpecificConnectionOrientedProtocolInAMultilinkAndConnectionlessEnvironment, Iplt, SecurePacketShield, Pipe, StreamControlTransmissionProtocol, FibreChannel, RsvpE2EIgnore, MobilityHeader, UdpLite, MultiprotocolLabelSwitchingInIp, MobileAdHocNetwork, Hip, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.AddressFamily // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets { public enum AddressFamily : ushort { None = (ushort) 0, IpV4 = (ushort) 1, IpV6 = (ushort) 2, NetworkServiceAccessPoint = (ushort) 3, HighLevelDataLink = (ushort) 4, Bbn1822 = (ushort) 5, Media802 = (ushort) 6, E163 = (ushort) 7, E164 = (ushort) 8, F69 = (ushort) 9, X121 = (ushort) 10, Ipx = (ushort) 11, AppleTalk = (ushort) 12, DecNetIv = (ushort) 13, BanyanVines = (ushort) 14, E164WithNetworkServiceAccessPointFormatSubaddresses = (ushort) 15, Dns = (ushort) 16, DistinguishedName = (ushort) 17, AsNumber = (ushort) 18, XtpOverIpV4 = (ushort) 19, XtpOverIpV6 = (ushort) 20, XtpNativeModeXtp = (ushort) 21, FibreChannelWorldwidePortName = (ushort) 22, FibreChannelWorldwideNodeName = (ushort) 23, Gwid = (ushort) 24, AfiForL2VpnInformation = (ushort) 25, EnhancedInteriorGatewayRoutingProtocolCommonServiceFamily = (ushort) 16384, EnhancedInteriorGatewayRoutingProtocolIpV4ServiceFamily = (ushort) 16385, EnhancedInteriorGatewayRoutingProtocolIpV6ServiceFamily = (ushort) 16386, LispCanonicalAddressFormat = (ushort) 16387, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsOptVersion // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Dns { public enum DnsOptVersion : byte { Version0, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.PcapError // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using System; using System.Diagnostics; using System.Text; namespace PcapDotNet.Core { internal class PcapError { [DebuggerNonUserCode] private PcapError() { } public static unsafe string GetErrorMessage(pcap* pcapDescriptor) { sbyte* numPtr = \u003CModule\u003E.pcap_geterr(pcapDescriptor); if ((IntPtr) numPtr == IntPtr.Zero) return (string) null; return new string(numPtr); } public static unsafe InvalidOperationException BuildInvalidOperation(string errorMessage, pcap* pcapDescriptor) { StringBuilder stringBuilder = new StringBuilder(errorMessage); if ((IntPtr) pcapDescriptor != IntPtr.Zero) { sbyte* numPtr = \u003CModule\u003E.pcap_geterr(pcapDescriptor); string str = (IntPtr) numPtr != IntPtr.Zero ? new string(numPtr) : (string) null; if (!string.IsNullOrEmpty(str)) { stringBuilder.Append(". WinPcap Error: "); stringBuilder.Append(str); } } return new InvalidOperationException(stringBuilder.ToString()); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataDelegationSigner // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.TrustAnchor)] [DnsTypeRegistration(Type = DnsType.DelegationSigner)] [DnsTypeRegistration(Type = DnsType.Cds)] [DnsTypeRegistration(Type = DnsType.DnsSecLookAsideValidation)] public sealed class DnsResourceDataDelegationSigner : DnsResourceDataSimple, IEquatable<DnsResourceDataDelegationSigner> { private const int ConstPartLength = 4; public ushort KeyTag { get; private set; } public DnsAlgorithm Algorithm { get; private set; } public DnsDigestType DigestType { get; private set; } public DataSegment Digest { get; private set; } public DataSegment ExtraDigest { get; private set; } public DnsResourceDataDelegationSigner(ushort keyTag, DnsAlgorithm algorithm, DnsDigestType digestType, DataSegment digest) { if (digest == null) throw new ArgumentNullException("digest"); this.KeyTag = keyTag; this.Algorithm = algorithm; this.DigestType = digestType; int val2; switch (this.DigestType) { case DnsDigestType.Sha1: val2 = 20; break; case DnsDigestType.Sha256: val2 = 32; break; default: val2 = int.MaxValue; break; } this.Digest = digest.Subsegment(0, Math.Min(digest.Length, val2)); this.ExtraDigest = digest.Subsegment(this.Digest.Length, digest.Length - this.Digest.Length); } internal DnsResourceDataDelegationSigner() : this((ushort) 0, DnsAlgorithm.None, DnsDigestType.Sha1, DataSegment.Empty) { } public bool Equals(DnsResourceDataDelegationSigner other) { if (other != null && (this.KeyTag.Equals(other.KeyTag) && this.Algorithm.Equals((object) other.Algorithm) && this.DigestType.Equals((object) other.DigestType))) return this.Digest.Equals(other.Digest); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataDelegationSigner); } public override int GetHashCode() { return Sequence.GetHashCode((object) BitSequence.Merge(this.KeyTag, (byte) this.Algorithm, (byte) this.DigestType), (object) this.Digest); } internal override int GetLength() { return 4 + this.Digest.Length; } internal override void WriteDataSimple(byte[] buffer, int offset) { ByteArrayExtensions.Write(buffer, offset, this.KeyTag, Endianity.Big); ByteArrayExtensions.Write(buffer, offset + 2, (byte) this.Algorithm); ByteArrayExtensions.Write(buffer, offset + 3, (byte) this.DigestType); this.Digest.Write(buffer, offset + 4); } internal override DnsResourceData CreateInstance(DataSegment data) { return (DnsResourceData) new DnsResourceDataDelegationSigner(data.ReadUShort(0, Endianity.Big), (DnsAlgorithm) data[2], (DnsDigestType) data[3], data.Subsegment(4, data.Length - 4)); } private static class Offset { public const int KeyTag = 0; public const int Algorithm = 2; public const int DigestType = 3; public const int Digest = 4; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.SamplingMethod // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll namespace PcapDotNet.Core { public abstract class SamplingMethod { internal abstract int Value { get; } internal abstract int Method { get; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.TcpOptionUnknown // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace PcapDotNet.Packets.Transport { public sealed class TcpOptionUnknown : TcpOptionComplex, IOptionUnknownFactory<TcpOptionType>, IEquatable<TcpOptionUnknown> { public const int OptionMinimumLength = 2; public const int OptionValueMinimumLength = 0; public ReadOnlyCollection<byte> Data { get; private set; } public override int Length { get { return 2 + this.Data.Count; } } public override bool IsAppearsAtMostOnce { get { return false; } } public TcpOptionUnknown(TcpOptionType optionType, IList<byte> data) : base(optionType) { this.Data = new ReadOnlyCollection<byte>(data); } public TcpOptionUnknown() : this((TcpOptionType) 255, (IList<byte>) new byte[0]) { } public bool Equals(TcpOptionUnknown other) { if (other == null || this.OptionType != other.OptionType) return false; return Enumerable.SequenceEqual<byte>((IEnumerable<byte>) this.Data, (IEnumerable<byte>) other.Data); } public override bool Equals(TcpOption other) { return this.Equals(other as TcpOptionUnknown); } public override int GetHashCode() { return base.GetHashCode() ^ IEnumerableExtensions.BytesSequenceGetHashCode((IEnumerable<byte>) this.Data); } public Option CreateInstance(TcpOptionType optionType, byte[] buffer, ref int offset, byte valueLength) { if ((int) valueLength < 0) return (Option) null; byte[] numArray = ByteArrayExtensions.ReadBytes(buffer, ref offset, (int) valueLength); return (Option) new TcpOptionUnknown(optionType, (IList<byte>) numArray); } internal override void Write(byte[] buffer, ref int offset) { base.Write(buffer, ref offset); ByteArrayExtensions.Write(buffer, ref offset, (IEnumerable<byte>) this.Data); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Igmp.IgmpReportVersion3Layer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Linq; namespace PcapDotNet.Packets.Igmp { public sealed class IgmpReportVersion3Layer : IgmpLayer { [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ReadOnlyCollection<IgmpGroupRecord> GroupRecords { get; set; } public override int Length { get { return IgmpDatagram.GetReportVersion3Length((IEnumerable<IgmpGroupRecord>) this.GroupRecords); } } public override IgmpMessageType MessageType { get { return IgmpMessageType.MembershipReportVersion3; } } public override TimeSpan MaxResponseTimeValue { get { return TimeSpan.Zero; } } public IgmpReportVersion3Layer() { this.GroupRecords = IListExtensions.AsReadOnly<IgmpGroupRecord>((IList<IgmpGroupRecord>) new IgmpGroupRecord[0]); } protected override void Write(byte[] buffer, int offset) { IgmpDatagram.WriteReportVersion3(buffer, offset, (IEnumerable<IgmpGroupRecord>) this.GroupRecords); } public override int GetHashCode() { return base.GetHashCode() ^ IEnumerableExtensions.SequenceGetHashCode<IgmpGroupRecord>((IEnumerable<IgmpGroupRecord>) this.GroupRecords); } protected override bool EqualFields(IgmpLayer other) { return this.EqualFields(other as IgmpReportVersion3Layer); } private bool EqualFields(IgmpReportVersion3Layer other) { if (other != null) return Enumerable.SequenceEqual<IgmpGroupRecord>((IEnumerable<IgmpGroupRecord>) this.GroupRecords, (IEnumerable<IgmpGroupRecord>) other.GroupRecords); return false; } } } <file_sep>using System; using System.Net; using OmnUtils; using System.Globalization; using log4net; namespace Weather.WundergroundAPI { // http://www.wunderground.com/weather/api/d/docs?d=data/conditions // PWS Update Protocol TO WUNDERGROUND.COM: // http://wiki.wunderground.com/index.php/PWS_-_Upload_Protocol // To upload a weather condition, you make a standard HTTP GET request with the ID, PASSWORD and weather conditions // as GET parameters. Here is the URL used in the uploading (if you browse here without parameters you will // get a brief usage): // http://weatherstation.wunderground.com/weatherstation/updateweatherstation.php // // GET parameters: // NOT all fields need to be set, the _required_ elements are: // action // ID // PASSWORD // dateutc // IMPORTANT: // - all fields must be url escaped // - no spaces or blanks, anywhere! // - excess values in baromin (inHg) will we dropped be WU // reference http://www.w3schools.com/tags/ref_urlencode.asp // Example of a full URL: // http://weatherstation.wunderground.com/weatherstation/updateweatherstation.php?ID=KCASANFR5&PASSWORD=<PASSWORD>&dateutc=2000-01-01+10%3A32%3A35&winddir=230&windspeedmph=12&windgustmph=12&tempf=70&rainin=0&baromin=29.1&dewptf=68.2&humidity=90&weather=&clouds=&softwaretype=vws%20versionxx&action=updateraw // List of fields: // ---------------- // action [action=updateraw] -- always supply this parameter to indicate you are making a weather observation upload // ID [ID as registered by wunderground.com] // PASSWORD [PASSWORD registered with this ID, case sensative] // dateutc - [YYYY-MM-DD HH:MM:SS (mysql format)] In Universal Coordinated Time (UTC) Not local time // winddir - [0-360 instantaneous wind direction] // windspeedmph - [mph instantaneous wind speed] // windgustmph - [mph current wind gust, using software specific time period] // windgustdir - [0-360 using software specific time period] // windspdmph_avg2m - [mph 2 minute average wind speed mph] // winddir_avg2m - [0-360 2 minute average wind direction] // windgustmph_10m - [mph past 10 minutes wind gust mph ] // windgustdir_10m - [0-360 past 10 minutes wind gust direction] // humidity - [% outdoor humidity 0-100%] // dewptf - [F outdoor dewpoint F] // tempf - [F outdoor temperature] // * for extra outdoor sensors use temp2f, temp3f, and so on // rainin - [rain inches over the past hour)] -- the accumulated rainfall in the past 60 min // dailyrainin - [rain inches so far today in local time] // baromin - [barometric pressure inches] // weather - [text] -- metar style (+RA) // clouds - [text] -- SKC, FEW, SCT, BKN, OVC // soiltempf - [F soil temperature] // * for sensors 2,3,4 use soiltemp2f, soiltemp3f, and soiltemp4f // soilmoisture - [%] // * for sensors 2,3,4 use soilmoisture2, soilmoisture3, and soilmoisture4 // leafwetness - [%] // + for sensor 2 use leafwetness2 // solarradiation - [W/m^2] // UV - [index] // visibility - [nm visibility] // indoortempf - [F indoor temperature F] // indoorhumidity - [% indoor humidity 0-100] // softwaretype - [text] ie: WeatherLink, VWS, WeatherDisplay // Pollution Fields: // see wiki: http://wiki.wunderground.com/index.php/PWS_-_Upload_Protocol // Response Text // The response from an HTTP GET request contains some debugging data. // Response -->> Meaning // "success" -->> The observation was ingested successfully // "INVALIDPASSWORDID|Password and/or id are incorrect" -->> Invalid user data entered in the ID and PASSWORD GET parameters // <b>RapidFire Server</b><br><br> -->> the minimum GET parameters ID, PASSWORD, action, and dateutc were not set // <b>usage</b><br> -->> // Automatically generate a WU station ID: // see wiki: http://wiki.wunderground.com/index.php/PWS_-_Upload_Protocol public class WUUpdateWeatherStationDto { #region log4net private static readonly ILog _logger = log4net.LogManager.GetLogger(typeof(WUUpdateWeatherStationDto)); private static readonly string _currTypeName = typeof(WUUpdateWeatherStationDto).Name; #endregion log4net private DateTime _dateUtc; public DateTime DateUtc { set { this._dateUtc = value; } } public string DateUtcGetStr { get { return "&dateutc=" + WebUtility.UrlEncode(this._dateUtc.ToString("yyyy-MM-dd HH:mm:ss")); } } private float? _tempf; // Temperature F public float? Tempf { set { this._tempf = value; } } public string TempfGetStr { get { if (this._tempf == null) return ""; return "&tempf=" + this._tempf.Value.ToString(CultureInfo.InvariantCulture); } } public float? _windSpeedMph; // Wind Speed Mph public float? WindSpeedMph { set { this._windSpeedMph = value; } } public string WindSpeedMphGetStr { get { if (this._windSpeedMph == null) return ""; return "&windspeedmph=" + this._windSpeedMph.Value.ToString(CultureInfo.InvariantCulture); } } public float? _windGustMph; // Wind Gust Mph public float? WindGustMph { set { this._windGustMph = value; } } public string WindGustMphGetStr { get { if (this._windGustMph == null) return ""; return "&windgustmph=" + this._windGustMph.Value.ToString(CultureInfo.InvariantCulture); } } public float? _windGustDir; // Wind Gust Dir public float? WindGustDir { set { this._windGustDir = value; } } public string WindGustDirGetStr { get { if (this._windGustDir == null) return ""; return "&windgustdir=" + this._windGustDir.Value.ToString(CultureInfo.InvariantCulture); } } public float? _windDir; // Wind Direction 0-360 public float? WindDir { set { this._windDir = value; } } public string WindDirGetStr { get { if (this._windDir == null) return ""; return "&winddir=" + this._windDir.Value.ToString(CultureInfo.InvariantCulture); } } public float? _humidity; //Humidity [% outdoor humidity 0-100%] public float? Humidity { set { this._humidity = value; } } public string HumidityGetStr { get { if (this._humidity == null) return ""; return "&humidity=" + this._humidity.Value.ToString(CultureInfo.InvariantCulture); } } public float? _rainIn; //Rainfall last hour public float? RainIn { set { this._rainIn = value; } } public string RainInGetStr { get { if (this._rainIn == null) return ""; return "&rainin=" + this._rainIn.Value.ToString(CultureInfo.InvariantCulture); } } public float? _dailyRainIn; //Rainfall 24hours public float? DailyRainIn { set { this._dailyRainIn = value; } } public string DailyRainInGetStr { get { if (this._dailyRainIn == null) return ""; return "&dailyrainin=" + this._dailyRainIn.Value.ToString(CultureInfo.InvariantCulture); } } public float? _dewPtF; //Dew Point F public float? DewPtF { set { this._dewPtF = value; } } public string DewPtFGetStr { get { if (this._dewPtF == null) return ""; return "&dewptf=" + this._dewPtF.Value.ToString(CultureInfo.InvariantCulture); } } public float? _baromIn; //Barometer In public float? BaromIn { set { this._baromIn = value; } } public string BaromInGetStr { get { if (this._baromIn == null) return ""; return "&baromin=" + this._baromIn.Value.ToString(CultureInfo.InvariantCulture); } } public float? _solarrad; //Solar radiation in W/m2 public float? SolarRad { set { this._solarrad = value; } } public string SolarRadGetStr { get { if (this._solarrad == null) return ""; return "&solarradiation=" + this._solarrad.Value.ToString(CultureInfo.InvariantCulture); } } } /// <summary> /// Type this adresse to see update syntax: /// http://weatherstation.wunderground.com/weatherstation/updateweatherstation.php /// </summary> public class WUUpdateWeatherStation { #region log4net private static readonly ILog _logger = log4net.LogManager.GetLogger(typeof(WUUpdateWeatherStation)); private static readonly string _currTypeName = typeof(WUUpdateWeatherStation).Name; #endregion log4net private readonly string _station_id; private readonly string _station_pwd; private readonly string _updateDnsUrl = "http://weatherstation.wunderground.com/weatherstation/updateweatherstation.php?ID={0}&PASSWORD={1}"; private readonly string _updateIpUrl = "http://172.16.58.3/weatherstation/updateweatherstation.php?ID={0}&PASSWORD={1}"; private string _updateURL = string.Empty; public WUUpdateWeatherStation(string station_id, string station_pwd) { _station_id = station_id; _station_pwd = station_pwd; //this._updateURL = this._updateDnsUrl.Args(this._station_id, this._station_pwd); _updateURL = _updateIpUrl.Args(_station_id, _station_pwd); } public void Map(string[] weather) { } private string ToUpdateString(WUUpdateWeatherStationDto wdto) { string updStr = ""; if (wdto != null) { updStr = _updateURL; updStr += wdto.DateUtcGetStr; //RecDateTime updStr += wdto.WindDirGetStr; //Wind Direction updStr += wdto.WindSpeedMphGetStr; //Wind Speed updStr += wdto.WindGustMphGetStr; //Wind Gust updStr += wdto.WindGustDirGetStr; //Wind Gust updStr += wdto.HumidityGetStr; //Humidity updStr += wdto.DewPtFGetStr; //Dew Point F updStr += wdto.TempfGetStr; //Temperature updStr += wdto.RainInGetStr; //Rainfall last hour updStr += wdto.DailyRainInGetStr; //Rainfall 24hours updStr += wdto.BaromInGetStr; //Barometer updStr += wdto.SolarRadGetStr; //SolarRad updStr += "&action=updateraw"; updStr += "&softwaretype=OmnObserver v3.1"; } return updStr; } public void Update(WUUpdateWeatherStationDto wdto) { string _currMethod = _currTypeName + ".Update() "; try { if (wdto != null) { string uriUpdStr = this.ToUpdateString(wdto); if (uriUpdStr != "") { #if DEBUG //_logger.Debug(_currMethod + "uri={0}".Args(uriUpdStr)); #endif HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriUpdStr); request.KeepAlive = true; request.ServicePoint.Expect100Continue = false; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); #if DEBUG //Debug.WriteLine("WUUpdate Response={0} Desc={1}".Args(response.StatusCode, response.StatusDescription)); #endif response.Close(); } } } catch (Exception ex) { _logger.Error(_currMethod + ex.Message); } } } }<file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsDataResourceRecord // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace PcapDotNet.Packets.Dns { public class DnsDataResourceRecord : DnsResourceRecord, IEquatable<DnsDataResourceRecord> { private const int MinimumLengthAfterBase = 6; public override sealed int Ttl { get; protected set; } public override sealed DnsResourceData Data { get; protected set; } public DnsDataResourceRecord(DnsDomainName domainName, DnsType type, DnsClass dnsClass, int ttl, DnsResourceData data) : base(domainName, type, dnsClass) { this.Ttl = ttl; this.Data = data; } public override string ToString() { return string.Format((IFormatProvider) CultureInfo.InvariantCulture, "{0} {1} {2}", (object) base.ToString(), (object) this.Ttl, (object) this.Data); } [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0")] public bool Equals(DnsDataResourceRecord other) { if (this.EqualsBase((DnsResourceRecord) other) && this.Ttl.Equals(other.Ttl)) return this.Data.Equals((object) other.Data); return false; } public override sealed bool Equals(object obj) { return this.Equals(obj as DnsDataResourceRecord); } public override sealed int GetHashCode() { return this.GetHashCodeBase() ^ Sequence.GetHashCode((object) this.Ttl, (object) this.Data); } internal static DnsDataResourceRecord Parse(DnsDatagram dns, int offsetInDns, out int numBytesRead) { DnsDomainName domainName; DnsType type; DnsClass dnsClass; if (!DnsResourceRecord.TryParseBase(dns, offsetInDns, out domainName, out type, out dnsClass, out numBytesRead)) return (DnsDataResourceRecord) null; if (offsetInDns + numBytesRead + 6 > dns.Length) return (DnsDataResourceRecord) null; int ttl = dns.ReadInt(offsetInDns + numBytesRead, Endianity.Big); ushort num = dns.ReadUShort(offsetInDns + numBytesRead + 4, Endianity.Big); numBytesRead += 6; if (offsetInDns + numBytesRead + (int) num > dns.Length) return (DnsDataResourceRecord) null; DnsResourceData data = DnsResourceData.Read(dns, type, offsetInDns + numBytesRead, (int) num); if (data == null) return (DnsDataResourceRecord) null; numBytesRead += (int) num; if (type == DnsType.Opt) return (DnsDataResourceRecord) new DnsOptResourceRecord(domainName, dnsClass, ttl, data); return new DnsDataResourceRecord(domainName, type, dnsClass, ttl, data); } internal override int GetLengthAfterBase(DnsDomainNameCompressionData compressionData, int offsetInDns) { return 6 + this.Data.GetLength(compressionData, offsetInDns); } internal override int Write(byte[] buffer, int dnsOffset, DnsDomainNameCompressionData compressionData, int offsetInDns) { int num1 = base.Write(buffer, dnsOffset, compressionData, offsetInDns); ByteArrayExtensions.Write(buffer, dnsOffset + offsetInDns + num1, this.Ttl, Endianity.Big); int num2 = num1 + 4; return num2 + this.Data.Write(buffer, dnsOffset, offsetInDns + num2, compressionData); } private static class OffsetAfterBase { public const int Ttl = 0; public const int DataLength = 4; public const int Data = 6; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsLongLivedQueryOpCode // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Dns { public enum DnsLongLivedQueryOpCode : ushort { None, Setup, Refresh, Event, } } <file_sep>// Copyright 2015 <NAME> // // 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. using Grib.Api.Interop; using Grib.Api.Interop.SWIG; using Grib.Api.Interop.Util; using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Runtime.InteropServices; namespace Grib.Api { /// <summary> /// GRIB file iterator object that provides methods for reading and writing messages. When iterated, returns /// instances of the <see cref="Grib.Api.GribMessage"/> class. /// </summary> public class GribFile: AutoRef, IEnumerable<GribMessage> { private IntPtr _pFileHandleProxy; private FileHandleProxy _fileHandleProxy; /// <summary> /// Initializes the <see cref="GribFile"/> class. /// </summary> static GribFile() { GribEnvironment.Init(); } /// <summary> /// Initializes a new instance of the <see cref="GribFile" /> class. File read rights are shared between processes. /// </summary> /// <param name="fileName">Name of the file.</param> /// <exception cref="System.IO.IOException">Could not open file. See inner exception for more detail.</exception> /// <exception cref="System.IO.FileLoadException">The file is empty.</exception> public GribFile (string fileName) { FileInfo fi = new FileInfo(fileName); // need a better check if (fi.Length < 4) { throw new FileLoadException("This file is empty or invalid."); } _pFileHandleProxy = GribApiNative.CreateFileHandleProxy(fileName); if (_pFileHandleProxy == IntPtr.Zero) { throw new IOException("Could not open file. See inner exception for more detail.", new Win32Exception(Marshal.GetLastWin32Error())); } _fileHandleProxy = (FileHandleProxy) Marshal.PtrToStructure(_pFileHandleProxy, typeof(FileHandleProxy)); FileName = fileName; Reference = new HandleRef(this, _fileHandleProxy.File); Context = GribApiProxy.GribContextGetDefault(); // set the message count here; the result seems to be connected to the message iterator so // that after you begin iterating messages, the count decreases until it reaches 1. int count = 0; GribApiProxy.GribCountInFile(Context, this, out count); MessageCount = count; } /// <summary> /// Called when [dispose]. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected override void OnDispose (bool disposing) { GribApiNative.DestroyFileHandleProxy(_pFileHandleProxy); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1" /> that can be used to iterate through the collection. /// </returns> public IEnumerator<GribMessage> GetEnumerator () { GribMessage msg; int i = 0; while ((msg = GribMessage.Create(this, i++)) != null) { yield return msg; } } /// <summary> /// NOT IMPLEMENTED. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection. /// </returns> /// <exception cref="System.NotImplementedException"></exception> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () { throw new NotImplementedException(); } /// <summary> /// Writes a message to the specified path. /// </summary> /// <param name="path">The path.</param> /// <param name="message">The message.</param> /// <param name="mode">The mode.</param> public static void Write (string path, GribMessage message, FileMode mode = FileMode.Create) { Write(path, new [] { message }, mode); } /// <summary> /// Writes all messages in the file to the specified path. /// </summary> /// <param name="path">The path.</param> /// <param name="file">The file.</param> /// <param name="mode">The mode.</param> public static void Write (string path, GribFile file, FileMode mode = FileMode.Create) { Write(path, file as IEnumerable<GribMessage>, mode); } /// <summary> /// Writes messages the specified path. /// </summary> /// <param name="path">The path.</param> /// <param name="messages">The messages.</param> /// <param name="mode">The mode.</param> public static void Write (string path, IEnumerable<GribMessage> messages, FileMode mode = FileMode.Create) { // TODO: Getting the buffer and writing to file in C++ precludes the need for byte[] copy using (FileStream fs = new FileStream(path, mode, FileAccess.Write, FileShare.Read, 8192)) { foreach (var message in messages) { fs.Write(message.Buffer, 0, message.Buffer.Length); } } } /// <summary> /// Gets the name of the file. /// </summary> /// <value> /// The name of the file. /// </value> public string FileName { get; private set; } /// <summary> /// Gets or sets the message count. /// </summary> /// <value> /// The message count. /// </value> public int MessageCount { get; protected set; } /// <summary> /// Gets or sets the context. /// </summary> /// <value> /// The context. /// </value> public GribContext Context { get; protected set; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataSink // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.Sink)] public sealed class DnsResourceDataSink : DnsResourceDataSimple, IEquatable<DnsResourceDataSink> { private const int ConstantPartLength = 2; public DnsSinkCoding Coding { get; private set; } public byte SubCoding { get; private set; } public DnsSinkCodingSubCoding CodingSubCoding { get { return (DnsSinkCodingSubCoding) BitSequence.Merge((byte) this.Coding, this.SubCoding); } } public DataSegment Data { get; private set; } public DnsResourceDataSink(DnsSinkCodingSubCoding codingSubCoding, DataSegment data) : this((DnsSinkCoding) ((uint) codingSubCoding >> 8), (byte) (codingSubCoding & (DnsSinkCodingSubCoding) 255), data) { } public DnsResourceDataSink(DnsSinkCoding coding, byte subCoding, DataSegment data) { this.Coding = coding; this.SubCoding = subCoding; this.Data = data; } internal DnsResourceDataSink() : this(DnsSinkCodingSubCoding.Asn1SnmpBasicEncodingRules, DataSegment.Empty) { } public bool Equals(DnsResourceDataSink other) { if (other != null && this.Coding.Equals((object) other.Coding) && this.SubCoding.Equals(other.SubCoding)) return this.Data.Equals(other.Data); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataSink); } public override int GetHashCode() { return Sequence.GetHashCode((object) this.CodingSubCoding, (object) this.Data); } internal override int GetLength() { return 2 + this.Data.Length; } internal override void WriteDataSimple(byte[] buffer, int offset) { ByteArrayExtensions.Write(buffer, offset, (byte) this.Coding); ByteArrayExtensions.Write(buffer, offset + 1, this.SubCoding); this.Data.Write(buffer, offset + 2); } internal override DnsResourceData CreateInstance(DataSegment data) { if (data.Length < 2) return (DnsResourceData) null; return (DnsResourceData) new DnsResourceDataSink((DnsSinkCoding) data[0], data[1], data.Subsegment(2, data.Length - 2)); } private static class Offset { public const int Coding = 0; public const int Subcoding = 1; public const int Data = 2; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WUnderground.Client.Models { public class Features { public int geolookup { get; set; } public int conditions { get; set; } public int forecast { get; set; } public int hourly { get; set; } } public class ResponseMetadata { public string version { get; set; } public string termsofService { get; set; } public Features features { get; set; } public Error error { get; set; } } public class Error { public string type { get; set; } public string description { get; set; } } public class Station { public string city { get; set; } public string state { get; set; } public string country { get; set; } public string icao { get; set; } public string lat { get; set; } public string lon { get; set; } public string neighborhood { get; set; } public string id { get; set; } public int distance_km { get; set; } public int distance_mi { get; set; } } public class Airport { public List<Station> station { get; set; } } public class Pws { public List<Station> station { get; set; } } public class NearbyWeatherStations { public Airport airport { get; set; } public Pws pws { get; set; } } public class Location { public string type { get; set; } public string country { get; set; } public string country_iso3166 { get; set; } public string country_name { get; set; } public string state { get; set; } public string city { get; set; } public string tz_short { get; set; } public string tz_long { get; set; } public string lat { get; set; } public string lon { get; set; } public string zip { get; set; } public string magic { get; set; } public string wmo { get; set; } public string l { get; set; } public string requesturl { get; set; } public string wuiurl { get; set; } public NearbyWeatherStations nearby_weather_stations { get; set; } } public class Image { public string url { get; set; } public string title { get; set; } public string link { get; set; } } public class DisplayLocation { public string full { get; set; } public string city { get; set; } public string state { get; set; } public string state_name { get; set; } public string country { get; set; } public string country_iso3166 { get; set; } public string zip { get; set; } public string magic { get; set; } public string wmo { get; set; } public string latitude { get; set; } public string longitude { get; set; } public string elevation { get; set; } } public class ObservationLocation { public string full { get; set; } public string city { get; set; } public string state { get; set; } public string country { get; set; } public string country_iso3166 { get; set; } public string latitude { get; set; } public string longitude { get; set; } public string elevation { get; set; } } public class Estimated { } public class CurrentObservation { public Image image { get; set; } public DisplayLocation display_location { get; set; } public ObservationLocation observation_location { get; set; } public Estimated estimated { get; set; } public string station_id { get; set; } public string observation_time { get; set; } public string observation_time_rfc822 { get; set; } public string observation_epoch { get; set; } public string local_time_rfc822 { get; set; } public string local_epoch { get; set; } public string local_tz_short { get; set; } public string local_tz_long { get; set; } public string local_tz_offset { get; set; } public string weather { get; set; } public string temperature_string { get; set; } public double temp_f { get; set; } public double temp_c { get; set; } public string relative_humidity { get; set; } public string wind_string { get; set; } public string wind_dir { get; set; } public int wind_degrees { get; set; } public double wind_mph { get; set; } public string wind_gust_mph { get; set; } public double wind_kph { get; set; } public string wind_gust_kph { get; set; } public string pressure_mb { get; set; } public string pressure_in { get; set; } public string pressure_trend { get; set; } public string dewpoint_string { get; set; } public int dewpoint_f { get; set; } public int dewpoint_c { get; set; } public string heat_index_string { get; set; } public string heat_index_f { get; set; } public string heat_index_c { get; set; } public string windchill_string { get; set; } public string windchill_f { get; set; } public string windchill_c { get; set; } public string feelslike_string { get; set; } public string feelslike_f { get; set; } public string feelslike_c { get; set; } public string visibility_mi { get; set; } public string visibility_km { get; set; } public string solarradiation { get; set; } public string UV { get; set; } public string precip_1hr_string { get; set; } public string precip_1hr_in { get; set; } public string precip_1hr_metric { get; set; } public string precip_today_string { get; set; } public string precip_today_in { get; set; } public string precip_today_metric { get; set; } public string icon { get; set; } public string icon_url { get; set; } public string forecast_url { get; set; } public string history_url { get; set; } public string ob_url { get; set; } public string nowcast { get; set; } } public class Forecastday { public int period { get; set; } public string icon { get; set; } public string icon_url { get; set; } public string title { get; set; } public string fcttext { get; set; } public string fcttext_metric { get; set; } public string pop { get; set; } public Date date { get; set; } public Temperature high { get; set; } public Temperature low { get; set; } public string conditions { get; set; } public string skyicon { get; set; } public Precipitation qpf_allday { get; set; } public Precipitation qpf_day { get; set; } public Precipitation qpf_night { get; set; } public Precipitation snow_allday { get; set; } public Precipitation snow_day { get; set; } public Precipitation snow_night { get; set; } public Wind maxwind { get; set; } public Wind avewind { get; set; } public int avehumidity { get; set; } public int maxhumidity { get; set; } public int minhumidity { get; set; } } public class HourlyForecast { public Time FCTTIME { get; set; } public TemperatureOrPrecipitation temp { get; set; } public TemperatureOrPrecipitation dewpoint { get; set; } public string condition { get; set; } public string icon { get; set; } public string icon_url { get; set; } public string fctcode { get; set; } public string sky { get; set; } public TemperatureOrPrecipitation wspd { get; set; } public WindDirection wdir { get; set; } public string wx { get; set; } public string uvi { get; set; } public string humidity { get; set; } public TemperatureOrPrecipitation windchill { get; set; } public TemperatureOrPrecipitation heatindex { get; set; } public TemperatureOrPrecipitation feelslike { get; set; } public TemperatureOrPrecipitation qpf { get; set; } public TemperatureOrPrecipitation snow { get; set; } public string pop { get; set; } public TemperatureOrPrecipitation mslp { get; set; } } public class TxtForecast { public string date { get; set; } public List<Forecastday> forecastday { get; set; } } public class Time { public string hour { get; set; } public string hour_padded { get; set; } public string min { get; set; } public string min_unpadded { get; set; } public string sec { get; set; } public string year { get; set; } public string mon { get; set; } public string mon_padded { get; set; } public string mon_abbrev { get; set; } public string mday { get; set; } public string mday_padded { get; set; } public string yday { get; set; } public string isdst { get; set; } public string epoch { get; set; } public string pretty { get; set; } public string civil { get; set; } public string month_name { get; set; } public string month_name_abbrev { get; set; } public string weekday_name { get; set; } public string weekday_name_night { get; set; } public string weekday_name_abbrev { get; set; } public string weekday_name_unlang { get; set; } public string weekday_name_night_unlang { get; set; } public string ampm { get; set; } public string tz { get; set; } public string age { get; set; } public string UTCDATE { get; set; } } public class Date { public string epoch { get; set; } public string pretty { get; set; } public int day { get; set; } public int month { get; set; } public int year { get; set; } public int yday { get; set; } public int hour { get; set; } public string min { get; set; } public int sec { get; set; } public string isdst { get; set; } public string monthname { get; set; } public string monthname_short { get; set; } public string weekday_short { get; set; } public string weekday { get; set; } public string ampm { get; set; } public string tz_short { get; set; } public string tz_long { get; set; } } public class Temperature { public string fahrenheit { get; set; } public string celsius { get; set; } } public class TemperatureOrPrecipitation { public string english { get; set; } public string metric { get; set; } } public class Precipitation { public double? @in { get; set; } public double? mm { get; set; } } public class WindDirection { public string dir { get; set; } public string degrees { get; set; } } public class Wind { public double mph { get; set; } public double kph { get; set; } public string dir { get; set; } public double degrees { get; set; } } public class Simpleforecast { public List<Forecastday> forecastday { get; set; } } public class Forecast { public TxtForecast txt_forecast { get; set; } public Simpleforecast simpleforecast { get; set; } } public class WeatherResponse { public ResponseMetadata response { get; set; } public Location location { get; set; } public CurrentObservation current_observation { get; set; } public Forecast forecast { get; set; } public List<HourlyForecast> hourly_forecast { get; set; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsGatewayIpV4 // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using PcapDotNet.Packets.IpV4; using System; namespace PcapDotNet.Packets.Dns { public sealed class DnsGatewayIpV4 : DnsGateway, IEquatable<DnsGatewayIpV4> { public IpV4Address Value { get; private set; } public override DnsGatewayType GatewayType { get { return DnsGatewayType.IpV4; } } public override int Length { get { return 4; } } public DnsGatewayIpV4(IpV4Address value) { this.Value = value; } public bool Equals(DnsGatewayIpV4 other) { if (other != null) return this.Value.Equals(other.Value); return false; } public override bool Equals(DnsGateway other) { return this.Equals(other as DnsGatewayIpV4); } internal override int DataGetHashCode() { return this.Value.GetHashCode(); } internal override void Write(byte[] buffer, int offset) { ByteArrayExtensions.Write(buffer, offset, this.Value, Endianity.Big); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Base.FuncExtensions // Assembly: PcapDotNet.Base, Version=0.10.0.20668, Culture=neutral, PublicKeyToken=<KEY> // MVID: E9656A63-0145-422C-B8C8-79FDD7FB4270 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Base.dll using System; namespace PcapDotNet.Base { public static class FuncExtensions { public static T[] GenerateArray<T>(this Func<T> generator, int size) { if (generator == null) throw new ArgumentNullException("generator"); T[] objArray = new T[size]; for (int index = 0; index != size; ++index) objArray[index] = generator(); return objArray; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataSimple // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; namespace PcapDotNet.Packets.Dns { public abstract class DnsResourceDataSimple : DnsResourceDataNoCompression { internal override sealed int WriteData(byte[] buffer, int offset) { this.WriteDataSimple(buffer, offset); return this.GetLength(); } internal abstract void WriteDataSimple(byte[] buffer, int offset); internal override sealed DnsResourceData CreateInstance(DnsDatagram dns, int offsetInDns, int length) { return this.CreateInstance(dns.Subsegment(offsetInDns, length)); } internal abstract DnsResourceData CreateInstance(DataSegment data); } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.TcpOption // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Transport { public abstract class TcpOption : Option, IEquatable<TcpOption> { private static readonly TcpOption _end = (TcpOption) new TcpOptionSimple(TcpOptionType.EndOfOptionList); private static readonly TcpOption _nop = (TcpOption) new TcpOptionSimple(TcpOptionType.NoOperation); public static TcpOption End { get { return TcpOption._end; } } public static TcpOption Nop { get { return TcpOption._nop; } } public TcpOptionType OptionType { get; private set; } protected TcpOption(TcpOptionType optionType) { this.OptionType = optionType; } public override sealed bool Equivalent(Option other) { return this.OptionType == ((TcpOption) other).OptionType; } public virtual bool Equals(TcpOption other) { if (other == null) return false; return this.Equivalent((Option) other); } public override sealed bool Equals(object obj) { return this.Equals(obj as TcpOption); } public override int GetHashCode() { return this.OptionType.GetHashCode(); } public override sealed string ToString() { return this.OptionType.ToString(); } internal override sealed Option Read(byte[] buffer, ref int offset, int length) { int num = offset + length; if (offset == num) return (Option) null; TcpOptionType optionType = (TcpOptionType) buffer[offset++]; switch (optionType) { case TcpOptionType.EndOfOptionList: return (Option) TcpOption.End; case TcpOptionType.NoOperation: return (Option) TcpOption.Nop; default: return OptionComplexFactory<TcpOptionType>.Read(optionType, buffer, ref offset, num - offset); } } internal override void Write(byte[] buffer, ref int offset) { buffer[offset++] = (byte) this.OptionType; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Ethernet.VLanTaggedFrameDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; namespace PcapDotNet.Packets.Ethernet { public sealed class VLanTaggedFrameDatagram : EthernetBaseDatagram { public const int HeaderLengthValue = 4; public const ushort NullVLanIdentifier = (ushort) 0; public const ushort DefaultPortVLanIdentifier = (ushort) 1; public const ushort MaxVLanIdentifier = (ushort) 4095; public override int HeaderLength { get { return 4; } } public ClassOfService PriorityCodePoint { get { return (ClassOfService) (((int) this[0] & 224) >> 5); } } public bool CanonicalFormatIndicator { get { return this.ReadBool(0, (byte) 16); } } public ushort VLanIdentifier { get { return (ushort) ((uint) this.ReadUShort(0, Endianity.Big) & 4095U); } } public ushort TagControlInformation { get { return VLanTaggedFrameDatagram.CalculateTagControlInformation(this.PriorityCodePoint, this.CanonicalFormatIndicator, this.VLanIdentifier); } } public override EthernetType EtherType { get { return (EthernetType) this.ReadUShort(2, Endianity.Big); } } internal VLanTaggedFrameDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public override ILayer ExtractLayer() { VLanTaggedFrameLayer taggedFrameLayer = new VLanTaggedFrameLayer(); taggedFrameLayer.PriorityCodePoint = this.PriorityCodePoint; taggedFrameLayer.CanonicalFormatIndicator = this.CanonicalFormatIndicator; taggedFrameLayer.VLanIdentifier = this.VLanIdentifier; taggedFrameLayer.EtherType = this.EtherType; return (ILayer) taggedFrameLayer; } protected override bool CalculateIsValid() { if (this.Length < this.HeaderLength) return false; Datagram payloadByEtherType = this.PayloadByEtherType; if (payloadByEtherType != null) return payloadByEtherType.IsValid; return true; } internal static void WriteHeader(byte[] buffer, int offset, ClassOfService priorityCodePoint, bool canonicalFormatIndicator, ushort vLanIdentifier, EthernetType etherType) { ushort num = VLanTaggedFrameDatagram.CalculateTagControlInformation(priorityCodePoint, canonicalFormatIndicator, vLanIdentifier); ByteArrayExtensions.Write(buffer, offset, num, Endianity.Big); ByteArrayExtensions.Write(buffer, offset + 2, (ushort) etherType, Endianity.Big); } internal static ushort CalculateTagControlInformation(ClassOfService priorityCodePoint, bool canonicalFormatIndicator, ushort vLanIdentifier) { return (ushort) (((int) priorityCodePoint << 5 & 224 | (canonicalFormatIndicator ? 16 : 0)) << 8 | (int) vLanIdentifier & 4095); } private static class Offset { public const int PriorityCodePoint = 0; public const int CanonicalFormatIndicator = 0; public const int VLanIdentifier = 0; public const int EtherTypeLength = 2; } private static class Mask { public const byte PriorityCodePoint = (byte) 224; public const byte CanonicalFormatIndicator = (byte) 16; public const ushort VLanIdentifier = (ushort) 4095; } private static class Shift { public const int PriorityCodePoint = 5; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpDestinationUnreachableDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System.Linq; namespace PcapDotNet.Packets.Icmp { [IcmpDatagramRegistration(IcmpMessageType.DestinationUnreachable)] public sealed class IcmpDestinationUnreachableDatagram : IcmpIpV4HeaderPlus64BitsPayloadDatagram { private static readonly byte _minCode = (byte) Enumerable.Min<IcmpCodeDestinationUnreachable>(TypeExtensions.GetEnumValues<IcmpCodeDestinationUnreachable>(typeof (IcmpCodeDestinationUnreachable))); private static readonly byte _maxCode = (byte) Enumerable.Max<IcmpCodeDestinationUnreachable>(TypeExtensions.GetEnumValues<IcmpCodeDestinationUnreachable>(typeof (IcmpCodeDestinationUnreachable))); public const ushort MinimumMaximumTransmissionUnit = (ushort) 68; public ushort NextHopMaximumTransmissionUnit { get { return this.ReadUShort(6, Endianity.Big); } } protected override byte MinCodeValue { get { return IcmpDestinationUnreachableDatagram._minCode; } } protected override byte MaxCodeValue { get { return IcmpDestinationUnreachableDatagram._maxCode; } } private IcmpDestinationUnreachableDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public override ILayer ExtractLayer() { IcmpDestinationUnreachableLayer unreachableLayer = new IcmpDestinationUnreachableLayer(); unreachableLayer.Code = (IcmpCodeDestinationUnreachable) this.Code; unreachableLayer.Checksum = new ushort?(this.Checksum); unreachableLayer.NextHopMaximumTransmissionUnit = this.NextHopMaximumTransmissionUnit; return (ILayer) unreachableLayer; } protected override bool CalculateIsValid() { if (!base.CalculateIsValid()) return false; if ((int) this.Code == 4) return (int) this.NextHopMaximumTransmissionUnit >= 68; return (int) this.NextHopMaximumTransmissionUnit == 0; } internal override IcmpDatagram CreateInstance(byte[] buffer, int offset, int length) { return (IcmpDatagram) new IcmpDestinationUnreachableDatagram(buffer, offset, length); } private static class Offset { public const int NextHopMtu = 6; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.PacketCommunicator // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using \u003CCppImplementationDetails\u003E; using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Runtime.InteropServices; namespace PcapDotNet.Core { public abstract class PacketCommunicator : IDisposable { private unsafe pcap* _pcapDescriptor = pcapDescriptor; private IpV4SocketAddress _ipV4Netmask = netmask as IpV4SocketAddress; private PacketCommunicatorMode _mode; protected unsafe pcap* PcapDescriptor { get { return this._pcapDescriptor; } } public unsafe bool NonBlocking { get { \u0024ArrayType\u0024\u0024\u0024BY0BAA\u0040D arrayTypeBy0BaAD; int num; switch (\u003CModule\u003E.pcap_getnonblock(this._pcapDescriptor, (sbyte*) &arrayTypeBy0BaAD)) { case -1: throw PcapError.BuildInvalidOperation("Error getting NonBlocking value", this._pcapDescriptor); case 0: num = 0; break; default: num = 1; break; } return num != 0; } set { \u0024ArrayType\u0024\u0024\u0024BY0BAA\u0040D arrayTypeBy0BaAD; if (\u003CModule\u003E.pcap_setnonblock(this._pcapDescriptor, value ? 1 : 0, (sbyte*) &arrayTypeBy0BaAD) != 0) throw PcapError.BuildInvalidOperation("Error setting NonBlocking to " + value.ToString(), this._pcapDescriptor); } } public unsafe PacketCommunicatorMode Mode { get { return this._mode; } set { if (\u003CModule\u003E.pcap_setmode(this._pcapDescriptor, (int) value) < 0) throw PcapError.BuildInvalidOperation("Error setting mode " + value.ToString(), this._pcapDescriptor); this._mode = value; } } public abstract PacketTotalStatistics TotalStatistics { get; } public unsafe int FileMinorVersion { get { return \u003CModule\u003E.pcap_minor_version(this._pcapDescriptor); } } public unsafe int FileMajorVersion { get { return \u003CModule\u003E.pcap_major_version(this._pcapDescriptor); } } public unsafe bool IsFileSystemByteOrder { get { return \u003CModule\u003E.pcap_is_swapped(this._pcapDescriptor) == 0; } } public IpV4SocketAddress IpV4Netmask { get { return this._ipV4Netmask; } } public unsafe int SnapshotLength { get { return \u003CModule\u003E.pcap_snapshot(this._pcapDescriptor); } } public unsafe ReadOnlyCollection<PcapDataLink> SupportedDataLinks { get { int* numPtr; int capacity = \u003CModule\u003E.pcap_list_datalinks(this._pcapDescriptor, &numPtr); if (capacity == -1) throw PcapError.BuildInvalidOperation("Failed getting supported datalinks", this._pcapDescriptor); try { List<PcapDataLink> list = new List<PcapDataLink>(capacity); for (int index = 0; index != capacity; ++index) { PcapDataLink pcapDataLink = new PcapDataLink(*(int*) ((long) index * 4L + (IntPtr) numPtr)); list.Add(pcapDataLink); } return new ReadOnlyCollection<PcapDataLink>((IList<PcapDataLink>) list); } finally { \u003CModule\u003E.pcap_free_datalinks(numPtr); } } } public unsafe PcapDataLink DataLink { get { return new PcapDataLink(\u003CModule\u003E.pcap_datalink(this._pcapDescriptor)); } set { if (\u003CModule\u003E.pcap_set_datalink(this._pcapDescriptor, value.Value) == -1) throw PcapError.BuildInvalidOperation("Failed setting datalink " + value.ToString(), this._pcapDescriptor); } } internal unsafe PacketCommunicator(pcap* pcapDescriptor, SocketAddress netmask) { } public unsafe void SetKernelBufferSize(int size) { if (\u003CModule\u003E.pcap_setbuff(this._pcapDescriptor, size) != 0) throw PcapError.BuildInvalidOperation("Error setting kernel buffer size to " + size.ToString((IFormatProvider) CultureInfo.InvariantCulture), this._pcapDescriptor); } public unsafe void SetKernelMinimumBytesToCopy(int size) { if (\u003CModule\u003E.pcap_setmintocopy(this._pcapDescriptor, size) != 0) throw PcapError.BuildInvalidOperation("Error setting kernel minimum bytes to copy to " + size.ToString((IFormatProvider) CultureInfo.InvariantCulture), this._pcapDescriptor); } public unsafe void SetSamplingMethod(SamplingMethod method) { if (method == null) throw new ArgumentNullException("method"); pcap_samp* pcapSampPtr = \u003CModule\u003E.pcap_setsampling(this._pcapDescriptor); *(int*) pcapSampPtr = method.Method; *(int*) ((IntPtr) pcapSampPtr + 4L) = method.Value; } public unsafe PacketCommunicatorReceiveResult ReceivePacket(out Packet packet) { this.AssertMode(PacketCommunicatorMode.Capture); pcap_pkthdr* pcapPkthdrPtr1; byte* numPtr; PacketCommunicatorReceiveResult communicatorReceiveResult = this.RunPcapNextEx(&pcapPkthdrPtr1, &numPtr); if (communicatorReceiveResult != PacketCommunicatorReceiveResult.Ok) { packet = (Packet) null; return communicatorReceiveResult; } IDataLink dataLink = (IDataLink) new PcapDataLink(\u003CModule\u003E.pcap_datalink(this._pcapDescriptor)); byte* unmanagedByteArray = numPtr; pcap_pkthdr* pcapPkthdrPtr2 = pcapPkthdrPtr1; DateTime dateTime = new DateTime(); PacketTimestamp.PcapTimestampToDateTime((timeval*) pcapPkthdrPtr1, out dateTime); int offset = 0; int count = *(int*) ((IntPtr) pcapPkthdrPtr2 + 8L); byte[] data = MarshalingServices.UnamangedToManagedByteArray(unmanagedByteArray, offset, count); packet = new Packet(data, dateTime, dataLink); return PacketCommunicatorReceiveResult.Ok; } public unsafe PacketCommunicatorReceiveResult ReceiveSomePackets(out int countGot, int maxPackets, HandlePacket callback) { this.AssertMode(PacketCommunicatorMode.Capture); PcapDataLink dataLink = new PcapDataLink(\u003CModule\u003E.pcap_datalink(this._pcapDescriptor)); PacketCommunicator.PacketHandler packetHandler = new PacketCommunicator.PacketHandler(callback, dataLink); PacketCommunicator.HandlerDelegate handlerDelegate = new PacketCommunicator.HandlerDelegate(packetHandler.Handle); // ISSUE: cast to a function pointer type __FnPtr<void (byte*, pcap_pkthdr*, byte*)> local = (__FnPtr<void (byte*, pcap_pkthdr*, byte*)>) (IntPtr) Marshal.GetFunctionPointerForDelegate((Delegate) handlerDelegate).ToPointer(); countGot = \u003CModule\u003E.pcap_dispatch(this._pcapDescriptor, maxPackets, local, (byte*) 0); GC.KeepAlive((object) handlerDelegate); switch (countGot) { case -2: countGot = 0; return PacketCommunicatorReceiveResult.BreakLoop; case -1: throw PcapError.BuildInvalidOperation("Failed reading from device", this._pcapDescriptor); case 0: if (packetHandler.PacketCounter != 0) { countGot = packetHandler.PacketCounter; return PacketCommunicatorReceiveResult.Eof; } break; } return PacketCommunicatorReceiveResult.Ok; } public unsafe PacketCommunicatorReceiveResult ReceivePackets(int count, HandlePacket callback) { this.AssertMode(PacketCommunicatorMode.Capture); PcapDataLink dataLink = new PcapDataLink(\u003CModule\u003E.pcap_datalink(this._pcapDescriptor)); PacketCommunicator.PacketHandler packetHandler = new PacketCommunicator.PacketHandler(callback, dataLink); PacketCommunicator.HandlerDelegate handlerDelegate = new PacketCommunicator.HandlerDelegate(packetHandler.Handle); // ISSUE: cast to a function pointer type __FnPtr<void (byte*, pcap_pkthdr*, byte*)> local = (__FnPtr<void (byte*, pcap_pkthdr*, byte*)>) (IntPtr) Marshal.GetFunctionPointerForDelegate((Delegate) handlerDelegate).ToPointer(); int num = \u003CModule\u003E.pcap_loop(this._pcapDescriptor, count, local, (byte*) 0); GC.KeepAlive((object) handlerDelegate); if (num == -2) return PacketCommunicatorReceiveResult.BreakLoop; if (num == -1) throw PcapError.BuildInvalidOperation("Failed reading from device", this._pcapDescriptor); return num == 0 && packetHandler.PacketCounter != count ? PacketCommunicatorReceiveResult.Eof : PacketCommunicatorReceiveResult.Ok; } public unsafe PacketCommunicatorReceiveResult ReceiveStatistics(int count, HandleStatistics callback) { this.AssertMode(PacketCommunicatorMode.Statistics); PacketCommunicator.HandlerDelegate handlerDelegate = new PacketCommunicator.HandlerDelegate(new PacketCommunicator.StatisticsHandler(callback).Handle); // ISSUE: cast to a function pointer type __FnPtr<void (byte*, pcap_pkthdr*, byte*)> local = (__FnPtr<void (byte*, pcap_pkthdr*, byte*)>) (IntPtr) Marshal.GetFunctionPointerForDelegate((Delegate) handlerDelegate).ToPointer(); int num = \u003CModule\u003E.pcap_loop(this._pcapDescriptor, count, local, (byte*) 0); GC.KeepAlive((object) handlerDelegate); if (num == -1) throw PcapError.BuildInvalidOperation("Failed reading from device", this._pcapDescriptor); return num != -2 ? PacketCommunicatorReceiveResult.Ok : PacketCommunicatorReceiveResult.BreakLoop; } public unsafe PacketCommunicatorReceiveResult ReceiveStatistics(out PacketSampleStatistics statistics) { this.AssertMode(PacketCommunicatorMode.Statistics); pcap_pkthdr* packetHeader; byte* packetData; PacketCommunicatorReceiveResult communicatorReceiveResult = this.RunPcapNextEx(&packetHeader, &packetData); if (communicatorReceiveResult != PacketCommunicatorReceiveResult.Ok) throw new InvalidOperationException("Got result " + communicatorReceiveResult.ToString() + " in statistics mode"); statistics = new PacketSampleStatistics(packetHeader, packetData); return PacketCommunicatorReceiveResult.Ok; } public unsafe void Break() { \u003CModule\u003E.pcap_breakloop(this._pcapDescriptor); } public unsafe void SendPacket(Packet packet) { if (packet == null) throw new ArgumentNullException("packet"); if (packet.Length == 0) return; fixed (byte* numPtr = &packet.Buffer[0]) { if (\u003CModule\u003E.pcap_sendpacket(this._pcapDescriptor, numPtr, packet.Length) != 0) throw PcapError.BuildInvalidOperation("Failed writing to device", this._pcapDescriptor); } } public abstract void Transmit(PacketSendBuffer sendBuffer, [MarshalAs(UnmanagedType.U1)] bool isSync); public unsafe BerkeleyPacketFilter CreateFilter(string filterValue) { return new BerkeleyPacketFilter(this._pcapDescriptor, filterValue, this._ipV4Netmask); } public unsafe void SetFilter(string filterValue) { using (BerkeleyPacketFilter filter = new BerkeleyPacketFilter(this._pcapDescriptor, filterValue, this._ipV4Netmask)) this.SetFilter(filter); } public unsafe void SetFilter(BerkeleyPacketFilter filter) { if (filter == null) throw new ArgumentNullException("filter"); filter.SetFilter(this._pcapDescriptor); } public unsafe PacketDumpFile OpenDump(string fileName) { return new PacketDumpFile(this._pcapDescriptor, fileName); } private unsafe void \u007EPacketCommunicator() { \u003CModule\u003E.pcap_close(this._pcapDescriptor); } protected unsafe InvalidOperationException BuildInvalidOperation(string errorMessage) { return PcapError.BuildInvalidOperation(errorMessage, this._pcapDescriptor); } private static unsafe Packet CreatePacket(pcap_pkthdr* packetHeader, byte* packetData, IDataLink dataLink) { DateTime dateTime = new DateTime(); PacketTimestamp.PcapTimestampToDateTime((timeval*) packetHeader, out dateTime); return new Packet(MarshalingServices.UnamangedToManagedByteArray(packetData, 0, *(int*) ((IntPtr) packetHeader + 8L)), dateTime, dataLink); } private unsafe PacketCommunicatorReceiveResult RunPcapNextEx(pcap_pkthdr** packetHeader, byte** packetData) { int num = \u003CModule\u003E.pcap_next_ex(this._pcapDescriptor, packetHeader, packetData); switch (num) { case -2: return PacketCommunicatorReceiveResult.Eof; case -1: throw PcapError.BuildInvalidOperation("Failed reading from device", this._pcapDescriptor); case 0: return PacketCommunicatorReceiveResult.Timeout; case 1: return PacketCommunicatorReceiveResult.Ok; default: throw new InvalidOperationException("Result value " + num.ToString((IFormatProvider) CultureInfo.InvariantCulture) + " is undefined"); } } private void AssertMode(PacketCommunicatorMode mode) { PacketCommunicatorMode communicatorMode1 = this._mode; if (communicatorMode1 != mode) { PacketCommunicatorMode communicatorMode2 = communicatorMode1; throw new InvalidOperationException("Wrong Mode. Must be in mode " + mode.ToString() + " and not in mode " + communicatorMode2.ToString()); } } protected virtual void Dispose([MarshalAs(UnmanagedType.U1)] bool _param1) { if (param0) { this.\u007EPacketCommunicator(); } else { // ISSUE: explicit finalizer call this.Finalize(); } } public virtual void Dispose() { this.Dispose(true); GC.SuppressFinalize((object) this); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private unsafe delegate void HandlerDelegate(byte* user, pcap_pkthdr* packetHeader, byte* packetData); private class PacketHandler { private HandlePacket _callback; private PcapDataLink _dataLink; private int _packetCounter; public int PacketCounter { get { return this._packetCounter; } } public PacketHandler(HandlePacket callback, PcapDataLink dataLink) { this._callback = callback; this._dataLink = dataLink; } public unsafe void Handle(byte* user, pcap_pkthdr* packetHeader, byte* packetData) { ++this._packetCounter; this._callback(PacketCommunicator.CreatePacket(packetHeader, packetData, (IDataLink) this._dataLink)); } } private class StatisticsHandler { private HandleStatistics _callback; public StatisticsHandler(HandleStatistics callback) { this._callback = callback; } public unsafe void Handle(byte* user, pcap_pkthdr* packetHeader, byte* packetData) { this._callback(new PacketSampleStatistics(packetHeader, packetData)); } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IpV4OptionTimedAddress // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using System; namespace PcapDotNet.Packets.IpV4 { public struct IpV4OptionTimedAddress : IEquatable<IpV4OptionTimedAddress> { private readonly IpV4Address _address; private readonly IpV4TimeOfDay _timeOfDay; public IpV4Address Address { get { return this._address; } } public IpV4TimeOfDay TimeOfDay { get { return this._timeOfDay; } } public IpV4OptionTimedAddress(IpV4Address address, IpV4TimeOfDay timeOfDay) { this._address = address; this._timeOfDay = timeOfDay; } public static bool operator ==(IpV4OptionTimedAddress value1, IpV4OptionTimedAddress value2) { return value1.Equals(value2); } public static bool operator !=(IpV4OptionTimedAddress value1, IpV4OptionTimedAddress value2) { return !(value1 == value2); } public bool Equals(IpV4OptionTimedAddress other) { if (this.Address.Equals(other.Address)) return this.TimeOfDay.Equals(other.TimeOfDay); return false; } public override bool Equals(object obj) { if (obj is IpV4OptionTimedAddress) return this.Equals((IpV4OptionTimedAddress) obj); return false; } public override int GetHashCode() { return Sequence.GetHashCode((object) this._address, (object) this._timeOfDay); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IpV4FragmentationOptions // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using System; namespace PcapDotNet.Packets.IpV4 { [Flags] public enum IpV4FragmentationOptions : ushort { None = (ushort) 0, MoreFragments = (ushort) 8192, DoNotFragment = (ushort) 16384, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataOptions // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.Opt)] public sealed class DnsResourceDataOptions : DnsResourceDataSimple, IEquatable<DnsResourceDataOptions> { public DnsOptions Options { get; private set; } public DnsResourceDataOptions(DnsOptions options) { this.Options = options; } internal DnsResourceDataOptions() : this(DnsOptions.None) { } public bool Equals(DnsResourceDataOptions other) { if (other != null) return this.Options.Equals(other.Options); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataOptions); } public override int GetHashCode() { return this.Options.GetHashCode(); } internal override int GetLength() { return this.Options.BytesLength; } internal override void WriteDataSimple(byte[] buffer, int offset) { this.Options.Write(buffer, offset); } internal override DnsResourceData CreateInstance(DataSegment data) { DnsOptions options = DnsOptions.Read(data); if (options == null) return (DnsResourceData) null; return (DnsResourceData) new DnsResourceDataOptions(options); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Igmp.IgmpCreateGroupRequestVersion0Code // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Igmp { public enum IgmpCreateGroupRequestVersion0Code : byte { Public, Private, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataKey // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Diagnostics.CodeAnalysis; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.Key)] public sealed class DnsResourceDataKey : DnsResourceDataSimple, IEquatable<DnsResourceDataKey> { private const int ConstantPartLength = 4; public bool AuthenticationProhibited { get; private set; } public bool ConfidentialityProhibited { get; private set; } public bool Experimental { get; private set; } public bool UserAssociated { get; private set; } public bool IpSec { get; private set; } public bool Email { get; private set; } public DnsKeyNameType NameType { get; private set; } public DnsKeySignatoryAttributes Signatory { get; private set; } public DnsKeyProtocol Protocol { get; private set; } public DnsAlgorithm Algorithm { get; private set; } [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Flags")] public ushort? FlagsExtension { get; private set; } public DataSegment PublicKey { get; private set; } [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "flags")] public DnsResourceDataKey(bool authenticationProhibited, bool confidentialityProhibited, bool experimental, bool userAssociated, bool ipSec, bool email, DnsKeyNameType nameType, DnsKeySignatoryAttributes signatory, DnsKeyProtocol protocol, DnsAlgorithm algorithm, ushort? flagsExtension, DataSegment publicKey) { this.AuthenticationProhibited = authenticationProhibited; this.ConfidentialityProhibited = confidentialityProhibited; this.Experimental = experimental; this.UserAssociated = userAssociated; this.IpSec = ipSec; this.Email = email; this.FlagsExtension = flagsExtension; this.NameType = nameType; this.Signatory = signatory; this.Protocol = protocol; this.Algorithm = algorithm; this.PublicKey = publicKey; } internal DnsResourceDataKey() : this(false, false, false, false, false, false, DnsKeyNameType.ZoneKey, DnsKeySignatoryAttributes.Zone, DnsKeyProtocol.All, DnsAlgorithm.None, new ushort?(), DataSegment.Empty) { } public bool Equals(DnsResourceDataKey other) { if (other != null && this.AuthenticationProhibited.Equals(other.AuthenticationProhibited) && (this.ConfidentialityProhibited.Equals(other.ConfidentialityProhibited) && this.Experimental.Equals(other.Experimental)) && (this.UserAssociated.Equals(other.UserAssociated) && this.IpSec.Equals(other.IpSec) && (this.Email.Equals(other.Email) && this.NameType.Equals((object) other.NameType) && (this.Signatory.Equals((object) other.Signatory) && this.Protocol.Equals((object) other.Protocol)) && this.Algorithm.Equals((object) other.Algorithm))) && (this.FlagsExtension.HasValue ? (!other.FlagsExtension.HasValue ? 0 : (this.FlagsExtension.Value.Equals(other.FlagsExtension.Value) ? 1 : 0)) : (!other.FlagsExtension.HasValue ? 1 : 0)) != 0) return this.PublicKey.Equals(other.PublicKey); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataKey); } public override int GetHashCode() { return Sequence.GetHashCode((object) BitSequence.Merge(BitSequence.Merge(this.AuthenticationProhibited, this.ConfidentialityProhibited, this.Experimental, this.UserAssociated, this.IpSec, this.Email), (byte) this.NameType, (byte) this.Signatory, (byte) this.Protocol), (object) BitSequence.Merge((byte) this.Algorithm, this.FlagsExtension.HasValue ? this.FlagsExtension.Value : (ushort) 0), (object) this.PublicKey); } internal override int GetLength() { int num1 = 4; ushort? flagsExtension = this.FlagsExtension; int num2 = (flagsExtension.HasValue ? new int?((int) flagsExtension.GetValueOrDefault()) : new int?()).HasValue ? 2 : 0; return num1 + num2 + this.PublicKey.Length; } internal override void WriteDataSimple(byte[] buffer, int offset) { byte num1 = (byte) 0; if (this.AuthenticationProhibited) num1 |= (byte) sbyte.MinValue; if (this.ConfidentialityProhibited) num1 |= (byte) 64; if (this.Experimental) num1 |= (byte) 32; if (this.UserAssociated) num1 |= (byte) 4; if (this.FlagsExtension.HasValue) num1 |= (byte) 16; byte num2 = (byte) ((DnsKeyNameType) num1 | this.NameType & (DnsKeyNameType) 3); ByteArrayExtensions.Write(buffer, offset, num2); byte num3 = (byte) 0; if (this.IpSec) num3 |= (byte) sbyte.MinValue; if (this.Email) num3 |= (byte) 64; byte num4 = (byte) ((DnsKeySignatoryAttributes) num3 | this.Signatory & (DnsKeySignatoryAttributes.General | DnsKeySignatoryAttributes.Unique | DnsKeySignatoryAttributes.Strong | DnsKeySignatoryAttributes.Zone)); ByteArrayExtensions.Write(buffer, offset + 1, num4); ByteArrayExtensions.Write(buffer, offset + 2, (byte) this.Protocol); ByteArrayExtensions.Write(buffer, offset + 3, (byte) this.Algorithm); if (this.FlagsExtension.HasValue) ByteArrayExtensions.Write(buffer, offset + 4, this.FlagsExtension.Value, Endianity.Big); this.PublicKey.Write(buffer, offset + 4 + (this.FlagsExtension.HasValue ? 2 : 0)); } internal override DnsResourceData CreateInstance(DataSegment data) { if (data.Length < 4) return (DnsResourceData) null; bool authenticationProhibited = data.ReadBool(0, (byte) sbyte.MinValue); bool confidentialityProhibited = data.ReadBool(0, (byte) 64); bool experimental = data.ReadBool(0, (byte) 32); bool flag = data.ReadBool(0, (byte) 16); bool userAssociated = data.ReadBool(0, (byte) 4); bool ipSec = data.ReadBool(1, (byte) sbyte.MinValue); bool email = data.ReadBool(1, (byte) 64); DnsKeyNameType nameType = (DnsKeyNameType) ((uint) data[0] & 3U); DnsKeySignatoryAttributes signatory = (DnsKeySignatoryAttributes) ((uint) data[1] & 15U); DnsKeyProtocol protocol = (DnsKeyProtocol) data[2]; DnsAlgorithm algorithm = (DnsAlgorithm) data[3]; ushort? flagsExtension = flag ? new ushort?(data.ReadUShort(4, Endianity.Big)) : new ushort?(); int offset = 4 + (flag ? 2 : 0); DataSegment publicKey = data.Subsegment(offset, data.Length - offset); return (DnsResourceData) new DnsResourceDataKey(authenticationProhibited, confidentialityProhibited, experimental, userAssociated, ipSec, email, nameType, signatory, protocol, algorithm, flagsExtension, publicKey); } private static class Offset { public const int AuthenticationProhibited = 0; public const int ConfidentialityProhibited = 0; public const int Experimental = 0; public const int IsFlagsExtension = 0; public const int UserAssociated = 0; public const int NameType = 0; public const int IpSec = 1; public const int Email = 1; public const int Signatory = 1; public const int Protocol = 2; public const int Algorithm = 3; public const int FlagsExtension = 4; } private static class Mask { public const byte AuthenticationProhibited = (byte) 128; public const byte ConfidentialityProhibited = (byte) 64; public const byte Experimental = (byte) 32; public const byte IsFlagsExtension = (byte) 16; public const byte UserAssociated = (byte) 4; public const byte IpSec = (byte) 128; public const byte Email = (byte) 64; public const byte NameType = (byte) 3; public const byte Signatory = (byte) 15; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Base.IListExtensions // Assembly: PcapDotNet.Base, Version=0.10.0.20668, Culture=neutral, PublicKeyToken=<KEY> // MVID: E9656A63-0145-422C-B8C8-79FDD7FB4270 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Base.dll using System; using System.Collections.Generic; using System.Collections.ObjectModel; namespace PcapDotNet.Base { public static class IListExtensions { public static ReadOnlyCollection<T> AsReadOnly<T>(this IList<T> list) { return new ReadOnlyCollection<T>(list); } public static IEnumerable<T> Range<T>(this IList<T> list, int offset, int count) { int length = Math.Min(offset + count, ((ICollection<T>) list).Count); for (int i = offset; i < length; ++i) yield return list[i]; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Igmp.IgmpQueryVersion2Layer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Igmp { public sealed class IgmpQueryVersion2Layer : IgmpVersion2Layer { public override IgmpMessageType MessageType { get { return IgmpMessageType.MembershipQuery; } } public override IgmpQueryVersion QueryVersion { get { return IgmpQueryVersion.Version2; } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsSinkCodingSubCoding // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Dns { public enum DnsSinkCodingSubCoding : ushort { None = (ushort) 0, Asn1SnmpBasicEncodingRules = (ushort) 257, Asn1SnmpDistinguishedEncodingRules = (ushort) 258, Asn1SnmpPer = (ushort) 259, Asn1SnmpPerUnaligned = (ushort) 260, Asn1SnmpCanonicalEncodingRules = (ushort) 261, Asn1SnmpPrivate = (ushort) 510, Asn1Osi1990BasicEncodingRules = (ushort) 513, Asn1Osi1990DistinguishedEncodingRules = (ushort) 514, Asn1Osi1990Per = (ushort) 515, Asn1Osi1990PerUnaligned = (ushort) 516, Asn1Osi1990CanonicalEncodingRules = (ushort) 517, Asn1Osi1990Private = (ushort) 766, Asn1Osi1994BasicEncodingRules = (ushort) 769, Asn1Osi1994DistinguishedEncodingRules = (ushort) 770, Asn1Osi1994Per = (ushort) 771, Asn1Osi1994PerUnaligned = (ushort) 772, Asn1Osi1994CanonicalEncodingRules = (ushort) 773, Asn1Osi1994Private = (ushort) 1022, AsnPrivateBasicEncodingRules = (ushort) 16129, AsnPrivateDistinguishedEncodingRules = (ushort) 16130, AsnPrivatePer = (ushort) 16131, AsnPrivatePerUnaligned = (ushort) 16132, AsnPrivateCanonicalEncodingRules = (ushort) 16133, AsnPrivatePrivate = (ushort) 16382, Mime7Bit = (ushort) 16641, Mime8Bit = (ushort) 16642, MimeBinary = (ushort) 16643, MimeQuotedPrintable = (ushort) 16644, MimeBase64 = (ushort) 16645, MimePrivate = (ushort) 16894, TextTaggedDataAscii = (ushort) 16897, TextTaggedDataUtf7 = (ushort) 16898, TextTaggedDataUtf8 = (ushort) 16899, TextTaggedDataAsciiMimeHeaderEscapes = (ushort) 16900, TextTaggedDataPrivate = (ushort) 17150, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Http.HttpContentTypeField // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; namespace PcapDotNet.Packets.Http { public sealed class HttpContentTypeField : HttpField, IEquatable<HttpContentTypeField> { private static readonly Regex _regex = HttpRegex.MatchEntire(HttpRegex.Concat(HttpRegex.Capture(HttpRegex.Token, "MediaType"), HttpRegex.Build('/'), HttpRegex.Capture(HttpRegex.Token, "MediaSubType"), HttpRegex.OptionalParameters)); public const string FieldName = "Content-Type"; public const string FieldNameUpper = "CONTENT-TYPE"; private const string MediaTypeGroupName = "MediaType"; private const string MediaSubTypeGroupName = "MediaSubType"; public string MediaType { get; private set; } public string MediaSubtype { get; private set; } public HttpFieldParameters Parameters { get; private set; } public HttpContentTypeField(string mediaType, string mediaSubtype, HttpFieldParameters parameters) : base("Content-Type", string.Format((IFormatProvider) CultureInfo.InvariantCulture, "{0}/{1}{2}", (object) mediaType, (object) mediaSubtype, (object) parameters)) { this.MediaType = mediaType; this.MediaSubtype = mediaSubtype; this.Parameters = parameters; } internal HttpContentTypeField(byte[] fieldValue) : base("Content-Type", (IList<byte>) fieldValue) { string @string = HttpRegex.GetString(fieldValue); Match match = HttpContentTypeField._regex.Match(@string); if (!match.Success) return; this.MediaType = Enumerable.First<Capture>(Enumerable.Cast<Capture>((IEnumerable) match.Groups["MediaType"].Captures)).Value; this.MediaSubtype = Enumerable.First<Capture>(Enumerable.Cast<Capture>((IEnumerable) match.Groups["MediaSubType"].Captures)).Value; this.Parameters = new HttpFieldParameters(MatchExtensions.GroupCapturesValues(match, "ParameterName"), MatchExtensions.GroupCapturesValues(match, "ParameterValue")); } public bool Equals(HttpContentTypeField other) { if (other != null && this.MediaType == other.MediaType && this.MediaSubtype == other.MediaSubtype) return this.Parameters.Equals(other.Parameters); return false; } public override bool Equals(HttpField other) { return this.Equals(other as HttpContentTypeField); } } } <file_sep>using Grib.Api.Interop.SWIG; using System; using System.Text; namespace Grib.Api.Interop { /// <summary> /// Wraps a grib_keys_iterator struct. /// </summary> public class GribKeysIterator : AutoRef { internal GribKeysIterator (IntPtr h) : base(h) { } /// <summary> /// Gets the next value in a series. /// </summary> /// <returns>False if there are no more values.</returns> public bool Next () { return GribApiProxy.GribKeysIteratorNext(this) != 0; } /// <summary> /// Called when [dispose]. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected override void OnDispose (bool disposing) { GribApiProxy.GribKeysIteratorDelete(this); } public string Name { get { StringBuilder sb = new StringBuilder(255); Interop.Util.GribApiNative.GetGribKeysIteratorName(sb, this.Reference.Handle); return sb.ToString(); } } /// <summary> /// Creates an instance of GribKeysIterator. /// </summary> /// <param name="handle">The handle of the message to iterate.</param> /// <param name="filters">The key filters.</param> /// <param name="nspace">The namespace of the keys to iterate.</param> /// <returns></returns> public static GribKeysIterator Create (GribHandle handle, uint filters, string nspace) { return GribApiProxy.GribKeysIteratorNew(handle, filters, nspace); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IpV4OptionLooseSourceRouting // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System.Collections.Generic; namespace PcapDotNet.Packets.IpV4 { [OptionTypeRegistration(typeof (IpV4OptionType), IpV4OptionType.LooseSourceRouting)] public class IpV4OptionLooseSourceRouting : IpV4OptionRoute, IOptionComplexFactory { public IpV4OptionLooseSourceRouting(IList<IpV4Address> route, byte pointedAddressIndex) : base(IpV4OptionType.LooseSourceRouting, route, pointedAddressIndex) { } public IpV4OptionLooseSourceRouting() : this((IList<IpV4Address>) new IpV4Address[0], (byte) 0) { } Option IOptionComplexFactory.CreateInstance(byte[] buffer, ref int offset, byte valueLength) { IpV4Address[] addresses; byte pointedAddressIndex; if (!IpV4OptionRoute.TryRead(out addresses, out pointedAddressIndex, buffer, ref offset, valueLength)) return (Option) null; return (Option) new IpV4OptionLooseSourceRouting((IList<IpV4Address>) addresses, pointedAddressIndex); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataAtmAddress // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.AtmA)] public sealed class DnsResourceDataAtmAddress : DnsResourceDataSimple, IEquatable<DnsResourceDataAtmAddress> { private const int ConstantPartLength = 1; public DnsAtmAddressFormat Format { get; private set; } public DataSegment Address { get; private set; } public DnsResourceDataAtmAddress(DnsAtmAddressFormat format, DataSegment address) { this.Format = format; this.Address = address; } internal DnsResourceDataAtmAddress() : this(DnsAtmAddressFormat.AtmEndSystemAddress, DataSegment.Empty) { } public bool Equals(DnsResourceDataAtmAddress other) { if (other != null && this.Format.Equals((object) other.Format)) return this.Address.Equals(other.Address); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataAtmAddress); } public override int GetHashCode() { return Sequence.GetHashCode((object) this.Format, (object) this.Address); } internal override int GetLength() { return 1 + this.Address.Length; } internal override void WriteDataSimple(byte[] buffer, int offset) { ByteArrayExtensions.Write(buffer, offset, (byte) this.Format); this.Address.Write(buffer, offset + 1); } internal override DnsResourceData CreateInstance(DataSegment data) { if (data.Length < 1) return (DnsResourceData) null; return (DnsResourceData) new DnsResourceDataAtmAddress((DnsAtmAddressFormat) data[0], data.Subsegment(1, data.Length - 1)); } private static class Offset { public const int Format = 0; public const int Address = 1; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IpV4OptionRoute // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace PcapDotNet.Packets.IpV4 { public abstract class IpV4OptionRoute : IpV4OptionComplex, IEquatable<IpV4OptionRoute> { public const int OptionMinimumLength = 3; public const int OptionValueMinimumLength = 1; public const byte PointedAddressIndexMaxValue = (byte) 62; private readonly ReadOnlyCollection<IpV4Address> _route; private readonly byte _pointedAddressIndex; public byte PointedAddressIndex { get { return this._pointedAddressIndex; } } public ReadOnlyCollection<IpV4Address> Route { get { return this._route; } } public override sealed int Length { get { return 3 + 4 * this.Route.Count; } } public override sealed bool IsAppearsAtMostOnce { get { return true; } } protected IpV4OptionRoute(IpV4OptionType optionType, IList<IpV4Address> route, byte pointedAddressIndex) : base(optionType) { if ((int) pointedAddressIndex > 62) throw new ArgumentOutOfRangeException("pointedAddressIndex", (object) pointedAddressIndex, "Maximum value is " + (object) 62); this._route = IListExtensions.AsReadOnly<IpV4Address>(route); this._pointedAddressIndex = pointedAddressIndex; } public bool Equals(IpV4OptionRoute other) { if (other == null || !this.Equivalent((Option) other) || (int) this.PointedAddressIndex != (int) other.PointedAddressIndex) return false; return Enumerable.SequenceEqual<IpV4Address>((IEnumerable<IpV4Address>) this.Route, (IEnumerable<IpV4Address>) other.Route); } public override sealed bool Equals(IpV4Option other) { return this.Equals(other as IpV4OptionRoute); } public override sealed int GetHashCode() { return base.GetHashCode() ^ this.PointedAddressIndex.GetHashCode() ^ IEnumerableExtensions.SequenceGetHashCode<IpV4Address>((IEnumerable<IpV4Address>) this.Route); } internal override sealed void Write(byte[] buffer, ref int offset) { base.Write(buffer, ref offset); buffer[offset++] = (byte) (4 + (int) this.PointedAddressIndex * 4); foreach (IpV4Address ipV4Address in this.Route) ByteArrayExtensions.Write(buffer, ref offset, ipV4Address, Endianity.Big); } internal static bool TryRead(out IpV4Address[] addresses, out byte pointedAddressIndex, byte[] buffer, ref int offset, byte valueLength) { addresses = (IpV4Address[]) null; pointedAddressIndex = (byte) 0; if ((int) valueLength < 1 || (int) valueLength % 4 != 1) return false; byte num = buffer[offset++]; if ((int) num % 4 != 0 || (int) num < 4) return false; pointedAddressIndex = (byte) ((int) num / 4 - 1); int length = (int) valueLength / 4; addresses = new IpV4Address[length]; for (int index = 0; index != length; ++index) addresses[index] = ByteArrayExtensions.ReadIpV4Address(buffer, ref offset, Endianity.Big); return true; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Grib.Api.Tests { static class Settings { public const string PACIFIC_WIND = ".\\TestData\\Pacific.wind.7days.grb"; public const string GRIB = ".\\TestData\\GRIB.grb"; public const string REG_LATLON_GRB1 = ".\\TestData\\regular_latlon_surface.grib1"; public const string REDUCED_LATLON_GRB2 = ".\\TestData\\reduced_latlon_surface.grib2"; public const string OUT_INDEX = ".\\TestData\\out.index"; public const string OUT_GRIB = ".\\TestData\\out.grb"; public const string GAUSS = ".\\TestData\\reduced_gaussian_model_level.grib1"; public const string BIN = ".\\TestData\\ds.waveh.bin"; public const string PNG_COMPRESSION = ".\\TestData\\MRMS2.grib2"; public const string COMPLEX_GRID = ".\\TestData\\gfs_0p50_2015101500_003.grb"; } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Base.ShortExtensions // Assembly: PcapDotNet.Base, Version=0.10.0.20668, Culture=neutral, PublicKeyToken=<KEY> // MVID: E9656A63-0145-422C-B8C8-79FDD7FB4270 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Base.dll using System.Net; namespace PcapDotNet.Base { public static class ShortExtensions { public static short ReverseEndianity(this short value) { return IPAddress.HostToNetworkOrder(value); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Http.HttpRequestMethod // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Text; namespace PcapDotNet.Packets.Http { public sealed class HttpRequestMethod : IEquatable<HttpRequestMethod> { private static readonly Dictionary<string, HttpRequestKnownMethod> _knownMethods = HttpRequestMethod.CreateKnownMethodsTable(); public string Method { get; private set; } public HttpRequestKnownMethod KnownMethod { get { HttpRequestKnownMethod requestKnownMethod; if (HttpRequestMethod._knownMethods.TryGetValue(this.Method, out requestKnownMethod)) return requestKnownMethod; return HttpRequestKnownMethod.Unknown; } } public int Length { get { return this.Method.Length; } } public HttpRequestMethod(string method) { this.Method = method; } public HttpRequestMethod(HttpRequestKnownMethod method) { this.Method = method.ToString().ToUpperInvariant(); if (!HttpRequestMethod._knownMethods.ContainsKey(this.Method)) throw new ArgumentException("Invalid known request method given: " + (object) method, "method"); } internal void Write(byte[] buffer, ref int offset) { ByteArrayExtensions.Write(buffer, ref offset, this.Method, Encoding.ASCII); } private static Dictionary<string, HttpRequestKnownMethod> CreateKnownMethodsTable() { Dictionary<string, HttpRequestKnownMethod> dictionary = new Dictionary<string, HttpRequestKnownMethod>(); foreach (HttpRequestKnownMethod requestKnownMethod in TypeExtensions.GetEnumValues<HttpRequestKnownMethod>(typeof (HttpRequestKnownMethod))) { if (requestKnownMethod != HttpRequestKnownMethod.Unknown) dictionary.Add(requestKnownMethod.ToString().ToUpperInvariant(), requestKnownMethod); } return dictionary; } public bool Equals(HttpRequestMethod other) { if (other != null) return this.Method.Equals(other.Method); return false; } public override bool Equals(object obj) { return this.Equals(obj as HttpRequestMethod); } public override int GetHashCode() { return this.Method.GetHashCode(); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceData // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace PcapDotNet.Packets.Dns { public abstract class DnsResourceData { private static readonly Dictionary<DnsType, DnsResourceData> _prototypes = DnsResourceData.InitializePrototypes(); internal const int StringMinimumLength = 1; public static Type GetDnsResourceDataType(DnsType dnsType) { DnsResourceData prototype = DnsResourceData.TryGetPrototype(dnsType); if (prototype == null) return (Type) null; return prototype.GetType(); } internal abstract int GetLength(DnsDomainNameCompressionData compressionData, int offsetInDns); internal int Write(byte[] buffer, int dnsOffset, int offsetInDns, DnsDomainNameCompressionData compressionData) { int num = this.WriteData(buffer, dnsOffset, offsetInDns + 2, compressionData); ByteArrayExtensions.Write(buffer, dnsOffset + offsetInDns, (ushort) num, Endianity.Big); return num + 2; } internal abstract int WriteData(byte[] buffer, int dnsOffset, int offsetInDns, DnsDomainNameCompressionData compressionData); internal static DnsResourceData Read(DnsDatagram dns, DnsType type, int offsetInDns, int length) { DnsResourceData prototype = DnsResourceData.TryGetPrototype(type); if (prototype != null) return prototype.CreateInstance(dns, offsetInDns, length); return (DnsResourceData) new DnsResourceDataAnything(dns.Subsegment(offsetInDns, length)); } internal abstract DnsResourceData CreateInstance(DnsDatagram dns, int offsetInDns, int length); internal static int GetStringLength(DataSegment str) { return 1 + str.Length; } internal static DataSegment ReadString(DataSegment data, ref int offset) { if (data.Length <= offset) return (DataSegment) null; int length = (int) data[offset++]; if (data.Length < offset + length) return (DataSegment) null; return data.Subsegment(ref offset, length); } internal static void WriteString(byte[] buffer, ref int offset, DataSegment str) { ByteArrayExtensions.Write(buffer, ref offset, (byte) str.Length); str.Write(buffer, ref offset); } private static DnsResourceData TryGetPrototype(DnsType type) { DnsResourceData dnsResourceData; if (!DnsResourceData._prototypes.TryGetValue(type, out dnsResourceData)) return (DnsResourceData) null; return dnsResourceData; } private static Dictionary<DnsType, DnsResourceData> InitializePrototypes() { return Enumerable.ToDictionary(Enumerable.Select(Enumerable.Where(Enumerable.SelectMany((IEnumerable<Type>) Assembly.GetExecutingAssembly().GetTypes(), (Func<Type, IEnumerable<DnsTypeRegistrationAttribute>>) (type => MemberInfoExtensions.GetCustomAttributes<DnsTypeRegistrationAttribute>((MemberInfo) type, false)), (type, attribute) => new { type = type, attribute = attribute }), param0 => typeof (DnsResourceData).IsAssignableFrom(param0.type)), param0 => new { Type = param0.attribute.Type, Prototype = (DnsResourceData) Activator.CreateInstance(param0.type, true) }), prototype => prototype.Type, prototype => prototype.Prototype); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpRedirectDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using PcapDotNet.Packets.IpV4; using System.Linq; namespace PcapDotNet.Packets.Icmp { [IcmpDatagramRegistration(IcmpMessageType.Redirect)] public sealed class IcmpRedirectDatagram : IcmpIpV4HeaderPlus64BitsPayloadDatagram { private static readonly byte _minCode = (byte) Enumerable.Min<IcmpCodeRedirect>(TypeExtensions.GetEnumValues<IcmpCodeRedirect>(typeof (IcmpCodeRedirect))); private static readonly byte _maxCode = (byte) Enumerable.Max<IcmpCodeRedirect>(TypeExtensions.GetEnumValues<IcmpCodeRedirect>(typeof (IcmpCodeRedirect))); public IpV4Address GatewayInternetAddress { get { return this.ReadIpV4Address(4, Endianity.Big); } } protected override byte MinCodeValue { get { return IcmpRedirectDatagram._minCode; } } protected override byte MaxCodeValue { get { return IcmpRedirectDatagram._maxCode; } } private IcmpRedirectDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public override ILayer ExtractLayer() { IcmpRedirectLayer icmpRedirectLayer = new IcmpRedirectLayer(); icmpRedirectLayer.Code = (IcmpCodeRedirect) this.Code; icmpRedirectLayer.Checksum = new ushort?(this.Checksum); icmpRedirectLayer.GatewayInternetAddress = this.GatewayInternetAddress; return (ILayer) icmpRedirectLayer; } internal override IcmpDatagram CreateInstance(byte[] buffer, int offset, int length) { return (IcmpDatagram) new IcmpRedirectDatagram(buffer, offset, length); } private static class Offset { public const int GatewayInternetAddress = 4; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataCertificationAuthorityAuthorization // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.CertificationAuthorityAuthorization)] public sealed class DnsResourceDataCertificationAuthorityAuthorization : DnsResourceDataSimple, IEquatable<DnsResourceDataCertificationAuthorityAuthorization> { private const int ConstantPartLength = 2; [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Flags")] public DnsCertificationAuthorityAuthorizationFlags Flags { get; private set; } public DataSegment Tag { get; private set; } public DataSegment Value { get; private set; } [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "flags")] public DnsResourceDataCertificationAuthorityAuthorization(DnsCertificationAuthorityAuthorizationFlags flags, DataSegment tag, DataSegment value) { if (tag == null) throw new ArgumentNullException("tag"); if (tag.Length > (int) byte.MaxValue) throw new ArgumentOutOfRangeException("tag", (object) tag.Length, string.Format((IFormatProvider) CultureInfo.InvariantCulture, "Cannot be longer than {0}", new object[1] { (object) byte.MaxValue })); this.Flags = flags; this.Tag = tag; this.Value = value; } internal DnsResourceDataCertificationAuthorityAuthorization() : this((DnsCertificationAuthorityAuthorizationFlags) 0, DataSegment.Empty, DataSegment.Empty) { } public bool Equals(DnsResourceDataCertificationAuthorityAuthorization other) { if (other != null && this.Flags.Equals((object) other.Flags) && this.Tag.Equals(other.Tag)) return Enumerable.SequenceEqual<byte>((IEnumerable<byte>) this.Value, (IEnumerable<byte>) other.Value); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataCertificationAuthorityAuthorization); } public override int GetHashCode() { return Sequence.GetHashCode((object) this.Flags, (object) this.Tag, (object) this.Value); } internal override int GetLength() { return 2 + this.Tag.Length + this.Value.Length; } internal override void WriteDataSimple(byte[] buffer, int offset) { ByteArrayExtensions.Write(buffer, offset, (byte) this.Flags); ByteArrayExtensions.Write(buffer, offset + 1, (byte) this.Tag.Length); this.Tag.Write(buffer, offset + 2); this.Value.Write(buffer, offset + 2 + this.Tag.Length); } internal override DnsResourceData CreateInstance(DataSegment data) { if (data.Length < 2) return (DnsResourceData) null; DnsCertificationAuthorityAuthorizationFlags flags = (DnsCertificationAuthorityAuthorizationFlags) data[0]; byte num = data[1]; int offset = 2 + (int) num; if (data.Length < offset) return (DnsResourceData) null; DataSegment tag = data.Subsegment(2, (int) num); DataSegment dataSegment = data.Subsegment(offset, data.Length - offset); return (DnsResourceData) new DnsResourceDataCertificationAuthorityAuthorization(flags, tag, dataSegment); } private static class Offset { public const int Flags = 0; public const int TagLength = 1; public const int Tag = 2; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.TcpOptionMood // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PcapDotNet.Packets.Transport { [OptionTypeRegistration(typeof (TcpOptionType), TcpOptionType.Mood)] public sealed class TcpOptionMood : TcpOptionComplex, IOptionComplexFactory, IEquatable<TcpOptionMood> { private static readonly Dictionary<string, TcpOptionMoodEmotion> _stringToEmotion = new Dictionary<string, TcpOptionMoodEmotion>() { { ":)", TcpOptionMoodEmotion.Happy }, { ":(", TcpOptionMoodEmotion.Sad }, { ":D", TcpOptionMoodEmotion.Amused }, { "%(", TcpOptionMoodEmotion.Confused }, { ":o", TcpOptionMoodEmotion.Bored }, { ":O", TcpOptionMoodEmotion.Surprised }, { ":P", TcpOptionMoodEmotion.Silly }, { ":@", TcpOptionMoodEmotion.Frustrated }, { ">:@", TcpOptionMoodEmotion.Angry }, { ":|", TcpOptionMoodEmotion.Apathetic }, { ";)", TcpOptionMoodEmotion.Sneaky }, { ">:)", TcpOptionMoodEmotion.Evil } }; private static readonly string[] _emotionToString = Enumerable.ToArray<string>(Enumerable.Select<KeyValuePair<string, TcpOptionMoodEmotion>, string>((IEnumerable<KeyValuePair<string, TcpOptionMoodEmotion>>) Enumerable.OrderBy<KeyValuePair<string, TcpOptionMoodEmotion>, TcpOptionMoodEmotion>((IEnumerable<KeyValuePair<string, TcpOptionMoodEmotion>>) TcpOptionMood._stringToEmotion, (Func<KeyValuePair<string, TcpOptionMoodEmotion>, TcpOptionMoodEmotion>) (pair => pair.Value)), (Func<KeyValuePair<string, TcpOptionMoodEmotion>, string>) (pair => pair.Key))); public const int OptionMinimumLength = 4; public const int OptionMaximumLength = 5; public const int OptionValueMinimumLength = 2; public const int OptionValueMaximumLength = 3; public TcpOptionMoodEmotion Emotion { get; private set; } public string EmotionString { get { int index = (int) this.Emotion; if (index >= TcpOptionMood._emotionToString.Length) throw new InvalidOperationException("No string value for emotion " + (object) this.Emotion); return TcpOptionMood._emotionToString[index]; } } public override int Length { get { return 2 + this.ValueLength; } } public override bool IsAppearsAtMostOnce { get { return false; } } private int ValueLength { get { return this.EmotionString.Length; } } public TcpOptionMood(TcpOptionMoodEmotion emotion) : base(TcpOptionType.Mood) { this.Emotion = emotion; } public TcpOptionMood() : this(TcpOptionMoodEmotion.Confused) { } public bool Equals(TcpOptionMood other) { if (other == null) return false; return this.Emotion == other.Emotion; } public override bool Equals(TcpOption other) { return this.Equals(other as TcpOptionMood); } public override int GetHashCode() { return base.GetHashCode() ^ this.Emotion.GetHashCode(); } Option IOptionComplexFactory.CreateInstance(byte[] buffer, ref int offset, byte valueLength) { if ((int) valueLength < 2 || (int) valueLength > 3) return (Option) null; TcpOptionMoodEmotion emotion = TcpOptionMood.StringToEmotion(Encoding.ASCII.GetString(ByteArrayExtensions.ReadBytes(buffer, ref offset, (int) valueLength))); if (emotion == TcpOptionMoodEmotion.None) return (Option) null; return (Option) new TcpOptionMood(emotion); } internal override void Write(byte[] buffer, ref int offset) { base.Write(buffer, ref offset); ByteArrayExtensions.Write(buffer, ref offset, (IEnumerable<byte>) Encoding.ASCII.GetBytes(this.EmotionString)); } private static TcpOptionMoodEmotion StringToEmotion(string emotionString) { TcpOptionMoodEmotion optionMoodEmotion; if (TcpOptionMood._stringToEmotion.TryGetValue(emotionString, out optionMoodEmotion)) return optionMoodEmotion; return TcpOptionMoodEmotion.None; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.PacketTimestamp // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using System; using System.Diagnostics; namespace PcapDotNet.Core { public sealed class PacketTimestamp { private static DateTime _minimumPacketTimestamp = new DateTime(); private static DateTime _maximumPacketTimestamp = new DateTime(); public static DateTime MaximumPacketTimestamp { get { return PacketTimestamp._maximumPacketTimestamp; } } public static DateTime MinimumPacketTimestamp { get { return PacketTimestamp._minimumPacketTimestamp; } } static PacketTimestamp() { PacketTimestamp.Initialize(); } [DebuggerNonUserCode] private PacketTimestamp() { } internal static unsafe void PcapTimestampToDateTime(timeval* pcapTimestamp, out DateTime dateTime) { DateTime dateTime1 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); dateTime = dateTime1; TimeSpan timeSpan = TimeSpan.FromSeconds((double) *(int*) pcapTimestamp) + TimeSpan.FromTicks((long) *(int*) ((IntPtr) pcapTimestamp + 4L) * 10L); DateTime dateTime2 = dateTime.Add(timeSpan); dateTime = dateTime2; DateTime dateTime3 = dateTime.ToLocalTime(); dateTime = dateTime3; } internal static unsafe void DateTimeToPcapTimestamp(DateTime dateTime, timeval* pcapTimestamp) { dateTime = dateTime.ToUniversalTime(); DateTime dateTime1 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); TimeSpan timeSpan = dateTime - dateTime1; *(int*) pcapTimestamp = (int) timeSpan.TotalSeconds; *(int*) ((IntPtr) pcapTimestamp + 4L) = (int) ((timeSpan.TotalMilliseconds - (double) *(int*) pcapTimestamp * 1000.0) * 1000.0); } private static unsafe void Initialize() { timeval timeval; // ISSUE: explicit reference operation // ISSUE: cast to a reference type // ISSUE: explicit reference operation ^(int&) @timeval = int.MinValue; // ISSUE: cast to a reference type // ISSUE: explicit reference operation ^(int&) ((IntPtr) &timeval + 4) = int.MinValue; PacketTimestamp.PcapTimestampToDateTime(&timeval, out PacketTimestamp._minimumPacketTimestamp); // ISSUE: explicit reference operation // ISSUE: cast to a reference type // ISSUE: explicit reference operation ^(int&) @timeval = int.MaxValue; // ISSUE: cast to a reference type // ISSUE: explicit reference operation ^(int&) ((IntPtr) &timeval + 4) = int.MaxValue; PacketTimestamp.PcapTimestampToDateTime(&timeval, out PacketTimestamp._maximumPacketTimestamp); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Http.HttpHeader // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace PcapDotNet.Packets.Http { public sealed class HttpHeader : IEnumerable<HttpField>, IEnumerable, IEquatable<HttpHeader> { private static readonly HttpHeader _empty = new HttpHeader(new HttpField[0]); private readonly Dictionary<string, HttpField> _fields = new Dictionary<string, HttpField>((IEqualityComparer<string>) StringComparer.OrdinalIgnoreCase); public static HttpHeader Empty { get { return HttpHeader._empty; } } public int BytesLength { get { return Enumerable.Sum<HttpField>((IEnumerable<HttpField>) this, (Func<HttpField, int>) (field => field.Length)) + 2; } } public HttpField this[string fieldName] { get { return this.GetField<HttpField>(fieldName); } } public HttpTransferEncodingField TransferEncoding { get { return this.GetField<HttpTransferEncodingField>("Transfer-Encoding"); } } public HttpContentLengthField ContentLength { get { return this.GetField<HttpContentLengthField>("Content-Length"); } } public HttpContentTypeField ContentType { get { return this.GetField<HttpContentTypeField>("Content-Type"); } } public HttpTrailerField Trailer { get { return this.GetField<HttpTrailerField>("Trailer"); } } public HttpHeader(IEnumerable<HttpField> fields) { this._fields = Enumerable.ToDictionary<HttpField, string, HttpField>(fields, (Func<HttpField, string>) (field => field.Name), (Func<HttpField, HttpField>) (field => field), (IEqualityComparer<string>) StringComparer.OrdinalIgnoreCase); } public HttpHeader(params HttpField[] fields) : this((IEnumerable<HttpField>) fields) { } internal HttpHeader(IEnumerable<KeyValuePair<string, IEnumerable<byte>>> fields) { Dictionary<string, IEnumerable<byte>> dictionary = new Dictionary<string, IEnumerable<byte>>((IEqualityComparer<string>) StringComparer.OrdinalIgnoreCase); foreach (KeyValuePair<string, IEnumerable<byte>> keyValuePair in fields) { string key = keyValuePair.Key; IEnumerable<byte> sequence; if (!dictionary.TryGetValue(key, out sequence)) { sequence = keyValuePair.Value; dictionary.Add(key, sequence); } else dictionary[key] = Enumerable.Concat<byte>(IEnumerableExtensions.Concat<byte>(sequence, (byte) 44), keyValuePair.Value); } this._fields = Enumerable.ToDictionary<KeyValuePair<string, IEnumerable<byte>>, string, HttpField>((IEnumerable<KeyValuePair<string, IEnumerable<byte>>>) dictionary, (Func<KeyValuePair<string, IEnumerable<byte>>, string>) (field => field.Key), (Func<KeyValuePair<string, IEnumerable<byte>>, HttpField>) (field => HttpField.CreateField(field.Key, Enumerable.ToArray<byte>(field.Value))), (IEqualityComparer<string>) StringComparer.OrdinalIgnoreCase); } public bool Equals(HttpHeader other) { if (other != null) return IDictionaryExtensions.DictionaryEquals<string, HttpField>((IDictionary<string, HttpField>) this._fields, (IDictionary<string, HttpField>) other._fields); return false; } public override bool Equals(object obj) { return this.Equals(obj as HttpHeader); } public override int GetHashCode() { return IEnumerableExtensions.SequenceGetHashCode<HttpField>(Enumerable.Select<KeyValuePair<string, HttpField>, HttpField>((IEnumerable<KeyValuePair<string, HttpField>>) this._fields, (Func<KeyValuePair<string, HttpField>, HttpField>) (pair => pair.Value))); } public override string ToString() { return IEnumerableExtensions.SequenceToString<HttpField>((IEnumerable<HttpField>) this, "\r\n"); } public IEnumerator<HttpField> GetEnumerator() { return (IEnumerator<HttpField>) this._fields.Values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator) this.GetEnumerator(); } public void Write(byte[] buffer, int offset) { this.Write(buffer, ref offset); } public void Write(byte[] buffer, ref int offset) { foreach (HttpField httpField in this) httpField.Write(buffer, ref offset); ByteArrayExtensions.WriteCarriageReturnLinefeed(buffer, ref offset); } private T GetField<T>(string fieldName) where T : HttpField { HttpField httpField; if (!this._fields.TryGetValue(fieldName, out httpField)) return default (T); return (T) httpField; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsOption // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Dns { public abstract class DnsOption : IEquatable<DnsOption> { public const int MinimumLength = 4; public DnsOptionCode Code { get; private set; } public int Length { get { return 4 + this.DataLength; } } public abstract int DataLength { get; } internal DnsOption(DnsOptionCode code) { this.Code = code; } public bool Equals(DnsOption other) { if (other != null && this.Code.Equals((object) other.Code) && this.GetType().Equals(other.GetType())) return this.EqualsData(other); return false; } public override sealed bool Equals(object obj) { return this.Equals(obj as DnsOption); } public override int GetHashCode() { return this.Code.GetHashCode() ^ this.DataGetHashCode(); } internal abstract bool EqualsData(DnsOption other); internal abstract int DataGetHashCode(); internal void Write(byte[] buffer, ref int offset) { ByteArrayExtensions.Write(buffer, ref offset, (ushort) this.Code, Endianity.Big); ByteArrayExtensions.Write(buffer, ref offset, (ushort) this.DataLength, Endianity.Big); this.WriteData(buffer, ref offset); } internal abstract void WriteData(byte[] buffer, ref int offset); internal static DnsOption CreateInstance(DnsOptionCode code, DataSegment data) { switch (code) { case DnsOptionCode.LongLivedQuery: return (DnsOption) DnsOptionLongLivedQuery.Read(data); case DnsOptionCode.UpdateLease: return (DnsOption) DnsOptionUpdateLease.Read(data); default: return (DnsOption) new DnsOptionAnything(code, data); } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.DeviceAttributes // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using System; namespace PcapDotNet.Core { [Flags] public enum DeviceAttributes { Loopback = 1, None = 0, } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsOptionLongLivedQuery // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; namespace PcapDotNet.Packets.Dns { public sealed class DnsOptionLongLivedQuery : DnsOption { private const int ConstDataLength = 18; public ushort Version { get; private set; } public DnsLongLivedQueryOpCode OpCode { get; private set; } public DnsLongLivedQueryErrorCode ErrorCode { get; private set; } public ulong Id { get; private set; } public uint LeaseLife { get; private set; } public override int DataLength { get { return 18; } } public DnsOptionLongLivedQuery(ushort version, DnsLongLivedQueryOpCode opCode, DnsLongLivedQueryErrorCode errorCode, ulong id, uint leaseLife) : base(DnsOptionCode.LongLivedQuery) { this.Version = version; this.OpCode = opCode; this.ErrorCode = errorCode; this.Id = id; this.LeaseLife = leaseLife; } internal override bool EqualsData(DnsOption other) { DnsOptionLongLivedQuery optionLongLivedQuery = (DnsOptionLongLivedQuery) other; if (this.Version.Equals(optionLongLivedQuery.Version) && this.OpCode.Equals((object) optionLongLivedQuery.OpCode) && this.ErrorCode.Equals((object) optionLongLivedQuery.ErrorCode) && this.Id.Equals(optionLongLivedQuery.Id)) return this.LeaseLife.Equals(optionLongLivedQuery.LeaseLife); return false; } internal override int DataGetHashCode() { return Sequence.GetHashCode((object) BitSequence.Merge(this.Version, (ushort) this.OpCode), (object) this.ErrorCode, (object) this.Id, (object) this.LeaseLife); } internal override void WriteData(byte[] buffer, ref int offset) { ByteArrayExtensions.Write(buffer, offset, this.Version, Endianity.Big); ByteArrayExtensions.Write(buffer, offset + 2, (ushort) this.OpCode, Endianity.Big); ByteArrayExtensions.Write(buffer, offset + 4, (ushort) this.ErrorCode, Endianity.Big); ByteArrayExtensions.Write(buffer, offset + 6, this.Id, Endianity.Big); ByteArrayExtensions.Write(buffer, offset + 14, this.LeaseLife, Endianity.Big); offset += this.DataLength; } internal static DnsOptionLongLivedQuery Read(DataSegment data) { if (data.Length != 18) return (DnsOptionLongLivedQuery) null; return new DnsOptionLongLivedQuery(data.ReadUShort(0, Endianity.Big), (DnsLongLivedQueryOpCode) data.ReadUShort(2, Endianity.Big), (DnsLongLivedQueryErrorCode) data.ReadUShort(4, Endianity.Big), data.ReadULong(6, Endianity.Big), data.ReadUInt(14, Endianity.Big)); } private static class Offset { public const int Version = 0; public const int OpCode = 2; public const int ErrorCode = 4; public const int Id = 6; public const int LeaseLife = 14; } } } <file_sep>using System; using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using WeatherNet; using WeatherNet.Clients; using System.Threading.Tasks; namespace WeatherNetUWPTest { [TestClass] public class UnitTest1 { [TestMethod] public async Task GetCurrentWeatherByCityNameTest() { //Specifying optional settings ClientSettings.ApiUrl = "http://api.openweathermap.org/data/2.5"; ClientSettings.ApiKey = "2de143494c0b295cca9337e1e96b00e0"; //Provide your own ApiKey here, this is just for testing //Exist var result = await CurrentWeather.GetByCityNameAsync("Dublin", "Ireland", "se", "metric"); Assert.IsTrue(result.Success); Assert.IsNotNull(result.Item); result = await CurrentWeather.GetByCityNameAsync("Dublin", "Ireland", "nl", "imperial"); Assert.IsTrue(result.Success); Assert.IsNotNull(result.Item); } [TestMethod] public async Task GetCurrentCurrentWeatherByCityIdTest() { //Does not exist var result = await CurrentWeather.GetByCityIdAsync(1111111); Assert.IsFalse(result.Success); Assert.IsNull(result.Item); //Exist result = await CurrentWeather.GetByCityIdAsync(2964574); Assert.IsTrue(result.Success); Assert.IsNotNull(result.Item); } [TestMethod] public async Task GetCurrentCurrentWeatherByCityCoordinatesTest() { //Does Not Exist var result = await CurrentWeather.GetByCoordinatesAsync(-1984453.363665, -1984453.363665); Assert.IsFalse(result.Success); Assert.IsNull(result.Item); //Exist result = await CurrentWeather.GetByCoordinatesAsync(53.363665, -6.255541); Assert.IsTrue(result.Success); Assert.IsNotNull(result.Item); result = await CurrentWeather.GetByCoordinatesAsync(53.363665, -6.255541, "nl", "imperial"); Assert.IsTrue(result.Success); Assert.IsNotNull(result.Item); } [TestMethod] public async Task GetFiveDaysForecastByCityNameTest() { //Does not exist var result = await FiveDaysForecast.GetByCityNameAsync("12345325231432", "32412342134231"); Assert.IsFalse(result.Success); Assert.IsNull(result.Items); //Exist result = await FiveDaysForecast.GetByCityNameAsync("Dublin", "Ireland"); Assert.IsTrue(result.Success); Assert.IsNotNull(result.Items); Assert.IsTrue(result.Items.Count > 0); Assert.IsNotNull(result.Items[0]); result = await FiveDaysForecast.GetByCityNameAsync("Dublin", "Ireland", "de", "metric"); Assert.IsTrue(result.Success); Assert.IsNotNull(result.Items); Assert.IsTrue(result.Items.Count > 0); Assert.IsNotNull(result.Items[0]); } [TestMethod] public async Task GetFiveDaysForecastByCityIdTest() { //Does not exist var result = await FiveDaysForecast.GetByCityIdAsync(-2964574); Assert.IsFalse(result.Success); Assert.IsNull(result.Items); //Exist result = await FiveDaysForecast.GetByCityIdAsync(2964574); Assert.IsTrue(result.Success); Assert.IsNotNull(result.Items); Assert.IsTrue(result.Items.Count > 0); Assert.IsNotNull(result.Items[0]); result = await FiveDaysForecast.GetByCityIdAsync(2964574, "de", "metric"); Assert.IsTrue(result.Success); Assert.IsNotNull(result.Items); Assert.IsTrue(result.Items.Count > 0); Assert.IsNotNull(result.Items[0]); } [TestMethod] public async Task GetFiveDaysForecastByCityCoordinatesTest() { //Does not exist var result = await FiveDaysForecast.GetByCoordinatesAsync(-1984453.363665, -1984453.363665); Assert.IsFalse(result.Success); Assert.IsNull(result.Items); //Exist result = await FiveDaysForecast.GetByCoordinatesAsync(53.363665, -6.255541, "se", "imperial"); Assert.IsTrue(result.Success); Assert.IsNotNull(result.Items); Assert.IsTrue(result.Items.Count > 0); Assert.IsNotNull(result.Items[0]); } [TestMethod] public async Task GetSixteenDaysForecastByCityNameTest() { //Does not exist var result = await SixteenDaysForecast.GetByCityNameAsync("testcitytest2", "testcitytest2", 14); Assert.IsFalse(result.Success); Assert.IsNull(result.Items); //Exist result = await SixteenDaysForecast.GetByCityNameAsync("Dublin", "Ireland", 14); Assert.IsTrue(result.Success); Assert.IsNotNull(result.Items); Assert.IsTrue(result.Items.Count > 0); Assert.IsNotNull(result.Items[0]); } [TestMethod] public async Task GetSixteenDaysForecastByCityIdTest() { //Does not exist var result = await SixteenDaysForecast.GetByCityIdAsync(1111111, 5); Assert.IsFalse(result.Success); Assert.IsNull(result.Items); //Exist result = await SixteenDaysForecast.GetByCityIdAsync(2964574, 14); Assert.IsTrue(result.Success); Assert.IsNotNull(result.Items); Assert.IsTrue(result.Items.Count > 0); Assert.IsNotNull(result.Items[0]); } [TestMethod] public async Task GetSixteenDaysForecastByCityCoordinatesTest() { //Does not exist var result = await SixteenDaysForecast.GetByCoordinatesAsync(-1984453.363665, -1984453.363665, 14); Assert.IsFalse(result.Success); Assert.IsNull(result.Items); //Exist result = await SixteenDaysForecast.GetByCoordinatesAsync(53.363665, -6.255541, 14);//, "se", "metric"); Assert.IsTrue(result.Success); Assert.IsNotNull(result.Items); Assert.IsTrue(result.Items.Count > 0); Assert.IsNotNull(result.Items[0]); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataRouteThrough // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.RouteThrough)] public sealed class DnsResourceDataRouteThrough : DnsResourceDataUShortDomainName { public ushort Preference { get { return this.Value; } } public DnsDomainName IntermediateHost { get { return this.DomainName; } } public DnsResourceDataRouteThrough(ushort preference, DnsDomainName intermediateHost) : base(preference, intermediateHost) { } internal DnsResourceDataRouteThrough() : this((ushort) 0, DnsDomainName.Root) { } internal override DnsResourceData CreateInstance(DnsDatagram dns, int offsetInDns, int length) { ushort preference; DnsDomainName domainName; if (!DnsResourceDataUShortDomainName.TryRead(out preference, out domainName, dns, offsetInDns, length)) return (DnsResourceData) null; return (DnsResourceData) new DnsResourceDataRouteThrough(preference, domainName); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpRouterAdvertisementLayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Linq; namespace PcapDotNet.Packets.Icmp { public sealed class IcmpRouterAdvertisementLayer : IcmpLayer { public TimeSpan Lifetime { get; set; } [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ReadOnlyCollection<IcmpRouterAdvertisementEntry> Entries { get; set; } public override IcmpMessageType MessageType { get { return IcmpMessageType.RouterAdvertisement; } } protected override uint Variable { get { return (uint) ((int) (byte) this.Entries.Count << 24 | 131072) | (uint) (ushort) this.Lifetime.TotalSeconds; } } protected override int PayloadLength { get { return IcmpRouterAdvertisementDatagram.GetPayloadLength(this.Entries.Count); } } protected override void WritePayload(byte[] buffer, int offset) { IcmpRouterAdvertisementDatagram.WriteHeaderAdditional(buffer, offset, (IEnumerable<IcmpRouterAdvertisementEntry>) this.Entries); } protected override bool EqualPayload(IcmpLayer other) { return this.EqualPayload(other as IcmpRouterAdvertisementLayer); } private bool EqualPayload(IcmpRouterAdvertisementLayer other) { if (other != null) return Enumerable.SequenceEqual<IcmpRouterAdvertisementEntry>((IEnumerable<IcmpRouterAdvertisementEntry>) this.Entries, (IEnumerable<IcmpRouterAdvertisementEntry>) other.Entries); return false; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataIsdn // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System.Collections.Generic; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.Isdn)] public sealed class DnsResourceDataIsdn : DnsResourceDataStrings { private const int MinNumStrings = 1; private const int MaxNumStrings = 2; public DataSegment IsdnAddress { get { return this.Strings[0]; } } public DataSegment Subaddress { get { if (this.Strings.Count != 2) return (DataSegment) null; return this.Strings[1]; } } public DnsResourceDataIsdn(DataSegment isdnAddress) : base(new DataSegment[1] { isdnAddress }) { } public DnsResourceDataIsdn(DataSegment isdnAddress, DataSegment subaddress) : base(isdnAddress, subaddress) { } internal DnsResourceDataIsdn() : this(DataSegment.Empty) { } internal override DnsResourceData CreateInstance(DataSegment data) { List<DataSegment> list = DnsResourceDataStrings.ReadStrings(data, 2); if (list == null) return (DnsResourceData) null; if (list.Count == 1) return (DnsResourceData) new DnsResourceDataIsdn(list[0]); if (list.Count == 2) return (DnsResourceData) new DnsResourceDataIsdn(list[0], list[1]); return (DnsResourceData) null; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpSecurityFailuresDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System.Linq; namespace PcapDotNet.Packets.Icmp { [IcmpDatagramRegistration(IcmpMessageType.SecurityFailures)] public sealed class IcmpSecurityFailuresDatagram : IcmpIpV4HeaderPlus64BitsPayloadDatagram { private static readonly byte _minCode = (byte) Enumerable.Min<IcmpCodeSecurityFailure>(TypeExtensions.GetEnumValues<IcmpCodeSecurityFailure>(typeof (IcmpCodeSecurityFailure))); private static readonly byte _maxCode = (byte) Enumerable.Max<IcmpCodeSecurityFailure>(TypeExtensions.GetEnumValues<IcmpCodeSecurityFailure>(typeof (IcmpCodeSecurityFailure))); public ushort Pointer { get { return this.ReadUShort(6, Endianity.Big); } } protected override byte MinCodeValue { get { return IcmpSecurityFailuresDatagram._minCode; } } protected override byte MaxCodeValue { get { return IcmpSecurityFailuresDatagram._maxCode; } } private IcmpSecurityFailuresDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public override ILayer ExtractLayer() { IcmpSecurityFailuresLayer securityFailuresLayer = new IcmpSecurityFailuresLayer(); securityFailuresLayer.Code = (IcmpCodeSecurityFailure) this.Code; securityFailuresLayer.Checksum = new ushort?(this.Checksum); securityFailuresLayer.Pointer = this.Pointer; return (ILayer) securityFailuresLayer; } protected override bool CalculateIsValid() { if (base.CalculateIsValid()) return (int) this.Pointer < this.IpV4.Length; return false; } internal override IcmpDatagram CreateInstance(byte[] buffer, int offset, int length) { return (IcmpDatagram) new IcmpSecurityFailuresDatagram(buffer, offset, length); } private static class Offset { public const int Pointer = 6; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Gre.GreDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using PcapDotNet.Packets.Ethernet; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace PcapDotNet.Packets.Gre { public sealed class GreDatagram : EthernetBaseDatagram { private bool _isValidRouting = true; public const int HeaderMinimumLength = 4; private ReadOnlyCollection<GreSourceRouteEntry> _routing; private bool? _isChecksumCorrect; private int? _activeSourceRouteEntryIndex; public override int HeaderLength { get { return GreDatagram.GetHeaderLength(this.ChecksumPresent, this.KeyPresent, this.SequenceNumberPresent, this.AcknowledgmentSequenceNumberPresent, (IEnumerable<GreSourceRouteEntry>) this.Routing); } } public override EthernetType EtherType { get { return this.ProtocolType; } } public bool ChecksumPresent { get { return ((int) this[0] & 128) == 128; } } public bool RoutingPresent { get { return ((int) this[0] & 64) == 64; } } public bool KeyPresent { get { return ((int) this[0] & 32) == 32; } } public bool SequenceNumberPresent { get { return ((int) this[0] & 16) == 16; } } public bool StrictSourceRoute { get { return ((int) this[0] & 8) == 8; } } public byte RecursionControl { get { return (byte) ((uint) this[0] & 7U); } } public bool AcknowledgmentSequenceNumberPresent { get { return ((int) this[1] & 128) == 128; } } public byte FutureUseBits { get { return (byte) (((int) this[1] & 120) >> 3); } } public GreVersion Version { get { return (GreVersion) ((uint) this[1] & 7U); } } public EthernetType ProtocolType { get { return (EthernetType) this.ReadUShort(2, Endianity.Big); } } public ushort Checksum { get { return this.ReadUShort(4, Endianity.Big); } } public bool IsChecksumCorrect { get { if (!this._isChecksumCorrect.HasValue) this._isChecksumCorrect = new bool?((int) this.CalculateChecksum() == (int) this.Checksum); return this._isChecksumCorrect.Value; } } public ushort RoutingOffset { get { return this.ReadUShort(6, Endianity.Big); } } public int? ActiveSourceRouteEntryIndex { get { this.TryParseRouting(); return this._activeSourceRouteEntryIndex; } } public GreSourceRouteEntry ActiveSourceRouteEntry { get { int? sourceRouteEntryIndex = this.ActiveSourceRouteEntryIndex; if (!sourceRouteEntryIndex.HasValue || sourceRouteEntryIndex.Value == this.Routing.Count) return (GreSourceRouteEntry) null; return this.Routing[sourceRouteEntryIndex.Value]; } } public uint Key { get { return this.ReadUInt(this.OffsetKey, Endianity.Big); } } public ushort KeyPayloadLength { get { return this.ReadUShort(this.OffsetKeyPayloadLength, Endianity.Big); } } public ushort KeyCallId { get { return this.ReadUShort(this.OffsetKeyCallId, Endianity.Big); } } public uint SequenceNumber { get { return this.ReadUInt(this.OffsetSequenceNumber, Endianity.Big); } } public uint AcknowledgmentSequenceNumber { get { return this.ReadUInt(this.OffsetAcknowledgmentSequenceNumber, Endianity.Big); } } public ReadOnlyCollection<GreSourceRouteEntry> Routing { get { this.TryParseRouting(); return this._routing; } } private int OffsetKey { get { return 4 + (this.ChecksumPresent || this.RoutingPresent ? 4 : 0); } } private int OffsetKeyPayloadLength { get { return this.OffsetKey; } } private int OffsetKeyCallId { get { return this.OffsetKey + 2; } } private int OffsetSequenceNumber { get { return this.OffsetKey + (this.KeyPresent ? 4 : 0); } } private int OffsetAcknowledgmentSequenceNumber { get { return this.OffsetSequenceNumber + (this.SequenceNumberPresent ? 4 : 0); } } private int OffsetRouting { get { return this.OffsetAcknowledgmentSequenceNumber + (this.AcknowledgmentSequenceNumberPresent ? 4 : 0); } } private bool IsValidRouting { get { this.TryParseRouting(); return this._isValidRouting; } } internal GreDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public override ILayer ExtractLayer() { return (ILayer) new GreLayer() { Version = this.Version, ProtocolType = this.ProtocolType, RecursionControl = this.RecursionControl, FutureUseBits = this.FutureUseBits, ChecksumPresent = this.ChecksumPresent, Checksum = (this.ChecksumPresent ? new ushort?(this.Checksum) : new ushort?()), Key = (this.KeyPresent ? new uint?(this.Key) : new uint?()), SequenceNumber = (this.SequenceNumberPresent ? new uint?(this.SequenceNumber) : new uint?()), AcknowledgmentSequenceNumber = (this.AcknowledgmentSequenceNumberPresent ? new uint?(this.AcknowledgmentSequenceNumber) : new uint?()), Routing = (this.RoutingPresent ? this.Routing : (ReadOnlyCollection<GreSourceRouteEntry>) null), RoutingOffset = (this.RoutingPresent ? new ushort?(this.RoutingOffset) : new ushort?()), StrictSourceRoute = this.StrictSourceRoute }; } protected override bool CalculateIsValid() { if (this.Length < 4 || this.Length < this.HeaderLength) return false; Datagram payloadByEtherType = this.PayloadByEtherType; if (!this.IsValidRouting || (int) this.FutureUseBits != 0 || this.Version != GreVersion.EnhancedGre && (this.Version != GreVersion.Gre || this.AcknowledgmentSequenceNumberPresent) || this.ChecksumPresent && !this.IsChecksumCorrect) return false; if (payloadByEtherType != null) return payloadByEtherType.IsValid; return true; } internal static int GetHeaderLength(bool isChecksumPresent, bool isKeyPresent, bool isSequenceNumberPresent, bool isAcknowledgmentSequenceNumberPresent, IEnumerable<GreSourceRouteEntry> routing) { return 4 + (isChecksumPresent || routing != null ? 4 : 0) + (isKeyPresent ? 4 : 0) + (isSequenceNumberPresent ? 4 : 0) + (isAcknowledgmentSequenceNumberPresent ? 4 : 0) + (routing != null ? Enumerable.Sum<GreSourceRouteEntry>(routing, (Func<GreSourceRouteEntry, int>) (entry => entry.Length)) + 4 : 0); } internal static void WriteHeader(byte[] buffer, int offset, byte recursionControl, byte flags, GreVersion version, EthernetType protocolType, bool checksumPresent, uint? key, uint? sequenceNumber, uint? acknowledgmentSequenceNumber, ReadOnlyCollection<GreSourceRouteEntry> routing, ushort? routingOffset, bool strictSourceRoute) { ByteArrayExtensions.Write(buffer, offset, (byte) ((checksumPresent ? 128 : 0) | (routing != null ? 64 : 0) | (key.HasValue ? 32 : 0) | (sequenceNumber.HasValue ? 16 : 0) | (strictSourceRoute ? 8 : 0) | (int) recursionControl & 7)); ByteArrayExtensions.Write(buffer, offset + 1, (byte) ((GreVersion) ((acknowledgmentSequenceNumber.HasValue ? 128 : 0) | (int) flags << 3 & 120) | version & (GreVersion) 7)); ByteArrayExtensions.Write(buffer, offset + 2, (ushort) protocolType, Endianity.Big); offset += 4; if (checksumPresent || routing != null) { offset += 2; ushort? nullable = routingOffset; if ((nullable.HasValue ? new int?((int) nullable.GetValueOrDefault()) : new int?()).HasValue) ByteArrayExtensions.Write(buffer, offset, routingOffset.Value, Endianity.Big); offset += 2; } if (key.HasValue) ByteArrayExtensions.Write(buffer, ref offset, key.Value, Endianity.Big); if (sequenceNumber.HasValue) ByteArrayExtensions.Write(buffer, ref offset, sequenceNumber.Value, Endianity.Big); if (acknowledgmentSequenceNumber.HasValue) ByteArrayExtensions.Write(buffer, ref offset, acknowledgmentSequenceNumber.Value, Endianity.Big); if (routing == null) return; foreach (GreSourceRouteEntry sourceRouteEntry in routing) sourceRouteEntry.Write(buffer, ref offset); ByteArrayExtensions.Write(buffer, ref offset, 0U, Endianity.Big); } internal static void WriteChecksum(byte[] buffer, int offset, int length, ushort? checksum) { ushort? nullable = checksum; ushort num = !(nullable.HasValue ? new int?((int) nullable.GetValueOrDefault()) : new int?()).HasValue ? GreDatagram.CalculateChecksum(buffer, offset, length) : checksum.Value; ByteArrayExtensions.Write(buffer, offset + 4, num, Endianity.Big); } private void TryParseRouting() { if (this._routing != null || !this.RoutingPresent) return; List<GreSourceRouteEntry> list = new List<GreSourceRouteEntry>(); int num1 = this.StartOffset + this.OffsetRouting; int offset = num1; int num2 = this.StartOffset + this.Length; while (num2 >= offset) { if (offset == num1 + (int) this.RoutingOffset) this._activeSourceRouteEntryIndex = new int?(list.Count); GreSourceRouteEntry entry; if (!GreSourceRouteEntry.TryReadEntry(this.Buffer, ref offset, num2 - offset, out entry)) { this._isValidRouting = false; break; } if (entry != null) list.Add(entry); else break; } this._routing = new ReadOnlyCollection<GreSourceRouteEntry>((IList<GreSourceRouteEntry>) list); } private ushort CalculateChecksum() { return GreDatagram.CalculateChecksum(this.Buffer, this.StartOffset, this.Length); } private static ushort CalculateChecksum(byte[] buffer, int offset, int length) { return DataSegment.Sum16BitsToChecksum(DataSegment.Sum16Bits(buffer, offset, Math.Min(4, length)) + DataSegment.Sum16Bits(buffer, offset + 4 + 2, length - 4 - 2)); } private static class Offset { public const int ChecksumPresent = 0; public const int RoutingPresent = 0; public const int KeyPresent = 0; public const int SequenceNumberPresent = 0; public const int StrictSourceRoute = 0; public const int RecursionControl = 0; public const int AcknowledgmentSequenceNumberPresent = 1; public const int FutureUseBits = 1; public const int Version = 1; public const int ProtocolType = 2; public const int Checksum = 4; public const int RoutingOffset = 6; } private static class Mask { public const byte ChecksumPresent = (byte) 128; public const byte RoutingPresent = (byte) 64; public const byte KeyPresent = (byte) 32; public const byte SequenceNumberPresent = (byte) 16; public const byte StrictSourceRoute = (byte) 8; public const byte RecursionControl = (byte) 7; public const byte AcknowledgmentSequenceNumberPresent = (byte) 128; public const byte FutureUseBits = (byte) 120; public const byte Version = (byte) 7; } private static class Shift { public const int FutureUseBits = 3; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Http.HttpContentLengthField // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using System; using System.Collections.Generic; using System.Globalization; namespace PcapDotNet.Packets.Http { public class HttpContentLengthField : HttpField { public const string FieldName = "Content-Length"; public const string FieldNameUpper = "CONTENT-LENGTH"; public uint? ContentLength { get; private set; } public HttpContentLengthField(uint contentLength) : base("Content-Length", contentLength.ToString((IFormatProvider) CultureInfo.InvariantCulture)) { this.ContentLength = new uint?(contentLength); } internal HttpContentLengthField(byte[] fieldValue) : base("Content-Length", (IList<byte>) fieldValue) { HttpParser httpParser = new HttpParser(fieldValue); uint? number; httpParser.DecimalNumber(out number); if (!httpParser.Success) return; this.ContentLength = number; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Base.IDictionaryExtensions // Assembly: PcapDotNet.Base, Version=0.10.0.20668, Culture=neutral, PublicKeyToken=<KEY> // MVID: E9656A63-0145-422C-B8C8-79FDD7FB4270 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Base.dll using System; using System.Collections.Generic; namespace PcapDotNet.Base { public static class IDictionaryExtensions { public static bool DictionaryEquals<TKey, TValue>(this IDictionary<TKey, TValue> dictionary1, IDictionary<TKey, TValue> dictionary2, IEqualityComparer<TValue> valueComparer) { if (valueComparer == null) throw new ArgumentNullException("valueComparer"); if (object.ReferenceEquals((object) dictionary1, (object) dictionary2)) return true; if (dictionary1 == null || dictionary2 == null || dictionary1.Count != dictionary2.Count) return false; foreach (KeyValuePair<TKey, TValue> keyValuePair in (IEnumerable<KeyValuePair<TKey, TValue>>) dictionary1) { TValue y; if (!dictionary2.TryGetValue(keyValuePair.Key, out y) || !valueComparer.Equals(keyValuePair.Value, y)) return false; } return true; } public static bool DictionaryEquals<TKey, TValue>(this IDictionary<TKey, TValue> dictionary1, IDictionary<TKey, TValue> dictionary2) { return IDictionaryExtensions.DictionaryEquals<TKey, TValue>(dictionary1, dictionary2, (IEqualityComparer<TValue>) EqualityComparer<TValue>.Default); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsGateway // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Dns { public abstract class DnsGateway : IEquatable<DnsGateway> { private static readonly DnsGatewayNone _none = new DnsGatewayNone(); public static DnsGatewayNone None { get { return DnsGateway._none; } } public abstract DnsGatewayType GatewayType { get; } public abstract int Length { get; } public abstract bool Equals(DnsGateway other); public override sealed bool Equals(object obj) { return this.Equals(obj as DnsGateway); } public override sealed int GetHashCode() { return this.GatewayType.GetHashCode() ^ this.DataGetHashCode(); } internal abstract int DataGetHashCode(); internal abstract void Write(byte[] buffer, int offset); internal static DnsGateway CreateInstance(DnsGatewayType gatewayType, DnsDatagram dns, int offsetInDns, int length) { switch (gatewayType) { case DnsGatewayType.None: return (DnsGateway) DnsGateway.None; case DnsGatewayType.IpV4: if (length < 4) return (DnsGateway) null; return (DnsGateway) new DnsGatewayIpV4(dns.ReadIpV4Address(offsetInDns, Endianity.Big)); case DnsGatewayType.IpV6: if (length < 16) return (DnsGateway) null; return (DnsGateway) new DnsGatewayIpV6(dns.ReadIpV6Address(offsetInDns, Endianity.Big)); case DnsGatewayType.DomainName: DnsDomainName domainName; int numBytesRead; if (!DnsDomainName.TryParse(dns, offsetInDns, length, out domainName, out numBytesRead)) return (DnsGateway) null; return (DnsGateway) new DnsGatewayDomainName(domainName); default: return (DnsGateway) null; } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Gre.GreSourceRouteEntryAs // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace PcapDotNet.Packets.Gre { public sealed class GreSourceRouteEntryAs : GreSourceRouteEntry { private readonly ReadOnlyCollection<ushort> _asNumbers; private readonly int _nextAsNumberIndex; public override GreSourceRouteEntryAddressFamily AddressFamily { get { return GreSourceRouteEntryAddressFamily.AsSourceRoute; } } public override byte PayloadLength { get { return (byte) (this.AsNumbers.Count * 2); } } public override byte PayloadOffset { get { return (byte) (this.NextAsNumberIndex * 2); } } protected override int PayloadHashCode { get { return IEnumerableExtensions.UShortsSequenceGetHashCode((IEnumerable<ushort>) this.AsNumbers); } } public ReadOnlyCollection<ushort> AsNumbers { get { return this._asNumbers; } } public int NextAsNumberIndex { get { return this._nextAsNumberIndex; } } public ushort NextAsNumber { get { return this.AsNumbers[this.NextAsNumberIndex]; } } public GreSourceRouteEntryAs(ReadOnlyCollection<ushort> asNumbers, int nextAsNumberIndex) { this._asNumbers = asNumbers; this._nextAsNumberIndex = nextAsNumberIndex; } internal GreSourceRouteEntryAs(ushort[] asNumbers, int nextAsNumberIndex) : this(IListExtensions.AsReadOnly<ushort>((IList<ushort>) asNumbers), nextAsNumberIndex) { } protected override bool EqualsPayloads(GreSourceRouteEntry other) { return Enumerable.SequenceEqual<ushort>((IEnumerable<ushort>) this.AsNumbers, (IEnumerable<ushort>) ((GreSourceRouteEntryAs) other).AsNumbers); } protected override void WritePayload(byte[] buffer, int offset) { foreach (ushort num in this.AsNumbers) ByteArrayExtensions.Write(buffer, ref offset, num, Endianity.Big); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Http.HttpField // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Text; namespace PcapDotNet.Packets.Http { public class HttpField : IEquatable<HttpField> { private static readonly Encoding _defaultEncoding = EncodingExtensions.Iso88591; public string Name { get; private set; } public ReadOnlyCollection<byte> Value { get; private set; } public string ValueString { get { return HttpField._defaultEncoding.GetString(Enumerable.ToArray<byte>((IEnumerable<byte>) this.Value)); } } public int Length { get { return this.Name.Length + 2 + this.Value.Count + 2; } } internal HttpField(string name, string value) : this(name, value, HttpField._defaultEncoding) { } internal HttpField(string name, string value, Encoding encoding) : this(name, encoding == null ? (IList<byte>) (byte[]) null : (IList<byte>) encoding.GetBytes(HttpField.NormalizeValue(value))) { } internal HttpField(string name, IList<byte> value) : this(name, IListExtensions.AsReadOnly<byte>(value)) { } internal HttpField(string name, ReadOnlyCollection<byte> value) { this.Name = name; this.Value = value; } public static HttpField CreateField(string fieldName, byte[] fieldValue) { if (fieldName == null) throw new ArgumentNullException("fieldName"); switch (fieldName.ToUpperInvariant()) { case "TRANSFER-ENCODING": return (HttpField) new HttpTransferEncodingField(fieldValue); case "CONTENT-LENGTH": return (HttpField) new HttpContentLengthField(fieldValue); case "CONTENT-TYPE": return (HttpField) new HttpContentTypeField(fieldValue); case "TRAILER": return (HttpField) new HttpTrailerField(fieldValue); default: return new HttpField(fieldName, (IList<byte>) Enumerable.ToArray<byte>((IEnumerable<byte>) fieldValue)); } } public static HttpField CreateField(string fieldName, string fieldValue, Encoding fieldValueEncoding) { if (fieldValueEncoding == null) throw new ArgumentNullException("fieldValueEncoding"); return HttpField.CreateField(fieldName, fieldValueEncoding.GetBytes(HttpField.NormalizeValue(fieldValue))); } public static HttpField CreateField(string fieldName, string fieldValue) { return HttpField.CreateField(fieldName, fieldValue, HttpField._defaultEncoding); } public virtual bool Equals(HttpField other) { if (other != null && this.Name.Equals(other.Name, StringComparison.OrdinalIgnoreCase)) return Enumerable.SequenceEqual<byte>((IEnumerable<byte>) this.Value, (IEnumerable<byte>) other.Value); return false; } public override sealed bool Equals(object obj) { return this.Equals(obj as HttpField); } public override sealed int GetHashCode() { return this.Name.ToUpperInvariant().GetHashCode() ^ IEnumerableExtensions.BytesSequenceGetHashCode((IEnumerable<byte>) this.Value); } public override sealed string ToString() { return string.Format((IFormatProvider) CultureInfo.InvariantCulture, "{0}: {1}", new object[2] { (object) this.Name, (object) this.ValueString }); } internal void Write(byte[] buffer, ref int offset) { ByteArrayExtensions.Write(buffer, ref offset, this.Name, Encoding.ASCII); ByteArrayExtensions.Write(buffer, ref offset, (byte) 58); ByteArrayExtensions.Write(buffer, ref offset, (byte) 32); ByteArrayExtensions.Write(buffer, ref offset, (IEnumerable<byte>) this.Value); ByteArrayExtensions.WriteCarriageReturnLinefeed(buffer, ref offset); } private static string NormalizeValue(string value) { StringBuilder stringBuilder = new StringBuilder(value.Length); int index = 0; label_15: while (index != value.Length) { if ((int) value[index] == 34) { int startIndex = index; for (++index; index != value.Length && (int) value[index] != 34; ++index) { if ((int) value[index] == 92 && index != value.Length - 1) ++index; } if ((int) value[index] == 34) ++index; stringBuilder.Append(value.Substring(startIndex, index - startIndex)); } else if ((int) value[index] == 9 || (int) value[index] == 32 || ((int) value[index] == 13 || (int) value[index] == 10)) { stringBuilder.Append(' '); ++index; while (true) { if (index != value.Length && ((int) value[index] == 9 || (int) value[index] == 32 || ((int) value[index] == 13 || (int) value[index] == 10))) ++index; else goto label_15; } } else { stringBuilder.Append(value[index]); ++index; } } return stringBuilder.ToString(); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Options`1 // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace PcapDotNet.Packets { public abstract class Options<T> where T : Option { private readonly ReadOnlyCollection<T> _options; public ReadOnlyCollection<T> OptionsCollection { get { return this._options; } } public int Count { get { return this.OptionsCollection.Count; } } public T this[int index] { get { return this.OptionsCollection[index]; } } public int BytesLength { get; private set; } public bool IsValid { get; private set; } internal Options(byte[] buffer, int offset, int length, T end) : this(Options<T>.Read(buffer, offset, length, end)) { this.BytesLength = length; } internal Options(IList<T> options, T end, int maximumBytesLength) : this(Options<T>.EndOptions(options, end), true) { if (this.BytesLength > maximumBytesLength) throw new ArgumentException(string.Concat(new object[4] { (object) "given options take ", (object) this.BytesLength, (object) " bytes and maximum number of bytes for options is ", (object) maximumBytesLength }), "options"); } private Options(IList<T> options, bool isValid) { this._options = IListExtensions.AsReadOnly<T>(options); this.IsValid = isValid; this.BytesLength = Options<T>.SumBytesLength((IEnumerable<T>) this.OptionsCollection); if (this.BytesLength % 4 == 0) return; this.BytesLength = (this.BytesLength / 4 + 1) * 4; } private Options(Tuple<IList<T>, bool> optionsAndIsValid) : this(optionsAndIsValid.Item1, optionsAndIsValid.Item2) { } public bool Equals(Options<T> other) { if (other == null || this.BytesLength != other.BytesLength) return false; return Enumerable.SequenceEqual<T>((IEnumerable<T>) this.OptionsCollection, (IEnumerable<T>) other.OptionsCollection); } public override sealed bool Equals(object obj) { return this.Equals(obj as Options<T>); } public override sealed int GetHashCode() { return this.BytesLength.GetHashCode() ^ IEnumerableExtensions.SequenceGetHashCode<T>((IEnumerable<T>) this.OptionsCollection); } public override sealed string ToString() { return IEnumerableExtensions.SequenceToString<T>((IEnumerable<T>) this.OptionsCollection, ", ", this.GetType().Name + " {", "}"); } internal void Write(byte[] buffer, int offset) { int num = offset + this.BytesLength; foreach (T obj in this.OptionsCollection) obj.Write(buffer, ref offset); while (offset < num) buffer[offset++] = (byte) 0; } private static IList<T> EndOptions(IList<T> options, T end) { if (options.Count == 0 || (Enumerable.Last<T>((IEnumerable<T>) options).Equivalent((Option) end) || Options<T>.SumBytesLength((IEnumerable<T>) options) % 4 == 0)) return options; return (IList<T>) new List<T>(IEnumerableExtensions.Concat<T>((IEnumerable<T>) options, end)); } private static int SumBytesLength(IEnumerable<T> options) { return Enumerable.Sum<T>(options, (Func<T, int>) (option => option.Length)); } private static Tuple<IList<T>, bool> Read(byte[] buffer, int offset, int length, T end) { int num = offset + length; List<T> list = new List<T>(); while (offset != num) { T obj = (T) end.Read(buffer, ref offset, num - offset); if ((object) obj == null || obj.IsAppearsAtMostOnce && Enumerable.Any<T>((IEnumerable<T>) list, new Func<T, bool>(((Option) obj).Equivalent))) return new Tuple<IList<T>, bool>((IList<T>) list, false); list.Add(obj); if (obj.Equivalent((Option) end)) break; } return new Tuple<IList<T>, bool>((IList<T>) list, true); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Ethernet.EthernetPayloadDatagrams // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using PcapDotNet.Packets.Arp; using PcapDotNet.Packets.IpV4; namespace PcapDotNet.Packets.Ethernet { internal class EthernetPayloadDatagrams { private readonly Datagram _payload; private IpV4Datagram _ipV4; private ArpDatagram _arp; private VLanTaggedFrameDatagram _vLanTaggedFrame; public IpV4Datagram IpV4 { get { if (this._ipV4 == null && this._payload != null) this._ipV4 = new IpV4Datagram(this._payload.Buffer, this._payload.StartOffset, IpV4Datagram.GetTotalLength(this._payload)); return this._ipV4; } } public ArpDatagram Arp { get { if (this._arp == null && this._payload != null) this._arp = ArpDatagram.CreateInstance(this._payload.Buffer, this._payload.StartOffset, this._payload.Length); return this._arp; } } public VLanTaggedFrameDatagram VLanTaggedFrame { get { if (this._vLanTaggedFrame == null && this._payload != null) this._vLanTaggedFrame = new VLanTaggedFrameDatagram(this._payload.Buffer, this._payload.StartOffset, this._payload.Length); return this._vLanTaggedFrame; } } public Datagram Payload { get { return this._payload; } } public EthernetPayloadDatagrams(Datagram payload) { this._payload = payload; } public Datagram Get(EthernetType ethernetType) { switch (ethernetType) { case EthernetType.IpV4: return (Datagram) this.IpV4; case EthernetType.Arp: return (Datagram) this.Arp; case EthernetType.VLanTaggedFrame: return (Datagram) this.VLanTaggedFrame; default: return (Datagram) null; } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IpV4OptionSimple // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.IpV4 { public sealed class IpV4OptionSimple : IpV4Option { public const int OptionLength = 1; public override int Length { get { return 1; } } public override bool IsAppearsAtMostOnce { get { return false; } } internal IpV4OptionSimple(IpV4OptionType optionType) : base(optionType) { } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.OptionComplexFactory`1 // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace PcapDotNet.Packets { internal static class OptionComplexFactory<TOptionType> { private static readonly Dictionary<TOptionType, IOptionComplexFactory> _complexOptions = OptionComplexFactory<TOptionType>.InitializeComplexOptions(); private static readonly IOptionUnknownFactory<TOptionType> _unknownFactoryOptionPrototype = OptionComplexFactory<TOptionType>.InitializeUnknownOptionPrototype(); public const int OptionHeaderLength = 2; internal static Option Read(TOptionType optionType, byte[] buffer, ref int offset, int length) { if (length < 1) return (Option) null; byte num = buffer[offset++]; if ((int) num < 2 || length + 1 < (int) num) return (Option) null; byte valueLength = (byte) ((uint) num - 2U); IOptionComplexFactory optionComplexFactory; if (!OptionComplexFactory<TOptionType>._complexOptions.TryGetValue(optionType, out optionComplexFactory)) return OptionComplexFactory<TOptionType>._unknownFactoryOptionPrototype.CreateInstance(optionType, buffer, ref offset, valueLength); return optionComplexFactory.CreateInstance(buffer, ref offset, valueLength); } private static IOptionUnknownFactory<TOptionType> InitializeUnknownOptionPrototype() { IEnumerable<IOptionUnknownFactory<TOptionType>> source = Enumerable.Select<Type, IOptionUnknownFactory<TOptionType>>(Enumerable.Where<Type>((IEnumerable<Type>) Assembly.GetExecutingAssembly().GetTypes(), (Func<Type, bool>) (type => typeof (IOptionUnknownFactory<TOptionType>).IsAssignableFrom(type))), (Func<Type, IOptionUnknownFactory<TOptionType>>) (type => (IOptionUnknownFactory<TOptionType>) Activator.CreateInstance(type))); if (Enumerable.Count<IOptionUnknownFactory<TOptionType>>(source) != 1) throw new InvalidOperationException("Must be only one unknown option for option type " + (object) typeof (TOptionType)); return Enumerable.First<IOptionUnknownFactory<TOptionType>>(source); } private static Dictionary<TOptionType, IOptionComplexFactory> InitializeComplexOptions() { return Enumerable.ToDictionary(Enumerable.Select(Enumerable.Where<Type>((IEnumerable<Type>) Assembly.GetExecutingAssembly().GetTypes(), (Func<Type, bool>) (type => { if (typeof (IOptionComplexFactory).IsAssignableFrom(type)) return OptionComplexFactory<TOptionType>.GetRegistrationAttribute(type) != null; return false; })), type => new { OptionType = OptionComplexFactory<TOptionType>.GetRegistrationAttribute(type).OptionType, Option = (IOptionComplexFactory) Activator.CreateInstance(type) }), option => (TOptionType) option.OptionType, option => option.Option); } private static OptionTypeRegistrationAttribute GetRegistrationAttribute(Type type) { IEnumerable<OptionTypeRegistrationAttribute> source = Enumerable.Where<OptionTypeRegistrationAttribute>(MemberInfoExtensions.GetCustomAttributes<OptionTypeRegistrationAttribute>((MemberInfo) type, false), (Func<OptionTypeRegistrationAttribute, bool>) (attribute => attribute.OptionTypeType == typeof (TOptionType))); if (!Enumerable.Any<OptionTypeRegistrationAttribute>(source)) return (OptionTypeRegistrationAttribute) null; return Enumerable.First<OptionTypeRegistrationAttribute>(source); } } } <file_sep>using System; using System.Data.SqlClient; using Microsoft.SqlServer.Server; using System.Net; namespace UpdateCWOP { using System.Globalization; using OmnUtils; public static class WundergroundUpdate { // Replace station id with your wunderground station id // Replace [password] with your wunderground password public const string WU_STATION_ID = "IYUCATNM14"; public const string WU_STATION_PWD = <PASSWORD>$"; // Enter existing table or view for the target and uncomment the attribute line [Microsoft.SqlServer.Server.SqlTrigger(Name = "UpdateWunderground", Target = "dbo.ISSData", Event = "FOR INSERT")] public static void Update() { // Replace with your own code SqlContext.Pipe.Send("Trigger FIRED"); SqlCommand command; SqlTriggerContext triggContext = SqlContext.TriggerContext; SqlPipe pipe = SqlContext.Pipe; SqlDataReader reader; string rootURL = "http://weatherstation.wunderground.com/weatherstation/updateweatherstation.php?ID={0}&PASSWORD={1}".Args(WU_STATION_ID, WU_STATION_PWD); string queryString = ""; int ReceiverId = 0; byte Channel = 8; DateTime recordDate = DateTime.Now; using (SqlConnection connection = new SqlConnection(@"context connection=true")) { connection.Open(); command = new SqlCommand(@"SELECT * FROM INSERTED;", connection); reader = command.ExecuteReader(); reader.Read(); if (reader.HasRows) { ReceiverId = (int)reader[0]; Channel = (byte)reader[1]; recordDate = (DateTime)reader[2]; } reader.Close(); command = new SqlCommand(@"SELECT * FROM dbo.Wunderground " + " WHERE ReceiverRecId = " + ReceiverId + " AND ChannelIndex = " + Channel + " AND RecDateTime = '" + recordDate + "';", connection); reader = command.ExecuteReader(); reader.Read(); if (reader.HasRows) { queryString += "&dateutc=" + DateTime.Parse(reader[2].ToString()).ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss"); //RecDateTime queryString += "&tempf=" + ((short)reader[3] / (double)10).ToString(CultureInfo.InvariantCulture); //Temperature queryString += "&windspeedmph=" + reader[5].ToString(); //Wind Speed queryString += "&windgustmph=" + reader[11].ToString(); //Wind Gust queryString += "&winddir=" + reader[6].ToString(); //Wind Direction queryString += "&humidity=" + reader[4].ToString(); //Humidity queryString += "&rainin=" + ((decimal)reader[9]).ToString(); //Rainfall hour queryString += "&dailyrainin=" + ((decimal)reader[10]).ToString(); //Rainfall hour queryString += "&dewptf=" + ((short)reader[7] / (double)10).ToString(); //Dew Point queryString += "&baromin=" + ((short)reader[8] / (double)1000).ToString(); //Barometer } reader.Close(); if (queryString != "") { queryString += "&action=updateraw"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(rootURL + queryString); request.KeepAlive = true; request.ServicePoint.Expect100Continue = false; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); response.Close(); } } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpCodeTimeExceeded // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets.Icmp { public enum IcmpCodeTimeExceeded : byte { TimeToLive, FragmentReassembly, } } <file_sep>// Decompiled with JetBrains decompiler // Type: __enative_startup_state // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using Microsoft.VisualC; using System.Runtime.CompilerServices; [NativeCppClass] [MiscellaneousBits(64)] [DebugInfoInPDB] internal enum __enative_startup_state { } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Core.LivePacketDevice // Assembly: PcapDotNet.Core, Version=0.10.0.20693, Culture=neutral, PublicKeyToken=<KEY> // MVID: 427ABC7F-BE5F-40B7-AD98-8005CFBC0786 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Core.dll using \u003CCppImplementationDetails\u003E; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; namespace PcapDotNet.Core { public sealed class LivePacketDevice : PacketDevice { private string _name; private string _description; private DeviceAttributes _attributes; private ReadOnlyCollection<DeviceAddress> _addresses; public override ReadOnlyCollection<DeviceAddress> Addresses { get { return new ReadOnlyCollection<DeviceAddress>((IList<DeviceAddress>) this._addresses); } } public override DeviceAttributes Attributes { get { return this._attributes; } } public override string Description { get { return this._description; } } public override string Name { get { return this._name; } } public static unsafe ReadOnlyCollection<LivePacketDevice> AllLocalMachine { get { pcap_if* pcapIfPtr; \u0024ArrayType\u0024\u0024\u0024BY0BAA\u0040D arrayTypeBy0BaAD; if (\u003CModule\u003E.pcap_findalldevs_ex((sbyte*) &\u003CModule\u003E.\u003F\u003F_C\u0040_08FFEMNKKP\u0040rpcap\u003F3\u003F1\u003F1\u003F\u0024AA\u0040, (pcap_rmtauth*) 0, &pcapIfPtr, (sbyte*) &arrayTypeBy0BaAD) == -1) throw new InvalidOperationException(string.Format((IFormatProvider) CultureInfo.InvariantCulture, "Failed getting devices. Error: {0}", new object[1] { (object) new string((sbyte*) &arrayTypeBy0BaAD) })); try { List<LivePacketDevice> list = new List<LivePacketDevice>(); for (pcap_if* device = pcapIfPtr; (IntPtr) device != IntPtr.Zero; device = (pcap_if*) *(long*) device) list.Add(new LivePacketDevice(device)); return new ReadOnlyCollection<LivePacketDevice>((IList<LivePacketDevice>) list); } finally { \u003CModule\u003E.pcap_freealldevs(pcapIfPtr); } } } private unsafe LivePacketDevice(pcap_if* device) { List<DeviceAddress> list = new List<DeviceAddress>(); pcap_addr* pcapAddress = (pcap_addr*) *(long*) ((IntPtr) device + 24L); if ((IntPtr) pcapAddress != IntPtr.Zero) { do { DeviceAddress deviceAddress = new DeviceAddress(pcapAddress); list.Add(deviceAddress); pcapAddress = (pcap_addr*) *(long*) pcapAddress; } while ((IntPtr) pcapAddress != IntPtr.Zero); } this._name = new string((sbyte*) *(long*) ((IntPtr) device + 8L)); this._description = new string((sbyte*) *(long*) ((IntPtr) device + 16L)); this._attributes = (DeviceAttributes) *(int*) ((IntPtr) device + 32L); this._addresses = new ReadOnlyCollection<DeviceAddress>((IList<DeviceAddress>) list); } public override sealed PacketCommunicator Open(int snapshotLength, PacketDeviceOpenAttributes attributes, int readTimeout) { // ISSUE: unable to decompile the method. } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CGurus.Weather.WundergroundAPI.Models { public class Forecast { public SimpleForecast SimpleForecast { get; set; } public TxtForecast Txt_Forecast { get; set; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Http.HttpResponseLayer // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Linq; namespace PcapDotNet.Packets.Http { public sealed class HttpResponseLayer : HttpLayer, IEquatable<HttpResponseLayer> { private DataSegment _reasonPhrase; public override bool IsRequest { get { return false; } } public uint? StatusCode { get; set; } public DataSegment ReasonPhrase { get { return this._reasonPhrase; } set { if (value == null) { this._reasonPhrase = (DataSegment) null; } else { int offset = Enumerable.Count<byte>(Enumerable.TakeWhile<byte>((IEnumerable<byte>) value, (Func<byte, bool>) (byteValue => (int) byteValue == 32))); this._reasonPhrase = value.Subsegment(offset, value.Length - offset); } } } internal override int FirstLineLength { get { int num1 = 0; if (this.Version == null) return num1; int num2 = num1 + (this.Version.Length + 1); if (!this.StatusCode.HasValue) return num2; int num3 = num2 + (UIntExtensions.DigitsCount(this.StatusCode.Value, 10.0) + 1); if (this.ReasonPhrase == null) return num3; return num3 + this.ReasonPhrase.Length + 2; } } public override bool Equals(HttpLayer other) { return this.Equals(other as HttpResponseLayer); } public bool Equals(HttpResponseLayer other) { if (base.Equals((HttpLayer) other)) { uint? statusCode1 = this.StatusCode; uint? statusCode2 = other.StatusCode; if (((int) statusCode1.GetValueOrDefault() != (int) statusCode2.GetValueOrDefault() ? 0 : (statusCode1.HasValue == statusCode2.HasValue ? 1 : 0)) != 0) { if (!object.ReferenceEquals((object) this.ReasonPhrase, (object) other.ReasonPhrase)) return this.ReasonPhrase.Equals(other.ReasonPhrase); return true; } } return false; } internal override void WriteFirstLine(byte[] buffer, ref int offset) { if (this.Version == null) return; this.Version.Write(buffer, ref offset); ByteArrayExtensions.Write(buffer, ref offset, (byte) 32); if (!this.StatusCode.HasValue) return; ByteArrayExtensions.WriteDecimal(buffer, ref offset, this.StatusCode.Value); ByteArrayExtensions.Write(buffer, ref offset, (byte) 32); if (this.ReasonPhrase == null) return; ByteArrayExtensions.Write(buffer, ref offset, this.ReasonPhrase); ByteArrayExtensions.WriteCarriageReturnLinefeed(buffer, ref offset); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Igmp.IIgmpLayerWithGroupAddress // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets.IpV4; namespace PcapDotNet.Packets.Igmp { public interface IIgmpLayerWithGroupAddress { IpV4Address GroupAddress { get; set; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: AcuLink_Bridge_Reader_CSharp.AutoClosingMessageBox // Assembly: AcuLink_Bridge_Reader_CS, Version=2014.9.18.2041, Culture=neutral, PublicKeyToken=null // MVID: 2DF0938E-D9D0-414E-AB5D-7B9A655FB464 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\AcuLink_Bridge_Reader_CS.exe using System; using System.Runtime.InteropServices; using System.Threading; using System.Windows.Forms; namespace AcuLink_Bridge_Reader_CSharp { public class AutoClosingMessageBox { private System.Threading.Timer _timeoutTimer; private string _caption; private const int WM_CLOSE = 16; private AutoClosingMessageBox(string text, string caption, int timeout) { this._caption = caption; this._timeoutTimer = new System.Threading.Timer(new TimerCallback(this.OnTimerElapsed), (object) null, timeout, -1); int num = (int) MessageBox.Show(text, caption); } public static void Show(string text, string caption, int timeout) { AutoClosingMessageBox closingMessageBox = new AutoClosingMessageBox(text, caption, timeout); } private void OnTimerElapsed(object state) { IntPtr window = AutoClosingMessageBox.FindWindow((string) null, this._caption); if (window != IntPtr.Zero) AutoClosingMessageBox.SendMessage(window, 16U, IntPtr.Zero, IntPtr.Zero); this._timeoutTimer.Dispose(); } [DllImport("user32.dll", SetLastError = true)] private static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataText // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System.Collections.ObjectModel; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.Txt)] [DnsTypeRegistration(Type = DnsType.Spf)] public sealed class DnsResourceDataText : DnsResourceDataStrings { public ReadOnlyCollection<DataSegment> Text { get { return this.Strings; } } public DnsResourceDataText(ReadOnlyCollection<DataSegment> strings) : base(strings) { } internal DnsResourceDataText() : base() { } internal override DnsResourceData CreateInstance(DataSegment data) { return (DnsResourceData) new DnsResourceDataText(DnsResourceDataStrings.ReadStrings(data, 0).AsReadOnly()); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsTypeBitmaps // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Base; using PcapDotNet.Packets; using System; using System.Collections.Generic; using System.Linq; namespace PcapDotNet.Packets.Dns { internal class DnsTypeBitmaps : IEquatable<DnsTypeBitmaps> { private const int MaxTypeBitmapsLength = 8704; public List<DnsType> TypesExist { get; private set; } public DnsTypeBitmaps(IEnumerable<DnsType> typesExist) { this.TypesExist = Enumerable.ToList<DnsType>(Enumerable.Distinct<DnsType>(typesExist)); this.TypesExist.Sort(); } public bool Contains(DnsType dnsType) { return this.TypesExist.BinarySearch(dnsType) >= 0; } public bool Equals(DnsTypeBitmaps other) { if (other != null) return Enumerable.SequenceEqual<DnsType>((IEnumerable<DnsType>) this.TypesExist, (IEnumerable<DnsType>) other.TypesExist); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsTypeBitmaps); } public override int GetHashCode() { return IEnumerableExtensions.SequenceGetHashCode<DnsType>((IEnumerable<DnsType>) this.TypesExist); } public int GetLength() { int num1 = 0; int num2 = -1; int val2 = -1; foreach (DnsType dnsType in this.TypesExist) { byte num3 = (byte) ((uint) dnsType >> 8); if ((int) num3 > num2) { if (val2 != -1) num1 += 2 + val2 / 8 + 1; num2 = (int) num3; val2 = -1; } val2 = Math.Max((int) (byte) dnsType, val2); } if (val2 != -1) num1 += 2 + val2 / 8 + 1; return num1; } public int Write(byte[] buffer, int offset) { int num1 = offset; int num2 = -1; int num3 = -1; byte[] windowBitmap = (byte[]) null; foreach (DnsType dnsType in this.TypesExist) { byte num4 = (byte) ((uint) dnsType >> 8); if ((int) num4 > num2) { if (num3 != -1) DnsTypeBitmaps.WriteBitmap(buffer, ref offset, (byte) num2, num3, windowBitmap); num2 = (int) num4; windowBitmap = new byte[32]; num3 = -1; } byte num5 = (byte) dnsType; num3 = Math.Max((int) num5, num3); windowBitmap[(int) num5 / 8] |= (byte) (1 << 7 - (int) num5 % 8); } if (num3 != -1) DnsTypeBitmaps.WriteBitmap(buffer, ref offset, (byte) num2, num3, windowBitmap); return offset - num1; } public static DnsTypeBitmaps CreateInstance(byte[] buffer, int offset, int length) { if (length > 8704) return (DnsTypeBitmaps) null; List<DnsType> list = new List<DnsType>(); while (length != 0) { if (length < 3) return (DnsTypeBitmaps) null; byte num1 = buffer[offset++]; byte num2 = buffer[offset++]; length -= 2; if ((int) num2 < 1 || (int) num2 > 32 || length < (int) num2) return (DnsTypeBitmaps) null; for (int index = 0; index != (int) num2; ++index) { byte num3 = buffer[offset++]; int num4 = 0; while ((int) num3 != 0) { if ((int) (byte) ((uint) num3 & 128U) == 128) list.Add((DnsType) (((int) num1 << 8) + 8 * index + num4)); num3 <<= 1; ++num4; } } length -= (int) num2; } return new DnsTypeBitmaps((IEnumerable<DnsType>) list); } private static void WriteBitmap(byte[] buffer, ref int offset, byte window, int maxBit, byte[] windowBitmap) { ByteArrayExtensions.Write(buffer, ref offset, window); byte num = (byte) (maxBit / 8 + 1); ByteArrayExtensions.Write(buffer, ref offset, num); new DataSegment(windowBitmap, 0, (int) num).Write(buffer, ref offset); } } } <file_sep> namespace CGurus.Weather.WundergroundAPI.Models { public class SimpleForecast { public SimpleForecastDay[] ForecastDay { get; set; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IOptionComplexFactory // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll namespace PcapDotNet.Packets { internal interface IOptionComplexFactory { Option CreateInstance(byte[] buffer, ref int offset, byte valueLength); } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Base.CharExtensions // Assembly: PcapDotNet.Base, Version=0.10.0.20668, Culture=neutral, PublicKeyToken=<KEY> // MVID: E9656A63-0145-422C-B8C8-79FDD7FB4270 // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Base.dll namespace PcapDotNet.Base { public static class CharExtensions { public static bool IsUppercaseAlpha(this char character) { if ((int) character >= 65) return (int) character <= 90; return false; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Transport.TcpOptionPartialOrderConnectionPermitted // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.Transport { [OptionTypeRegistration(typeof (TcpOptionType), TcpOptionType.PartialOrderConnectionPermitted)] public sealed class TcpOptionPartialOrderConnectionPermitted : TcpOptionComplex, IOptionComplexFactory, IEquatable<TcpOptionPartialOrderConnectionPermitted> { private static readonly TcpOptionPartialOrderConnectionPermitted _instance = new TcpOptionPartialOrderConnectionPermitted(); public const int OptionLength = 2; public const int OptionValueLength = 0; public override int Length { get { return 2; } } public override bool IsAppearsAtMostOnce { get { return true; } } public TcpOptionPartialOrderConnectionPermitted() : base(TcpOptionType.PartialOrderConnectionPermitted) { } public bool Equals(TcpOptionPartialOrderConnectionPermitted other) { return other != null; } public override bool Equals(TcpOption other) { return this.Equals(other as TcpOptionPartialOrderConnectionPermitted); } Option IOptionComplexFactory.CreateInstance(byte[] buffer, ref int offset, byte valueLength) { if ((int) valueLength != 0) return (Option) null; return (Option) TcpOptionPartialOrderConnectionPermitted._instance; } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Icmp.IcmpEchoReplyDatagram // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; namespace PcapDotNet.Packets.Icmp { [IcmpDatagramRegistration(IcmpMessageType.EchoReply)] public sealed class IcmpEchoReplyDatagram : IcmpIdentifiedDatagram { private IcmpEchoReplyDatagram(byte[] buffer, int offset, int length) : base(buffer, offset, length) { } public override ILayer ExtractLayer() { IcmpEchoReplyLayer icmpEchoReplyLayer = new IcmpEchoReplyLayer(); icmpEchoReplyLayer.Checksum = new ushort?(this.Checksum); icmpEchoReplyLayer.Identifier = this.Identifier; icmpEchoReplyLayer.SequenceNumber = this.SequenceNumber; return (ILayer) icmpEchoReplyLayer; } internal override IcmpDatagram CreateInstance(byte[] buffer, int offset, int length) { return (IcmpDatagram) new IcmpEchoReplyDatagram(buffer, offset, length); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.PacketBuilder // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using System; using System.Collections.Generic; using System.Linq; namespace PcapDotNet.Packets { public class PacketBuilder { private readonly ILayer[] _layers; private readonly DataLink _dataLink; public PacketBuilder(params ILayer[] layers) { if (layers == null) throw new ArgumentNullException("layers"); if (layers.Length == 0) throw new ArgumentException("At least one layer must be given", "layers"); DataLinkKind? dataLink = layers[0].DataLink; if (!dataLink.HasValue) throw new ArgumentException("First layer (" + (object) layers[0].GetType() + ") must provide a DataLink", "layers"); this._layers = layers; this._dataLink = new DataLink(dataLink.Value); } public PacketBuilder(IEnumerable<ILayer> layers) : this(Enumerable.ToArray<ILayer>(layers)) { } public static Packet Build(DateTime timestamp, params ILayer[] layers) { return new PacketBuilder(layers).Build(timestamp); } public static Packet Build(DateTime timestamp, IEnumerable<ILayer> layers) { return new PacketBuilder(layers).Build(timestamp); } public Packet Build(DateTime timestamp) { int[] layersLength = Enumerable.ToArray<int>(Enumerable.Select<ILayer, int>((IEnumerable<ILayer>) this._layers, (Func<ILayer, int>) (layer => layer.Length))); int length = Enumerable.Sum((IEnumerable<int>) layersLength); byte[] numArray = new byte[length]; this.WriteLayers(layersLength, numArray, length); this.FinalizeLayers(numArray, length); return new Packet(numArray, timestamp, (IDataLink) this._dataLink); } private void WriteLayers(int[] layersLength, byte[] buffer, int length) { int offset = 0; for (int index = 0; index != this._layers.Length; ++index) { ILayer layer = this._layers[index]; int num = layersLength[index]; ILayer previousLayer = index == 0 ? (ILayer) null : this._layers[index - 1]; ILayer nextLayer = index == this._layers.Length - 1 ? (ILayer) null : this._layers[index + 1]; layer.Write(buffer, offset, length - offset - num, previousLayer, nextLayer); offset += num; } } private void FinalizeLayers(byte[] buffer, int length) { int offset = length; for (int index = this._layers.Length - 1; index >= 0; --index) { ILayer layer = this._layers[index]; ILayer nextLayer = index == this._layers.Length - 1 ? (ILayer) null : this._layers[index + 1]; offset -= layer.Length; layer.Finalize(buffer, offset, length - offset - layer.Length, nextLayer); } } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.IpV4.IpV4OptionStreamIdentifier // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using System; namespace PcapDotNet.Packets.IpV4 { [OptionTypeRegistration(typeof (IpV4OptionType), IpV4OptionType.StreamIdentifier)] public sealed class IpV4OptionStreamIdentifier : IpV4OptionComplex, IOptionComplexFactory, IEquatable<IpV4OptionStreamIdentifier> { public const int OptionLength = 4; private readonly ushort _identifier; public ushort Identifier { get { return this._identifier; } } public override int Length { get { return 4; } } public override bool IsAppearsAtMostOnce { get { return true; } } public IpV4OptionStreamIdentifier(ushort identifier) : base(IpV4OptionType.StreamIdentifier) { this._identifier = identifier; } public IpV4OptionStreamIdentifier() : this((ushort) 0) { } public bool Equals(IpV4OptionStreamIdentifier other) { if (other == null) return false; return (int) this.Identifier == (int) other.Identifier; } public override bool Equals(IpV4Option other) { return this.Equals(other as IpV4OptionStreamIdentifier); } public override int GetHashCode() { return base.GetHashCode() ^ this.Identifier.GetHashCode(); } Option IOptionComplexFactory.CreateInstance(byte[] buffer, ref int offset, byte valueLength) { if ((int) valueLength != 2) return (Option) null; return (Option) new IpV4OptionStreamIdentifier(ByteArrayExtensions.ReadUShort(buffer, ref offset, Endianity.Big)); } internal override void Write(byte[] buffer, ref int offset) { base.Write(buffer, ref offset); ByteArrayExtensions.Write(buffer, ref offset, this.Identifier, Endianity.Big); } } } <file_sep>// Decompiled with JetBrains decompiler // Type: PcapDotNet.Packets.Dns.DnsResourceDataIpV6 // Assembly: PcapDotNet.Packets, Version=0.10.0.20671, Culture=neutral, PublicKeyToken=<KEY> // MVID: 47DD9BFD-D1F0-4258-9A45-7763FC0E6FDD // Assembly location: C:\Users\clafrance\Documents\Visual Studio 2013\Samples\Weather\AcuLinkBridge\PcapDotNet.Packets.dll using PcapDotNet.Packets; using PcapDotNet.Packets.IpV6; using System; namespace PcapDotNet.Packets.Dns { [DnsTypeRegistration(Type = DnsType.Aaaa)] public sealed class DnsResourceDataIpV6 : DnsResourceDataSimple, IEquatable<DnsResourceDataIpV6> { public IpV6Address Data { get; private set; } public DnsResourceDataIpV6(IpV6Address data) { this.Data = data; } internal DnsResourceDataIpV6() : this(IpV6Address.Zero) { } public bool Equals(DnsResourceDataIpV6 other) { if (other != null) return this.Data.Equals(other.Data); return false; } public override bool Equals(object obj) { return this.Equals(obj as DnsResourceDataIpV6); } public override int GetHashCode() { return this.Data.GetHashCode(); } internal override int GetLength() { return 16; } internal override void WriteDataSimple(byte[] buffer, int offset) { ByteArrayExtensions.Write(buffer, offset, this.Data, Endianity.Big); } internal override DnsResourceData CreateInstance(DataSegment data) { if (data.Length != 16) return (DnsResourceData) null; return (DnsResourceData) new DnsResourceDataIpV6(data.ReadIpV6Address(0, Endianity.Big)); } } } <file_sep>namespace ForecastPCL.Test { using System; using ForecastIOPortable; using NUnit.Framework; /// <summary> /// Unit tests for the Helpers class. /// </summary> [TestFixture] public class HelperTests { /// <summary> /// Tests conversion of 0 Unix time to a DateTime object. /// Ensures we're using the correct base time. /// </summary> [Test] public void ConvertZero() { var expected = new DateTimeOffset(1970, 1, 1, 0, 0, 0, new TimeSpan()); var actual = 0.ToDateTimeOffset(); Assert.That(actual, Is.EqualTo(expected)); } /// <summary> /// Tests conversion of a particular date and time in Unix time to a known DateTime. /// Ensures such conversion works as it should. /// </summary> [Test] public void ConvertSpecificDate() { var expected = new DateTimeOffset(2014, 7, 23, 3, 40, 49, new TimeSpan()); var actual = 1406086849.ToDateTimeOffset(); Assert.That(actual, Is.EqualTo(expected)); } /// <summary> /// Tests conversion of a DateTime set to the Unix base back to an integer. /// Ensures we're using the correct base time. /// </summary> [Test] public void ConvertBackZero() { var expected = 0; var actual = new DateTimeOffset(1970, 1, 1, 0, 0, 0, new TimeSpan()).ToUnixTime(); Assert.That(actual, Is.EqualTo(expected)); } /// <summary> /// Tests conversion of a known DateTime back to an integer. /// Ensures such conversion works as it should. /// </summary> [Test] public void ConvertBackSpecificDate() { var expected = 1406086849; var actual = new DateTimeOffset(2014, 7, 23, 3, 40, 49, new TimeSpan()).ToUnixTime(); Assert.That(actual, Is.EqualTo(expected)); } } }
10138c8e51487bf2b95a3ca29788f1eebb85f782
[ "Markdown", "C#" ]
405
C#
ESOmenium/WeatherSampleCode
347368537ff2316a5cccf49fe8cfd65c6d176ab4
c3cc9898acd2ba94173f11aaf9102cce99777607
refs/heads/master
<file_sep>// // ViewControllerInterface.swift // MVC // // Created by <NAME>. on 5/9/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit protocol ViewControllerInterface: class { associatedtype ContentView var contentView: ContentView { get } func loadContentView() -> ContentView } extension ViewControllerInterface where Self: UIViewController { var contentView: ContentView { return view as! ContentView } } extension ViewControllerInterface where ContentView: NibViewInterface { func loadContentView() -> ContentView { return ContentView.loadFromNib(owner: self, options: nil) } } <file_sep>target 'MVC' do use_frameworks! pod 'Alamofire', '~> 5.0' pod 'AlamofireImage', '~> 4.0' end<file_sep>// // EmptyComicsCollectionViewCell.swift // MVC // // Created by <NAME>. on 5/11/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit final class EmptyComicsCollectionViewCell: UICollectionViewCell { static let reuseId: String = "EmptyComicsCollectionViewCell" } <file_sep>// // CharactersViewController+State.swift // MVC // // Created by <NAME>. on 5/9/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation extension CharactersViewController { class State { enum Kind { case empty case error(Error) case initial case showingData([Character]) } static func state(_ kind: Kind, vc: CharactersViewController) -> State { switch kind { case .empty: return EmptyState(vc: vc) case let .error(error): return ErrorState(error: error, vc: vc) case .initial: return InitialState(vc: vc) case let .showingData(characters): return ShowingDataState(characters: characters, vc: vc) } } weak var vc: CharactersViewController! init(vc: CharactersViewController) { self.vc = vc } func enter() { vc.contentView.tableView.reloadData() } } final class EmptyState: State { } final class ErrorState: State { let error: Error init(error: Error, vc: CharactersViewController) { self.error = error super.init(vc: vc) } } final class InitialState: State { } final class ShowingDataState: State { var characters: [Character] init(characters: [Character], vc: CharactersViewController) { self.characters = characters super.init(vc: vc) } func addNewCharacters(_ characters: [Character]) { guard !characters.isEmpty else { return } let numberOfExistingItems = vc.contentView.tableView.numberOfRows(inSection: 0) let totalNumberOfItems = (numberOfExistingItems - 1) + characters.count let indexPaths = ((numberOfExistingItems - 1) ... (totalNumberOfItems - 1)).map({ IndexPath(row: $0, section: 0) }) vc.contentView.tableView.performUsingPresentationValues { self.characters.append(contentsOf: characters) self.vc.contentView.tableView.insertRows(at: indexPaths, with: .none) } } } } <file_sep>// // AppCoordinator.swift // MVC // // Created by <NAME>. on 5/9/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit protocol AppCoordinatorInterface { var window: UIWindow { get } init(window: UIWindow) func start() } final class AppCoordinator: AppCoordinatorInterface { let window: UIWindow init(window: UIWindow) { self.window = window } func start() { window.rootViewController = UINavigationController(rootViewController: CharactersViewController()) } } <file_sep>// // CharacterDetailContentView.swift // MVC // // Created by <NAME>. on 5/11/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit final class CharacterDetailContentView: UIView, NibViewInterface { static var nib: UINib = UINib(nibName: "CharacterDetailContentView", bundle: nil) @IBOutlet private weak var characterImageView: UIImageView! @IBOutlet private weak var comicsContainerView: UIView! var character: Character! { didSet { if let url = character.thumbnail.url { characterImageView.af.setImage(withURL: url) } } } func addComicsView(_ childView: UIView) { comicsContainerView.addFullSubview(childView) } } <file_sep>// // Constants.swift // MVC // // Created by <NAME>. on 5/9/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation struct Constants { static let baseURL = URL(string: "https://gateway.marvel.com")! static let apikey = "a71aed242ded875a2afe7d8787e3c923" static let privateKey = "84a27dd2942ce3675202e76ae48135dec0c257b2" } <file_sep>// // UIView.swift // MVC // // Created by <NAME>. on 5/11/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit extension UIView { func addFullSubview(_ subview: UIView) { addSubview(subview) constraintFullSubview(subview) } func constraintFullSubview(_ subview: UIView) { subview.translatesAutoresizingMaskIntoConstraints = false subview.topAnchor.constraint(equalTo: topAnchor).isActive = true subview.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true subview.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true subview.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true } } <file_sep>// // ErrorCharacterTableViewCell.swift // MVC // // Created by <NAME>. on 5/9/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit final class ErrorCharacterTableViewCell: UITableViewCell { static let reuseId: String = "ErrorCharacterTableViewCell" @IBOutlet private weak var errorLabel: UILabel! var errorText: String! { didSet { errorLabel.text = errorText } } } <file_sep>// // CharactersViewController.swift // MVC // // Created by <NAME>. on 5/5/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit final class CharactersViewController: NibViewController<CharactersContentView> { // MARK: - Private properties private lazy var state: State = State.state(.initial, vc: self) private var searchTask: DispatchWorkItem? private var queryText: String? // MARK: - View Controller life cycle override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Heroes of Marvel" contentView.tableView.dataSource = self contentView.tableView.delegate = self contentView.searchBar.delegate = self } } //MARK: - UITableViewDataSource extension CharactersViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let showingDataState = state as? ShowingDataState else { return 1 } return showingDataState.characters.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch state { case is EmptyState: return tableView.dequeueReusableCell(withIdentifier: EmptyCharacterTableViewCell.reuseId, for: indexPath) case let errorState as ErrorState: let cell = tableView.dequeueReusableCell(withIdentifier: ErrorCharacterTableViewCell.reuseId, for: indexPath) as! ErrorCharacterTableViewCell cell.errorText = errorState.error.localizedDescription return cell case is InitialState: return tableView.dequeueReusableCell(withIdentifier: InitialCharacterTableViewCell.reuseId, for: indexPath) case let showingDataState as ShowingDataState: let cell = tableView.dequeueReusableCell(withIdentifier: ShowingDataCharacterTableViewCell.reuseId, for: indexPath) as! ShowingDataCharacterTableViewCell cell.character = showingDataState.characters[indexPath.row] return cell default: return UITableViewCell(style: .default, reuseIdentifier: nil) } } } //MARK: - UITableViewDelegate extension CharactersViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let showingDataState = state as? ShowingDataState else { return } self.navigationController?.pushViewController(CharacterDetailViewController(character: showingDataState.characters[indexPath.row]), animated: true) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch state { case is ShowingDataState: return 70.0 default: return tableView.bounds.height } } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { guard let showingDataState = state as? ShowingDataState, indexPath.item > 0, let queryText = queryText else { return } if indexPath.item == showingDataState.characters.count - 1 { contentView.activityIndicator.startAnimating() getCharacters(name: queryText, offset: showingDataState.characters.count) { [weak self] (result) in guard let self = self else { return } switch result { case .success(let characters): showingDataState.addNewCharacters(characters.data.results) case .failure(let error): self.state = State.state(.error(error), vc: self) self.state.enter() } self.contentView.activityIndicator.stopAnimating() } } } } //MARK: - UISearchBarDelegate extension CharactersViewController: UISearchBarDelegate { func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { searchBar.setShowsCancelButton(true, animated: true) } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { self.searchTask?.cancel() guard !searchText.isEmpty else { return } queryText = searchText let task = DispatchWorkItem { [weak self] in self?.getCharacters(name: searchText, result: { [weak self] response in guard let self = self else { return } switch response { case .success(let result): self.state = State.state(result.data.results.count == 0 ? .empty : .showingData(result.data.results), vc: self) self.state.enter() case .failure(let error): self.state = State.state(.error(error), vc: self) self.state.enter() } }) } self.searchTask = task DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25, execute: task) } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() if let cancelButton : UIButton = searchBar.value(forKey: "cancelButton") as? UIButton { cancelButton.isEnabled = true } } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchBar.setShowsCancelButton(false, animated: false) searchBar.text = nil searchBar.resignFirstResponder() } } // MARK: - Requests private extension CharactersViewController { func getCharacters(name: String, limit: Int? = 20, offset: Int? = nil, result: @escaping (Result<GetCharactersResponse, Error>) -> Void) { let request = CharacterRouter.getCharacters(name: name, limit: limit, offset: offset) Networking.request(request) { (response: Result<GetCharactersResponse, Error>) in result(response) } } } <file_sep>// // NibViewController.swift // MVC // // Created by <NAME>. on 5/9/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit class NibViewController<ContentView: UIView & NibViewInterface>: ViewController<ContentView> { override func loadContentView() -> ContentView { return ContentView.loadFromNib(owner: self, options: nil) } } <file_sep>// // NibViewInterface.swift // MVC // // Created by <NAME>. on 5/9/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit protocol NibViewInterface: class { static var nib: UINib { get } } extension NibViewInterface { static var bundle: Bundle { return Bundle(for: Self.self) } static func loadFromNib(owner: Any? = nil, options: [UINib.OptionsKey: Any]? = nil) -> Self { return nib.instantiate(withOwner: owner, options: options)[0] as! Self } } <file_sep># MVC Custom MVC with Content View ```pod install``` to use project <file_sep>// // ShowingDataComicsCollectionViewCell.swift // MVC // // Created by <NAME>. on 5/11/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit final class ShowingDataComicsCollectionViewCell: UICollectionViewCell { static let reuseId: String = "ShowingDataComicsCollectionViewCell" var comics: Comics! { didSet { activityIndicator.startAnimating() comicsImageView.image = nil if let url = comics.thumbnail.url { comicsImageView.af.setImage(withURL: url) { _ in self.activityIndicator.stopAnimating() } } } } @IBOutlet private weak var comicsImageView: UIImageView! private let activityIndicator: UIActivityIndicatorView = { let activityIndicator = UIActivityIndicatorView(style: .large) activityIndicator.hidesWhenStopped = true return activityIndicator }() override func awakeFromNib() { super.awakeFromNib() comicsImageView.addFullSubview(activityIndicator) } } <file_sep>// // LoadingComicsCollectionViewCell.swift // MVC // // Created by <NAME>. on 5/11/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit final class LoadingComicsCollectionViewCell: UICollectionViewCell { static let reuseId: String = "LoadingComicsCollectionViewCell" } <file_sep>// // CharacterComicsViewController.swift // MVC // // Created by <NAME>. on 5/11/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit final class CharacterComicsViewController: NibViewController<CharacterComicsContentView> { // MARK: - Initializers init(characterId: Int) { self.characterId = characterId super.init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Private properties private let characterId: Int private lazy var state = State.state(.loading, vc: self) // MARK: - View Controller life cycle override func viewDidLoad() { super.viewDidLoad() contentView.collectionView.delegate = self contentView.collectionView.dataSource = self getComics(characterId: characterId) { [weak self] response in guard let self = self else { return } switch response { case .success(let result): self.state = State.state(result.data.results.count == 0 ? .empty : .showingData(result.data.results), vc: self) self.state.enter() case .failure(let error): self.state = State.state(.error(error), vc: self) self.state.enter() } } } } //MARK: - UICollectionViewDataSource extension CharacterComicsViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { guard let showingDataState = state as? ShowingDataState else { return 1 } return showingDataState.comics.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { switch state { case let showingData as ShowingDataState: let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ShowingDataComicsCollectionViewCell.reuseId, for: indexPath) as! ShowingDataComicsCollectionViewCell cell.comics = showingData.comics[indexPath.row] return cell case is EmptyState: let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmptyComicsCollectionViewCell.reuseId, for: indexPath) return cell case let error as ErrorState: let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ErrorComicsCollectionViewCell.reuseId, for: indexPath) as! ErrorComicsCollectionViewCell cell.errorText = error.error.localizedDescription return cell case is LoadingState: let cell = collectionView.dequeueReusableCell(withReuseIdentifier: LoadingComicsCollectionViewCell.reuseId, for: indexPath) return cell default: return UICollectionViewCell(frame: collectionView.frame) } } } //MARK: - UICollectionViewDelegate extension CharacterComicsViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { guard let showingDataState = state as? ShowingDataState, indexPath.item > 0 else { return } if indexPath.item == showingDataState.comics.count - 1 { getComics(characterId: characterId, offset: showingDataState.comics.count) { [weak self] (result) in guard let self = self else { return } switch result { case .success(let comics): showingDataState.addNewComics(comics.data.results) case .failure(let error): self.state = State.state(.error(error), vc: self) self.state.enter() } } } } } //MARK: - UICollectionViewDelegateFlowLayout extension CharacterComicsViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { switch state { case is ShowingDataState: let height = collectionView.bounds.height - 20.0 let width = height / 1.5 return CGSize(width: width, height: height) default: return collectionView.bounds.size } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { switch state { case is ShowingDataState: return UIEdgeInsets(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0) default: return .zero } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 10.0 } } // MARK: - Requests private extension CharacterComicsViewController { func getComics(characterId: Int, limit: Int? = 5, offset: Int? = nil, result: @escaping (Result<GetComicsResponse, Error>) -> Void) { let request = CharacterRouter.getCharacterComics(characterId: characterId, limit: limit, offset: offset) Networking.request(request) { (response: Result<GetComicsResponse, Error>) in result(response) } } } <file_sep>// // EmptyCharacterTableViewCell.swift // MVC // // Created by <NAME>. on 5/9/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit final class EmptyCharacterTableViewCell: UITableViewCell { static let reuseId: String = "EmptyCharacterTableViewCell" } <file_sep>// // CharactersContentView.swift // MVC // // Created by <NAME>. on 5/9/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit final class CharactersContentView: UIView, NibViewInterface { static var nib: UINib = UINib(nibName: "CharactersContentView", bundle: nil) @IBOutlet weak var tableView: UITableView! let searchBar: UISearchBar = { let searchBar = UISearchBar() searchBar.searchBarStyle = .minimal searchBar.returnKeyType = .done searchBar.placeholder = "Enter a name" searchBar.sizeToFit() return searchBar }() let activityIndicator: UIActivityIndicatorView = { let activityIndicator = UIActivityIndicatorView(style: .medium) activityIndicator.sizeToFit() activityIndicator.hidesWhenStopped = true return activityIndicator }() override func awakeFromNib() { super.awakeFromNib() tableView.tableHeaderView = searchBar tableView.tableFooterView = activityIndicator tableView.register(UINib(nibName: "InitialCharacterTableViewCell", bundle: nil), forCellReuseIdentifier: InitialCharacterTableViewCell.reuseId) tableView.register(UINib(nibName: "ErrorCharacterTableViewCell", bundle: nil), forCellReuseIdentifier: ErrorCharacterTableViewCell.reuseId) tableView.register(UINib(nibName: "EmptyCharacterTableViewCell", bundle: nil), forCellReuseIdentifier: EmptyCharacterTableViewCell.reuseId) tableView.register(UINib(nibName: "ShowingDataCharacterTableViewCell", bundle: nil), forCellReuseIdentifier: ShowingDataCharacterTableViewCell.reuseId) } } <file_sep>// // InitialCharacterTableViewCell.swift // MVC // // Created by <NAME>. on 5/9/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit final class InitialCharacterTableViewCell: UITableViewCell { static let reuseId: String = "InitialCharacterTableViewCell" } <file_sep>// // CharacterDetailViewController.swift // MVC // // Created by <NAME>. on 5/11/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit final class CharacterDetailViewController: NibViewController<CharacterDetailContentView> { // MARK: - Initializers init(character: Character) { self.character = character super.init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Private properties private let character: Character private var comicsController: CharacterComicsViewController! { didSet { addChild(comicsController) contentView.addComicsView(comicsController.view) comicsController.didMove(toParent: self) } } // MARK: - View Controller life cycle override func viewDidLoad() { super.viewDidLoad() navigationItem.title = character.name contentView.character = character comicsController = CharacterComicsViewController(characterId: character.id) } } <file_sep>// // ErrorComicsCollectionViewCell.swift // MVC // // Created by <NAME>. on 5/11/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit final class ErrorComicsCollectionViewCell: UICollectionViewCell { static let reuseId: String = "ErrorComicsCollectionViewCell" @IBOutlet private weak var errorLabel: UILabel! var errorText: String! { didSet { errorLabel.text = errorText } } } <file_sep>// // CharacterComicsViewController+State.swift // MVC // // Created by <NAME>. on 5/11/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit extension CharacterComicsViewController { class State { enum Kind { case empty case error(Error) case loading case showingData([Comics]) } weak var vc: CharacterComicsViewController! static func state(_ kind: Kind, vc: CharacterComicsViewController) -> State { switch kind { case .empty: return EmptyState(vc: vc) case .error(let error): return ErrorState(error: error, vc: vc) case .loading: return LoadingState(vc: vc) case .showingData(let comics): return ShowingDataState(comics: comics , vc: vc) } } init(vc: CharacterComicsViewController) { self.vc = vc } func enter() { vc.contentView.collectionView.reloadData() } } final class EmptyState: State { } final class ErrorState: State { let error: Error init(error: Error, vc: CharacterComicsViewController) { self.error = error super.init(vc: vc) } } final class LoadingState: State { } final class ShowingDataState: State { var comics: [Comics] init(comics: [Comics], vc: CharacterComicsViewController) { self.comics = comics super.init(vc: vc) } func addNewComics(_ comics: [Comics]) { guard !comics.isEmpty else { return } let numberOfExistingItems = vc.contentView.collectionView.numberOfItems(inSection: 0) let totalNumberOfItems = (numberOfExistingItems - 1) + comics.count let indexPaths = ((numberOfExistingItems - 1) ... (totalNumberOfItems - 1)).map({ IndexPath(row: $0, section: 0) }) vc.contentView.collectionView.performUsingPresentationValues { self.comics.append(contentsOf: comics) self.vc.contentView.collectionView.insertItems(at: indexPaths) } } } } <file_sep>// // CharacterComicsContentView.swift // MVC // // Created by <NAME>. on 5/11/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit final class CharacterComicsContentView: UIView, NibViewInterface { static var nib: UINib = UINib(nibName: "CharacterComicsContentView", bundle: nil) @IBOutlet weak var collectionView: UICollectionView! override func awakeFromNib() { super.awakeFromNib() collectionView.register(UINib(nibName: "ShowingDataComicsCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: ShowingDataComicsCollectionViewCell.reuseId) collectionView.register(UINib(nibName: "LoadingComicsCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: LoadingComicsCollectionViewCell.reuseId) collectionView.register(UINib(nibName: "ErrorComicsCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: ErrorComicsCollectionViewCell.reuseId) collectionView.register(UINib(nibName: "EmptyComicsCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: EmptyComicsCollectionViewCell.reuseId) } } <file_sep>// // ShowingDataCharacterTableViewCell.swift // MVC // // Created by <NAME>. on 5/9/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit import AlamofireImage final class ShowingDataCharacterTableViewCell: UITableViewCell { static let reuseId: String = "ShowingDataCharacterTableViewCell" @IBOutlet private weak var characterImageView: UIImageView! @IBOutlet private weak var characterNameLabel: UILabel! var character: Character! { didSet { characterImageView.image = nil if let url = character.thumbnail.url { characterImageView.af.setImage(withURL: url) } characterNameLabel.text = character.name } } } <file_sep>// // ViewController.swift // MVC // // Created by <NAME>. on 5/9/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import UIKit class ViewController<ContentView: UIView>: UIViewController, ViewControllerInterface { init() { super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } final override func loadView() { view = loadContentView() } func loadContentView() -> ContentView { fatalError("Should be overriden") } } <file_sep>// // Networking.swift // MVC // // Created by <NAME>. on 5/9/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import Alamofire final class Networking { static func request<T: Decodable>(_ urlRequest: URLRequestConvertible, result: @escaping(Swift.Result<T, Swift.Error>) -> Void) { AF.request(urlRequest).responseDecodable(of: T.self) { response in switch response.result { case .success(let value): result(.success(value)) case .failure(let error): switch response.response?.statusCode { case 403: result(.failure(Error.forbidden)) case 404: result(.failure(Error.notFound)) case 409: result(.failure(Error.conflict)) case 500: result(.failure(Error.internalServerError)) default: result(.failure(Error.descripted(code: response.response?.statusCode, description: error.localizedDescription))) } } } } } extension Networking { enum Error: Swift.Error { case forbidden case notFound case conflict case internalServerError case descripted(code: Int?, description: String) } } extension Networking.Error: LocalizedError { var errorDescription: String? { switch self { case .forbidden: return "Status code 403" case .notFound: return "Status code 404" case .conflict: return "Status code 409" case .internalServerError: return "Status code 500" case let .descripted(code, description): return "An error was found" + "\n" + "Code" + ": " + "\(String(describing: code))" + "\n" + "Description" + ": " + description } } }
b8179030d84cce73b15d95e4e8749a1b41522c2e
[ "Swift", "Ruby", "Markdown" ]
26
Swift
demonukg/MVC
5d3df3f9fb04c190853652dd9f2b7b2b4a321439
aafd2b50a25a776b2f07e6971379de3cecab98fc
refs/heads/master
<repo_name>GeeKayeBehnke/GitHubExample2017<file_sep>/GitHubExample2017/main.swift // // main.swift // GitHubExample2017 // // Created by behnke on 12/6/17. // Copyright © 2017 behnke. All rights reserved. // import Foundation print("Hello, World!")
31b8bc25848b7ad8018b2ef4f1f8f22b83a09160
[ "Swift" ]
1
Swift
GeeKayeBehnke/GitHubExample2017
84f14b6d0fc4863b67f76757330acd7da9ceba5d
fc15ff099f3a8cb65162f668fd22bc6837267e13
refs/heads/main
<repo_name>renantms/payment-sabadell<file_sep>/src/main/java/br/com/invillia/payment/control/PaymentControl.java package br.com.invillia.payment.control; import br.com.invillia.payment.domain.request.PaymentRequest; import br.com.invillia.payment.domain.response.PaymentResponse; import br.com.invillia.payment.service.PaymentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.net.URI; import java.util.List; import java.util.Optional; @RestController @RequestMapping("/payment") public class PaymentControl { private PaymentService paymentService; @Autowired public PaymentControl(PaymentService paymentService){ this.paymentService = paymentService; } @GetMapping public ResponseEntity<List<PaymentResponse>> getPayment(@RequestParam(required = false) String name, @RequestParam(required = false, defaultValue = "0") int page, @RequestParam(required = false, defaultValue = "5") int size){ List<PaymentResponse> paymentResponses = paymentService.getPayment(name, page, size); if(paymentResponses.isEmpty()){ return ResponseEntity.notFound().build(); } return ResponseEntity.ok(paymentResponses); } @PostMapping public ResponseEntity<PaymentResponse> postPayment(@RequestBody PaymentRequest paymentRequest){ Optional<PaymentResponse> paymentResponse = paymentService.postPayment(paymentRequest); if(paymentResponse.isEmpty()) { return ResponseEntity.badRequest().build(); } return ResponseEntity.created(URI.create(paymentResponse.get().getName())).body(paymentResponse.get()); } } <file_sep>/src/test/java/br/com/invillia/payment/service/PaymentServiceTest.java package br.com.invillia.payment.service; import br.com.invillia.payment.domain.PaymentMapper; import br.com.invillia.payment.domain.request.PaymentRequest; import br.com.invillia.payment.domain.response.PaymentResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.boot.test.context.SpringBootTest; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.*; @SpringBootTest public class PaymentServiceTest { private PaymentService paymentService; @Mock private PaymentClientService paymentClientService; @Mock private ProducerPaymentService producerPaymentService; private List<PaymentRequest> paymentRequests; @BeforeEach void beforeEach(){ MockitoAnnotations.openMocks(this); paymentService = new PaymentService(paymentClientService, producerPaymentService); this.paymentRequests = new ArrayList<>(); paymentRequests.add(new PaymentRequest()); paymentRequests.get(0).setName("Renan"); paymentRequests.get(0).setValue(new BigDecimal("300")); paymentRequests.add(new PaymentRequest()); paymentRequests.get(1).setName("Renan"); } private void configureGet(String name, List<PaymentResponse> payment) { Mockito.when(paymentClientService.getPayment(name, 0, 5)).thenReturn(payment.stream() .filter((value -> value.getName().equals(name))).collect(Collectors.toList())); } private List<PaymentResponse> configureGetAndReturn(String name, List<PaymentRequest> payment) { List<PaymentResponse> paymentResponses = payment.stream().map(PaymentMapper.INSTANCE::paymentRequestToPaymentResponse).collect(Collectors.toList()); configureGet(name, paymentResponses); return paymentService.getPayment(name, 0, 5); } private void configurePost(PaymentRequest paymentRequest) { Mockito.when(producerPaymentService.postPayment(paymentRequest)).thenReturn(paymentRequest.verify()); } private Optional<PaymentResponse> configurePostAndReturn(PaymentRequest paymentRequest) { configurePost(paymentRequest); return paymentService.postPayment(paymentRequest); } @Test void getWillFindPayment(){ List<PaymentResponse> paymentResponses = configureGetAndReturn("Renan", paymentRequests); List<PaymentResponse> payment = paymentRequests.stream().map(PaymentMapper.INSTANCE::paymentRequestToPaymentResponse).collect(Collectors.toList()); assertTrue(payment.equals(paymentResponses)); } @Test void getWillNotFindPayment(){ List<PaymentResponse> paymentResponses = configureGetAndReturn("Scolari", paymentRequests); assertTrue(paymentResponses.isEmpty()); } @Test void postWillCreatePayment(){ Optional<PaymentResponse> paymentResponse = configurePostAndReturn(paymentRequests.get(0)); PaymentResponse payment = PaymentMapper.INSTANCE.paymentRequestToPaymentResponse(paymentRequests.get(0)); assertTrue(paymentResponse.isPresent()); assertEquals(payment, paymentResponse.get()); } @Test void postWillNotCreatePayment(){ Optional<PaymentResponse> paymentResponse = configurePostAndReturn(paymentRequests.get(1)); assertFalse(paymentResponse.isPresent()); } } <file_sep>/src/main/java/br/com/invillia/payment/service/PaymentService.java package br.com.invillia.payment.service; import br.com.invillia.payment.domain.PaymentMapper; import br.com.invillia.payment.domain.request.PaymentRequest; import br.com.invillia.payment.domain.response.PaymentResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class PaymentService { private PaymentClientService paymentClientService; private ProducerPaymentService producerPaymentService; @Autowired public PaymentService(PaymentClientService paymentClientService, ProducerPaymentService producerPaymentService) { this.paymentClientService = paymentClientService; this.producerPaymentService = producerPaymentService; } public List<PaymentResponse> getPayment(String name, int page, int size) { return paymentClientService.getPayment(name, page, size); } public Optional<PaymentResponse> postPayment(PaymentRequest paymentRequest) { if(!producerPaymentService.postPayment(paymentRequest)){ return Optional.empty(); } return Optional.of(PaymentMapper.INSTANCE.paymentRequestToPaymentResponse(paymentRequest)); } }
20a175492a1f23d05d44264049d59c53203b3f39
[ "Java" ]
3
Java
renantms/payment-sabadell
3480fe4d73c0d0991962867ac610df213332039f
99da1c0e5098376a11b2e6d7fcfcc82d7a51c0b3
refs/heads/master
<file_sep>import de.cgi.selenium.pageobjects.HornbachMainPage; import io.github.bonigarcia.seljup.SeleniumExtension; import io.github.bonigarcia.wdm.WebDriverManager; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; @ExtendWith(SeleniumExtension.class) public class JUnitTestExample { ChromeDriver chromeDriver; FirefoxDriver firefoxDriver; public JUnitTestExample(ChromeDriver chromeDriver,FirefoxDriver firefoxDriver) { this.chromeDriver = chromeDriver; this.firefoxDriver=firefoxDriver; } public JUnitTestExample() { WebDriverManager.chromedriver().setup(); WebDriverManager.firefoxdriver().setup(); } @Test public void testWithOneChrome() { this.chromeDriver = new ChromeDriver(); chromeDriver.get("https://www.hornbach.de/"); HornbachMainPage hbHomePage = new HornbachMainPage(); hbHomePage.hoverOverSortiment(chromeDriver); hbHomePage.goToSortiment(chromeDriver); System.out.println(chromeDriver.getTitle()); chromeDriver.close(); } @Test public void testWithOneFireFox() { this.firefoxDriver=new FirefoxDriver(); firefoxDriver.get("https://www.hornbach.de/"); HornbachMainPage hbHomePage = new HornbachMainPage(); hbHomePage.hoverOverSortiment(firefoxDriver); hbHomePage.goToSortiment(firefoxDriver); System.out.println(firefoxDriver.getTitle()); firefoxDriver.close(); } @Test public void testWithChromeAndFirefox() { this.chromeDriver = new ChromeDriver(); this.firefoxDriver=new FirefoxDriver(); chromeDriver.get("https://www.hornbach.de/"); firefoxDriver.get("https://www.hornbach.de/"); HornbachMainPage hbHomePageF = new HornbachMainPage(); HornbachMainPage hbHomePageC = new HornbachMainPage(); hbHomePageC.hoverOverSortiment(chromeDriver); hbHomePageF.hoverOverSortiment(firefoxDriver); hbHomePageC.goToSortiment(chromeDriver); hbHomePageF.goToSortiment(firefoxDriver); System.out.println(chromeDriver.getTitle()); System.out.println(firefoxDriver.getTitle()); chromeDriver.close(); firefoxDriver.close(); } }<file_sep>public class SeleniumFirstTest { public static void main(String[] args) { /*WebDriver chromeDriver = new ChromeDriverBuilder().setDriverLocation("C:\\chromedriver\\84\\chromedriver.exe").build(); chromeDriver.get("https://www.hornbach.de/"); HornbachMainPage hbHomePage = new HornbachMainPage(); hbHomePage.hoverOverSortiment(chromeDriver); hbHomePage.goToSortiment(chromeDriver); System.out.println(chromeDriver.getTitle()); chromeDriver.close();*/ JUnitTestExample jUnitTestExample = new JUnitTestExample(); jUnitTestExample.testWithOneChrome(); jUnitTestExample.testWithOneFireFox(); jUnitTestExample.testWithChromeAndFirefox(); /*JUnitStartTeardown unitStartTeardown = new JUnitStartTeardown(); unitStartTeardown.test();*/ } } <file_sep>package de.cgi.selenium.pageobjects; import io.github.bonigarcia.wdm.WebDriverManager; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class NineGagMainPage { private By trending = By.xpath("//a[@href='/trending']"); private By fresh = By.xpath("//a[@href='/fresh']"); private By popupAccept = By.xpath("//button[contains(text(),'I ACCEPT')]"); public void goToTrending(WebDriver driver){ driver.findElement(trending).click(); } public void goToFresh(WebDriver driver){ driver.findElement(fresh).click(); } public void closePopup(WebDriver driver){ WebDriverWait wait = new WebDriverWait(driver,15); wait.until(ExpectedConditions.visibilityOfElementLocated(popupAccept)); driver.findElement(popupAccept).click(); } } <file_sep>package de.cgi.selenium.pageobjects; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; public class HornbachMainPage { private By sortiment = By.xpath("//a[@title='Sortiment']"); public HornbachMainPage(){ //check if mainpage is loaded } public void goToSortiment(WebDriver driver){ driver.findElement(sortiment).click(); } public void hoverOverSortiment(WebDriver driver) { Actions action = new Actions(driver); WebElement we = driver.findElement(sortiment); action.moveToElement(we).moveToElement(driver.findElement(sortiment)).build().perform(); } }
750db4a919599a7b8898194edd09912b52358f2d
[ "Java" ]
4
Java
GoranStuc/testingstuff
8ff8a865d272fcd26a43e2428adad68d51a25430
6207b1b0d20d04f0e70fc3e08f41effe53b92189
refs/heads/master
<repo_name>wasanthag/concourse_ci_pipelines<file_sep>/create_and_upload_base_image/Dockerfile FROM alpine:3.4 RUN apk update RUN apk add python RUN apk add py-pip RUN apk add python-dev RUN apk add py-requests RUN apk add py-lxml COPY requirements.txt /tmp/ RUN pip install --requirement /tmp/requirements.txt #COPY acicobra-1.3_2h-py2.7.egg /opt/ #COPY acimodel-1.3_2h-py2.7.egg /opt/ #RUN easy_install-2.7 -Z /opt/acicobra-1.3_2h-py2.7.egg #RUN easy_install-2.7 -Z /opt/acimodel-1.3_2h-py2.7.egg <file_sep>/run-unit-test.sh #!/bin/sh set -e -u -x #easy_install-2.7 -Z /opt/acicobra-1.3_2h-py2.7.egg #easy_install-2.7 -Z /opt/acimodel-1.3_2h-py2.7.egg sleep 10 python github-code/api.py & sleep 10 #curl http://localhost:5000/health python github-code/unit-test.py <file_sep>/unit-test.py #!/usr/bin/env python import unittest from bs4 import BeautifulSoup import urllib2 import time class TestACIFlask(unittest.TestCase): def test_health_score_range(self): link = urllib2.urlopen("http://localhost:5000/date") Html = link.read() link.close() u_date = time.strftime("%d/%m/%Y") soup = BeautifulSoup(Html,"lxml") cdate = soup.find('div',{'class':'date'}).text print cdate self.assertTrue(cdate == u_date) if __name__ == '__main__': unittest.main() <file_sep>/Dockerfile FROM whewawal/concourse-ci-demo COPY api.py /opt/ COPY templates /opt/templates EXPOSE 5000 CMD python /opt/api.py <file_sep>/api.py from flask import Flask, render_template app = Flask(__name__) def get_date(): import time #print "getting date" return time.strftime("%d/%m/%Y") def get_time(): import time #print "getting time" return time.strftime("%I:%M:%S") @app.route('/date') def print_date(): return render_template("date.html", cdate=get_date()) @app.route('/time') def print_time(): return render_template("time.html", cdate=get_time()) if __name__ == '__main__': try: app.run(debug=False,host="0.0.0.0") except KeyboardInterrupt: pass <file_sep>/README.md # concourse_ci_pipelines various CICD pipelines based on concourse CI - create and upload base image This pipeline builds a docker image based on a Dockerfile inside a github repo and uploads the built image to a docker repository such as docker hub or any docker repo in the format containers.xyz.com/container. Dockerfile used copies pip requirements file on to the container and runs pip install. Other python packgae installers can be used as well, ex. easy_install - run unit tests This pipeline pulls docker image from a docker image repository and runs unit test cases against code stored in a github repo - deploy to kuberenetes cluster This pipeline pulls a docker image ,runs unit tests , package the code and docker image and uploads to a docker image repository if the unit tests pass. Then that docker image (including unit tests passed code) is deployed to a Kubernetes cluster based on a spec file. This use a fork from concourse CI community resources jcderr/concourse-kubernetes-resource Crdentials such as github and docker hub login can be added in to a crdentials.yml file and use with concourse fly cli option -l crdentials.yml. These crdentials files should be added in to .gitignore to prevent them from being exposed to public. <file_sep>/create_and_upload_base_image/requirements.txt pyaml flask flask-restful bs4 lxml
4264019cab9558b34413868c337a4eae13cfa705
[ "Markdown", "Python", "Text", "Dockerfile", "Shell" ]
7
Dockerfile
wasanthag/concourse_ci_pipelines
38aebb1879731ba6976ea893f274cd8a4ce4ba6a
446d765b2c8160badf8312564373f15f493b0ebf
refs/heads/master
<file_sep>var self = require('sdk/self'); var { ToggleButton } = require('sdk/ui/button/toggle'); var tabs = require("sdk/tabs"); var l3nsOn = false; var button = ToggleButton({ id: "switch-l33t-mode", label: "Switch leet lens on/off", icon: { "16": "./icon-16.png", "32": "./icon-32.png", "64": "./icon-64.png" }, onChange: function() { if (!l3nsOn) { setLens(tabs.activeTab); tabs.on("ready", setLens); } else { tabs.removeListener("ready", setLens); } l3nsOn = !l3nsOn; } }); function setLens(tab) { tab.attach({ contentScriptFile: self.data.url("leet-lens.js") }); } <file_sep>#Leet Lens Firefox add-on for viewing English text in l33t f0rm. Made just4fun ####Installation You may just install it from https://addons.mozilla.org/ru/firefox/addon/leet-lens/ -OR- From source: * install node and npm if not installed * install jpm `npm install jpm --global` if not installed * `jpm xpi` in root directory of l33t-l3n5 * In firefox press `Ctrl + O` and choose \*.xpi file in directory * Have fun! <file_sep> /** * Transform text with l33t equivalent * @param text source text * @return */ function transformAllLeet(text) { var result = ""; for (var i = 0; i < text.length; i++) { result += transformCharLeet(text.charAt(i)); } return result; } /** * Transorm single char to 1337 equivalent. * @param char source char * @return transformed char */ function transformCharLeet(char) { switch (char) { case 'a': return '4'; case 'b': return '8'; case 'c': return '('; case 'd': return 'd'; case 'e': return '3'; case 'f': return 'f'; case 'g': return '6'; case 'h': return 'h'; case 'i': return '!'; case 'j': return 'j'; case 'k': return 'k'; case 'l': return '1'; case 'm': return 'm'; case 'n': return 'n'; case 'o': return '0'; case 'p': return 'p'; case 'q': return 'q'; case 'r': return 'r'; case 's': return '5'; case 't': return '7'; case 'u': return 'u'; case 'v': return 'v'; case 'w': return 'w'; case 'x': return 'x'; case 'y': return 'y'; case 'z': return '2'; default: return char; } } /* * Replece all the body with l33t */ function replaceNode(node, func) { var tagName = node.parentNode.tagName; if (tagName == "STYLE" || tagName == "SCRIPT") return; if (!node.hasChildNodes()) { var source = node.textContent; // 3 - type of TEXT_NODE if (node.nodeType == 3) node.textContent = func(source); } else { node = node.firstChild; while (node) { replaceNode(node, func); node = node.nextSibling; } } } replaceNode(document.body, transformAllLeet);
da789a57f2266071f24daa66cffccbd1b7741853
[ "JavaScript", "Markdown" ]
3
JavaScript
takahawk/l33t-l3n5
f588bbf3e7a17a0ad50d2890c7fec00f147fa2b7
5c43d9a234ef3dbbe887aaadb7215c8affbda6d6
refs/heads/master
<file_sep>var DoPattern = (function (viewport, options) { "use strict"; var stage; var circles = []; var connector; var connections = []; var initialize = function() { stage = arguments[0]; var vertices = arguments[1]; //create background stage.addChild(Utils.createjs.createRectangle(0, 0, viewport.width, viewport.height, options.background.color)); //ceate a circle for each polygon vertex and add it to stage for(var i = 0; i < vertices.length; i++) { var circle = Utils.createjs.createCircle(vertices[i], options.circle.radius, options.circle.color); circles.push(circle); stage.addChild(circle); } //create a new shape representing the line that is drawn between the circles connector = new createjs.Shape(); stage.addChild(connector); //create middle circle and add it to stage var finger = Utils.createjs.createCircle(viewport.center, options.circle.radius, options.circle.color); finger.on("pressmove", dragFinger); finger.on("pressup", liftFinger); stage.addChild(finger); //add the center as the first connectionBar connections.push(viewport.center); }; var dragFinger = function(event) { //update position event.currentTarget.x = event.stageX; event.currentTarget.y = event.stageY; //check if the finger overlapps one of the circles for(var i = 0; i < circles.length; i++) { if(hitTest(event.currentTarget, circles[i])) { //if it does, check if that circle was previously touched if (connections.indexOf(circles[i]) === -1) { connections.push(circles[i]); } } } //clear old connectionBar graphics connector.graphics.clear(); //draw line between all connected circles var len = connections.length; for(var i = 0; i < len - 1; i++) { Utils.createjs.drawLine(connector, connections[i], connections[i + 1], options.connector.thickness, options.connector.color); } //draw line between last connected circle to the current touch position var endPoint = { x: event.stageX, y: event.stageY }; Utils.createjs.drawLine(connector, connections[len - 1], endPoint, options.connector.thickness, options.connector.color); }; //check if the circles were touched in the right order //connections and circles should contain the same objects in the same positions var liftFinger = function(event) { //remove the first element of connections which was the screen center connections.shift(); //compare the arrays var result = true; for(var i = 0; i < circles.length; i++) { if(circles[i] !== connections[i]) { result = false; } } Game.changeView(EndGame, result); }; //check if two circles are are overlapping var hitTest = function(source, target) { var sourceRadius = source.radius; var targetRadius = target.radius; var minDist = sourceRadius + targetRadius; var distBetweenCenters = Math.sqrt((source.x - target.x) * (source.x - target.x) + (source.y - target.y) * (source.y - target.y)); return distBetweenCenters < minDist; }; var destroy = function() { stage.removeAllChildren(); stage = null; circles = []; connector = null; connections = []; }; return { initialize: initialize, destroy: destroy }; })(Game.viewport, Game.options); <file_sep>var Menu = (function(viewport, options) { "use strict"; var stage; var initialize = function() { stage = arguments[0]; //create background stage.addChild(Utils.createjs.createRectangle(0, 0, viewport.width, viewport.height, options.background.color)); //calculate logo position relative to the center of the screen var logoPosition = { x: viewport.center.x + options.logo.offsetX, y: viewport.center.y + options.logo.offsetY }; //create text logo var logo = Utils.createjs.createCenteredText(options.logo.text, options.logo.size + "px Nunito", options.logo.color, logoPosition); stage.addChild(logo); //create play button var playButton = Utils.createjs.createCenteredRoundButton(viewport.center, options.playButton.width, options.playButton.height, options.playButton.radius, options.playButton.backgroundColor, options.playButton.text, options.playButton.fontSize + "px Nunito", options.playButton.fontColor); playButton.on("click", function() { Game.changeView(ShowPattern); }); stage.addChild(playButton); //create animated lines var line = new createjs.Shape(); line.graphics.setStrokeStyle(options.connector.thickness, "round") .beginStroke(options.connector.color); stage.addChild(line); var x1 = viewport.width; var y1 = 0.6 * viewport.height; var x2 = 0; var y2 = 0.9 * viewport.height; var command = line.graphics.moveTo(x1, y1) .lineTo(x1, y1) .command; var t1 = createjs.Tween.get(command, {paused: true}).to({x: x2, y: y2}, 3000); x1 = 0.6 * viewport.width; y1 = -100; x2 = viewport.width; y2 = 0.8 * viewport.height; command = line.graphics.moveTo(x1, y1) .lineTo(x1, y1) .command; var t2 = createjs.Tween.get(command, {paused: true}).to({x: x2, y: y2}, 3000); t1.play(t2); t1.setPaused(false); }; var destroy = function() { stage.removeAllChildren(); stage = null; }; return { initialize: initialize, destroy: destroy }; })(Game.viewport, Game.options); <file_sep>var ShowPattern = (function (viewport, options) { "use strict"; var stage; var initialize = function() { stage = arguments[0]; var tweens = []; //create background stage.addChild(Utils.createjs.createRectangle(0, 0, viewport.width, viewport.height, options.background.color)); //the number of vertices depends on the current level var vertices = Game.levelSettings[Game.level].vertices; //ceate a circle for each polygon vertex and add it to stage var vertices = Utils.getPolygonVertices(viewport.center, options.polygon.radius, vertices); for(var i = 0; i < vertices.length; i++) { stage.addChild(Utils.createjs.createCircle(vertices[i], options.circle.radius, options.circle.color)); } //create middle circle and add it to stage var finger = Utils.createjs.createCircle(viewport.center, options.circle.radius, options.circle.color); stage.addChild(finger); //create a new shape representing the line that is drawn between the circles var connector = new createjs.Shape(); connector.graphics.setStrokeStyle(options.connector.thickness, "round") .beginStroke(options.connector.color); stage.addChild(connector); //shuffle the vertices in order to get random patterns Utils.shuffleArray(vertices); //add the center point to the vertices array in order to generate the tweens easier vertices.unshift(viewport.center); //the speed depends on the current level var speed = Game.levelSettings[Game.level].speed; //generate tweens var command; for(var i = 0; i < vertices.length - 1; i++) { command = connector.graphics.moveTo(vertices[i].x, vertices[i].y) .lineTo(vertices[i].x, vertices[i].y) .command; tweens.push(createjs.Tween.get(command, {paused: true}).to({x: vertices[i + 1].x, y: vertices[i + 1].y}, speed)); } //done generating tweens, remove the center point from the vertices array vertices.shift(); //each tween will trigger the next one for(var i = 0; i < tweens.length; i++) { tweens[i].play(tweens[i + 1]); } //the last tween will trigger the transition to the next scene tweens.pop().call(function() { Game.changeView(DoPattern, vertices); }); tweens[0].setPaused(false); }; var destroy = function() { stage.removeAllChildren(); stage = null; }; return { initialize: initialize, destroy: destroy }; })(Game.viewport, Game.options);
e6a5e658cfbdf2dc09488e46823082eca0904f3d
[ "JavaScript" ]
3
JavaScript
achirita/unlock
d44a405f3e04d4d7f344dbb8293fd1e2be2afdb0
9d1f6112942b010f7683d5da78aa0b1c2e81aac3
refs/heads/master
<file_sep><?php namespace App\Http\Controllers; use App\Models\Categoria; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; class CategoriaController extends Controller { public function index() { $categorias=Categoria::paginate(5); /* $categorias=$categorias->distinct()->get(); */ return view('categorias.index', compact('categorias')); } public function create() { return view('categorias.create'); } public function store(Request $request) { $validator=Validator::make($request->all(), [ 'nombre' => ['required'], ]); if(!$validator->fails()) { $categoria = Categoria::create([ 'nombre' => $request['nombre'], ]); return redirect()->route('categorias.index', $categoria->id)->with('success', 'Categoria añadido correctamente'); }else{ return response()->json(['status_code'=>400,'message'=>$validator->errors()]); } } public function show(Categoria $categoria){ return view('categorias.show', compact('categoria')); } public function edit(Categoria $categoria) { return view('categorias.edit', compact('categoria')); } public function update(Request $request, Categoria $categoria) { $data = $request->only('nombre'); $categoria->update($data); return redirect()->route('horarios.show', $categoria->id)->with('success', 'Categoria actualizado correctamente'); } public function destroy(Categoria $categoria) { $categoria->delete(); return back()->with('success','categoria eliminado correctamente'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Support\Facades\Validator; use App\Models\GruposEntrenamientos; use Illuminate\Http\Request; class GrupoController extends Controller { public function index() { $grupos=GruposEntrenamientos::paginate(5); return view('grupos.index', compact('grupos')); } public function create() { return view('grupos.create'); } public function store(Request $request) { $validator=Validator::make($request->all(), [ 'nombre' => ['required', 'string', 'max:255'], 'cupo' => ['required'], 'instructor_id' => ['required'], 'disciplina_id' => ['required'] ]); if(!$validator->fails()) { $grupo = GruposEntrenamientos::create([ 'nombre' => $request['nombre'], 'cupo' => $request['cupo'], 'instructor_id' => $request['instructor_id'], 'disciplina_id' =>$request['disciplina_id'], ]); return redirect()->route('grupos.show', $grupo->id)->with('success', 'grupo creado correctamente'); }else{ return response()->json(['status_code'=>400,'message'=>$validator->errors()]); } } public function show(GruposEntrenamientos $grupo) { return view('grupos.show', compact('grupo')); } public function edit(GruposEntrenamientos $grupo) { return view('grupos.edit', compact('grupo')); } public function update(Request $request, GruposEntrenamientos $grupo) { $data = $request->only('nombre', 'cupo','instructor_id','disciplina_id'); $grupo->update($data); return redirect()->route('grupos.show', $grupo->id)->with('success', 'Grupo actualizado correctamente'); } public function destroy(GruposEntrenamientos $grupo) { $grupo ->delete(); return back()->with('success','Grupo eliminado correctamente'); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Descuento extends Model { use HasFactory; protected $table = 'descuentos'; protected $fillable = [ 'criterio', 'descuento', 'estado' ]; } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Persona; use App\Models\Administrador; use App\Models\User; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Hash; use Carbon\Carbon; class AdministradorController extends Controller { public function index() { $administradores=Administrador::join('personas','personas.id','=','administradores.persona_id') ->select('administradores.*','personas.nombre','personas.apellido','personas.correo') ->get(); return view('administradores.index', compact('administradores')); } public function create() { return view('administradores.create'); } public function store(Request $request) { $validator=Validator::make($request->all(), [ 'nombre' => ['required', 'string', 'max:255'], 'correo' => ['required', 'string', 'email', 'max:255', 'unique:personas'], 'password' => ['<PASSWORD>'], 'apellido' => ['required'], 'carnet_identidad' => ['required'], 'telefono' => ['required'], 'tipo_administrador' => ['required'] ]); if(!$validator->fails()) { $persona = Persona::create([ 'nombre' => $request['nombre'], 'apellido' => $request['apellido'], 'fecha_nacimiento' => Carbon::now('America/La_Paz')->toDateString(), 'carnet_identidad' => $request['carnet_identidad'], 'correo' => $request['correo'], 'telefono' => $request['telefono'], ]); $user = User::create([ 'name' => $request['nombre'], 'email' => $request['correo'], 'password' => <PASSWORD>($request['password']), 'persona_id' => $persona->id, ]); $administrador = Administrador::create([ 'tipo_administrador' => $request['tipo_administrador'], 'persona_id' => $persona->id, ]); return redirect()->route('administradores.show', $administrador->id)->with('success', 'Administrador creado correctamente'); }else{ return response()->json(['status_code'=>400,'message'=>$validator->errors()]); } } public function show(Administrador $administrador) { $administrador=Administrador::select('administradores.*','personas.nombre','personas.apellido','personas.fecha_nacimiento','personas.carnet_identidad','personas.correo','personas.telefono') ->join('personas','personas.id','=','administradores.persona_id') ->where('administradores.id',$administrador['id']) ->first(); return view('administradores.show', compact('administrador')); } public function edit(Administrador $administrador) { return view('administradores.edit', compact('administrador')); } public function update(Request $request, Administrador $administrador) { $validator=Validator::make($request->all(), [ 'nombre' => ['required', 'string', 'max:255'], 'apellido' => ['required'], 'correo' => ['required', 'string', 'email', 'max:255', 'unique:personas'], 'carnet_identidad' => ['required'], 'telefono' => ['required'], 'tipo_administrador' => ['required'] ]); if ($validator->fails()) { return redirect()->back()->withInput()->withErrors($validator->errors()); } $data = $request->only('nombre', 'apellido','correo','carnet_identidad','telefono', 'tipo_administrador'); $password=$request->input('password'); if($password) $data['password'] = bcrypt($password); $administrador->join('personas','personas.id','=','administradores.persona_id') ->join('users','users.persona_id','=','personas.id') ->update($data); return redirect()->route('administradores.show', $administrador->id)->with('success', 'Administrador actualizado correctamente'); } public function destroy(Administrador $administrador) { $administrador->delete(); return back()->with('success','administrador eliminado correctamente'); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class AlquilerCasillero extends Model { use HasFactory; protected $table = 'alquiler_casilleros'; protected $fillable = [ 'fecha', 'cantidad', 'importe', 'total', 'casillero_id', 'cliente_id', 'administrador_id' ]; } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Persona; use App\Models\Cliente; use Illuminate\Support\Facades\Validator; use Carbon\Carbon; class ClienteController extends Controller { public function index() { $clientes=Cliente::join('personas','personas.id','=','clientes.persona_id') ->select('clientes.*','personas.nombre','personas.apellido','personas.correo') ->get(); return view('clientes.index', compact('clientes')); } public function create() { return view('clientes.create'); } public function store(Request $request) { $validator=Validator::make($request->all(), [ 'nombre' => ['required', 'string', 'max:255'], 'apellido' => ['required'], 'correo' => ['required', 'string', 'email', 'max:255', 'unique:personas'], 'carnet_identidad' => ['required'], 'telefono' => ['required'], 'antiguedad' => ['required'] ]); if(!$validator->fails()) { $persona = Persona::create([ 'nombre' => $request['nombre'], 'apellido' => $request['apellido'], 'fecha_nacimiento' => Carbon::now('America/La_Paz')->toDateString(), 'carnet_identidad' => $request['carnet_identidad'], 'correo' => $request['correo'], 'telefono' => $request['telefono'], ]); $cliente = Cliente::create([ 'antiguedad' => $request['antiguedad'], 'persona_id' => $persona->id, ]); return redirect()->route('clientes.index', $cliente->id)->with('success', 'Cliente creado correctamente'); }else{ return response()->json(['status_code'=>400,'message'=>$validator->errors()]); } } public function show(Cliente $cliente) { $cliente=Cliente::select('clientes.*','personas.nombre','personas.apellido','personas.fecha_nacimiento','personas.carnet_identidad','personas.correo','personas.telefono') ->join('personas','personas.id','=','clientes.persona_id') ->where('clientes.id',$cliente['id']) ->first(); return view('clientes.show', compact('cliente')); } public function edit(Cliente $cliente) { return view('clientes.edit', compact('cliente')); } public function update(Request $request, Cliente $cliente) { $validator=Validator::make($request->all(), [ 'nombre' => ['required', 'string', 'max:255'], 'apellido' => ['required'], 'correo' => ['required', 'string', 'email', 'max:255', 'unique:personas'], 'carnet_identidad' => ['required'], 'telefono' => ['required'], 'antiguedad' => ['required'] ]); if ($validator->fails()) { return redirect()->back()->withInput()->withErrors($validator->errors()); } $data = $request->only('nombre', 'apellido','correo','carnet_identidad','telefono', 'antiguedad'); $cliente->join('personas','personas.id','=','clientes.persona_id')->update($data); return redirect()->route('clientes.show', $cliente->id)->with('success', 'Cliente actualizado correctamente'); } public function destroy(Cliente $cliente) { $cliente->delete(); return back()->with('success','cliente eliminado correctamente'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Persona; use App\Models\Instructor; use Illuminate\Support\Facades\Validator; use Carbon\Carbon; class InstructorController extends Controller { public function index() { $instructores=Instructor::join('personas','personas.id','=','instructores.persona_id') ->select('instructores.*','personas.nombre','personas.apellido','personas.correo') ->get(); return view('instructores.index', compact('instructores')); } public function create() { return view('instructores.create'); } public function store(Request $request) { $validator=Validator::make($request->all(), [ 'nombre' => ['required', 'string', 'max:255'], 'apellido' => ['required'], 'correo' => ['required', 'string', 'email', 'max:255', 'unique:personas'], 'carnet_identidad' => ['required'], 'telefono' => ['required'], 'tipo_instructor' => ['required'] ]); if(!$validator->fails()) { $persona = Persona::create([ 'nombre' => $request['nombre'], 'apellido' => $request['apellido'], 'fecha_nacimiento' => Carbon::now('America/La_Paz')->toDateString(), 'carnet_identidad' => $request['carnet_identidad'], 'correo' => $request['correo'], 'telefono' => $request['telefono'], ]); $instructor = Instructor::create([ 'tipo_instructor' => $request['tipo_instructor'], 'persona_id' => $persona->id, ]); return redirect()->route('instructores.index', $instructor->id)->with('success', 'Instructor creado correctamente'); }else{ return response()->json(['status_code'=>400,'message'=>$validator->errors()]); } } public function show(Instructor $instructor) { $instructor=Instructor::select('instructores.*','personas.nombre','personas.apellido','personas.fecha_nacimiento','personas.carnet_identidad','personas.correo','personas.telefono') ->join('personas','personas.id','=','instructores.persona_id') ->where('instructores.id',$instructor['id']) ->first(); return view('instructores.show', compact('instructor')); } public function edit(Instructor $instructor) { return view('instructores.edit', compact('instructor')); } public function update(Request $request, Instructor $instructor) { $validator=Validator::make($request->all(), [ 'nombre' => ['required', 'string', 'max:255'], 'apellido' => ['required'], 'correo' => ['required', 'string', 'email', 'max:255', 'unique:personas'], 'carnet_identidad' => ['required'], 'telefono' => ['required'], 'tipo_instructor' => ['required'] ]); if ($validator->fails()) { return redirect()->back()->withInput()->withErrors($validator->errors()); } $data = $request->only('nombre','apellido','correo','carnet_identidad','telefono','tipo_instructor'); $instructor->join('personas','personas.id','=','instructores.persona_id')->update($data); return redirect()->route('instructores.index', $instructor->id)->with('success', 'Instructor actualizado correctamente'); } public function destroy(Instructor $instructor) { $instructor->delete(); return back()->with('success','Instructor eliminado correctamente'); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class BoletaInscripcion extends Model { use HasFactory; protected $table = 'boletas_de_inscripciones'; protected $fillable = [ 'fecha_inscripcion', 'fecha_inicio', 'fecha_fin', 'importe', 'total', 'descuento_id', 'cliente_id', 'administrador_id' ]; } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class GruposEntrenamientos extends Model { use HasFactory; protected $table = 'grupos_de_entrenamientos'; protected $fillable = [ 'nombre', 'cupo', 'instructor_id', 'disciplina_id', ]; } <file_sep><?php namespace App\Http\Controllers; use App\Models\Casillero; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; use App\Models\Estado; class CasillerController extends Controller { public function index() { $casilleros=Casillero::paginate(5); /* $categorias=$categorias->distinct()->get(); */ return view('casilleros.index', compact('casilleros')); } public function create() { return view('casilleros.create'); } public function store(Request $request) { $validator=Validator::make($request->all(), [ 'numero' => ['required'], 'tiempo' => ['required'], ]); if(!$validator->fails()) { $estado = Estado::create([ 'nombre' => $request['nombre'], ] ); $casillero = Casillero::create([ 'numero' => $request['numero'], 'tiempo' => $request['tiempo'], 'costo' => $request['costo'], 'estado_id' => $estado->id, ]); return redirect()->route('casilleros.index', $casillero->id)->with('success', 'Casillero creado correctamente'); }else{ return response()->json(['status_code'=>400,'message'=>$validator->errors()]); } } public function show(Casillero $casillero){ return view('casilleros.show', compact('casillero')); } public function edit(Casillero $casillero) { return view('casilleros.edit', compact('casillero')); } public function update(Request $request, Casillero $casillero) { $data = $request->only('numero','tiempo','costo','nombre'); $casillero->update($data); return redirect()->route('salas.show', $casillero->id)->with('success', 'Sala actualizado correctamente'); } public function destroy(Casillero $casillero) { $casillero->delete(); return back()->with('success','Casillero eliminado correctamente'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Auth; class AccesoController extends Controller { public function login(Request $request) { $validator=Validator::make($request->all(), [ 'email' => ['required', 'string', 'email'], 'password' => ['<PASSWORD>'], ]); if($validator->fails()){ return response()->json(['error'=>$validator->errors()->first('email')]); } $credentials=request(['email','password']); if(!Auth::attempt($credentials)){ return response()->json(['error'=>'datos invalidos']); } $user=User::where('email',$request->email)->first(); $tokenResult=$user->createToken('authToken')->plainTextToken; return response()->json(['token'=>$tokenResult, 'email'=>Auth::user()->email, 'error'=>null, 'id'=>$user->id, 'verification'=>Auth::user()->email_verified_at]); } } <file_sep><?php namespace App\Http\Controllers; use App\Models\Estado; use App\Models\Sala; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; class SalaController extends Controller { public function index() { $salas=Sala::paginate(5); return view('salas.index', compact('salas')); } public function create() { return view('salas.create'); } public function store(Request $request) { $validator=Validator::make($request->all(), [ 'tamaño' => ['required'], 'nombre' => ['required'], ]); if(!$validator->fails()) { $estado = Estado::create([ 'nombre' => $request['nombre'], ] ); $sala = Sala::create([ 'tamaño' => $request['tamaño'], 'estado_id' => $estado->id, ]); return redirect()->route('salas.index', $sala->id)->with('success', 'Sala creado correctamente'); }else{ return response()->json(['status_code'=>400,'message'=>$validator->errors()]); } } public function show(Sala $sala){ return view('salas.show', compact('sala')); } public function edit(Sala $sala) { return view('salas.edit', compact('sala')); } public function update(Request $request, Sala $sala) { $data = $request->only('tamaño','estado_id'); $sala->update($data); return redirect()->route('salas.show', $sala->id)->with('success', 'Sala actualizado correctamente'); } public function destroy(Sala $sala) { $sala->delete(); return back()->with('success','Sala eliminado correctamente'); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Casillero extends Model { use HasFactory; protected $table = 'casilleros'; protected $fillable = [ 'numero', 'tiempo', 'costo', 'estado_id' ]; } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Horario; use Illuminate\Support\Facades\Validator; class HorarioController extends Controller { public function index(){ $horarios=Horario::paginate(5); return view('horarios.index',compact('horarios')); } public function create() { return view('horarios.create'); } public function store(Request $request) { $validator=Validator::make($request->all(), [ 'hora_inicio' => ['required'], 'hora_fin' => ['required'], 'dia' => ['required'], 'sala_id' => ['required'], 'grupo_id' => ['required'] ]); if(!$validator->fails()) { $horario = Horario::create([ 'hora_inicio' => $request['hora_inicio'], 'hora_fin' => $request['hora_fin'], 'dia' => $request['dia'], 'sala_id' => $request['sala_id'], 'grupo_id' => $request['grupo_id'], ]); return redirect()->route('horarios.index', $horario->id)->with('success', 'Horario añadido correctamente'); }else{ return response()->json(['status_code'=>400,'message'=>$validator->errors()]); } } public function show(Horario $horario){ return view('horarios.show', compact('horario')); } public function edit(Horario $horario) { return view('horarios.edit', compact('horario')); } public function update(Request $request, Horario $horario) { $data = $request->only('hora_inicio', 'hora_fin','dia','sala_id'); $horario->update($data); return redirect()->route('horarios.show', $horario->id)->with('success', 'Horario actualizado correctamente'); } public function destroy(Horario $horario) { $horario->delete(); return back()->with('success','Horario eliminado correctamente'); } } <file_sep><?php namespace App\Http\Controllers; use App\Models\Categoria; use App\Models\Disciplina; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; class DisciplinaController extends Controller { public function index() { $disciplinas=Disciplina::paginate(5); return view('disciplinas.index', compact('disciplinas')); } public function create() { return view('disciplinas.create'); } public function store(Request $request) { $validator=Validator::make($request->all(), [ 'nombre' => ['required'], 'costo' => ['required'], 'nomb_categoria' => ['required'] ]); if(!$validator->fails()) { $categoria = Categoria::create([ 'nombre' => $request['nomb_categoria'], ]); $disciplina =Disciplina::create([ 'nombre' => $request['nombre'], 'costo' => $request['costo'], 'categoria_id' => $categoria->id, ]); return redirect()->route('disciplinas.index', $disciplina->id)->with('success', 'Disciplina creado correctamente'); }else{ return response()->json(['status_code'=>400,'message'=>$validator->errors()]); } } public function show(Categoria $categoria){ return view('categorias.show', compact('categoria')); } public function edit(Categoria $categoria) { return view('categorias.edit', compact('categoria')); } public function update(Request $request, Categoria $categoria) { $data = $request->only('nombre','costo','categoria_id'); $categoria->update($data); return redirect()->route('categorias.show', $categoria->id)->with('success', 'Categoria actualizado correctamente'); } } <file_sep><?php use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); Auth::routes(); Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home'); //Rutas para el administrador// Route::get('/administradores', [App\Http\Controllers\AdministradorController::class, 'index'])->name('administradores.index'); Route::get('/administradores/create', [App\Http\Controllers\AdministradorController::class, 'create'])->name('administradores.create'); Route::post('/administradores', [App\Http\Controllers\AdministradorController::class, 'store'])->name('administradores.store'); Route::get('/administradores/{administrador}', [App\Http\Controllers\AdministradorController::class, 'show'])->name('administradores.show'); Route::get('/administradores/{administrador}/edit', [App\Http\Controllers\AdministradorController::class, 'edit'])->name('administradores.edit'); Route::put('/administradores/{administrador}', [App\Http\Controllers\AdministradorController::class, 'update'])->name('administradores.update'); Route::delete('/administradores/{administrador}', [App\Http\Controllers\AdministradorController::class, 'destroy'])->name('administradores.delete'); //Rutas para el instructor// Route::get('/instructores', [App\Http\Controllers\InstructorController::class, 'index'])->name('instructores.index'); Route::get('/instructores/create', [App\Http\Controllers\InstructorController::class, 'create'])->name('instructores.create'); Route::post('/instructores', [App\Http\Controllers\InstructorController::class, 'store'])->name('instructores.store'); Route::get('/instructores/{instructor}', [App\Http\Controllers\InstructorController::class, 'show'])->name('instructores.show'); Route::get('/instructores/{instructor}/edit', [App\Http\Controllers\InstructorController::class, 'edit'])->name('instructores.edit'); Route::put('/instructores/{instructor}', [App\Http\Controllers\InstructorController::class, 'update'])->name('instructores.update'); Route::delete('/instructores/{instructor}', [App\Http\Controllers\InstructorController::class, 'destroy'])->name('instructores.delete'); //Rutas para el cliente// Route::get('/clientes', [App\Http\Controllers\ClienteController::class, 'index'])->name('clientes.index'); Route::get('/clientes/create', [App\Http\Controllers\ClienteController::class, 'create'])->name('clientes.create'); Route::post('/clientes', [App\Http\Controllers\ClienteController::class, 'store'])->name('clientes.store'); Route::get('/clientes/{cliente}', [App\Http\Controllers\ClienteController::class, 'show'])->name('clientes.show'); Route::get('/clientes/{cliente}/edit', [App\Http\Controllers\ClienteController::class, 'edit'])->name('clientes.edit'); Route::put('/clientes/{cliente}', [App\Http\Controllers\ClienteController::class, 'update'])->name('clientes.update'); Route::delete('/clientes/{cliente}', [App\Http\Controllers\ClienteController::class, 'destroy'])->name('clientes.delete'); //Rutas para descuento// Route::get('/descuentos/create', [App\Http\Controllers\DescuentoController::class, 'create'])->name('descuentos.create'); Route::get('/descuentos', [App\Http\Controllers\DescuentoController::class, 'index'])->name('descuentos.index'); Route::post('/descuentos', [App\Http\Controllers\DescuentoController::class, 'store'])->name('descuentos.store'); Route::delete(' /descuentos/{descuento}', [App\Http\Controllers\DescuentoController::class, 'destroy'])->name('descuentos.delete'); //Rutas para categorias// Route::get('/categorias/create', [App\Http\Controllers\CategoriaController::class, 'create'])->name('categorias.create'); Route::get('/categorias', [App\Http\Controllers\CategoriaController::class, 'index'])->name('categorias.index'); Route::post('/categorias', [App\Http\Controllers\CategoriaController::class, 'store'])->name('categorias.store'); Route::delete('/categorias/{categoria}', [App\Http\Controllers\CategoriaController::class, 'destroy'])->name('categorias.delete'); //Rutas para disciplinas// Route::get('/disciplinas/create', [App\Http\Controllers\DisciplinaController::class, 'create'])->name('disciplinas.create'); Route::get('/disciplinas', [App\Http\Controllers\DisciplinaController::class, 'index'])->name('disciplinas.index'); Route::post('/disciplinas', [App\Http\Controllers\DisciplinaController::class, 'store'])->name('disciplinas.store'); Route::delete('/disciplinas/{disciplina}', [App\Http\Controllers\DisciplinaController::class, 'destroy'])->name('disciplinas.delete'); //Rutas para grupos// Route::get('/grupos/create', [App\Http\Controllers\GrupoController::class, 'create'])->name('grupos.create'); Route::get('/grupos', [App\Http\Controllers\GrupoController::class, 'index'])->name('grupos.index'); Route::post('/grupos', [App\Http\Controllers\GrupoController::class, 'store'])->name('grupos.store'); Route::delete('/grupos/{grupo}', [App\Http\Controllers\GrupoController::class, 'destroy'])->name('grupos.delete'); Route::get('/grupos/{grupo}', [App\Http\Controllers\GrupoController::class, 'show'])->name('grupos.show'); //Rutas para horarios// Route::get('/horarios/create', [App\Http\Controllers\HorarioController::class, 'create'])->name('horarios.create'); Route::get('/horarios', [App\Http\Controllers\HorarioController::class, 'index'])->name('horarios.index'); Route::post('/horarios', [App\Http\Controllers\HorarioController::class, 'store'])->name('horarios.store'); Route::delete('/horarios/{horario}', [App\Http\Controllers\HorarioController::class, 'destroy'])->name('horarios.delete'); Route::get('/horarios/{horario}', [App\Http\Controllers\HorarioController::class, 'show'])->name('horarios.show'); //Rutas para casilleros// Route::get('/casilleros/create', [App\Http\Controllers\CasillerController::class, 'create'])->name('casilleros.create'); Route::get('/casilleros', [App\Http\Controllers\CasillerController::class, 'index'])->name('casilleros.index'); Route::post('/casilleros', [App\Http\Controllers\CasillerController::class, 'store'])->name('casilleros.store'); Route::delete('/casilleros/{casillero}', [App\Http\Controllers\CasillerController::class, 'destroy'])->name('casilleros.delete'); Route::get('/casilleros/{casillero}', [App\Http\Controllers\CasillerController::class, 'show'])->name('casilleros.show'); //Rutas para salas// Route::get('/salas/create', [App\Http\Controllers\SalaController::class, 'create'])->name('salas.create'); Route::get('/salas', [App\Http\Controllers\SalaController::class, 'index'])->name('salas.index'); Route::post('/salas', [App\Http\Controllers\SalaController::class, 'store'])->name('salas.store'); Route::delete('/salas/{sala}', [App\Http\Controllers\SalaController::class, 'destroy'])->name('salas.delete'); Route::get('/salas/{sala}', [App\Http\Controllers\SalaController::class, 'show'])->name('salas.show'); //Rutas para aparatos// Route::get('/aparatos/create', [App\Http\Controllers\AparatoController::class, 'create'])->name('aparatos.create'); Route::get('/aparatos', [App\Http\Controllers\AparatoController::class, 'index'])->name('aparatos.index'); Route::post('/aparatos', [App\Http\Controllers\AparatoController::class, 'store'])->name('aparatos.store'); Route::delete('/aparatos/{aparato}', [App\Http\Controllers\AparatoController::class, 'destroy'])->name('aparatos.delete'); Route::get('/aparatos/{aparato}', [App\Http\Controllers\AparatoController::class, 'show'])->name('aparatos.show'); //Rutas para Alquiler// Route::get('/alquileres/create', [App\Http\Controllers\AlquilerController::class, 'create'])->name('alquileres.create'); Route::get('/alquileres', [App\Http\Controllers\AlquilerController::class, 'index'])->name('alquileres.index'); Route::post('/alquileres', [App\Http\Controllers\AlquilerController::class, 'store'])->name('alquileres.store'); Route::delete('/alquileres/{alquiler}', [App\Http\Controllers\AlquilerController::class, 'destroy'])->name('alquileres.delete'); Route::get('/alquileres/{alquiler}', [App\Http\Controllers\AlquilerController::class, 'show'])->name('alquileres.show'); Route::get('/alquileres/{alquiler}/edit', [App\Http\Controllers\AlquilerController::class, 'edit'])->name('alquileres.edit'); Route::put('/alquileres/{alquiler}', [App\Http\Controllers\AlquilerController::class, 'update'])->name('alquileres.update'); //Rutas para Inscripcion// Route::get('/inscripciones/create', [App\Http\Controllers\InscripcionController::class, 'create'])->name('inscripciones.create'); Route::get('/inscripciones', [App\Http\Controllers\InscripcionController::class, 'index'])->name('inscripciones.index'); Route::post('/inscripciones', [App\Http\Controllers\InscripcionController::class, 'store'])->name('inscripciones.store'); Route::delete('/inscripciones/{inscripcion}', [App\Http\Controllers\InscripcionController::class, 'destroy'])->name('inscripciones.delete'); Route::get('/inscripciones/{inscripcion}', [App\Http\Controllers\InscripcionController::class, 'show'])->name('inscripciones.show'); Route::get('/inscripciones/{inscripcion}/edit', [App\Http\Controllers\InscripcionController::class, 'edit'])->name('inscripciones.edit'); Route::put('/inscripciones/{inscripcion}', [App\Http\Controllers\InscripcionController::class, 'update'])->name('inscripciones.update'); //Rutas para user// Route::get('/users', [App\Http\Controllers\UserController::class, 'index'])->name('users.index'); <file_sep><?php namespace App\Http\Controllers; use App\Models\Descuento; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; class DescuentoController extends Controller { public function index() { $descuentos=Descuento::paginate(5); return view('descuentos.index', compact('descuentos')); } public function create() { return view('descuentos.create'); } public function store(Request $request) { $validator=Validator::make($request->all(), [ 'criterio' => ['required'], 'descuento' => ['required'], 'estado' => ['required'] ]); if(!$validator->fails()) { $descuento1 = Descuento::create([ 'criterio' => $request['criterio'], 'descuento' => $request['descuento'], 'estado' => $request['estado'] ]); return redirect()->route('descuentos.index', $descuento1->id)->with('success', 'Descuento creado correctamente'); }else{ return response()->json(['status_code'=>400,'message'=>$validator->errors()]); } } public function show(Descuento $descuento){ return view('descuentos.show', compact('descuento')); } public function edit(Descuento $descuento) { return view('descuentos.edit', compact('descuento')); } public function update(Request $request, Descuento $descuento1) { $data = $request->only('criterio','descuento','estado'); $descuento1->update($data); return redirect()->route('horarios.show', $descuento1->id)->with('success', 'Descuento actualizado correctamente'); } public function destroy(Descuento $descuento) { $descuento->delete(); return back()->with('success','Descuento eliminado correctamente'); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Horario extends Model { use HasFactory; protected $table = 'horarios'; protected $fillable = [ 'hora_inicio', 'hora_fin', 'dia', 'sala_id', 'grupo_id' ]; } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Disciplina extends Model { use HasFactory; protected $table = 'disciplinas'; protected $fillable = [ 'nombre', 'costo', 'categoria_id' ]; } <file_sep><?php namespace App\Http\Controllers; use App\Models\AlquilerCasillero; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; class AlquilerController extends Controller { public function index() { $alquileres=AlquilerCasillero::paginate(5); return view('alquileres.index', compact('alquileres')); } public function create() { return view('alquileres.create'); } public function store(Request $request) { $validator=Validator::make($request->all(), [ 'fecha' => ['required'], 'cantidad' => ['required'], 'importe' => ['required'], 'total' => ['required'], 'casillero_id' => ['required'], 'cliente_id' => ['required'], 'administrador_id' => ['required'], ]); if(!$validator->fails()) { $alquiler = AlquilerCasillero::create([ 'fecha' => $request['fecha'], 'cantidad' => $request['cantidad'], 'importe' => $request['importe'], 'total' => $request['total'], 'casillero_id' => $request['casillero_id'], 'cliente_id' => $request['cliente_id'], 'administrador_id' => $request['administrador_id'], ]); return redirect()->route('alquileres.index', $alquiler->id)->with('success', 'Alquiler Añadido Correctamente'); }else{ return response()->json(['status_code'=>400,'message'=>$validator->errors()]); } } public function show(AlquilerCasillero $alquiler){ return view('alquileres.show', compact('alquiler')); } public function edit(AlquilerCasillero $alquiler) { return view('alquileres.edit', compact('alquiler')); } public function update(Request $request, AlquilerCasillero $alquiler) { $data = $request->only('fecha','cantidad','importe','total','casillero_id','cliente_id','administrador_id'); $alquiler->update($data); return redirect()->route('alquileres.show', $alquiler->id)->with('success', 'Alquiler actualizado correctamente'); } public function destroy(AlquilerCasillero $alquiler) { $alquiler->delete(); return back()->with('success','Sala eliminado correctamente'); } } <file_sep><?php namespace App\Http\Controllers; use App\Models\BoletaInscripcion; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; class InscripcionController extends Controller { public function index() { $inscripciones=BoletaInscripcion::paginate(5); return view('inscripciones.index', compact('inscripciones')); } public function create() { return view('inscripciones.create'); } public function store(Request $request) { $validator=Validator::make($request->all(), [ 'fecha_inscripcion' => ['required'], 'fecha_inicio' => ['required'], 'fecha_fin' => ['required'], 'importe' => ['required'], 'total' => ['required'], 'descuento_id' => ['required'], 'cliente_id' => ['required'], 'administrador_id' => ['required'], ]); if(!$validator->fails()) { $inscripcion = BoletaInscripcion::create([ 'fecha_inscripcion' => $request['fecha_inscripcion'], 'fecha_inicio' => $request['fecha_inicio'], 'fecha_fin' => $request['fecha_fin'], 'importe' => $request['importe'], 'total' => $request['total'], 'descuento_id' => $request['descuento_id'], 'cliente_id' => $request['cliente_id'], 'administrador_id' => $request['administrador_id'], ]); return redirect()->route('inscripciones.index', $inscripcion->id)->with('success', 'Inscripcion Creada Correctamente'); }else{ return response()->json(['status_code'=>400,'message'=>$validator->errors()]); } } public function show(BoletaInscripcion $inscripcion){ return view('inscripciones.show', compact('inscripcion')); } public function edit(BoletaInscripcion $inscripcion) { return view('inscripciones.edit', compact('inscripcion')); } public function update(Request $request, BoletaInscripcion $inscripcion) { $data = $request->only('fecha_inscripcion','fecha_inicio','fecha_fin','importe','total','descuento_id','cliente_id','administrador_id'); $inscripcion->update($data); return redirect()->route('inscripciones.show', $inscripcion->id)->with('success', 'Inscripcion actualizada correctamente'); } public function destroy(BoletaInscripcion $inscripcion) { $inscripcion->delete(); return back()->with('success','Inscripcion eliminado correctamente'); } } <file_sep><?php namespace App\Http\Controllers; use App\Models\Aparato; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; use App\Models\Estado; class AparatoController extends Controller { public function index() { $aparatos=Aparato::paginate(5); /* $categorias=$categorias->distinct()->get(); */ return view('aparatos.index', compact('aparatos')); } public function create() { return view('aparatos.create'); } public function store(Request $request) { $validator=Validator::make($request->all(), [ 'nombre_aparato' => ['required'], 'marca' => ['required'], 'modelo' => ['required'], 'nombre_estado' => ['required'], 'sala_id' => ['required'], ]); if(!$validator->fails()) { $estado = Estado::create([ 'nombre' => $request['nombre_estado'], ] ); $aparato = Aparato::create([ 'nombre' => $request['nombre_aparato'], 'marca' => $request['marca'], 'modelo' => $request['modelo'], 'estado_id' => $estado->id, 'sala_id' => $request['sala_id'], ]); return redirect()->route('aparatos.index', $aparato->id)->with('success', 'Aparato creado correctamente'); }else{ return response()->json(['status_code'=>400,'message'=>$validator->errors()]); } } public function show(Aparato $aparato){ return view('aparatos.show', compact('aparato')); } public function destroy(Aparato $aparato) { $aparato->delete(); return back()->with('success','Aparato eliminado correctamente'); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Aparato extends Model { use HasFactory; protected $table = 'aparatos'; protected $fillable = [ 'nombre', 'marca', 'modelo', 'estado_id', 'sala_id' ]; }
5d0f8b2228e3210fd93fa251a3ab7366034b2278
[ "PHP" ]
23
PHP
JhonatanWCL99/gimnasiosi1
dbbade23b64a98153c8b32cf78045f3aa7eb3432
9755dcd8f901ce771e7a6b602ccf8b87f92051fb
refs/heads/master
<repo_name>seyleigh/burgurz<file_sep>/db/seeds.sql INSERT INTO burgers (burger_name, devoured) VALUES ("Avacado and Fried egg", false); INSERT INTO burgers (burger_name, devoured) VALUES ("Black Bean patty", false); INSERT INTO burgers (burger_name, devoured) VALUES ("Turkey with Avacado", false);<file_sep>/README.md # Eat the Burger This is an app that utilises: * Javascript * HTML * CSS * Express * Node * Handlebars (yuck) * Mysql --- ## [Link to Heroku](https://mighty-lake-47636.herokuapp.com/) --- The user can enter in a burger and it will be added to the mySQL tables and displayed on a list of uneaten burgers. Then they can click the button to eat the burger which will change the value of whether its eaten or not and move it to the opposite list. Theres also an option to delete the burger from the list if you're just sick of looking at it. ![Page Example](public/assets/img/demo.png)
93347dbdd7f288af7456fa95402b5d4bf2e2114f
[ "Markdown", "SQL" ]
2
SQL
seyleigh/burgurz
17f3d68e47e98ae71317f23636c4ca68253982d5
e191cb0bab378a729997193f50fc38fa29d15586
refs/heads/main
<repo_name>Ori2846/3drunner<file_sep>/PlayerController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { Rigidbody m_Rigidbody; public float m_Speed; void Start() { //Fetch the Rigidbody component you attach from your GameObject m_Rigidbody = GetComponent<Rigidbody>(); //Set the speed of the GameObject } void Update() { if (Input.GetKey(KeyCode.LeftShift)) { transform.Translate(Vector3.forward * Time.deltaTime *m_Speed *1.5f); } else { transform.Translate(Vector3.forward * Time.deltaTime *m_Speed); } if (Input.GetKey(KeyCode.UpArrow)) { GetComponent<Rigidbody>().velocity = Vector3.up * 5; } if (Input.GetKey(KeyCode.RightArrow)) { //Rotate the sprite about the Y axis in the positive direction transform.Rotate(new Vector3(0, 1, 0) * Time.deltaTime * 40, Space.World); } if (Input.GetKey(KeyCode.LeftArrow)) { //Rotate the sprite about the Y axis in the negative direction transform.Rotate(new Vector3(0, -1, 0) * Time.deltaTime * 40, Space.World); } } } <file_sep>/README.md ![2021-09-07 18_22_11-Run and Gun - backup - PC, Mac Linux Standalone - Unity 2019 4 18f1 Personal _](https://user-images.githubusercontent.com/74078771/132431324-894961e5-2fe0-433b-b63f-9a2cd5aa4b6d.png) # 3drunner
04f92ff8fc2e6933e453f078f716660b8a20699d
[ "Markdown", "C#" ]
2
C#
Ori2846/3drunner
fcf5355f128779e51aafa76e7363ee7d0fa4e823
0f04955e4269e5d71925ade99d5cdf6f1d2df51d
refs/heads/develop
<file_sep>export default function Animaciones() { return ( <div> <h1>Animaciones</h1> </div> ) } <file_sep>import React from 'react' import { Container } from './styles' import Router from './Router' function App() { return ( <Container> <Router /> </Container> ) } export default App <file_sep>import styled from 'styled-components/macro'; export const Container = styled.div` margin: 20px 0 ; padding: 5px; border-radius: 8px ; box-shadow: 0 0 3px 1px #a6b1ff; text-align: center; h1{ display: ; } `; export const Content = styled.div` display: flex; flex-flow: wrap; justify-content: center; `; export const slide = styled.div` padding: 7px; width: 120px; margin: 1em; background-color: salmon; text-align: center; transition: all 1s; border-radius: 8px; &:hover { color: #fff; } `; export const SlideLeftRight = styled(slide)` box-shadow: inset 5px 0 1px royalblue; &:hover { box-shadow: inset 150px 0 1px royalblue; } `; export const SlideRightLeft = styled(slide)` box-shadow: inset -5px 0 1px royalblue; &:hover { box-shadow: inset -150px 0 1px royalblue; } `; export const SlideTopBottom = styled(slide)` box-shadow: inset 0 5px 1px royalblue; &:hover { box-shadow: inset 0 60px 1px royalblue; } `; export const SlideBottomTop = styled(slide)` box-shadow: inset 0 -5px 1px royalblue; &:hover { box-shadow: inset 0 -60px 1px royalblue; } `; export const DobleSlideHorizontal = styled(slide)` &:hover { box-shadow: inset 150px 0 1px royalblue, inset -150px 0 1px royalblue; } `; export const DobleSlideVertical = styled(slide)` &:hover { box-shadow: inset 0 50px 1px royalblue, inset 0 -50px 1px royalblue; } `;<file_sep>import styled from 'styled-components/macro'; export const Container = styled.div` margin: 20px 0 ; padding: 5px; border-radius: 8px ; box-shadow: 0 0 3px 1px #a6b1ff; text-align: center; `; export const Content = styled.div` display: flex; flex-flow: wrap; justify-content: center; `; export const menu = styled.div` box-sizing: border-box; width: 25%; margin: 1em auto; font-size: 1em; color: royalblue; position: relative; cursor: pointer; @media screen and (max-width: 755px) { width: 30%; } @media screen and (max-width: 600px) { width: 45%; } @media screen and (max-width: 424px) { width: 70%; } &::before { content: ""; display: block; height: .2em; background: royalblue; position: absolute; left: 0; box-shadow: 0 .4em , 0 .8em ; } `; export const MenuPrincipal = styled(menu)` padding-left: 1.8em; @media screen and (max-width: 424px) { padding-left: 1.4em; } &::before { width: 1.4em; } `; export const MenuSecundario = styled(menu)` padding-left: .6em; @media screen and (max-width: 424px) { padding-left: .4em; } &::before { width:.2em; border-radius: 50%; } `;<file_sep>import { Container, BotonNormal, BotonRealista } from './styles' export default function Botones() { return( <Container> <h3>Botones</h3> <BotonNormal>Enviar</BotonNormal> <BotonRealista>Enviar</BotonRealista> </Container> ) }<file_sep>import { Container, Content, MenuPrincipal, MenuSecundario } from "./styled"; export default function IconsMenu() { return( <Container> <h3>Icons menu</h3> <Content> <MenuPrincipal>Menu principal</MenuPrincipal> <MenuSecundario>Menu Secundario</MenuSecundario> </Content> </Container> ) }<file_sep>export { default } from './Textos' <file_sep>import Botones from '../../components/Botones' import Textos from '../../components/Textos' import IconsMenu from '../../components/IconsMenu' import BackgroundSlide from '../../components/BackgroundSlide' export default function Estilos() { return ( <div> <h1>Estilos Basicos</h1> <Botones /> <h1>Estilos Avanzados</h1> <Textos /> <IconsMenu /> <BackgroundSlide /> </div> ) } <file_sep>import styled from 'styled-components/macro'; export const Container = styled.div` padding: 10px; border-radius: 8px ; box-shadow: 0 0 3px 1px #a6b1ff; `; export const TxtDegradado = styled.p` position: relative; margin: 0; font-size: 1.7em; text-align: center; font-weight: 800; z-index: 1; &::before { color: transparent; background: linear-gradient( 65deg, yellow, red); -webkit-background-clip: text; content: "Texto con fondo degradado"; position: absolute; width: 100%; top: -3px; left: -2px; z-index: 0; } `;<file_sep>import { BrowserRouter, Switch, Route } from 'react-router-dom' import { Content } from './styles' import Header from '../components/Header' import Home from '../Pages/Home' import Estilos from '../Pages/Estilos' import Animaciones from '../Pages/Animaciones' export default function Router() { return ( <BrowserRouter> <Header /> <Content> <Switch> <Route path='/estilos'> <Estilos /> </Route> <Route path='/animaciones'> <Animaciones /> </Route> <Route path='/'> <Home /> </Route> </Switch> </Content> </BrowserRouter> ) } <file_sep>export { default } from './Estilos' <file_sep>import styled from 'styled-components/macro'; export const Container = styled.div` margin: 20px 0 ; padding: 5px; border-radius: 8px ; box-shadow: 0 0 3px 1px #a6b1ff; display: flex; flex-flow: wrap; justify-content: center; h3 { width: 100%; text-align: center; margin-bottom: 20px; } `; const btn = styled.button` margin: 1em; display: inline-block; background-color: green; height: 3em; line-height: 3em; padding: 0 1.5em; color: #fff; text-decoration: none; cursor: pointer; `; export const BotonNormal = styled(btn)` border: none; text-transform: uppercase; border-radius: 1.5em; &:hover { background-color: darken(green, 20); } &:active { transform: scale(.95); } `; export const BotonRealista = styled(btn)` box-sizing: border-box; border: 1px solid darken(green, 20); border-bottom-width: 4px; line-height: 2.8em; border-radius: .3em; box-shadow: 0 0 1px rgba(green, .1) inset; &:active { line-height: 3em; } `;<file_sep>export { default } from './IconsMenu';
6219af936feeac15d65b84b513d442fe779208b9
[ "JavaScript" ]
13
JavaScript
nickothan/practica-de-conocimientos
c01bdeb88ddffe0545603409fc74a12c73909170
6feb9d0a0c68edc4220a0ea5dbd67b0c91bbeda0
refs/heads/master
<file_sep>export interface Article { title: string; contents: string; imgSrc: string; date: string; }
b37d950c844c3b2756b222d61128ae10378a836b
[ "TypeScript" ]
1
TypeScript
thjang94/homepage_project
0964fd2ec9479bee4d028d72152da9fbe9890342
b0d6a67479f911e7e3894c60b4928f5d370493b4
refs/heads/main
<repo_name>wangEtsu/muffin_break<file_sep>/barista-diary.js // set initial counts localStorage.setItem("day", 20); localStorage.setItem("dayCount", 0); function getRandomArbitrary(min, max) { return Math.ceil(Math.random() * (max - min) + min); } console.log(localStorage.getItem("dayCount")); // 4 shifts per day if(parseInt(localStorage.getItem("dayCount")) == 4) { localStorage.setItem('day',parseInt(localStorage.getItem("day")) + 1); localStorage.setItem("dayCount", 0); } $('select[name^="month"]').val(8); $('select[name^="day"]').val(localStorage.getItem("day")); $('select[name^="year"]').val(2021); // 2 hours shift $($('.noPadding.question.checkable.multi-choice').find("input[name^='question'][value=2]")).trigger('click') // tigger random checkboxes for (let i = 0; i < 6; i++) { $($('.noPadding.question.checkable.tick-box').find("input[name^='question']")[getRandomArbitrary(1, 7)]).trigger('click') } // reset counter localStorage.setItem("dayCount", parseInt(localStorage.getItem('dayCount')) + 1); $('.next').trigger('click');
984d3c6864081d01ec6a05ba293a5ebc5c678841
[ "JavaScript" ]
1
JavaScript
wangEtsu/muffin_break
d6cc5ae1ed44de2a4f23c892e087eafad13c7bf9
66626f8430b047a7a5a7847341d7ecd692bb821a
refs/heads/master
<repo_name>s20168/ASD<file_sep>/Zadanie3.py # set_of_numbers = [0, 1, 1, 0, 1, 0, 1] set_of_numbers = [4, 14, 14, 4, 14, 4, 14] for i in range(len(set_of_numbers) - 1, -1, -1): index = 0 for j in range(0, i + 1, 1): if set_of_numbers[j] > set_of_numbers[index]: temporary_index = j list = set_of_numbers[i] set_of_numbers[i] = set_of_numbers[index] set_of_numbers[index] = list print('Sorted list is: ', set_of_numbers)<file_sep>/Heapsort.py import time def swap(arr, maximum, largest): if maximum != largest: array = arr[largest] arr[largest] = arr[maximum] arr[maximum] = array def leftchild(largest_index): left = largest_index * 2 + 1 return left def rightchild(largest_index): right = largest_index * 2 + 2 return right def heap_sort(array): start_time = time.time() n = len(array) for i in range(((n - 1) // 2), -1, -1): heapify(array, n, i) for i in range(n - 1, 0, -1): swap(array, 0, i) n -= 1 heapify(array, n, 0) end_time = time.time() time_elapsed = end_time - start_time return time_elapsed def heapify(arr, heap, largest_index): max_index = largest_index left_child = leftchild(max_index) right_child = rightchild(max_index) if left_child < heap and arr[left_child] > arr[max_index]: max_index = left_child if right_child < heap and arr[right_child] > arr[max_index]: max_index = right_child if max_index != largest_index: swap(arr, max_index, largest_index) heapify(arr, heap, max_index)<file_sep>/Stopwatch.py import random, sys from Heapsort import heap_sort from Bubblesort import bubble_sort from Quicksort import quick_sort_test sys.setrecursionlimit(55000) class Stopwatch: def count(self): random_array_high = [] for i in range(0, 20000): n = random.randint(0, 1) random_array_high.append(n) sorted_array = sorted(random_array_high) reverse_sorted_array = list(reversed(sorted_array)) random_heapsort_time = 0 random_quicksort_time = 0 random_bubblesort_time = 0 sorted_heapsort_time = 0 sorted_quicksort_time = 0 sorted_bubblesort_time = 0 reverse_sorted_heapsort_time = 0 reverse_sorted_quicksort_time = 0 reverse_sorted_bubblesort_time = 0 random_quicksort_time += quick_sort_test(random_array_high.copy()) random_heapsort_time += heap_sort(random_array_high.copy()) random_bubblesort_time += bubble_sort(random_array_high.copy()) sorted_heapsort_time += heap_sort(sorted_array.copy()) sorted_quicksort_time += quick_sort_test(sorted_array.copy()) sorted_bubblesort_time += bubble_sort(sorted_array.copy()) reverse_sorted_quicksort_time += quick_sort_test(reverse_sorted_array.copy()) reverse_sorted_heapsort_time += heap_sort(reverse_sorted_array.copy()) reverse_sorted_bubblesort_time += bubble_sort(reverse_sorted_array.copy()) print(str("RandomHeapsort: ") + str("{0:.15f}".format(random_heapsort_time / 100))) print(str("RandomQuicksort: ") + str("{0:.15f}".format(random_quicksort_time / 100))) print(str("RandomBubblesort: ") + str("{0:.15f}".format(random_bubblesort_time / 100))) print(str("SortedHeapsort: ") + str("{0:.15f}".format(sorted_heapsort_time / 100))) print(str("SortedQuicksort: ") + str("{0:.15f}".format(sorted_quicksort_time / 100))) print(str("SortedBubblesort: ") + str("{0:.15f}".format(sorted_bubblesort_time / 100))) print(str("ReverseSortedHeapsort: ") + str("{0:.15f}".format(reverse_sorted_heapsort_time / 100))) print(str("ReverseSortedQuicksort: ") + str("{0:.15f}".format(reverse_sorted_quicksort_time / 100))) print(str("ReverseSortedBubblesort: ") + str("{0:.15f}".format(reverse_sorted_bubblesort_time / 100))) if __name__ == '__main__': xx = Stopwatch() xx.count()<file_sep>/Quicksort.py import time def quick_sort(A, p, r): if p < r: q = partition(A, p, r) quick_sort(A, p, q - 1) quick_sort(A, q + 1, r) def partition(A, p, r): pivot = A[r] smaller = p for i in range(p, r): if A[i] <= pivot: A[smaller], A[i] = A[i], A[smaller] smaller = smaller + 1 A[smaller], A[r] = A[r], A[smaller] return smaller def quick_sort_test(A): start_time = time.time() quick_sort(A, 0, len(A) - 1) end_time = time.time() time_elapsed = end_time - start_time return time_elapsed<file_sep>/Bubblesort.py import time def bubble_sort(arr): start_time = time.time() has_swapped = True num_of_iterations = 0 while has_swapped: has_swapped = False for i in range(len(arr) - num_of_iterations - 1): if arr[i] > arr[i + 1]: arr[i], arr[i + 1] = arr[i + 1], arr[i] has_swapped = True num_of_iterations += 1 end_time = time.time() time_elapsed = end_time - start_time return time_elapsed
a3743053018fbee6fc7a6975c868a27c9823f328
[ "Python" ]
5
Python
s20168/ASD
dabd55748879e66a6e212947fd514314bcc8088a
884828c07fb012cca8c28343e8b27ac833fdb034
refs/heads/master
<file_sep>#!/bin/bash mkdir dump-cache rm dump-cache/*.dump grep rw-p /proc/$1/maps | sed -n 's/^\([0-9a-f]*\)-\([0-9a-f]*\) .*$/\1 \2/p' | while read start stop; do gdb --batch --pid $1 -ex "dump memory dump-cache/$1-$start-$stop.dump 0x$start 0x$stop"; done cat dump-cache/*.dump > $1-dump
980b182273e67d143deceb906621a97cae6e1fdd
[ "Shell" ]
1
Shell
4shadoww/linux-memory-dumper
0a48bed82e6f71fff3f4e4b543c4e459bb197726
d91f9bbbcf7862c31263e0dedc03d1503a78cc4e
refs/heads/master
<repo_name>chrysler76/logoergo<file_sep>/email.php <?php header("Content-type: image/png"); // Your email address which will be shown in the image $email = "<EMAIL>"; $length = (strlen($email)*8); $im = @ImageCreate ($length, 20) or die ("Kann keinen neuen GD-Bild-Stream erzeugen"); $background_color = ImageColorAllocate ($im, 255, 255, 255); // White: 255,255,255 $text_color = ImageColorAllocate ($im, 7, 7, 7); imagestring($im, 3,5,2,$email, $text_color); imagepng ($im); ?>
5ef7b10cb91b8a1bd33c37e5e5b38fa55d8f6bdf
[ "PHP" ]
1
PHP
chrysler76/logoergo
2fda77dca287860dbc9fc6af7c74e023281116f4
e43ad6fbfd3a11cb3886fec56c04f8d40c75046a
refs/heads/master
<repo_name>be222dd/Round-Robin-Alghorithm<file_sep>/src/RR.java /** * Created by beysimeryalmaz on 2017-11-12. */ /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; /** * * @author beysimeryalmaz */ public class RR{ // The list of processes to be scheduled public ArrayList<Process> processes; public ArrayList<Process> tempList; public GantChart chart=new GantChart(); // the quantum time - which indicates the maximum allowable time a process can run once it is scheduled int tq; // keeps track of which process should be executed next public Queue<Process> schedulingQueue; public int time; public Process lastExecutedProcess; public boolean hasLeftFlag=true; // Class constructor public RR(ArrayList<Process> processes, int tq) { schedulingQueue = new LinkedList<Process>(); lastExecutedProcess=null; this.processes = processes; this.tq = tq; this.processes=processes; tempList=new ArrayList<>(processes); tempList.sort((p1, p2) -> p1.getArrivalTime() - p2.getArrivalTime()); this.time=0; } public void run() { /* * This is where you put your code * hints: * 1. do not forget to sort the processes by arrival time * 2. think about CPU idle times */ while(!tempList.isEmpty() || !schedulingQueue.isEmpty() ||hasLeftFlag ){ //selects the processes according to their arrival time and put them into the queue putToScheduleQ(); //removes them from temproray list removeFromList(); //checking if last executed process finished otherwise adds it to the queue again if(lastExecutedProcess!=null){ if(!lastExecutedProcess.isScheduled()){ schedulingQueue.add(lastExecutedProcess); } } //checks if there is a process to execute or cpu has to wait for a process to come if(schedulingQueue.isEmpty()){ time=tempList.get(0).getArrivalTime();//idle time }else{ executeTheProcess(); } } //sorting for the test case processes.sort((p1,p2)->p1.getArrivalTime()-p2.getArrivalTime()); printProcesses(); printGanttChart(); } public void printProcesses(){ System.out.println("Table FORM"); for(Process process:processes){ System.out.println("Id "+process.getProcessId()+" CT "+process.getCompletedTime()+" TAT "+process.getTurnaroundTime()+" WT "+process.getWaitingTime()); } } public void printGanttChart(){ // TODO Print the demonstration of the scheduling algorithm using Gantt Chart System.out.println("\nGantt Chart"); chart.printIds(); System.out.println(""); chart.printExTimes(); System.out.println(""); } public void putToScheduleQ(){ for(Process process:tempList){ if(process.getArrivalTime()<=time && process.getBurstTime()>=process.getRemainingBurstTime()){ schedulingQueue.add(process); } } } public void removeFromList(){ tempList.removeIf(process->process.getArrivalTime()<=time); } public void executeTheProcess(){ Process process=schedulingQueue.remove(); if(process.getRemainingBurstTime()>tq){ process.setRemainingBurstTime(process.getRemainingBurstTime()-tq); time+=tq; chart.processIds.add(process.getProcessId()); chart.exeTimes.add(time); }else{ if(process.getRemainingBurstTime()<tq){ time+=process.getRemainingBurstTime(); }else{ time+=tq; } chart.processIds.add(process.getProcessId()); chart.exeTimes.add(time); process.setRemainingBurstTime(0); process.setCompletedTime(time); process.setTurnaroundTime(time-process.getArrivalTime()); process.setWaitingTime(process.getTurnaroundTime()-process.getBurstTime()); } lastExecutedProcess=process; hasLeftFlag=!process.isScheduled(); } }<file_sep>/src/GantChart.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.util.ArrayList; /** * * @author beysimeryalmaz */ public class GantChart { public ArrayList<Integer> processIds=new ArrayList<>(); public ArrayList<Integer> exeTimes=new ArrayList<>(); public void printIds(){ for(Integer id:processIds) System.out.print(" P"+id+" |"); } public void printExTimes(){ for(Integer time:exeTimes){ if(time<10) System.out.print(" "+time); else System.out.print(" "+time); }} }
f8817bb0c33d80b907636a55c249ed69fe603245
[ "Java" ]
2
Java
be222dd/Round-Robin-Alghorithm
b6ae5494869ca3c121c02f1ec3f8571589a7a532
647526e3edde475b8301de8901226850764c6b6f
refs/heads/master
<repo_name>420805513/Text0810<file_sep>/app/src/main/java/com/example/dllo/text0810/Text.java package com.example.dllo.text0810; /** * Created by dllo on 16/10/21. */ public class Text { private String b; } <file_sep>/README.md # Text0810 项目描述
f28d76a09180edf5520866e328a876d1dbd99910
[ "Markdown", "Java" ]
2
Java
420805513/Text0810
52da8110e776c6d1d2701d03455a91bafd9a05a7
b21b99be9739e6ef4bbeb5332fa99a23d0e27b64
refs/heads/main
<repo_name>wabzqem/AU-COVID-vaccine-certs<file_sep>/Shared/Service/DataFetchers.swift // // DataFetchers.swift // AU COVID Verifier // // Created by <NAME> on 15/9/21. // import Foundation import UIKit class QRCodeFetcher: ObservableObject { @Published var image: UIImage? func getQRCode(irn: Int, completion: ((_ image: UIImage) -> Void)?) { let request = URLRequest(url: URL(string: "https://medicare.whatsbeef.net/?irn=\(irn)")!) URLSession.shared.dataTask(with: request) {(data, response, error) in if let data = data { DispatchQueue.main.async { self.image = UIImage(data: data) if let completion = completion, let image = self.image { completion(image) } } } }.resume() } } class VaccineStatusFetcher: ObservableObject { @Published var vaccineData: VaccineData? @Published var errorMessage: String? func getVaccineData(irn: Int) { let request = URLRequest(url: URL(string: "https://www2.medicareaustralia.gov.au/moaapi/moa-ihs/record/cir/data/\(irn)")!) URLSession.shared.dataTask(with: request) {(data, response, error) in if let data = data { DispatchQueue.main.async { do { self.vaccineData = try JSONDecoder().decode(VaccineData.self, from: data) } catch { do { self.errorMessage = try JSONDecoder().decode(ErrorResponse.self, from: data).errorList.first?.description } catch { } print("Couldn't fetch vaccine status") } } } }.resume() } } <file_sep>/Shared/UIComponents/LoginWebView.swift // // LoginWebView.swift // AU COVID Cert (iOS) // // Created by <NAME> on 15/9/21. // import Foundation import SwiftUI import Combine import WebKit struct SAWebView: View { var completionHandler: (_ success: Bool) -> Void var body: some View { LoginWebView() { success in completionHandler(success) } } } struct LoginWebView: UIViewRepresentable { var navigationHelper = WebViewHelper() var completionHandler: (_ success: Bool) -> Void init(completionHandler: @escaping (_ success: Bool) -> Void) { self.completionHandler = completionHandler } func makeUIView(context: UIViewRepresentableContext<LoginWebView>) -> WKWebView { let webview = WKWebView() webview.navigationDelegate = navigationHelper navigationHelper.completeHandler = { success in completionHandler(success) } if let _ = UserDefaults.standard.string(forKey: "refresh_token") { navigationHelper.doOauth(webView: webview) } else { let loginUrl = URL(string: "https://auth.my.gov.au/mga/sps/oauth/oauth20/authorize?response_type=code&client_id=wMm0AZnbwHYwKc1njWUF&state=007dc45f40b987d733c42ca4b08f98127f4fc100&scope=register&redirect_uri=au.gov.my.medicare:/oidcclient/redirect_uri&device_name=Richard%E2%80%99s%20iPhone%20XS%20Max&device_type=iPhone")! let request = URLRequest(url: loginUrl, cachePolicy: .returnCacheDataElseLoad) webview.load(request) } return webview } func updateUIView(_ webview: WKWebView, context: UIViewRepresentableContext<LoginWebView>) { } } extension URL { func containsParameter(name: String) -> Bool { let a = URLComponents(url: self, resolvingAgainstBaseURL: false)?.queryItems?.filter { queryItem in queryItem.name == name } return a?.count ?? 0 > 0 } func getParameterValue(name: String) -> String? { return URLComponents(url: self, resolvingAgainstBaseURL: false)?.queryItems?.filter { queryItem in queryItem.name == name }.first?.value } } struct TokenResponse: Codable { // or Decodable let access_token: String let refresh_token: String } class WebViewHelper: NSObject, WKNavigationDelegate, ObservableObject { private var loggedIn = false var completeHandler: ((_ success: Bool) -> Void)? func doOauth(webView: WKWebView) { let refreshToken = UserDefaults.standard.string(forKey: "refresh_token") guard let refreshToken = refreshToken else { return } var request = URLRequest(url: URL(string: "https://auth.my.gov.au/mga/sps/oauth/oauth20/token")!) request.httpMethod = "POST" request.addValue("Medicare/2 CFNetwork/1240.0.4 Darwin/20.6.0", forHTTPHeaderField: "User-Agent") request.httpBody = "refresh_token=\(refreshToken)&client_id=wMm0AZnbwHYwKc1njWUF&redirect_uri=au.gov.my.medicare:/oidcclient/redirect_uri&grant_type=refresh_token".data(using: .utf8) doOauth(request, webView: webView) } func doOauth(_ request: URLRequest, webView: WKWebView) { URLSession.shared.dataTask(with: request) {(data, response, error) in guard let data = data else { return } do { let res = try JSONDecoder().decode(TokenResponse.self, from: data) HTTPCookieStorage.shared.removeCookies(since: Date(timeIntervalSince1970: 0)) DispatchQueue.main.async { [weak webView] in webView?.configuration.websiteDataStore.removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), modifiedSince: Date(timeIntervalSince1970: 0)) { webView?.customUserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Medicare 4.3.2" UserDefaults.standard.set(res.refresh_token, forKey: "refresh_token") UserDefaults.standard.set(res.access_token, forKey: "access_token") var kickoffRequest = URLRequest(url: URL(string: "https://www2.medicareaustralia.gov.au/moasso/sps/oidc/rp/moa/kickoff/mobile")!) kickoffRequest.addValue("Bearer \(res.access_token)", forHTTPHeaderField: "Authorization") kickoffRequest.addValue("APP", forHTTPHeaderField: "route") kickoffRequest.addValue("EXPIOS", forHTTPHeaderField: "device-type") kickoffRequest.addValue("", forHTTPHeaderField: "Cookie") webView!.load(kickoffRequest) } } } catch { return } }.resume() } func doOauth(code: String, webView: WKWebView) { var request = URLRequest(url: URL(string: "https://auth.my.gov.au/mga/sps/oauth/oauth20/token")!) request.httpMethod = "POST" request.httpBody = "code=\(code)&client_id=wMm0AZnbwHYwKc1njWUF&redirect_uri=au.gov.my.medicare:/oidcclient/redirect_uri&grant_type=authorization_code".data(using: .utf8) doOauth(request, webView: webView) } func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { if let url = navigationAction.request.url { if (url.getParameterValue(name: "_eventId") == "close") { // The close button in the top right decisionHandler(.cancel) completeHandler?(false) return } if url.scheme == "au.gov.my.medicare" { if (url.containsParameter(name: "code")) { guard let code = url.getParameterValue(name: "code") else { decisionHandler(.cancel) return } doOauth(code: code, webView: webView) } else if (url.path.contains("login_success")) { // TODO: Try waiting here and loading member list directly let request = URLRequest(url: URL(string: "https://www2.medicareaustralia.gov.au/moaonline/")!) webView.load(request) loggedIn = true /*URLSession.shared.dataTask(with: request) {(data, response, error) in print("got list") }.resume()*/ } decisionHandler(.cancel) return } else { if (navigationAction.request.value(forHTTPHeaderField: "Authorization") != nil) { decisionHandler(.allow) return } else { guard let url = navigationAction.request.url, navigationAction.request.httpMethod == "GET", let access_token = UserDefaults.standard.string(forKey: "access_token") else { decisionHandler(.allow) return } let newRequest = NSMutableURLRequest(url: url) newRequest.setValue("Bearer \(access_token)", forHTTPHeaderField: "Authorization") webView.load(newRequest as URLRequest) decisionHandler(.cancel) return } } } decisionHandler(.allow) } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { if (loggedIn) { sleep(2) webView.configuration.websiteDataStore.httpCookieStore.getAllCookies { cookies in cookies.forEach { cookie in if (cookie.domain.contains("medicareaustralia.gov.au") && ( cookie.path == "/" || cookie.path == "/moaapi")) { HTTPCookieStorage.shared.setCookie(cookie) let newCookie = HTTPCookie(properties: [ .domain: "medicare.whatsbeef.net", .name: cookie.name, .value: cookie.value, .path: "/", .secure: cookie.isSecure ]) if let newCookie = newCookie { HTTPCookieStorage.shared.setCookie(newCookie) //URLSession.shared.configuration.httpCookieStorage?.setCookie(newCookie) print("set cookie \(newCookie.name): \(newCookie.value)") } } } self.completeHandler?(true) } } } func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { print("didStartProvisionalNavigation") } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { print("didFailProvisionalNavigation") } func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { print("webviewDidCommit") } func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { print("didReceiveAuthenticationChallenge") completionHandler(.performDefaultHandling, nil) } } <file_sep>/Shared/Views/PDFView.swift // // PDFView.swift // AU COVID Cert // // Created by <NAME> on 20/9/21. // import SwiftUI import PDFKit import Combine struct PDFViewM: View { var irn: Int @State var data : Data? @State var pdfView = PDFView() var body: some View { VStack { if let data = data { PDFViewUI(pdfView: $pdfView, data: data, singlePage: true) } }.onAppear() { DispatchQueue.init(label: "bgData").async { self.data = try? Data(contentsOf: URL(string: "https://medicare.whatsbeef.net/pdf?irn=\(irn)")!) } }.toolbar { Button(action: shareButton) { Image(systemName: "square.and.arrow.up") } } } func shareButton() { if let pdfData = $pdfView.wrappedValue.document?.dataRepresentation() { let objectsToShare = [pdfData] let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil) activityVC.popoverPresentationController?.sourceView = pdfView UIApplication.shared.windows.first?.rootViewController?.present(activityVC, animated: true, completion: nil) } } } extension PDFDocument { func addImage(_ image: UIImage) { guard let page = page(at: 0) else { return } let box = page.bounds(for: .mediaBox) let area = CGRect(x: box.midX - 70, y: 15, width: 140, height: 140) let imageAnnotation = MyImageAnnotation(bounds: area, image: image) page.addAnnotation(imageAnnotation) } } class MyImageAnnotation: PDFAnnotation { var image: UIImage required init?(coder: NSCoder) { fatalError("coder not supported") } init(bounds: CGRect, image: UIImage) { self.image = image super.init(bounds: bounds, forType: .stamp, withProperties: nil) } override func draw(with box: PDFDisplayBox, in context: CGContext) { super.draw(with: box, in: context) guard let cgImage = image.cgImage else { return } UIGraphicsPushContext(context) context.saveGState() // Drawing code goes here context.draw(cgImage, in: bounds) context.restoreGState() UIGraphicsPopContext() } } /*struct PDFView_Previews: PreviewProvider { @State var pdfDocument: PDFDocument? static var previews: some View { PDFViewM(irn: 4, pdfDocument: $pdfDocument) } }*/ struct PDFViewUI: UIViewRepresentable { typealias UIViewType = PDFView @Binding var pdfView: PDFView let data: Data let singlePage: Bool func makeUIView(context _: UIViewRepresentableContext<PDFViewUI>) -> UIViewType { $pdfView.wrappedValue.document = PDFDocument(data: data) if singlePage { pdfView.displayMode = .singlePage } pdfView.autoScales = true QRCodeFetcher().getQRCode(irn: 4) { image in pdfView.document?.addImage(image) } return pdfView } func updateUIView(_ pdfView: UIViewType, context _: UIViewRepresentableContext<PDFViewUI>) { pdfView.document = PDFDocument(data: data) } } <file_sep>/Shared/Views/ContentView.swift // // ContentView.swift // Shared // // Created by <NAME> on 12/9/21. // import SwiftUI import UIKit import WebKit import Combine struct ContentView: View { @State private var loginSuccess = false @State private var isPresented = true { didSet { if !isPresented && members.count == 0 && loginSuccess { fetchMembers() } } } @State var members: [Member] var body: some View { NavigationView { VStack { List(members) { member in NavigationLink(destination: CertView(member: member)) { Text("\(member.memberDisplayName) (\(member.memberIRN))") .padding() } } } .navigationTitle("Members") .toolbar { Button(loginSuccess ? "Logout" : "Login") { if (loginSuccess) { WKWebView.init().configuration.websiteDataStore.removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), modifiedSince: Date(timeIntervalSince1970: 0)) {} HTTPCookieStorage.shared.removeCookies(since: Date(timeIntervalSince1970: 0)) UserDefaults.standard.removeObject(forKey: "access_token") UserDefaults.standard.removeObject(forKey: "refresh_token") members = [] loginSuccess = false } else { isPresented = true } } } } .sheet(isPresented: $isPresented) { SAWebView { success in loginSuccess = success isPresented = false } } } private func fetchMembers() { let request = URLRequest(url: URL(string: "https://www2.medicareaustralia.gov.au/moaapi/moa-ihs/member-list")!) URLSession.shared.dataTask(with: request) {(data, response, error) in if let data = data { do { let members = try JSONDecoder().decode(Members.self, from: data) self.members = members.memberList } catch { print("Couldn't fetch member list: \(String(describing: String(data: data, encoding: .utf8)))") } } }.resume() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView(members: [Member(memberDisplayName: "<NAME>", memberIRN: 4, claimant: true)]) } } <file_sep>/Shared/Views/CertView.swift // // CertView.swift // AU COVID Verifier // // Created by <NAME> on 14/9/21. // import SwiftUI import Combine struct CertView: View { var member: Member @StateObject var imageFetcher = QRCodeFetcher() @StateObject var dataFetcher = VaccineStatusFetcher() var vaccineDetail: String { return "Valid From \(dataFetcher.vaccineData?.immunisationRecordData.immunisationStatus.vaccineInfo.last?.immunisationDate ?? "Loading...")" } var body: some View { VStack { if (dataFetcher.vaccineData != nil) { VStack { HStack { Text(member.memberDisplayName).font(.title2).padding() Text("DOB: \(dataFetcher.vaccineData?.immunisationRecordData.individualDetails.dateOfBirth ?? "")").font(.title2).padding() } Text("Last vaccine: \(dataFetcher.vaccineData?.immunisationRecordData.immunisationStatus.vaccineInfo.last?.vaccineBrand ?? "")").padding() }.navigationTitle("COVID-19 Certificate").padding() Image(uiImage: imageFetcher.image ?? UIImage()) .resizable() .scaledToFit().padding() Text(vaccineDetail) Spacer(minLength: 100) } else if let error = dataFetcher.errorMessage { Text(error) } else { Text("Loading...") } }.onAppear { if (imageFetcher.image == nil) { imageFetcher.getQRCode(irn: member.memberIRN, completion: nil) dataFetcher.getVaccineData(irn: member.memberIRN) } }.toolbar { HStack { Text("") NavigationLink(destination: PDFViewM(irn: member.memberIRN)) { Text("PDF") } } } } } struct CertView_Previews: PreviewProvider { static var previews: some View { CertView(member: Member(memberDisplayName: "<NAME>", memberIRN: 1, claimant: true)) } } <file_sep>/Shared/AU_COVID_VerifierApp.swift // // AU_COVID_VerifierApp.swift // Shared // // Created by <NAME> on 12/9/21. // import SwiftUI @main struct AU_COVID_VerifierApp: App { var body: some Scene { WindowGroup { ContentView(members: []) } } } <file_sep>/README.md # AU COVID-19 Vaccine iOS app ## What This is an application for iOS and macOS that lets you log in to myGov, fetches your medicare information and displays a QR code with your vaccine data, in the same format that EU apps use. QR Codes created with this app can be verified and cannot be forged. You can only get obtain a QR code if you have been vaccinated, and the system is therefore much more trustworthy than what our government has provided us with. You can use this application as a wallet, or scan the QR code from another covid certificate wallet application. Other apps developed by the EU will show a warning saying the signature is not valid, but wallet apps will still hold the certificates and be verifiable by the corresponding AU verification app. This is to be used in combination with the Verifier application, which has the corresponding public key to verify certificates. ## How The app logs in to medicare the same way that the government's Express Plus Medicare mobile app does. To fetch the QR code (and only to fetch the QR code), it then sends a request to https://medicare.whatsbeef.net, which proxies the request to medicare. As the response comes back, the proxy component converts the response into the EU QR code format, signs it with its private key, and sends it back to the app in image format. <file_sep>/Shared/Models/Members.swift // // Members.swift // AU COVID Verifier // // Created by <NAME> on 14/9/21. // import Foundation struct Members: Codable { var memberList: [Member] } struct Member: Hashable, Codable, Identifiable { var id: Int { get { return memberIRN } } var memberDisplayName: String var memberIRN: Int var claimant: Bool } <file_sep>/Shared/Models/VaccineData.swift // // File.swift // AU COVID Verifier // // Created by <NAME> on 15/9/21. // import Foundation struct VaccineData: Codable { var immunisationRecordData: ImmunisationRecordData } struct ImmunisationRecordData: Codable { var individualDetails: IndividualDetails var immunisationStatus: ImmunisationStatus } struct IndividualDetails: Codable { var firstName: String var lastName: String var dateOfBirth: String var initial: String var ihi: String } struct ImmunisationStatus: Codable { var vaccineInfo: [VaccineInfo] } struct VaccineInfo: Codable { var vaccineBrand: String var immunisationDate: String } struct ErrorResponse: Codable { var errorList: [ErrorList] } struct ErrorList: Codable { var type: String var code: String var description: String }
7407ed2f8ad532be259b84dc5ad5ffa71cf57f36
[ "Swift", "Markdown" ]
9
Swift
wabzqem/AU-COVID-vaccine-certs
66e27b3355b0ea6600c5e10eb15c2d111f1e606d
b5456d3eee388317eba674c8739e357429f3d0a3
refs/heads/master
<file_sep>import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { LoadingController } from 'ionic-angular/components/loading/loading-controller'; import { AngularFireDatabase } from 'angularfire2/database'; import { ProductDetailsPage } from '../consumer'; @IonicPage() @Component({ selector: 'page-product-list', templateUrl: 'product-list.html', }) export class ProductListPage { products: any[] = []; constructor(public navCtrl: NavController, public navParams: NavParams, private loadingCtrl: LoadingController, private afDB: AngularFireDatabase) { } ngOnInit() { let loadingPopup = this.loadingCtrl.create({ spinner: 'crescent', content: '' }); loadingPopup.present(); this.afDB.list('/products', ref => ref.orderByChild('id')).valueChanges() .subscribe(items => { this.products = items; //console.log(this.products); loadingPopup.dismiss(); this.products.forEach(product => { console.log(product.name); }) }); } productDetails(product) { console.log(product); this.navCtrl.push(ProductDetailsPage, {selectedProduct: product}); } } <file_sep>import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, ViewController, ToastController } from 'ionic-angular'; import * as moment from 'moment'; import { AngularFireDatabase } from 'angularfire2/database'; import { AppStateServiceProvider } from '../../../providers/app-state-service/app-state-service'; import { Observable } from 'rxjs/Observable'; import { IProfile, IFacetimeRequest } from '../../../models/models'; @IonicPage() @Component({ selector: 'page-event-modal', templateUrl: 'event-modal.html', }) export class EventModalPage { event: any; minDate: any; usersList: Observable<IProfile[]>; nutritionistList: IProfile[] = []; myId: any; constructor(public navCtrl: NavController, public navParams: NavParams, public viewCtrl: ViewController, private fDb: AngularFireDatabase, public appState: AppStateServiceProvider, private toast: ToastController, ) { this.event = { startTime: new Date().toISOString(), endTime: new Date().toISOString(), allDay: false, idFrom: this.appState.userProfile.id, nameFrom: this.appState.userProfile.firstName + ' ' + this.appState.userProfile.lastName, idTo: '', nameTo: '', callIdFrom: this.appState.userProfile.callId, status: 'pending' }; let preselectedDate = moment(this.navParams.get('selectedDay')).format(); if (preselectedDate) { this.event.startTime = preselectedDate; this.event.endTime = preselectedDate; } this.minDate = moment().format('YYYY-MM-DDTHH:mm'); } ionViewDidLoad() { let profiles = []; this.fDb.database.ref('/profiles').orderByChild('isNutritionist').equalTo(true).on('value', (snapshot) => { profiles = snapshot.val(); for (var prof in profiles) { console.log(prof); if (prof !== this.appState.userProfile.id) { this.nutritionistList.push(profiles[prof]); } } }); } requestTalk() { console.log('Requested to: ' + this.event); if (this.event) { let facetimeReq = {} as IFacetimeRequest facetimeReq.idFrom = this.event.idFrom; facetimeReq.nameFrom = this.event.nameFrom; facetimeReq.idTo = this.event.idTo; facetimeReq.nameTo = this.event.nameTo; facetimeReq.status = 'pending'; facetimeReq.callIdFrom = this.event.callIdFrom; facetimeReq.startTime = this.event.startTime facetimeReq.endTime = this.event.endTime; facetimeReq.title = facetimeReq.nameFrom + '--' + facetimeReq.nameTo facetimeReq.callIdTo = 0; this.fDb.list('/faceTimeRequests').push(facetimeReq) .then(res => { this.toast.create({ message: 'Request sent!', duration: 3000 }).present(); this.dismiss(); }); } } dismiss() { this.viewCtrl.dismiss(); } generateRandom(): number { var min = 11111111; var max = 99999999; return Math.floor(Math.random() * (max - min + 1) + min); } selectDoctor(doctor) { this.event.idTo = doctor.id; this.event.nameTo = doctor.firstName + ' ' + doctor.lastName; } } <file_sep>import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, LoadingController, ToastController } from 'ionic-angular'; import { BarcodeScanner } from '@ionic-native/barcode-scanner'; import { AuthanticationServiceProvider } from '../../../providers/providers'; import { AngularFireAuth } from 'angularfire2/auth'; import { LoginPage } from '../../auth/auth'; @IonicPage() @Component({ selector: 'page-register-kit', templateUrl: 'register-kit.html', }) export class RegisterKitPage { barcode: string; uid: string; constructor(public navCtrl: NavController, public navParams: NavParams, private toast: ToastController, private barcodeScanner: BarcodeScanner, private loadingCtrl: LoadingController, private authProvider: AuthanticationServiceProvider, private afAuth: AngularFireAuth, ) { } ionViewWillLoad() { let loadingPopup = this.loadingCtrl.create({ spinner: 'crescent', content: '' }); loadingPopup.present(); let removePop = true; try { this.afAuth.authState.subscribe(userAuth => { if (userAuth) { this.uid = userAuth.uid; if (removePop) { loadingPopup.dismiss() removePop = false; } } else { console.log('auth false'); if (removePop) { loadingPopup.dismiss() removePop = false; } this.navCtrl.setRoot(LoginPage); } }); } catch (error) { if (removePop) { loadingPopup.dismiss() removePop = false; } this.toast.create({ message: error.message, duration: 3000 }).present(); } } ionViewDidLoad() { console.log('ionViewDidLoad RegisterKitPage'); } scanBarcode() { // let scanOption: BarcodeScannerOptions = { // } this.barcodeScanner.scan() .then((barcodeData) => { console.log(barcodeData.text); this.barcode = barcodeData.text; }).catch(error => { console.log(error); }) } registerBarcode() { console.log(this.barcode); let loadingPopup = this.loadingCtrl.create({ spinner: 'crescent', content: '' }); loadingPopup.present(); let removePop = true; this.authProvider.addUserKit(this.uid, this.barcode); if (removePop) { loadingPopup.dismiss() removePop = false; this.navCtrl.popToRoot(); } } } <file_sep>import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, ModalController, AlertController } from 'ionic-angular'; import { IFacetimeRequestView, IProfile, IFacetimeRequest } from '../../../models/models'; import { AppStateServiceProvider } from '../../../providers/app-state-service/app-state-service'; import { AngularFireDatabase } from 'angularfire2/database'; import { AngularFireAuth } from 'angularfire2/auth'; import * as moment from 'moment'; import { LoginPage } from '../../auth/auth'; import { ConfrencePage } from '../../shared/shared'; // import { CalendarComponent } from 'ionic2-calendar/calendar'; // import { MonthViewComponent } from 'ionic2-calendar/monthview'; // import { WeekViewComponent } from 'ionic2-calendar/weekview'; // import { DayViewComponent } from 'ionic2-calendar/dayview'; @IonicPage() @Component({ selector: 'page-consumer-appointments', templateUrl: 'consumer-appointments.html', }) export class ConsumerAppointmentsPage { userProfile: IProfile; myAppointments: IFacetimeRequestView[] = []; selectedDay = new Date(); viewTitle: string; calendar = { mode: 'month', currentDate: new Date() }; constructor(public navCtrl: NavController, public navParams: NavParams, private modalCtrl: ModalController, private alertCtrl: AlertController, public appState: AppStateServiceProvider, private fDb: AngularFireDatabase, private afAuth: AngularFireAuth, ) { if (!this.afAuth.auth.currentUser) { this.navCtrl.setRoot(LoginPage); } } ionViewDidLoad() { console.log(this.myAppointments); } ionViewWillLoad() { this.afAuth.authState.subscribe(userAuth => { if (userAuth) { if (this.appState.userProfile) { this.userProfile = this.appState.userProfile; if (this.userProfile) { if (!this.userProfile.isNutritionist) { let allrequests; this.fDb.database.ref('/faceTimeRequests').orderByChild('idFrom').equalTo(this.afAuth.auth.currentUser.uid).on('value', (snapshot) => { allrequests = snapshot.val(); this.myAppointments = [] let currentDateTime = new Date(); for (var req in allrequests) { var request = allrequests[req] if (request && request.status !== 'deleted') { let faceTime = request; faceTime.startTime = new Date(request.startTime); faceTime.endTime = new Date(request.endTime); if ((currentDateTime >= faceTime.startTime) && (currentDateTime <= faceTime.endTime)) { faceTime.isActive = true; request.isActive = true; } else { faceTime.isActive = false; request.isActive = false; } request.key = req; this.myAppointments.push(faceTime); } } }); } } } else { console.log('auth false'); this.navCtrl.setRoot(LoginPage); } } else { console.log('auth false'); this.navCtrl.setRoot(LoginPage); } }); if (this.appState.userProfile) { this.userProfile = this.appState.userProfile; } } addEvent() { let modal = this.modalCtrl.create('EventModalPage', { selectedDay: this.selectedDay }); modal.present(); } onEventSelected(event) { let start = moment(event.startTime).format('LLLL'); let end = moment(event.endTime).format('LLLL'); let alert = this.alertCtrl.create({ title: '' + event.title, subTitle: 'From: ' + start + '<br>To: ' + end, buttons: ['OK'] }) alert.present(); } onTimeSelected(ev) { this.selectedDay = ev.selectedTime; } call(callToId, callFromId) { let modal = this.modalCtrl.create(ConfrencePage, { callToId: callToId, callFromId: callFromId }); modal.present(); // console.log(callToId); // this.navCtrl.push(ConfrencePage, // { // callToId: callToId, // callFromId: callFromId // }); } acceptCall(requestKey) { //let allmyrequeststome = []; console.log(requestKey + ' ' + this.myAppointments.length); let request = this.myAppointments.find(req => req.key === requestKey); console.log(JSON.stringify(request)); if (request) { const reqToUpdate: IFacetimeRequest = { idFrom: request.idFrom, idTo: request.idTo, nameFrom: request.nameFrom, nameTo: request.nameTo, status: 'accepted', callIdTo: this.generateRandom(), callIdFrom: request.callIdFrom, startTime: request.startTime, endTime: request.endTime, title: request.title }; this.fDb.object(`/faceTimeRequests/${requestKey}`).update(reqToUpdate); } } deleteCallReq(requestKey) { console.log(requestKey + ' ' + this.myAppointments.length); let request = this.myAppointments.find(req => req.key === requestKey); console.log(JSON.stringify(request)); if (request) { const reqToUpdate: IFacetimeRequest = { idFrom: request.idFrom, idTo: request.idTo, nameFrom: request.nameFrom, nameTo: request.nameTo, status: 'deleted', callIdTo: request.callIdTo, callIdFrom: request.callIdFrom, startTime: request.startTime, endTime: request.endTime, title: request.title }; this.fDb.object(`/faceTimeRequests/${requestKey}`).update(reqToUpdate); } } generateRandom(): number { var min = 11111111; var max = 99999999; return Math.floor(Math.random() * (max - min + 1) + min); } onViewTitleChanged(title) { this.viewTitle = title; } getTime(dateTime): string { return moment(dateTime).format('HH:mm A'); } }<file_sep>import { Component } from '@angular/core'; import { NavController, IonicPage, ToastController } from 'ionic-angular'; import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms' import { IUser, IProfile } from '../../../models/models'; import { AuthanticationServiceProvider, AppStateServiceProvider, StorageHelperProvider, UserDataPreloaderProvider } from '../../../providers/providers'; import { LoadingController } from 'ionic-angular/components/loading/loading-controller'; import { Events } from 'ionic-angular/util/events'; import { SignupTypePage, ForgotPage, ConsumerProfilePage, EmailVerificationPage } from '../auth'; import { PractitionerTabsPage } from '../../practitioner/practitioner'; import { ConsumerDashboardPage } from '../../consumer/consumer'; @IonicPage() @Component({ selector: 'page-login', templateUrl: 'login.html' }) export class LoginPage { isReadyToLogin: boolean; item: any; form: FormGroup; user = {} as IUser; loginForm: FormGroup; userProfile: IProfile; rememberMe: boolean = true; private appState: any; constructor(public navCtrl: NavController, public events: Events, public formBuilder: FormBuilder, private toast: ToastController, appState: AppStateServiceProvider, public authProvider: AuthanticationServiceProvider, public storageHelper: StorageHelperProvider, public preLoader: UserDataPreloaderProvider, private loadingCtrl: LoadingController) { this.appState = appState; } ionViewWillLoad() { this.loginForm = this.formBuilder.group({ email: new FormControl('', Validators.compose([ Validators.required, Validators.pattern('^[a-zA-Z0-9\._-]+@[a-zA-Z0-9\.-]+\.[a-zA-Z]{2,6}$') ])), password: new FormControl('', Validators.compose([ Validators.minLength(5), Validators.required, Validators.pattern('^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9]+$') ])) }); this.storageHelper.getLastUser() .then(data => { if (data) { this.loginForm.get('email').setValue(data.userName); this.loginForm.get('password').setValue(data.userPwd); } }) .catch(error => { console.log(error); }); } ionViewDidLoad() { console.log('Login loaded...'); } goToSignupOptions() { this.navCtrl.push(SignupTypePage); } forgot() { this.navCtrl.push(ForgotPage); } async signIn(values) { let user = {} as IUser; user.email = values.email; user.password = values.<PASSWORD>; console.log(user); let loadingPopup = this.loadingCtrl.create({ spinner: 'crescent', content: '' }); loadingPopup.present(); try { this.authProvider.loginUser(user.email, user.password) .then(data => { let emailVerified = data.emailVerified; if (emailVerified) { this.appState.loginState = true; console.log(data.uid); this.preLoader.preloadUserData(data.uid, data.email).then(data => { console.log('Data Loaded'); this.userProfile = this.appState.userProfile; console.log(this.appState.userProfile); if (this.appState.userProfile) { this.events.publish('profile:recieved', this.appState.userProfile); if (this.userProfile.isNutritionist) { loadingPopup.dismiss(); this.navCtrl.setRoot(PractitionerTabsPage); this.events.publish('profile:recieved', this.appState.userProfile); } else if (this.userProfile.isProfileComplete) { loadingPopup.dismiss(); this.navCtrl.setRoot(ConsumerDashboardPage); this.events.publish('profile:recieved', this.appState.userProfile); } else { loadingPopup.dismiss(); this.navCtrl.setRoot(ConsumerProfilePage, { profile: this.userProfile }); } if (this.rememberMe) { let lastUser = { userName: user.email, userPwd: <PASSWORD> }; this.storageHelper.setLastUser(lastUser); } else { this.storageHelper.removeLastUser(); } } else { console.log('User Profile not found'); loadingPopup.dismiss(); this.toast.create({ message: 'User profile not found!', duration: 3000 }).present(); } }); } else { console.log('Email not verified.'); loadingPopup.dismiss() this.navCtrl.push(EmailVerificationPage); } }) .catch(error => { var errorMessage: string = error.message; loadingPopup.dismiss().then(() => { this.toast.create({ message: errorMessage, duration: 3000 }).present(); }); }); } catch (error) { this.toast.create({ message: error.message, duration: 3000 }).present(); } } validationMessages = { 'email': [ { type: 'required', message: 'Email is required.' }, { type: 'pattern', message: 'Enter a valid email.' } ], 'password': [ { type: 'required', message: '<PASSWORD>.' } ] }; } <file_sep>export interface IFacetimeRequest { idFrom: string; nameFrom: string; idTo: string; nameTo: string status: string; //pending -->(accepted, deleted) callIdTo: number; callIdFrom: number; startTime: string; endTime: string; title: string; } export interface IFacetimeRequestView { idFrom: string; nameFrom: string; idTo: string; nameTo: string status: string; //pending -->(accepted, deleted) key: string; callIdTo: number; callIdFrom: number; startTime: string; endTime: string; title: string; isActive: boolean; }<file_sep>import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { PractitionerTabsPage } from './practitioner-tabs'; @NgModule({ declarations: [ PractitionerTabsPage ], imports: [ IonicPageModule.forChild(PractitionerTabsPage) ] }) export class PractitionerTabsPageModule {} <file_sep> import { Component } from '@angular/core'; import { NavController, ModalController, FabContainer, ToastController, LoadingController, PopoverController, Events } from 'ionic-angular'; import { AngularFireAuth } from 'angularfire2/auth'; import { IProfile } from '../../../models/models'; import { AuthanticationServiceProvider, AppStateServiceProvider, ConfrenceServiceProvider } from '../../../providers/providers'; import { ProductListPage, RegisterKitPage, UserOptionsPage } from '../consumer'; import { LoginPage } from '../../auth/auth'; import { CallControlBoxPage } from '../../shared/shared'; @Component({ selector: 'page-consumer-dashboard', templateUrl: 'consumer-dashboard.html', }) export class ConsumerDashboardPage { pageContent: any; userProfile: IProfile; userOrders: any[]; userKits: any; myCallerId: number = 0; private appState: any; incomingCallId; incomingCall: boolean = false; showRegisterKit: boolean = false; showBuyOption: boolean = true; showWaitingMessage: boolean = false; private confSvc: any; constructor(public navCtrl: NavController, private afAuth: AngularFireAuth, public modalCtrl: ModalController, private loadingCtrl: LoadingController, private toast: ToastController, private toastCtrl: ToastController, private authProvider: AuthanticationServiceProvider, appState: AppStateServiceProvider, confService: ConfrenceServiceProvider, private popoverCtrl: PopoverController, public events: Events, ) { this.appState = appState; this.confSvc = confService; } ionViewWillLoad() { let loadingPopup = this.loadingCtrl.create({ spinner: 'crescent', content: '' }); loadingPopup.present(); let removePop = true; try { this.afAuth.authState.subscribe(userAuth => { if (userAuth) { if (this.appState.userProfile) { this.userProfile = this.appState.userProfile; this.userOrders = this.appState.userOrders; this.userKits = this.appState.userKits; if (this.userOrders.length > 0) { this.showRegisterKit = true; this.showBuyOption = false; this.showWaitingMessage = false; } if (this.userKits) { this.showRegisterKit = false; this.showWaitingMessage = true; this.showBuyOption = true; } // this.events.subscribe('incomingCall', evt => { // this.incomingCallHandler(evt); // }); this.confSvc.initialize(this.userProfile.callId, this.userProfile.email).then(data => { let infoLabel = "Your local ID : " + this.confSvc.sessionId; console.log(infoLabel); }); if (removePop) { loadingPopup.dismiss() removePop = false; } } else { console.log('User Profile not found'); if (removePop) { loadingPopup.dismiss() removePop = false; } this.navCtrl.setRoot(LoginPage); } } }); } catch (error) { if (removePop) { loadingPopup.dismiss() removePop = false; } this.toast.create({ message: error.message, duration: 3000 }).present(); } } ionViewDidLoad() { //this.navCtrl.popToRoot(); } openModel(pageName, userList) { this.modalCtrl.create(pageName, null, { cssClass: 'inset-modal' }) .present(); } answerCall(inCallerId) { let modal = this.modalCtrl.create(CallControlBoxPage, { incommingCallerId: inCallerId }, { cssClass: 'inset-modal' }); modal.present(); } generateRandom(): number { var min = 11111111; var max = 99999999; return Math.floor(Math.random() * (max - min + 1) + min); } signOut(fab: FabContainer) { fab.close(); this.authProvider.logoutUser() .then(authData => { console.log("Logged out"); // toast message this.presentToast('bottom', 'You are now logged out'); this.navCtrl.setRoot(LoginPage); }, error => { var errorMessage: string = error.message; console.log(errorMessage); }); } presentToast(position: string, message: string) { let toast = this.toastCtrl.create({ message: message, position: position, duration: 3000 }); toast.present(); } openShoping() { this.navCtrl.push(ProductListPage); } registerKit() { this.navCtrl.push(RegisterKitPage) } presentPopover(event) { let popover = this.popoverCtrl.create(UserOptionsPage, { page: this.pageContent }) popover.present({ ev: event }); } // incomingCallHandler(e) { // let incommingCallId = e.detail.callId; // let callerId = e.detail.callerId; // let callerName = e.detail.callerNickname; // if (e.detail.autoAnswerActivated === false) { // console.log('Auto Answer is False'); // } // let modal = this.modalCtrl.create(CallControlBoxPage, // { callerId: callerId, callerName: callerName }, // { cssClass: 'inset-modal' }); // modal.onDidDismiss(data => { // var result = data.result; // if (result === 'accepted') { // console.log('accepted'); // let modal = this.modalCtrl.create(ConfrencePage, // { // callToId: callerId, // callFromId: this.userProfile.callId // }); // modal.present(); // } else { // this.confSvc.webRTCClient.refuseCall(incommingCallId); // console.log('rejected'); // } // }) // modal.present(); // } } <file_sep>import { IAddress } from "./models"; export interface IProfile { id: string; firstName: string; lastName: string; email: string phone: string; Addresses: IAddress[] dob: string; birthgender: string; currentgender: string; bodyweight: string; height: string; race: string; sleepquality: string; isNutritionist: boolean; nutritionistLicenseNumber: string; isProfileComplete: boolean; profilePicUrl: string; callId: number; isAdmin: boolean; } <file_sep>import { AngularFireDatabase } from 'angularfire2/database'; import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, ToastController, LoadingController, Events } from 'ionic-angular'; import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms'; import { AngularFireAuth } from 'angularfire2/auth'; import 'rxjs/add/operator/take'; import { IProfile } from '../../../models/models'; import { AuthanticationServiceProvider, AppStateServiceProvider, StorageHelperProvider } from '../../../providers/providers'; import { LoginPage } from '../auth'; import { ConsumerDashboardPage } from '../../consumer/consumer'; @IonicPage() @Component({ selector: 'page-demographic', templateUrl: 'demographic.html', }) export class DemographicPage { backgroundImage = './assets/img/bg1.jpg'; profileForm: FormGroup; isNutritionist: boolean = false; nutritionistLicenseNumber: string = ''; userEmail: string; profile: IProfile; constructor(public navCtrl: NavController, public navParams: NavParams, public events: Events, public formBuilder: FormBuilder, private toast: ToastController, private afAuth: AngularFireAuth, private afDb: AngularFireDatabase, private loadingCtrl: LoadingController, private appState: AppStateServiceProvider, private storageHelper: StorageHelperProvider, public authProvider: AuthanticationServiceProvider ) { } ionViewWillLoad() { this.isNutritionist = this.navParams.get('isNutritionist'); this.nutritionistLicenseNumber = this.navParams.get('nutritionistLicenseNumber'); this.afAuth.authState.subscribe(userAuth => { if (userAuth) { this.userEmail = userAuth.email; this.storageHelper.getProfile(userAuth.uid) .then((val) => { var value = JSON.stringify(val); this.setProfileVal(JSON.parse(value)); }) } else { console.log('auth false'); this.navCtrl.setRoot(LoginPage); } }); this.createForm(); } ionViewDidLoad() { } onSubmit(values) { if (values) { let loadingPopup = this.loadingCtrl.create({ spinner: 'crescent', content: '' }); loadingPopup.present(); this.profile = {} as IProfile this.profile.firstName = values.firstName; this.profile.lastName = values.lastName; this.profile.phone = values.phone; if (this.nutritionistLicenseNumber) { this.profile.isNutritionist = true; this.profile.nutritionistLicenseNumber = this.nutritionistLicenseNumber; } this.afAuth.authState.subscribe(auth => { if (auth && auth.uid) { this.profile.email = auth.email; this.profile.id = auth.uid; this.storageHelper.setProfile(auth.uid, this.profile) .then((val) => { console.log(this.profile); //Update local state object this.appState.localStorageProfile = this.profile; this.authProvider.updateUserProfile(this.profile, auth.uid) .then(pData => { const profRef = this.afDb.object('/profiles/' + auth.uid); profRef.snapshotChanges().subscribe(profData => { this.profile = profData.payload.val(); this.appState.userProfile = this.profile; this.events.publish('profile:recieved', this.appState.userProfile); console.log(profData); loadingPopup.dismiss() this.storageHelper.clearStorage(); this.navCtrl.setRoot(ConsumerDashboardPage); }); }) .catch(error => { console.log(error.message); loadingPopup.dismiss() this.toast.create({ message: error.message, duration: 3000 }).present(); }) }) .catch((error) => { console.log(error.message); }) } else { this.navCtrl.setRoot(LoginPage); } }); } else { this.toast.create({ message: 'No user data found', duration: 3000 }).present(); } } setProfileVal(profile) { if (profile) { this.isNutritionist = profile.isNutritionist; if (profile.nutritionistLicenseNumber) { this.nutritionistLicenseNumber = profile.nutritionistLicenseNumber; } } console.log(this.isNutritionist); console.log(this.nutritionistLicenseNumber); } createForm() { this.profileForm = this.formBuilder.group({ firstName: new FormControl('', Validators.required), lastName: new FormControl('', Validators.required), phone: new FormControl('', Validators.compose([ Validators.required, Validators.pattern('^[1-9][0-9]{9,11}$') ])), terms: new FormControl(true, Validators.pattern('true')) }); } validationMessages = { 'firstname': [ { type: 'required', message: 'Name is required.' } ], 'lastname': [ { type: 'required', message: 'Last name is required.' } ], 'phone': [ { type: 'required', message: 'Phone is required.' }, { type: 'validCountryPhone', message: 'Phone incorrect for the country selected' } ] }; } <file_sep>const Countries = [ { 'name': 'United States', 'callingCode': '+1', 'countryCode': 'US', 'currencyCode': 'USD', 'currencySymbl': '$', 'regions': [ { "name": "District of Columbia", "code": "DC", "subdivision": "district" }, { "name": "American Samoa", "code": "AS", "subdivision": "outlying territory" }, { "name": "Guam", "code": "GU", "subdivision": "outlying territory" }, { "name": "Northern Mariana Islands", "code": "MP", "subdivision": "outlying territory" }, { "name": "Puerto Rico", "code": "PR", "subdivision": "outlying territory" }, { "name": "United States Minor Outlying Islands", "code": "UM", "subdivision": "outlying territory" }, { "name": "Virgin Islands, U.S.", "code": "VI", "subdivision": "outlying territory" }, { "name": "Alabama", "code": "AL", "subdivision": "state" }, { "name": "Alaska", "code": "AK", "subdivision": "state" }, { "name": "Arizona", "code": "AZ", "subdivision": "state" }, { "name": "Arkansas", "code": "AR", "subdivision": "state" }, { "name": "California", "code": "CA", "subdivision": "state" }, { "name": "Colorado", "code": "CO", "subdivision": "state" }, { "name": "Connecticut", "code": "CT", "subdivision": "state" }, { "name": "Delaware", "code": "DE", "subdivision": "state" }, { "name": "Florida", "code": "FL", "subdivision": "state" }, { "name": "Georgia", "code": "GA", "subdivision": "state" }, { "name": "Hawaii", "code": "HI", "subdivision": "state" }, { "name": "Idaho", "code": "ID", "subdivision": "state" }, { "name": "Illinois", "code": "IL", "subdivision": "state" }, { "name": "Indiana", "code": "IN", "subdivision": "state" }, { "name": "Iowa", "code": "IA", "subdivision": "state" }, { "name": "Kansas", "code": "KS", "subdivision": "state" }, { "name": "Kentucky", "code": "KY", "subdivision": "state" }, { "name": "Louisiana", "code": "LA", "subdivision": "state" }, { "name": "Maine", "code": "ME", "subdivision": "state" }, { "name": "Maryland", "code": "MD", "subdivision": "state" }, { "name": "Massachusetts", "code": "MA", "subdivision": "state" }, { "name": "Michigan", "code": "MI", "subdivision": "state" }, { "name": "Minnesota", "code": "MN", "subdivision": "state" }, { "name": "Mississippi", "code": "MS", "subdivision": "state" }, { "name": "Missouri", "code": "MO", "subdivision": "state" }, { "name": "Montana", "code": "MT", "subdivision": "state" }, { "name": "Nebraska", "code": "NE", "subdivision": "state" }, { "name": "Nevada", "code": "NV", "subdivision": "state" }, { "name": "New Hampshire", "code": "NH", "subdivision": "state" }, { "name": "New Jersey", "code": "NJ", "subdivision": "state" }, { "name": "New Mexico", "code": "NM", "subdivision": "state" }, { "name": "New York", "code": "NY", "subdivision": "state" }, { "name": "North Carolina", "code": "NC", "subdivision": "state" }, { "name": "North Dakota", "code": "ND", "subdivision": "state" }, { "name": "Ohio", "code": "OH", "subdivision": "state" }, { "name": "Oklahoma", "code": "OK", "subdivision": "state" }, { "name": "Oregon", "code": "OR", "subdivision": "state" }, { "name": "Pennsylvania", "code": "PA", "subdivision": "state" }, { "name": "Rhode Island", "code": "RI", "subdivision": "state" }, { "name": "South Carolina", "code": "SC", "subdivision": "state" }, { "name": "South Dakota", "code": "SD", "subdivision": "state" }, { "name": "Tennessee", "code": "TN", "subdivision": "state" }, { "name": "Texas", "code": "TX", "subdivision": "state" }, { "name": "Utah", "code": "UT", "subdivision": "state" }, { "name": "Vermont", "code": "VT", "subdivision": "state" }, { "name": "Virginia", "code": "VA", "subdivision": "state" }, { "name": "Washington", "code": "WA", "subdivision": "state" }, { "name": "West Virginia", "code": "WV", "subdivision": "state" }, { "name": "Wisconsin", "code": "WI", "subdivision": "state" }, { "name": "Wyoming", "code": "WY", "subdivision": "state" } ] }, { 'name': 'Canada', 'callingCode': '+1', 'countryCode': 'CA', 'currencyCode': 'CAD', 'currencySymbl': '$', 'regions': [ { "name": "Alberta", "code": "AB", "subdivision": "province", "native": "Alberta" }, { "name": "British Columbia", "code": "BC", "subdivision": "province", "native": "Colombie-Britannique" }, { "name": "Manitoba", "code": "MB", "subdivision": "province", "native": "Manitoba" }, { "name": "New Brunswick", "code": "NB", "subdivision": "province", "native": "Nouveau-Brunswick" }, { "name": "Newfoundland and Labrador", "code": "NL", "subdivision": "province", "native": "Terre-Neuve-et-Labrador" }, { "name": "<NAME>", "code": "NS", "subdivision": "province", "native": "Nouvelle-Écosse" }, { "name": "Ontario", "code": "ON", "subdivision": "province", "native": "Ontario" }, { "name": "<NAME>", "code": "PE", "subdivision": "province", "native": "Île-du-Prince-Édouard" }, { "name": "Quebec", "code": "QC", "subdivision": "province", "native": "Québec" }, { "name": "Saskatchewan", "code": "SK", "subdivision": "province", "native": "Saskatchewan" }, { "name": "Northwest Territories", "code": "NT", "subdivision": "territory", "native": "Territoires du Nord-Ouest" }, { "name": "Nunavut", "code": "NU", "subdivision": "territory", "native": "Nunavut" }, { "name": "Yukon", "code": "YT", "subdivision": "territory", "native": "Yukon" } ] }, { 'name': 'Mexico', 'callingCode': '+52', 'countryCode': 'MX', 'currencyCode': 'MXN', 'currencySymbl': 'N$', 'regions': [ { "name": "Distrito Federal", "code": "DIF", "subdivision": "federal district" }, { "name": "Aguascalientes", "code": "AGU", "subdivision": "state" }, { "name": "Baja California", "code": "BCN", "subdivision": "state" }, { "name": "Baja California Sur", "code": "BCS", "subdivision": "state" }, { "name": "Campeche", "code": "CAM", "subdivision": "state" }, { "name": "Chiapas", "code": "CHP", "subdivision": "state" }, { "name": "Chihuahua", "code": "CHH", "subdivision": "state" }, { "name": "Coahuila", "code": "COA", "subdivision": "state" }, { "name": "Colima", "code": "COL", "subdivision": "state" }, { "name": "Durango", "code": "DUR", "subdivision": "state" }, { "name": "Guanajuato", "code": "GUA", "subdivision": "state" }, { "name": "Guerrero", "code": "GRO", "subdivision": "state" }, { "name": "Hidalgo", "code": "HID", "subdivision": "state" }, { "name": "Jalisco", "code": "JAL", "subdivision": "state" }, { "name": "Michoacán", "code": "MIC", "subdivision": "state" }, { "name": "Morelos", "code": "MOR", "subdivision": "state" }, { "name": "México", "code": "MEX", "subdivision": "state" }, { "name": "Nayarit", "code": "NAY", "subdivision": "state" }, { "name": "<NAME>", "code": "NLE", "subdivision": "state" }, { "name": "Oaxaca", "code": "OAX", "subdivision": "state" }, { "name": "Puebla", "code": "PUE", "subdivision": "state" }, { "name": "Querétaro", "code": "QUE", "subdivision": "state" }, { "name": "<NAME>", "code": "ROO", "subdivision": "state" }, { "name": "<NAME>", "code": "SLP", "subdivision": "state" }, { "name": "Sinaloa", "code": "SIN", "subdivision": "state" }, { "name": "Sonora", "code": "SON", "subdivision": "state" }, { "name": "Tabasco", "code": "TAB", "subdivision": "state" }, { "name": "Tamaulipas", "code": "TAM", "subdivision": "state" }, { "name": "Tlaxcala", "code": "TLA", "subdivision": "state" }, { "name": "Veracruz", "code": "VER", "subdivision": "state" }, { "name": "Yucatán", "code": "YUC", "subdivision": "state" }, { "name": "Zacatecas", "code": "ZAC", "subdivision": "state" } ] } ]; export default Countries;<file_sep>export * from './user'; export * from './country'; export * from './profile'; export * from './address'; export * from './facetimeRequest'; export * from './order'; <file_sep>import { Component } from '@angular/core'; import { IonicPage, NavController, LoadingController, AlertController, ToastController, ActionSheetController } from 'ionic-angular'; import { AuthanticationServiceProvider, AppStateServiceProvider, ImageProvider } from '../../../providers/providers'; import { AngularFireDatabase } from 'angularfire2/database'; import { AngularFireAuth } from 'angularfire2/auth'; import { IProfile } from '../../../models/models'; import { LoginPage } from '../../auth/auth'; @IonicPage() @Component({ selector: 'page-practitioner-profile', templateUrl: 'practitioner-profile.html' }) export class PractitionerProfilePage { profilePicture: any = "./assets/imgs/chatterplace.png" userProfile: IProfile; email: any; profileChanged: boolean = false; private appState: any; constructor(public navCtrl: NavController, public alertCtrl: AlertController, public loadingCtrl: LoadingController, public actionSheetCtrl: ActionSheetController, private toastCtrl: ToastController, appState: AppStateServiceProvider, public afAuth: AngularFireAuth, public afDb: AngularFireDatabase, public authProvider: AuthanticationServiceProvider, public imgProvider: ImageProvider ) { this.appState = appState; } ionViewWillLoad() { this.afAuth.authState.subscribe(userAuth => { if (userAuth) { this.email = this.afAuth.auth.currentUser.email; if (this.appState.userProfile) { this.userProfile = this.appState.userProfile; if (this.userProfile && this.userProfile.profilePicUrl) { this.profilePicture = this.userProfile.profilePicUrl; } } else { console.log('auth false'); this.navCtrl.setRoot(LoginPage); } } else { console.log('auth false'); this.navCtrl.setRoot(LoginPage); } }); } logout() { this.authProvider.logoutUser() .then(authData => { console.log("Logged out"); // toast message this.presentToast('bottom', 'You are now logged out'); this.navCtrl.setRoot(LoginPage); }, error => { var errorMessage: string = error.message; console.log(errorMessage); }); } presentAlert(title) { let alert = this.alertCtrl.create({ title: title, buttons: ['OK'] }); alert.present(); } presentToast(position: string, message: string) { let toast = this.toastCtrl.create({ message: message, position: position, duration: 3000 }); toast.present(); } showImageOption() { let actionSheet = this.actionSheetCtrl.create({ title: 'Select source', buttons: [ { text: 'Image Gallery', icon: 'images', handler: () => { this.changeImage('lib'); } }, { text: 'Camera', icon: 'camera', handler: () => { this.changeImage('cam'); } } ] }); actionSheet.present(); } changeImage(sourceType) { console.log('Change Image'); this.imgProvider.selectImage(sourceType).then(imgData => { if (imgData) { this.profilePicture = imgData; this.profileChanged = true; } }).catch(error => { console.log(error); }) } saveProfileImage() { if (this.profilePicture) { this.authProvider.uploadImage(this.profilePicture, this.userProfile.id); this.profileChanged = false; } } ionViewCanEnter() { if (this.appState.loginState) { return this.appState.loginState; } else { this.navCtrl.setRoot(LoginPage) } } } <file_sep>export * from './login/login'; export * from './forgot/forgot'; export * from './demographic/demographic' export * from './personal-info/personal-info'; export * from './health-info/health-info'; export * from './email-verification/email-verification'; export * from './signup/signup';<file_sep>import { NgModule } from '@angular/core'; import { IonicPageModule, IonicPage } from 'ionic-angular'; import { ConsumerDashboardPage } from './consumer-dashboard'; @IonicPage() @NgModule({ declarations: [ ConsumerDashboardPage, ], imports: [ IonicPageModule.forChild(ConsumerDashboardPage), ], }) export class ConsumerDashboardPageModule {} <file_sep>import { Events, Platform, ModalController } from 'ionic-angular'; import { Injectable } from '@angular/core'; import 'rxjs/add/operator/map'; import { ConfrencePage } from '../../pages/shared/shared'; import { AppStateServiceProvider, StorageHelperProvider } from '../providers'; // import { AngularFireAuth } from 'angularfire2/auth'; //import { NativeAudio } from '@ionic-native/native-audio'; declare var iosrtc; declare var apiRTC; declare var apiCC; @Injectable() export class ConfrenceServiceProvider { webRTCClient: any; sessionId: any; started: boolean = false; myCallId: string; private appState: any; vedioDevices: any = []; currentVedioDevice: any; constructor( public events: Events, public modalCtrl: ModalController, appState: AppStateServiceProvider, public platform: Platform) { this.appState = appState; this.refreshVideoView = this.refreshVideoView.bind(this); } initialize(callId, userName): Promise<any> { this.myCallId = callId; return new Promise(resolve => { if (!this.started) { if (callId) { apiRTC.init({ apiKey: "<KEY>", apiCCId: callId, nickname: userName, onReady: (e) => { this.sessionReadyHandler(e); this.webRTCClient = apiCC.session.createWebRTCClient({}); this.sessionId = apiCC.session.apiCCId; this.started = true; console.log(this.sessionId); console.log(this.webRTCClient) return resolve('started!'); } }); } else { apiRTC.init({ apiKey: "<KEY>", onReady: (e) => { this.sessionReadyHandler(e); this.webRTCClient = apiCC.session.createWebRTCClient({}); this.sessionId = apiCC.session.apiCCId; this.started = true; console.log(this.sessionId); console.log(this.webRTCClient) return resolve('started!'); } }); } } else if (this.started && !this.webRTCClient) { this.webRTCClient = apiCC.session.createWebRTCClient({}); this.sessionId = apiCC.session.apiCCId; return resolve('created!'); } else { return resolve('already started!'); } }); } sessionReadyHandler(e) { console.log('Settingup Handlers'); console.log("sessionReadyHandler"); apiCC.getMediaDevices().then(media => { if (media && media.length > 0) { media.forEach(element => { if (element.kind === 'videoinput') { this.vedioDevices.push(element); } }); // media.forEach((dev, indx) => { // if (dev.kind === 'videoinput') { // this.vedioDevices.push(dev); // } // }); } // console.log(media); }) console.log(this.vedioDevices); apiRTC.addEventListener("incomingCall", evt => { console.log('incoming.....'); if (this.appState.currentView === 'confrence') { this.events.publish('incomingCall', evt); } else { let callerId = evt.detail.callerId; let modal = this.modalCtrl.create(ConfrencePage, { callToId: callerId, callFromId: this.myCallId }); modal.present().then(data => { this.events.publish('incomingCall', evt); setTimeout(this.refreshVideoView, 2000); }) } }); apiRTC.addEventListener("callEstablished", evt => { console.log('established.....'); this.events.publish('callEstablished', evt); setTimeout(this.refreshVideoView, 4000); }); apiRTC.addEventListener("userMediaError", evt => { this.events.publish('userMediaError', evt); }); apiRTC.addEventListener("callEstablished", evt => { this.events.publish('callEstablished', evt); }); apiRTC.addEventListener("remoteHangup", evt => { this.events.publish('remoteHangup', evt); }); apiRTC.addEventListener("remoteStreamAdded", evt => { this.events.publish('remoteStreamAdded', evt); setTimeout(this.refreshVideoView, 100); }); apiRTC.addEventListener("userMediaSuccess", evt => { this.events.publish('userMediaSuccess', evt); }); apiRTC.addEventListener("hangup", evt => { if (!this.webRTCClient) { this.webRTCClient.hangUp(); } this.events.publish('hangup', evt); }); apiRTC.addEventListener("webRTCClientCreated", (e) => { console.log("webRTC Client Created"); this.webRTCClient.setAllowMultipleCalls(false); this.webRTCClient.setVideoBandwidth(300); this.webRTCClient.setUserAcceptOnIncomingCall(false); //this.webRTCClient.UserAcceptOnIncomingDataCall(false); }); } refreshVideoView() { if (this.platform.is('ios')) { console.log("REFRESH"); if (iosrtc) { iosrtc.refreshVideos(); } } } tango() { console.log('Tango Called'); this.events.publish('tango', { message: this.sessionId }); } isUserConnected(uId): string { console.log(`Check id: ${uId}`); let userInfo = ''; //let tet = apiCC.session.getConnectedUserInfo(userId, userInfo); let tet = apiCC.session.getConnectedUserInfo(uId, 'all'); console.log(tet); let tempo = apiCC.session.getConnectedUserIdsList(); console.log(tempo); console.log(apiCC.session.isConnectedUser(uId)) return userInfo; //isConnectedUser() } reverseCamera(callId) { if (this.vedioDevices && this.vedioDevices.length > 0) { let baseIndex = 0; if (this.currentVedioDevice) { const sourceId = this.vedioDevices[baseIndex].deviceId; if (sourceId === this.currentVedioDevice) { this.currentVedioDevice = this.vedioDevices[++baseIndex].deviceId; } else { this.currentVedioDevice = sourceId; } } else { this.currentVedioDevice = this.vedioDevices[baseIndex].deviceId; } var constraints = { video: { deviceId: this.currentVedioDevice ? { exact: this.currentVedioDevice } : undefined } }; this.webRTCClient.setVideoSourceId(this.currentVedioDevice, constraints) this.webRTCClient.updateMediaDeviceOnCall(callId); console.log(`Current vedio sourceID: ${this.currentVedioDevice}`); } } }<file_sep>import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, LoadingController } from 'ionic-angular'; import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms'; import { AngularFireAuth } from 'angularfire2/auth'; import { AuthanticationServiceProvider, AppStateServiceProvider } from '../../../../providers/providers'; import { IProfile } from '../../../../models/models'; import { LoginPage } from '../../auth'; import { ConsumerDashboardPage } from '../../../consumer/consumer'; @IonicPage() @Component({ selector: 'page-consumer-profile', templateUrl: 'consumer-profile.html', }) export class ConsumerProfilePage { personalInfoForm: FormGroup; genders: string[] = [ "Male", "Female" ]; email: string; uid: string; profile: IProfile; constructor(public navCtrl: NavController, public navParams: NavParams, public formBuilder: FormBuilder, private afAuth: AngularFireAuth, private loadingCtrl: LoadingController, public authProvider: AuthanticationServiceProvider, private appState: AppStateServiceProvider) { this.createForm(); } ionViewWillLoad() { let loadingPopup = this.loadingCtrl.create({ spinner: 'crescent', content: '' }); loadingPopup.present(); let removePop = true; this.afAuth.authState.subscribe(userAuth => { if (userAuth) { this.email = this.afAuth.auth.currentUser.email; this.uid = this.afAuth.auth.currentUser.uid; this.profile = this.navParams.get('profile'); if (removePop) { loadingPopup.dismiss() removePop = false; } } else { console.log('auth false'); if (removePop) { loadingPopup.dismiss() removePop = false; } this.navCtrl.setRoot(LoginPage); } }); } onSubmit(values) { if (!this.profile) { this.profile = {} as IProfile } this.profile.dob = values.dob; this.profile.birthgender = values.gender; this.profile.isProfileComplete = true; console.log(this.profile); this.authProvider.updateUserProfile(this.profile, this.uid) .then(profData => { //this.profile = profData.payload.val(); this.appState.userProfile = this.profile; this.navCtrl.setRoot(ConsumerDashboardPage); }).catch((error) => { console.log(error.message); }); } createForm() { this.personalInfoForm = this.formBuilder.group({ dob: new FormControl('', Validators.required), gender: new FormControl('', Validators.required) }); } skip() { this.navCtrl.setRoot(ConsumerDashboardPage); } validationMessages = { 'dob': [ { type: 'required', message: 'Date of birth is required.' } ], 'gender': [ { type: 'required', message: 'Gender at birth is required.' } ] } } <file_sep>import { Injectable } from '@angular/core'; import * as seedrandom from 'seedrandom' @Injectable() export class SharedUtilsProvider { constructor() { console.log('Hello SharedUtilsProvider Provider'); } getIdNumberFromSeed(seed): number { var rng = seedrandom(seed); let random = rng.int32(); console.log(random); return Math.abs(random); } } <file_sep>import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { CallControlBoxPage } from './callControlBox'; @NgModule({ declarations: [ CallControlBoxPage, ], imports: [ IonicPageModule.forChild(CallControlBoxPage), ], }) export class CallControlBoxPageModule {}<file_sep>import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, LoadingController } from 'ionic-angular'; import { FormBuilder, FormControl, Validators, FormGroup } from '@angular/forms'; import { IProfile } from '../../../models/models'; import { AppStateServiceProvider, StorageHelperProvider } from '../../../providers/providers'; import { AngularFireAuth } from 'angularfire2/auth'; import { LoginPage, HealthInfoPage } from '../auth'; @IonicPage() @Component({ selector: 'page-personal-info', templateUrl: 'personal-info.html', }) export class PersonalInfoPage { backgroundImage = './assets/img/bg1.jpg'; genders: string[] = [ "Male", "Female" ]; personalInfoForm: FormGroup; profile: IProfile; email: string; uid: string; constructor(public navCtrl: NavController, public navParams: NavParams, public formBuilder: FormBuilder, private afAuth: AngularFireAuth, private loadingCtrl: LoadingController, private appState: AppStateServiceProvider, private storageHelper: StorageHelperProvider,) { } ionViewWillLoad() { let loadingPopup = this.loadingCtrl.create({ spinner: 'crescent', content: '' }); loadingPopup.present(); this.afAuth.authState.subscribe(userAuth => { if (userAuth) { this.email = this.afAuth.auth.currentUser.email; this.uid = this.afAuth.auth.currentUser.uid; if (this.appState.localStorageProfile) { this.profile = this.appState.localStorageProfile; console.log('Inside Addres'); console.log(this.appState.localStorageProfile); this.updateFormValues(); } loadingPopup.dismiss(); } else { console.log('auth false'); loadingPopup.dismiss(); this.navCtrl.setRoot(LoginPage); } }); this.createForm(); } onSubmit(values) { if (!this.profile) { this.profile = {} as IProfile } this.profile.dob = values.dob; this.profile.birthgender = values.birthgender; this.profile.currentgender = values.currentgender console.log(this.profile); this.storageHelper.setProfile(this.uid, this.profile) .then((val) => { //Update local state object this.appState.localStorageProfile = this.profile; this.navCtrl.setRoot(HealthInfoPage); }) .catch((error) => { console.log(error.message); }); } createForm() { if (this.profile) { this.personalInfoForm = this.formBuilder.group({ dob: new FormControl(this.profile.dob, Validators.required), birthgender: new FormControl(this.profile.birthgender, Validators.required), currentgender: new FormControl(this.profile.currentgender, Validators.required), }); } else { this.personalInfoForm = this.formBuilder.group({ dob: new FormControl('', Validators.required), birthgender: new FormControl('', Validators.required), currentgender: new FormControl('', Validators.required), }); } } updateFormValues() { this.personalInfoForm.get('dob').setValue(this.profile.dob); this.personalInfoForm.get('birthgender').setValue(this.profile.birthgender); this.personalInfoForm.get('currentgender').setValue(this.profile.currentgender); } validationMessages = { 'dob': [ { type: 'required', message: 'Date of birth is required.' } ], 'birthgender': [ { type: 'required', message: 'Gender at birth is required.' } ], 'currentgender': [ { type: 'required', message: 'Current gender at birth is required.' } ], } } <file_sep>import { Component } from '@angular/core'; import { IonicPage, NavController, LoadingController, ToastController, PopoverController } from 'ionic-angular'; import { AngularFireAuth } from 'angularfire2/auth'; import { IProfile } from '../../../models/models'; import { AppStateServiceProvider, ConfrenceServiceProvider } from '../../../providers/providers'; import { LoginPage } from '../../auth/auth'; import { PractitionerOptionsPage, PatientsPage, PractitionerAppointmentsPage, NotificationPage } from '../practitioner'; @IonicPage() @Component({ selector: 'page-practitioner-tabs', templateUrl: 'practitioner-tabs.html' }) export class PractitionerTabsPage { patientsRoot = PatientsPage appointmentsRoot = PractitionerAppointmentsPage notificationRoot = NotificationPage pageContent: any; private appState: any; private confSvc: any; userProfile: IProfile; constructor(public navCtrl: NavController, private loadingCtrl: LoadingController, private afAuth: AngularFireAuth, appState: AppStateServiceProvider, confService: ConfrenceServiceProvider, private toast: ToastController, private popoverCtrl: PopoverController) { this.appState = appState; this.confSvc = confService; } ionViewWillLoad() { let loadingPopup = this.loadingCtrl.create({ spinner: 'crescent', content: '' }); loadingPopup.present(); let removePop = true; try { this.afAuth.authState.subscribe(userAuth => { if (userAuth) { if (this.appState.userProfile) { this.userProfile = this.appState.userProfile; this.confSvc.initialize(this.userProfile.callId, this.userProfile.email).then(data => { let infoLabel = "Your local ID : " + this.confSvc.sessionId; console.log(infoLabel); }); if (removePop) { loadingPopup.dismiss() removePop = false; } } else { console.log('User Profile not found'); if (removePop) { loadingPopup.dismiss() removePop = false; } this.navCtrl.setRoot(LoginPage); } } }); } catch (error) { if (removePop) { loadingPopup.dismiss() removePop = false; } this.toast.create({ message: error.message, duration: 3000 }).present(); } } ionViewDidLoad() { //this.navCtrl.popToRoot(); } presentPopover(event) { let popover = this.popoverCtrl.create(PractitionerOptionsPage, { page: this.pageContent }) popover.present({ ev: event }); } ionViewCanEnter() { if (this.appState.loginState) { return this.appState.loginState; } else { this.navCtrl.setRoot(LoginPage) } } } <file_sep>import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { PractitionerDashboardPage } from './practitioner-dashboard'; @NgModule({ declarations: [ PractitionerDashboardPage, ], imports: [ IonicPageModule.forChild(PractitionerDashboardPage), ], }) export class PractitionerDashboardPageModule {} <file_sep>import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, AlertController, Events } from 'ionic-angular'; import { AngularFireAuth } from 'angularfire2/auth'; import { ConfrenceServiceProvider, AppStateServiceProvider } from '../../../providers/providers'; @IonicPage() @Component({ selector: 'page-confrence', templateUrl: 'confrence.html', }) export class ConfrencePage { calling: boolean = false; callReady: boolean = false; callIncomming: boolean = false; inCall: boolean = false; muted: boolean = false; currentCallId: string; calleeId: string callerId: string callerEmail: string; private confSvc: any; private appState: any; incommingCallerName: string; constructor(public navCtrl: NavController, public navParams: NavParams, private fAuth: AngularFireAuth, public events: Events, appState: AppStateServiceProvider, private alertCtrl: AlertController, confService: ConfrenceServiceProvider) { this.confSvc = confService; this.appState = appState; this.calleeId = this.navParams.get('callToId'); this.callerId = this.navParams.get('callFromId'); console.log(`Caller: ${this.callerId}`); console.log(`Reciver: ${this.calleeId}`); // if (this.fAuth.auth.currentUser) { // //var proccessing = false; // // if (this.incomingCallId && proccessing) { // // proccessing = true; // // console.log('Answering..'); // // this.answerCall(this.incomingCallId); // // } // // if (this.outgoingCalleeId && proccessing) { // // proccessing = true; // // console.log('Calling..'); // // this.makeCall(this.outgoingCalleeId); // // } // } else { // this.navCtrl.setRoot('LoginPage'); // } } ionViewDidLeave() { this.events.publish('viewLoaded', { viewName: '' }); this.events.unsubscribe('incomingCall') this.events.unsubscribe('callEstablished') this.events.unsubscribe('userMediaError') this.events.unsubscribe('userMediaSuccess') this.events.unsubscribe('remoteStreamAdded') this.events.unsubscribe('hangup') } ionViewDidLoad() { this.events.publish('viewLoaded', { viewName: 'confrence' }); this.callerEmail = this.appState.userProfile.email; this.events.subscribe('incomingCall', evt => { this.incomingCallHandler(evt); }); this.events.subscribe('callEstablished', evt => { this.callEstablishedHandler(evt); }); this.events.subscribe('userMediaError', evt => { this.userMediaErrorHandler(evt); }); this.events.subscribe('userMediaSuccess', evt => { this.userMediaSuccessHandler(evt); }); this.events.subscribe('remoteStreamAdded', evt => { this.remoteStreamAddedHandler(evt); console.log('Remote Media added REMOTE'); }); this.events.subscribe('hangup', evt => { this.hangupHandler(evt); }); this.sessionReadyHandler(); } sessionReadyHandler() { // this.confSvc.initialize(this.callerId, this.callerEmail).then(data => { // let infoLabel = "Your local ID : " + this.confSvc.sessionId; // console.log(infoLabel); // this.showCallWaitingControls(); // }); this.showCallWaitingControls(); } ionViewWillLoad() { this.incommingCallerName = ''; if (!this.fAuth.auth.currentUser) { this.navCtrl.setRoot('LoginPage'); } } callEstablishedHandler(e) { this.showInCallControls(); } incomingCallHandler(e) { this.currentCallId = e.detail.callId; let callerId = e.detail.callerId; let callerName = e.detail.callerNickname; if (callerName) { this.incommingCallerName = callerName; } else if (callerId) { this.incommingCallerName = callerId; } else { this.incommingCallerName = ''; } if (this.currentCallId) { this.showIncomingCallControls(); } } remoteStreamAddedHandler(e) { console.log("remoteStreamAddedHandler", e); this.removeChildrenElements('remote'); this.confSvc.webRTCClient.addStreamInDiv( e.detail.stream, e.detail.callType, "remote", 'remoteElt-' + e.detail.callId, { width: "100%", height: "100%" }, false ); this.currentCallId = e.detail.callId; console.log('REMOTE MEDIA ADDED'); } userMediaSuccessHandler(e) { console.log("userMediaSuccessHandler", e); this.removeChildrenElements('mini'); this.confSvc.webRTCClient.addStreamInDiv( e.detail.stream, e.detail.callType, "mini", 'miniElt-' + e.detail.callId, { width: "100%", height: "100%" }, true ); this.currentCallId = e.detail.callId; console.log('USER MEDIA ADDED'); } userMediaErrorHandler(e) { console.log('User Media Error'); this.confSvc.webRTCClient.hangUp(); this.showCallWaitingControls(); } removeMediaElements(callId) { this.confSvc.webRTCClient.removeElementFromDiv('mini', 'miniElt-' + callId); this.confSvc.webRTCClient.removeElementFromDiv('remote', 'remoteElt-' + callId); } removeChildrenElements(parentId) { let parentElm = document.getElementById(parentId); while (parentElm.firstChild) { parentElm.removeChild(parentElm.firstChild); } } hangupHandler(e) { console.log("hangupHandler"); this.confSvc.webRTCClient.setUserAcceptOnIncomingCall(true); this.removeMediaElements(e.detail.callId); this.showCallWaitingControls(); } muteMe() { let audioMuted = this.confSvc.webRTCClient.isAudioMuted(this.currentCallId) console.log(`Audio Mute: ${audioMuted}`) this.muted = audioMuted; if (this.muted) { console.log('Muted'); console.log('Unmuting...'); } if (!this.muted) { console.log('UnMuted'); console.log('Muting...'); } this.confSvc.webRTCClient.toggleAudioMute(this.currentCallId); this.muted = !this.muted; } reversecamera() { console.log('camera changed'); this.confSvc.reverseCamera(this.currentCallId); } back() { const alert = this.alertCtrl.create({ title: 'Leave meeting?', message: 'Do you want leave this meeting?', buttons: [ { text: 'Stay', role: 'cancel', handler: () => { console.log('Stay clicked'); } }, { text: 'Leave', handler: () => { console.log('Leave clicked'); this.removeMediaElements(this.currentCallId); this.hangup(); this.navCtrl.pop().then(() => { console.log('Clearing apiRTC'); }) } } ] }); alert.present(); } showCallingControls() { this.calling = true; this.callReady = false; this.inCall = false; this.callIncomming = false; } showInCallControls() { console.log('Intialize IN call controls'); this.callReady = false; this.calling = false; this.inCall = true; this.callIncomming = false; } showIncomingCallControls() { console.log('Intialize incomming call controls'); this.calling = false; this.callReady = false; this.inCall = false; this.callIncomming = true; } showCallWaitingControls() { console.log('Intialize call ready controls'); this.callReady = true; this.calling = false; this.inCall = false; this.callIncomming = false; } call() { var callId = this.confSvc.webRTCClient.call(this.calleeId); if (callId != null) { console.log(`Calling to: ${this.calleeId}`) this.showCallingControls(); this.currentCallId = callId; } } answer() { this.confSvc.webRTCClient.acceptCall(this.currentCallId); this.incommingCallerName = ''; this.showInCallControls(); } reject() { this.confSvc.webRTCClient.refuseCall(this.currentCallId); this.confSvc.webRTCClient.setUserAcceptOnIncomingCall(true); this.showCallWaitingControls(); } disconnect() { this.confSvc.webRTCClient.hangUp(this.currentCallId); this.confSvc.webRTCClient.setUserAcceptOnIncomingCall(true); this.showCallWaitingControls(); } hangup() { this.confSvc.webRTCClient.hangUp(this.currentCallId); this.confSvc.webRTCClient.setUserAcceptOnIncomingCall(true); this.showCallWaitingControls(); } } <file_sep>export * from './app-state-service/app-state-service'; export * from './confrence-service/confrence-service'; export * from './user-service/authantication-service' export * from './storage-helper/storage-helper'; export * from './image-provider/image-provider'; export * from './user-data-preloader/user-data-preloader'; export * from './shared-utils/shared-utils';<file_sep>import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, PopoverController } from 'ionic-angular'; import { PractitionerOptionsPage } from '../practitioner'; import { AppStateServiceProvider } from '../../../providers/providers'; import { LoginPage } from '../../auth/auth'; @IonicPage() @Component({ selector: 'page-patients', templateUrl: 'patients.html', }) export class PatientsPage { pageContent: any; private appState: any; constructor(public navCtrl: NavController, public navParams: NavParams, private popoverCtrl: PopoverController, appState: AppStateServiceProvider, ) { this.appState = appState; } ionViewDidLoad() { console.log('ionViewDidLoad PatientsPage'); } presentPopover(event) { let popover = this.popoverCtrl.create(PractitionerOptionsPage, { page: this.pageContent }) popover.present({ ev: event }); } ionViewCanEnter() { if (this.appState.loginState) { return this.appState.loginState; } else { this.navCtrl.setRoot(LoginPage) } } } <file_sep>import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, ToastController, ModalController } from 'ionic-angular'; import { FormGroup, Validators, FormControl, FormBuilder } from '@angular/forms'; import emailMask from 'text-mask-addons/dist/emailMask'; import { PasswordValidator } from '../../../../validators/validators'; import { AuthanticationServiceProvider, SharedUtilsProvider } from '../../../../providers/providers'; import { IProfile, IUser } from '../../../../models/models'; import { LoadingController } from 'ionic-angular/components/loading/loading-controller'; import * as firebase from 'firebase'; import { LoginPage } from '../../auth'; import { ConsumerConditionsPage } from '../signup'; @IonicPage() @Component({ selector: 'page-consumer-signup', templateUrl: 'consumer-signup.html', }) export class ConsumerSignupPage { customerForm: FormGroup; matchingPasswordsGroup: FormGroup; profile: IProfile; emailMask = emailMask; constructor(public navCtrl: NavController, public navParams: NavParams, public formBuilder: FormBuilder, private toast: ToastController, private modalCtrl: ModalController, private loadingCtrl: LoadingController, public authProvider: AuthanticationServiceProvider, public sharedUtils: SharedUtilsProvider) { } ionViewWillLoad() { this.createForms(); } ionViewDidEnter() { //this.showingConditions = false; } onSubmit(values) { if (values) { let loadingPopup = this.loadingCtrl.create({ spinner: 'crescent', content: '' }); loadingPopup.present(); let removePop = true; let user = {} as IUser; user.email = values.email; user.password = <PASSWORD>.<PASSWORD>; this.authProvider.registerUser(user.email, user.password) .then(data => { this.profile = {} as IProfile; this.profile.id = data.uid; this.profile.email = user.email; this.profile.isNutritionist = false; this.profile.firstName = values.firstName; this.profile.lastName = values.lastName; this.profile.phone = values.phone; this.profile.isProfileComplete = false; this.profile.callId= this.sharedUtils.getIdNumberFromSeed(user.email); this.profile.isAdmin=false; console.log('Registered'); console.log(data); this.authProvider.loginUser(user.email, user.password) .then(data => { this.authProvider.updateUserProfile(this.profile, data.uid).then(data => { let user: any = firebase.auth().currentUser; user.sendEmailVerification().then( (success) => { //Show toast and redirect to login this.toast.create({ message: 'Verification mail sent, Please verify your email', duration: 4000 }).present(); this.navCtrl.setRoot(LoginPage); console.log("please verify your email") }).catch((err) => { console.log(err) }); //this.navCtrl.setRoot(ConsumerProfilePage, { profile: this.profile }); if (removePop) { loadingPopup.dismiss() removePop = false; } this.navCtrl.setRoot(LoginPage); }).catch(error => { if (removePop) { loadingPopup.dismiss() removePop = false; } this.toast.create({ message: `profile not saved ${user.email}`, duration: 3000 }).present(); this.navCtrl.setRoot(LoginPage) }) }).catch(error => { if (removePop) { loadingPopup.dismiss() removePop = false; } this.toast.create({ message: `login problem ${user.email}`, duration: 3000 }).present(); this.navCtrl.setRoot(LoginPage) }) }) .catch(error => { if (removePop) { loadingPopup.dismiss() removePop = false; } this.toast.create({ message: error, duration: 3000 }).present(); }) } else { this.toast.create({ message: 'No user data found', duration: 3000 }).present(); } } createForms() { this.matchingPasswordsGroup = new FormGroup({ password: new FormControl('', Validators.compose([ Validators.minLength(5), Validators.required, Validators.pattern('^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9]+$') ])), confirmPassword: new FormControl('', Validators.required) }, (formGroup: FormGroup) => { return PasswordValidator.areEqual(formGroup); }); this.customerForm = this.formBuilder.group({ firstName: new FormControl('', Validators.required), lastName: new FormControl('', Validators.required), phone: new FormControl('', Validators.compose([ Validators.required, Validators.pattern('^[1-9][0-9]{9,11}$') ])), email: new FormControl('', Validators.compose([ Validators.required, Validators.pattern('^[a-zA-Z0-9\._-]+@[a-zA-Z0-9\.-]+\.[a-zA-Z]{2,6}$') ])), password: <PASSWORD>, terms: new FormControl(false, Validators.pattern('true')), }); } conditions() { let conditionModal = this.modalCtrl.create(ConsumerConditionsPage); conditionModal.onDidDismiss(data => { let condition = data.condition; if (condition) { if (condition === 'accept') { this.customerForm.get('terms').setValue(true); } else { this.customerForm.get('terms').setValue(false); } } else { this.customerForm.get('terms').setValue(false); } }); conditionModal.present(); } validationMessages = { 'firstname': [ { type: 'required', message: 'First name is required.' } ], 'lastname': [ { type: 'required', message: 'Last name is required.' } ], 'phone': [ { type: 'required', message: 'Phone is required.' }, { type: 'validCountryPhone', message: 'Phone incorrect for the country selected' } ], 'email': [ { type: 'required', message: 'Email is required.' }, { type: 'pattern', message: 'Enter a valid email.' } ], 'password': [ { type: 'required', message: 'Password is required.' }, { type: 'minlength', message: 'Password must be at least 5 characters long.' }, { type: 'pattern', message: 'Your password must contain at least one uppercase, one lowercase, and one number.' } ], 'confirmPassword': [ { type: 'required', message: 'Confirm password is required' } ], 'terms': [ { type: 'pattern', message: 'You must accept terms and conditions.' } ] }; }<file_sep>import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { ConsumerAppointmentsPage } from './consumer-appointments'; @NgModule({ declarations: [ ConsumerAppointmentsPage, ], imports: [ IonicPageModule.forChild(ConsumerAppointmentsPage), ], }) export class AppointmentsPageModule {}<file_sep>import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, LoadingController } from 'ionic-angular'; import { AngularFireAuth } from 'angularfire2/auth'; import { AngularFireDatabase } from 'angularfire2/database'; import { SocialSharing } from '@ionic-native/social-sharing'; import { ConsumerDashboardPage, CartPage } from '../consumer'; import { LoginPage } from '../../auth/auth'; @IonicPage() @Component({ selector: 'page-product-details', templateUrl: 'product-details.html', }) export class ProductDetailsPage { product: any; constructor(public navCtrl: NavController, public navParams: NavParams, private loadingCtrl: LoadingController, private afAuth: AngularFireAuth, private afDb: AngularFireDatabase, private socialSharing: SocialSharing) { } ionViewWillLoad() { this.product = this.navParams.get('selectedProduct'); console.log(this.product); let loadingPopup = this.loadingCtrl.create({ spinner: 'crescent', content: '' }); let removePop: boolean = true; loadingPopup.present(); if (!this.product) { let productName = this.navParams.get('prodName'); if (productName) { //LOAD Product from DB this.afDb.list('/products', ref => ref.orderByChild('BRONZE').equalTo(productName)).valueChanges() .subscribe(items => { this.product = items[0]; //console.log(this.products); if (removePop) { loadingPopup.dismiss() removePop = false; } }); if (removePop) { loadingPopup.dismiss() removePop = false; } } else { this.afAuth.authState.subscribe(userAuth => { if (userAuth) { this.navCtrl.setRoot(ConsumerDashboardPage) } else { console.log('auth false'); if (removePop) { loadingPopup.dismiss() removePop = false; } this.navCtrl.setRoot(LoginPage); } }); } } else { if (removePop) { loadingPopup.dismiss() removePop = false; } } } ionViewDidLoad() { console.log('ionViewDidLoad ProductDetailsPage'); } addToCart() { console.log('Add to cart.'); this.navCtrl.push(CartPage, { selectedProduct: this.product }); } shareByWhatsApp() { // this.socialSharing.canShareVia('whatsapp').then(() => { this.socialSharing.shareViaWhatsApp('Check this out: SynerOme://product-details/' + this.product.name, null, null).then((data) => { console.log(data); }).catch((error) => { console.log(error); }); // }).catch((error) => { // console.log(error); // }); } shareByTwitter() { console.log('Twitter'); } shareByFacebook() { console.log('FACEBOOK'); } goBack(){ this.navCtrl.pop(); } } <file_sep>import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { PractitionerOptionsPage } from './practitioner-options'; @NgModule({ declarations: [ PractitionerOptionsPage, ], imports: [ IonicPageModule.forChild(PractitionerOptionsPage), ], }) export class PractitionerOptionsPageModule {} <file_sep>import { Component } from '@angular/core'; import { IonicPage, NavController } from 'ionic-angular'; @IonicPage() @Component({ selector: 'page-consumer-tabs', templateUrl: 'consumer-tabs.html' }) export class ConsumerTabsPage { homeRoot = 'HomePage' myHealthRoot = 'MyHealthPage' genesRoot = 'GenesPage' snpRoot = 'SnpPage' constructor(public navCtrl: NavController) {} } <file_sep>import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; import { AngularFireAuth } from 'angularfire2/auth'; import { LoginPage } from '../../auth/auth'; @Component({ selector: 'page-preferences', templateUrl: 'preferences.html' }) export class PreferencesPage { // this tells the tabs component which Pages // should be each tab's root Page constructor(public navCtrl: NavController, private afAuth: AngularFireAuth) { } ionViewWillLoad() { this.afAuth.authState.subscribe(userAuth => { if (userAuth) { //Add adition code for handling setting presistance management } else { console.log('auth false'); this.navCtrl.setRoot(LoginPage); } }); } } <file_sep>import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, ViewController, } from 'ionic-angular'; import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms'; import Countries from '../../../models/countries' import { IAddress } from '../../../models/models'; @IonicPage() @Component({ selector: 'page-address', templateUrl: 'address.html', }) export class AddressPage { addressForm: FormGroup; countries: any[] = Countries selectedRegions: any[]; coutryDialCode: string; groupedRegions: any[]; address: IAddress; constructor(public navCtrl: NavController, public navParams: NavParams, public formBuilder: FormBuilder, public viewCtrl: ViewController) { this.selectedRegions = this.countries[0].regions; this.coutryDialCode = this.countries[0].callingCode; this.selectedRegions = this.selectedRegions.sort((a, b) => { return (a.name.charAt(0) > b.name.charAt(0)) ? 1 : ((b.name.charAt(0) > a.name.charAt(0)) ? -1 : 0); }); } ionViewWillLoad() { this.createForm(); } ionViewDidLoad() { console.log('ionViewDidLoad AddressPage'); } createForm() { this.addressForm = this.formBuilder.group({ isDefault: new FormControl(true, Validators.required), street: new FormControl('', Validators.required), city: new FormControl('', Validators.required), country: new FormControl(this.countries[0], Validators.required), region: new FormControl(this.selectedRegions[0], Validators.required), zip: new FormControl('', Validators.compose([ Validators.required, Validators.pattern('^[0-9]{5,7}$') ])), }); } getRegions() { this.selectedRegions = this.addressForm.value.country.regions; this.selectedRegions = this.selectedRegions.sort((a, b) => { return (a.name.charAt(0) > b.name.charAt(0)) ? 1 : ((b.name.charAt(0) > a.name.charAt(0)) ? -1 : 0); }); this.coutryDialCode = this.addressForm.value.country.callingCode; } onSubmit(values) { if (values) { this.address = {} as IAddress this.address.street = values.street this.address.city = values.city; this.address.country = values.country.name; this.address.region = values.region.name; this.address.zip = values.zip; this.address.isDefault = values.isDefault; this.address.type = 'shipping'; this.viewCtrl.dismiss({ address: this.address }); } } updateFormValues() { this.addressForm.get('street').setValue(this.address.street); this.addressForm.get('city').setValue(this.address.city); this.addressForm.get('zip').setValue(this.address.zip); var country = this.countries.find(ctry => ctry.name == this.address.country); if (country) { this.addressForm.get('country').setValue(country); var states = country.regions; if (states) { console.log(states); this.selectedRegions = states; var state = states.find(stat => stat.name == this.address.region); if (state) { console.log(state); this.addressForm.get('region').setValue(state); } } } } close() { this.viewCtrl.dismiss(); } validationMessages = { 'street': [ { type: 'required', message: 'street/ building required.' } ], 'city': [ { type: 'required', message: 'City name is required.' } ], 'country': [ { type: 'required', message: 'Please select a country.' } ], 'region': [ { type: 'required', message: 'Please select a country.' } ], 'zip': [ { type: 'required', message: 'Zip is required. 5-7 digits between 0-9' }, { type: 'validCountryPhone', message: 'Zip incorrect for the country selected' } ] }; //NOT USED groupRegons(regions) { let sortedRegions = regions.sort((a, b) => { return (a.name.charAt(0) > b.name.charAt(0)) ? 1 : ((b.name.charAt(0) > a.name.charAt(0)) ? -1 : 0); }); let currentLetter = false; let currentRegions = []; sortedRegions.forEach((value) => { if (value.name.charAt(0) != currentLetter) { currentLetter = value.name.charAt(0); let newGroup = { letter: currentLetter, regions: [] }; newGroup.regions = currentRegions; this.groupedRegions.push(newGroup); } currentRegions.push(value); }); } } <file_sep>export * from './health/health'; // export * from './auth/auth'; // export * from './consumer/consumer'; // export * from './practitioner/practitioner'; <file_sep>import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { PractitionerConditionsPage } from './practitioner-conditions'; @NgModule({ declarations: [ PractitionerConditionsPage, ], imports: [ IonicPageModule.forChild(PractitionerConditionsPage), ], }) export class PractitionerConditionsPageModule {} <file_sep>import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/operator/map'; import { Storage } from '@ionic/storage'; import { IProfile } from '../../models/models'; @Injectable() export class StorageHelperProvider { constructor(private storage: Storage) { } setProfile(uid: string, profile: IProfile): Promise<any> { return this.storage.set(uid, profile).then((value) => { return value; }); } getStep(): Promise<string> { return this.storage.get('profStep').then((value) => { return value; }); } getProfile(uid: string): Promise<IProfile> { return this.storage.get(uid).then((value) => { return value; }); } clearStorage() { this.storage.clear(); } getLastUser(): Promise<any> { return this.storage.get('lastUser') .then((value) => { return value; }).catch(error => { console.log(error); return null; }) } setLastUser(user) { return this.storage.set('lastUser', user) .then((value) => { return value; }).catch(error => { console.log(error); return null; }) } removeLastUser() { return this.storage.remove('lastUser') .then(res => { return true; }).catch(error => { console.log(error); return false; }) } setItem(key, value) { this.storage.set(key, value); } removeItem(key) { this.storage.remove(key); } } <file_sep>import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, PopoverController } from 'ionic-angular'; import { UserOptionsPage } from '../../consumer/consumer'; @IonicPage() @Component({ selector: 'page-practitioner-dashboard', templateUrl: 'practitioner-dashboard.html', }) export class PractitionerDashboardPage { pageContent: any; constructor(public navCtrl: NavController, public navParams: NavParams, private popoverCtrl: PopoverController) { } ionViewDidLoad() { console.log('ionViewDidLoad PractitionerDashboardPage'); } presentPopover(event) { let popover = this.popoverCtrl.create(UserOptionsPage, { page: this.pageContent }) popover.present({ ev: event }); } } <file_sep>import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, ViewController } from 'ionic-angular'; @IonicPage() @Component({ selector: 'page-callControlBox', templateUrl: 'callControlBox.html', }) export class CallControlBoxPage { callerId: string = ''; callerName: string = ''; result: any; constructor(public navCtrl: NavController, public navParams: NavParams, public viewCtrl: ViewController) { this.callerId = this.navParams.get('callerId'); this.callerName = this.navParams.get('callerName'); } reject() { this.result = 'rejected' this.dismiss(); } accept() { this.result = 'accepted' this.dismiss(); } dismiss() { let data = { 'result': this.result }; this.viewCtrl.dismiss(data); } ionViewDidLoad() { } ionViewWillLoad() { } } <file_sep>import { Injectable } from '@angular/core'; import { Events, LoadingController } from 'ionic-angular'; import { AngularFireDatabase } from 'angularfire2/database'; import { AppStateServiceProvider } from '../providers'; import { IProfile } from '../../models/models'; @Injectable() export class UserDataPreloaderProvider { userProfile: IProfile; userOrders: any; userKits: any; userData: any; private appState: any; constructor(public events: Events, public afDb: AngularFireDatabase, appState: AppStateServiceProvider, public loadingCtrl: LoadingController) { this.appState = appState; events.subscribe('profile:updated', profile => { if (profile !== undefined && profile !== "") { this.userProfile = profile; this.appState.userProfile = profile; } }) events.subscribe('profile:updated', kitData => { if (kitData) { this.userKits = kitData.payload.val(); if (this.userKits) { this.appState.kitData = this.userKits; } } }) } preloadUserData(userId, userEmail): Promise<any> { console.log(userId); console.log(userEmail); return new Promise(resolve => { this.getUserProfile(userId).then(profData => { console.log('1'); this.getUserOrders(userEmail).then(orderData => { console.log('2'); this.getUserKits(userId).then(kitData => { console.log('3'); console.log('calling resolve'); console.log(this.userProfile); console.log(this.userOrders); this.userData = { profile: this.userProfile, orders: this.userOrders, kits: this.userKits }; return resolve(this.userData); }).catch(error => { console.log('-3'); return resolve(error); }); }).catch(error => { console.log('-2'); return resolve(error); }); }).catch(error => { console.log('-1'); return resolve(error); }); }); } getUserProfile(uid): Promise<IProfile> { return new Promise(resolve => { const profRef = this.afDb.object('/profiles/' + uid); profRef.snapshotChanges().subscribe(profData => { this.userProfile = profData.payload.val(); if (this.userProfile) { this.appState.userProfile = this.userProfile; if (this.appState.userProfile) { this.events.publish('profile:recieved', this.appState.userProfile); } resolve(this.userProfile); } }); }); } getUserOrders(email): Promise<any> { return new Promise(resolve => { const orderRef = this.afDb.list('/Orders/', ref => ref.orderByChild('userMail').equalTo(email)).valueChanges(); orderRef.subscribe(orderData => { if (orderData) { this.userOrders = orderData; if (orderData) { this.appState.userOrders = orderData; resolve(this.userOrders); } else { resolve(null); } } else { resolve(null); } }); }); } getUserKits(uid): Promise<any> { return new Promise(resolve => { const profRef = this.afDb.object('/userKits/' + uid); if (profRef) { profRef.snapshotChanges().subscribe(kitData => { if (kitData) { console.log(kitData) this.userKits = kitData.payload.val(); if (this.userKits) { this.appState.userKits = this.userKits; resolve(this.userKits); } else { resolve(null); } } else { resolve(null); } }); } else { resolve(null); } }); } } <file_sep>import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { PractitionerAppointmentsPage } from './practitioner-appointments'; import { NgCalendarModule } from 'ionic2-calendar/calendar.module'; @NgModule({ declarations: [ PractitionerAppointmentsPage, ], imports: [ NgCalendarModule, IonicPageModule.forChild(PractitionerAppointmentsPage), ], }) export class AppointmentsPageModule {}<file_sep>import { Component, ViewChild } from '@angular/core'; import { Platform, Nav, Events } from 'ionic-angular'; import { Deeplinks } from '@ionic-native/deeplinks'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { ProductDetailsPage } from '../pages/consumer/consumer'; @Component({ templateUrl: 'app.html' }) export class MyApp { @ViewChild(Nav) nav: Nav; rootPage: any = 'LoginPage'; //rootPage: any = 'ConfrencePage'; selectedTheme: string = 'light-theme'; constructor(private platform: Platform, public events: Events, private statusBar: StatusBar, private splashScreen: SplashScreen, public deeplinks: Deeplinks, ) { this.initializeApp(); } initializeApp() { this.splashScreen.show(); this.platform.ready().then(() => { this.statusBar.styleDefault(); this.splashScreen.hide(); //ON PLATFORM READY CREATE DEEP LINKS this.deeplinks.routeWithNavController(this.nav, { '/product-details/:prodName': ProductDetailsPage }).subscribe((match) => { console.log('Successfully routed', match); }, (nomatch) => { console.log('Unmatched Route', nomatch); }); }); } } <file_sep>import { IFacetimeRequest } from '../../../models/facetimeRequest'; import { IProfile } from '../../../models/profile'; import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, ViewController, ToastController } from 'ionic-angular'; import { AngularFireDatabase } from 'angularfire2/database'; import { AppStateServiceProvider } from '../../../providers/app-state-service/app-state-service'; @IonicPage() @Component({ selector: 'page-user-list', templateUrl: 'user-list.html', }) export class UserListPage { otherusers: IProfile[] = []; myId: any; constructor(public navCtrl: NavController, public navParams: NavParams, public viewCtrl: ViewController, private fDb: AngularFireDatabase, public appState: AppStateServiceProvider, private toast: ToastController, ) { } ionViewDidLoad() { let profiles = []; this.fDb.database.ref('/profiles').orderByChild('isNutritionist').equalTo(true).on('value', (snapshot) => { profiles = snapshot.val(); for (var prof in profiles) { console.log(prof); if (prof !== this.appState.userProfile.id) { this.otherusers.push(profiles[prof]); } } }); } requestTalk(user) { console.log('Requested to: ' + user); if (user) { let facetimeReq = {} as IFacetimeRequest facetimeReq.idFrom = this.appState.userProfile.id; facetimeReq.nameFrom = this.appState.userProfile.firstName facetimeReq.idTo = user.id; facetimeReq.nameTo = user.firstName; facetimeReq.status = 'pending'; facetimeReq.callIdFrom = this.generateRandom(); facetimeReq.callIdTo = 0; this.fDb.list('/faceTimeRequests').push(facetimeReq) .then(res => { this.toast.create({ message: 'Request sent!', duration: 3000 }).present(); }); // facetimeReq.status = 'pending'; // this.fDb.database.ref('/faceTimeRequests').child(facetimeReq.idTo).push(facetimeReq) // .then(res => { // this.toast.create({ // message: 'Request sent!', // duration: 3000 // }).present(); // }) } this.dismiss(); } dismiss() { this.viewCtrl.dismiss(); } generateRandom(): number { var min = 11111111; var max = 99999999; return Math.floor(Math.random() * (max - min + 1) + min); } } <file_sep>import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, LoadingController, ToastController } from 'ionic-angular'; import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms'; import { IProfile } from '../../../models/models'; import { AngularFireAuth } from 'angularfire2/auth'; import { AppStateServiceProvider, StorageHelperProvider, AuthanticationServiceProvider } from '../../../providers/providers'; import { AngularFireDatabase } from 'angularfire2/database'; import { LoginPage } from '../auth'; import { ConsumerDashboardPage } from '../../consumer/consumer'; @IonicPage() @Component({ selector: 'page-health-info', templateUrl: 'health-info.html', }) export class HealthInfoPage { backgroundImage = './assets/img/bg1.jpg'; races: string[] = [ "White", "African American", "Asian", "Alaska Natives", "American Indian", "Native Hawaiian" ]; seelpqualities: string[] = [ "Amazin", "Wakeup frequently", "Wakeup exausted", "Alaska Natives", "Disfficulty breathing/sleep apnea" ]; healthInfoForm: FormGroup; profile: IProfile; email: string; uid: string; constructor(public navCtrl: NavController, public navParams: NavParams, public formBuilder: FormBuilder, private toast: ToastController, private afAuth: AngularFireAuth, private afDb: AngularFireDatabase, private loadingCtrl: LoadingController, private appState: AppStateServiceProvider, private storageHelper: StorageHelperProvider, public authProvider: AuthanticationServiceProvider) { } ionViewWillLoad() { let loadingPopup = this.loadingCtrl.create({ spinner: 'crescent', content: '' }); loadingPopup.present(); this.afAuth.authState.subscribe(userAuth => { if (userAuth) { this.email = this.afAuth.auth.currentUser.email; this.uid = this.afAuth.auth.currentUser.uid; if (this.appState.localStorageProfile) { this.profile = this.appState.localStorageProfile; console.log('Inside Addres'); console.log(this.appState.localStorageProfile); this.updateFormValues(); } loadingPopup.dismiss(); } else { console.log('auth false'); loadingPopup.dismiss(); this.navCtrl.setRoot(LoginPage); } }); this.createForm(); } onSubmit(values) { if (!this.profile) { this.profile = {} as IProfile } this.profile.bodyweight = values.bodyweight; this.profile.height = values.height; this.profile.race = values.race; this.profile.sleepquality = values.sleepquality; let loadingPopup = this.loadingCtrl.create({ spinner: 'crescent', content: '' }); loadingPopup.present(); this.storageHelper.setProfile(this.uid, this.profile) .then((val) => { //Update local state object this.appState.localStorageProfile = this.profile; this.authProvider.updateUserProfile(this.profile, this.uid) .then(data => { const profRef = this.afDb.object('/profiles/' + this.uid); profRef.snapshotChanges().subscribe(profData => { this.profile = profData.payload.val(); this.appState.localStorageProfile = this.profile; console.log(data); loadingPopup.dismiss() this.storageHelper.clearStorage(); this.navCtrl.setRoot(ConsumerDashboardPage); }); }) .catch(error => { console.log(error.message); loadingPopup.dismiss() this.toast.create({ message: error.message, duration: 3000 }).present(); }) }) .catch((error) => { console.log(error.message); }); } createProfile(profile: IProfile, uid: string) { } createForm() { if (this.profile) { this.healthInfoForm = this.formBuilder.group({ bodyweight: new FormControl(this.profile.bodyweight, Validators.required), height: new FormControl(this.profile.height, Validators.required), race: new FormControl(this.profile.race, Validators.required), sleepquality: new FormControl(this.profile.sleepquality, Validators.required), }); } else { this.healthInfoForm = this.formBuilder.group({ bodyweight: new FormControl('', Validators.required), height: new FormControl('', Validators.required), race: new FormControl('', Validators.required), sleepquality: new FormControl('', Validators.required), }); } } updateFormValues() { this.healthInfoForm.get('bodyweight').setValue(this.profile.bodyweight); this.healthInfoForm.get('height').setValue(this.profile.height); this.healthInfoForm.get('race').setValue(this.profile.race); this.healthInfoForm.get('sleepquality').setValue(this.profile.sleepquality); } validationMessages = { 'bodyweight': [ { type: 'required', message: 'Body wheigh is required.' } ], 'height': [ { type: 'required', message: 'Height is required.' } ], 'race': [ { type: 'required', message: 'Race is required.' } ], 'sleepquality': [ { type: 'required', message: 'Sleep quality is required.' } ], } }<file_sep>import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { ConsumerDashboardPage } from '../consumer'; @IonicPage() @Component({ selector: 'page-order-final', templateUrl: 'order-final.html', }) export class OrderFinalPage { order: any; userLastName: string; orderShippingAddress: any; loadView: boolean = false; constructor(public navCtrl: NavController, public navParams: NavParams) { } ionViewDidLoad() { this.order = this.navParams.get('finalOrder'); this.userLastName = this.navParams.get('userLastName'); if (this.order) { this.orderShippingAddress = this.order.shippingAddress; this.loadView = true; } } goHome() { this.navCtrl.setRoot(ConsumerDashboardPage); } } <file_sep>import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { RegisterKitPage } from './register-kit'; @NgModule({ declarations: [ RegisterKitPage, ], imports: [ IonicPageModule.forChild(RegisterKitPage), ], }) export class RegisterKitPageModule {} <file_sep>export * from './practitioner-dashboard/practitioner-dashboard'; export * from './notification/notification'; export * from './patients/patients'; export * from './practitioner-dashboard/practitioner-dashboard'; export * from './practitioner-options/practitioner-options'; export * from './practitioner-profile/practitioner-profile'; export * from './practitioner-tabs/practitioner-tabs'; export * from './practitioner-appointments/practitioner-appointments';<file_sep>import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { MyHealthPage } from './my-health'; @NgModule({ declarations: [ MyHealthPage, ], imports: [ IonicPageModule.forChild(MyHealthPage), ], }) export class MyHealthPageModule {} <file_sep>import { Events } from 'ionic-angular'; import { Injectable } from '@angular/core'; import { IProfile } from '../../models/profile'; @Injectable() export class AppStateServiceProvider { loginState: boolean = false; userProfile: IProfile; localStorageProfile: IProfile; userOrders: any[]; userKits: any; currentView: string; constructor(public events: Events) { console.log('App state Contructor called'); this.events.subscribe('viewLoaded', data => { this.currentView = data.viewName; console.log(this.currentView); }); } clearData() { this.loginState = false; this.userProfile = null; this.userKits = null; this.userOrders = null; } } <file_sep>export * from './product-list/product-list'; export * from './product-details/product-details'; export * from './cart/cart'; export * from './address/address'; export * from './address-list/address-list'; export * from './order-final/order-final'; export * from './register-kit/register-kit'; export * from './user-options/user-options'; export * from './user-profile/user-profile'; export * from './consumer-tabs/consumer-tabs'; export * from './home/home'; export * from './consumer-dashboard/consumer-dashboard'; export * from './preferences/preferences'; export * from './consumer-appointments/consumer-appointments';<file_sep>import { Component } from '@angular/core'; import { Health } from '@ionic-native/health'; import { Platform } from 'ionic-angular/platform/platform'; @Component({ selector: 'page-health', templateUrl: 'health.html' }) export class HealthPage { height: number; currentHeight = 'No Data'; stepcount = 'No Data'; workouts = []; constructor(private health: Health, private platform: Platform) { console.log('Health says...') this.platform.ready().then(() => { this.health.isAvailable().then(available => { if (available) { console.log(available); this.health.requestAuthorization([ 'distance', 'nutrition', //read and write permissions { read: ['steps'], //read only permission write: ['height', 'weight'] //write only permission } ]) .then(res => { console.log(res) this.loadHealthData(); }) .catch(e => console.log(e)); } }).catch(error => { console.log(error); this.health.promptInstallFit().then(res => { console.log(res); }).catch(error => { console.log(error); }) }) }); } // Save a new height saveHeight() { this.health.store({ startDate: new Date(new Date().getTime() - 8 * 60 * 1000), // three minutes ago endDate: new Date(), dataType: 'height', value: '165', sourceName: 'SynerOme', sourceBundleId: 'com.SynerOme.Mobile' }).then(res => { console.log(res); this.loadHealthData(); }).catch(error => { console.log(error); }) } // Save a new dummy workout saveWorkout() { let workout = { startDate: new Date(new Date().getTime() - 3 * 60 * 1000), // three minutes ago endDate: new Date(), dataType: 'steps', value: '180', sourceName: 'SynerOme', sourceBundleId: 'com.SynerOme.Mobile' }; this.health.store(workout).then(res => { console.log(res); this.loadHealthData(); }).catch(error => { console.log(error); }) this.health.store(workout).then(res => { this.loadHealthData(); }) } // Reload all our data loadHealthData() { this.health.query({ startDate: new Date(new Date().getTime() - 3 * 24 * 60 * 60 * 1000), // three days ago endDate: new Date(), // now dataType: 'height' }).then(res => { this.currentHeight = res.value; }).catch(error => { console.log('No height: ', error); }) this.health.queryAggregated({ startDate: new Date(new Date().getTime() - 3 * 24 * 60 * 60 * 1000), // three days ago endDate: new Date(), // now dataType: 'steps', bucket: 'day' }).then(res => { // let stepSum = res.reduce((a, b) => a.value + b.value, 0); // this.stepcount = stepSum; console.log('No steps: ', res); }).catch(error => { console.log('No steps: ', error); }) } ngOnInit() { //Called after the constructor, initializing input properties, and the first call to ngOnChanges. //Add 'implements OnInit' to the class. console.log('Health ...') } }<file_sep>This is demo project for [SynerOme](https://www.synerome.com/). ## How to use this code To use this project, either create a new pull request or download the zip. Prerquists: *nodejs *electronjs *ionic 3+ Run following command to install dependencies: ```bash $ sudo npm install -g ionic cordova $ npm install ``` ### Run the project: To run the project use the command below: ```bash $ cd <project directory> $ ionic serve ``` <file_sep>import { IAddress } from "./models"; export interface IOrder { productReference: string; userMail: string; userID: string; shippingAddress: IAddress; price: number; tax: number; amountPaid: number; payPalStatus: string; fullfilled: boolean; kitFor: any; }<file_sep>import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { ConsumerProfilePage } from './consumer-profile'; @NgModule({ declarations: [ ConsumerProfilePage, ], imports: [ IonicPageModule.forChild(ConsumerProfilePage), ], }) export class ConsumerProfilePageModule {} <file_sep>import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms'; import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, ModalController, Events } from 'ionic-angular'; import { LoadingController } from 'ionic-angular/components/loading/loading-controller'; import { AngularFireAuth } from 'angularfire2/auth'; import { IProfile, IAddress, IOrder } from '../../../models/models'; import { AppStateServiceProvider, AuthanticationServiceProvider } from '../../../providers/providers'; import { AngularFireDatabase } from 'angularfire2/database'; import { PayPal, PayPalPayment, PayPalConfiguration } from '@ionic-native/paypal'; import { LoginPage } from '../../auth/auth'; import { OrderFinalPage, AddressPage, AddressListPage } from '../consumer'; @IonicPage() @Component({ selector: 'page-cart', templateUrl: 'cart.html', }) export class CartPage { product: any; processed: boolean = true; price: number; tax: number; total: number; currency: string; uid: string; userProfile: IProfile; enableBuy: boolean = false; shippingAddress: IAddress; kitFor: string = 'me'; kitUserInfo: any; kitForForm: FormGroup; private appState: any; constructor(public navCtrl: NavController, public navParams: NavParams, private events: Events, public formBuilder: FormBuilder, private loadingCtrl: LoadingController, public modelCtrl: ModalController, private afAuth: AngularFireAuth, private afDb: AngularFireDatabase, appState: AppStateServiceProvider, private authProvider: AuthanticationServiceProvider, private payPal: PayPal) { this.appState = appState; this.product = this.navParams.get('selectedProduct'); this.kitUserInfo = { firstName: '', lastName: '', dob: '', } this.createForm(); } ionViewWillLoad() { let loadingPopup = this.loadingCtrl.create({ spinner: 'crescent', content: '' }); loadingPopup.present(); this.afAuth.authState.subscribe(userAuth => { if (userAuth) { this.uid = userAuth.uid; this.userProfile = this.appState.userProfile console.log(this.userProfile); if (this.product) { this.price = this.product.price; var tax = 0; if (this.product.taxPer) { tax = this.product.taxPer; } this.tax = this.price * tax; this.total = +this.price + +this.tax; this.currency = this.product.currency; this.processed = true; console.log(this.total); } if (this.userProfile) { console.log('Shout out'); if (this.userProfile.Addresses) { if (this.userProfile.Addresses.length == 1) { this.shippingAddress = this.userProfile.Addresses[0]; } else { this.shippingAddress = this.userProfile.Addresses.find(adr => adr.isDefault) } this.enableBuy = true; } } loadingPopup.dismiss(); } else { console.log('auth false'); loadingPopup.dismiss(); this.navCtrl.setRoot(LoginPage); } }); } ionViewDidLoad() { } purchase(kitForValues) { if (kitForValues) { let loadingPopup = this.loadingCtrl.create({ spinner: 'crescent', content: '' }); loadingPopup.present(); this.kitUserInfo.firstName = kitForValues.firstName; this.kitUserInfo.lastName = kitForValues.lastName; this.kitUserInfo.dob = kitForValues.dob; //BUIDL ORDER OBJECT let order = {} as IOrder; order.productReference = `[${this.product.name}][${this.total}][${new Date().toString()}]` order.userMail = this.userProfile.email; order.userID = this.userProfile.id order.shippingAddress = this.shippingAddress; order.price = this.price; order.tax = this.tax; order.amountPaid = this.total; order.fullfilled = false; order.kitFor = this.kitUserInfo; console.log(order); if (order) { //INTIALIZE PAYMENT this.payPal.init({ PayPalEnvironmentProduction: '<KEY>', PayPalEnvironmentSandbox: '<KEY>' }).then(() => { this.payPal.prepareToRender('PayPalEnvironmentSandbox', new PayPalConfiguration({ })).then(() => { let payment = new PayPalPayment(this.total.toString(), 'USD', order.productReference, 'sale'); this.payPal.renderSinglePaymentUI(payment).then((res) => { console.log('Result from Paypal: ', res); if (res && res.response) { let resposeString = JSON.stringify(res.response); order.payPalStatus = resposeString; this.addOrderToDB(order); loadingPopup.dismiss(); this.navCtrl.setRoot(OrderFinalPage, { finalOrder: order, userLastName: this.userProfile.lastName }); } }, (err) => { console.log('Error: ', err) loadingPopup.dismiss(); }); }, (conf) => { console.log('Configuration Error: ', conf) loadingPopup.dismiss(); }); }, (init) => { console.log('Init Error: ', init) loadingPopup.dismiss(); }); } } } addOrderToDB(order: IOrder) { if (order) { let orderList = this.afDb.list('Orders'); return orderList.push(order) .then(res => { console.log(res); }); } } addAddress() { let addressModel = this.modelCtrl.create(AddressPage); addressModel.onDidDismiss(data => { if (data && data.address) { this.addAddressToProfile(data.address); } }); addressModel.present() } addAddressToProfile(addressObj) { let address = {} as IAddress; address = addressObj console.log(address); let loadingPopup = this.loadingCtrl.create({ spinner: 'crescent', content: '' }); loadingPopup.present(); if (!this.userProfile.Addresses) { this.userProfile.Addresses = [] as IAddress[]; } if (address.isDefault) { this.userProfile.Addresses.forEach(adr => { adr.isDefault = false }); } this.userProfile.Addresses.push(address); this.authProvider.updateUserProfile(this.userProfile, this.uid) .then(profDate => { const profRef = this.afDb.object('/profiles/' + this.uid); let profSubs = profRef.snapshotChanges().subscribe(profData => { this.userProfile = profData.payload.val(); this.appState.userProfile = this.userProfile; this.events.publish('profile:recieved', this.userProfile); this.userProfile = this.appState.userProfile; profSubs.unsubscribe(); if (this.userProfile) { console.log('Shout out again'); if (this.userProfile.Addresses) { if (this.userProfile.Addresses.length == 1) { this.shippingAddress = this.userProfile.Addresses[0]; } else { this.shippingAddress = this.userProfile.Addresses.find(adr => adr.isDefault) } this.enableBuy = true; } } loadingPopup.dismiss() //this.navCtrl.push(CartPage, { selectedProduct: this.product }); }); }) .catch(error => { console.log(error); loadingPopup.dismiss() }) } changeAddress() { if (this.userProfile && this.userProfile.Addresses) { if (this.userProfile.Addresses.length > 1) { let addressModel = this.modelCtrl.create(AddressListPage, { addressList: this.userProfile.Addresses }); addressModel.onDidDismiss(data => { if (data && data.address) { this.shippingAddress = data.address; } }); addressModel.present() } } } kitForOptionChange() { console.log('option changed'); if (this.kitFor === 'me') { // this.appState.userProfile. this.kitForForm.get('firstName').setValue(this.appState.userProfile.firstName); this.kitForForm.get('lastName').setValue(this.appState.userProfile.lastName); this.kitForForm.get('dob').setValue(this.appState.userProfile.dob); } else if (this.kitFor === 'other') { this.kitForForm.get('firstName').setValue(''); this.kitForForm.get('lastName').setValue(''); this.kitForForm.get('dob').setValue(''); } } createForm() { console.log('creating kit form form'); this.kitForForm = this.formBuilder.group({ firstName: new FormControl('', Validators.required), lastName: new FormControl('', Validators.required), dob: new FormControl('', Validators.required), }); this.kitForForm.get('firstName').setValue(this.appState.userProfile.firstName); this.kitForForm.get('lastName').setValue(this.appState.userProfile.lastName); this.kitForForm.get('dob').setValue(this.appState.userProfile.dob); } validationMessages = { 'dob': [ { type: 'required', message: 'Date of birth is required.' } ], 'firstName': [ { type: 'required', message: 'First name is required.' } ], 'lastName': [ { type: 'required', message: 'Last name is required.' } ] } } <file_sep>import { NgModule } from '@angular/core'; import { IonicPageModule, IonicPage } from 'ionic-angular'; import { ConsumerSignupPage } from './consumer-signup'; import { TextMaskModule } from 'angular2-text-mask'; @IonicPage() @NgModule({ declarations: [ ConsumerSignupPage, ], imports: [ IonicPageModule.forChild(ConsumerSignupPage), TextMaskModule, ], }) export class SignupPageModule {} <file_sep>import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/operator/map'; import { AngularFireAuth } from 'angularfire2/auth'; import { AngularFireDatabase } from 'angularfire2/database'; import { IProfile } from '../../models/profile'; import { AppStateServiceProvider } from '../app-state-service/app-state-service'; import * as firebase from 'firebase'; import { LoadingController } from 'ionic-angular/components/loading/loading-controller'; import { Events } from 'ionic-angular'; @Injectable() export class AuthanticationServiceProvider { constructor(public http: Http, public events: Events, private afAuth: AngularFireAuth, public afDb: AngularFireDatabase, public appState: AppStateServiceProvider, public loadingCtrl: LoadingController) { } loginUser(newEmail: string, newPassword: string): Promise<any> { return this.afAuth.auth.signInWithEmailAndPassword(newEmail, newPassword) } resetPassword(email: string): Promise<any> { return this.afAuth.auth.sendPasswordResetEmail(email); } logoutUser(): Promise<any> { this.appState.clearData(); return this.afAuth.auth.signOut(); } registerUser(email: string, password: string): Promise<any> { return this.afAuth.auth.createUserWithEmailAndPassword(email, password); } updateUserProfile(userProfile: IProfile, uid: string): Promise<any> { return this.afDb.object(`profiles/${uid}`).set(userProfile); } deleteUserProfile(uid: string): Promise<any> { return this.afDb.object(`profiles/${uid}`).remove(); } uploadImage(image: string, userId: string): any { let loadingPopup = this.loadingCtrl.create({ spinner: 'crescent', content: '' }); loadingPopup.present(); let storageRef = firebase.storage().ref('profileImages'); let imageRef = storageRef.child(`${userId}.jpg`); return imageRef.putString(image, 'data_url') .then(data => { if (data) { const profRef = this.afDb.object('/profiles/' + userId); profRef.update({ profilePicUrl: data.downloadURL }); this.getUserProfile(userId); loadingPopup.dismiss(); } }).catch(error => { console.log(error); loadingPopup.dismiss(); }) } getUserProfile(uid) { const profRef = this.afDb.object('/profiles/' + uid); profRef.snapshotChanges().subscribe(profData => { let userProfile = profData.payload.val(); if (userProfile) { this.appState.userProfile = userProfile; if (this.appState.userProfile) { this.events.publish('profile:recieved', this.appState.userProfile); } } }); } addUserKit(uid, barcode) { let kitData = { rawDnaData: '', intervenstions: '', dataRecieved: false }; return this.afDb.object(`userKits/${uid}/${barcode}`).set(kitData).then(data => { this.events.publish('userdata:updated', data); }) } } <file_sep>export * from './callControlBox/callControlBox'; export * from './confrence/confrence'; export * from './event-modal/event-modal'; export * from './user-list/user-list';<file_sep>import { ConfrencePageModule } from './../pages/shared/confrence/confrence.module'; import { SharedUtilsProvider } from './../providers/shared-utils/shared-utils'; import { NgModule, ErrorHandler } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular'; import { MyApp } from './app.component'; import { IonicStorageModule } from '@ionic/storage'; import { HttpModule } from '@angular/http'; import { AngularFireModule } from 'angularfire2'; // for auth import { AngularFireAuthModule } from 'angularfire2/auth'; // for database import { AngularFireDatabaseModule } from 'angularfire2/database'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { BarcodeScanner } from '@ionic-native/barcode-scanner'; import { AuthanticationServiceProvider, AppStateServiceProvider, UserDataPreloaderProvider, ConfrenceServiceProvider, StorageHelperProvider, ImageProvider } from '../providers/providers'; import { NativeAudio } from '@ionic-native/native-audio'; import { PayPal } from '@ionic-native/paypal'; import { Deeplinks } from '@ionic-native/deeplinks'; import { SocialSharing } from '@ionic-native/social-sharing'; import { Health } from '@ionic-native/health'; import { Camera } from '@ionic-native/camera'; import { ForgotPage, SignupTypePage, ConsumerSignupPage, ConsumerConditionsPage, EmailVerificationPage, ConsumerProfilePage, PractitionerSignupPage, PractitionerConditionsPage, DemographicPage, PersonalInfoPage, HealthInfoPage } from '../pages/auth/auth'; import { UserProfilePage, ConsumerDashboardPage, PreferencesPage, ProductListPage, ProductDetailsPage, CartPage, OrderFinalPage, AddressPage, AddressListPage, RegisterKitPage, UserOptionsPage, ConsumerAppointmentsPage } from '../pages/consumer/consumer'; import {HealthPage } from '../pages/pages'; import { UserListPage, CallControlBoxPage } from '../pages/shared/shared'; import { PractitionerTabsPage, PractitionerOptionsPage, PractitionerAppointmentsPage, PractitionerProfilePage, PatientsPage, NotificationPage } from '../pages/practitioner/practitioner'; import { NgCalendarModule } from 'ionic2-calendar/calendar.module'; var firebaseConfig = { apiKey: "<KEY>", authDomain: "synerome-f2748.firebaseapp.com", databaseURL: "https://synerome-f2748.firebaseio.com", projectId: "synerome-f2748", storageBucket: "synerome-f2748.appspot.com", messagingSenderId: "355513485520" }; @NgModule({ declarations: [ MyApp, ForgotPage, SignupTypePage, ConsumerSignupPage, ConsumerConditionsPage, EmailVerificationPage, ConsumerProfilePage, PractitionerSignupPage, PractitionerConditionsPage, DemographicPage, PersonalInfoPage, HealthInfoPage, UserProfilePage, ConsumerDashboardPage, PreferencesPage, ConsumerAppointmentsPage, ProductListPage, ProductDetailsPage, CartPage, OrderFinalPage, AddressPage, AddressListPage, UserListPage, HealthPage, RegisterKitPage, UserOptionsPage, CallControlBoxPage, PractitionerTabsPage, PractitionerOptionsPage, PractitionerProfilePage, PatientsPage, PractitionerAppointmentsPage, NotificationPage ], imports: [ BrowserModule, IonicModule.forRoot(MyApp), AngularFireModule.initializeApp(firebaseConfig), AngularFireDatabaseModule, AngularFireAuthModule, IonicStorageModule.forRoot({ name: '__synerDb' }), NgCalendarModule, HttpModule, ConfrencePageModule ], bootstrap: [IonicApp], entryComponents: [ MyApp, ForgotPage, SignupTypePage, ConsumerSignupPage, ConsumerConditionsPage, EmailVerificationPage, ConsumerProfilePage, PractitionerSignupPage, PractitionerConditionsPage, DemographicPage, PersonalInfoPage, HealthInfoPage, UserProfilePage, ConsumerDashboardPage, PreferencesPage, ConsumerAppointmentsPage, ProductListPage, CartPage, OrderFinalPage, AddressPage, AddressListPage, ProductDetailsPage, UserListPage, HealthPage, RegisterKitPage, UserOptionsPage, CallControlBoxPage, PractitionerTabsPage, PractitionerOptionsPage, PractitionerProfilePage, PatientsPage, PractitionerAppointmentsPage, NotificationPage ], providers: [ StatusBar, SplashScreen, { provide: ErrorHandler, useClass: IonicErrorHandler }, AuthanticationServiceProvider, AppStateServiceProvider, UserDataPreloaderProvider, ConfrenceServiceProvider, NativeAudio, StorageHelperProvider, PayPal, Deeplinks, SocialSharing, Health, Camera, ImageProvider, BarcodeScanner, UserDataPreloaderProvider, SharedUtilsProvider ] }) export class AppModule { }<file_sep>import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { ConfrencePage } from './confrence'; @NgModule({ declarations: [ ConfrencePage, ], imports: [ IonicPageModule.forChild(ConfrencePage), ] }) export class ConfrencePageModule {} <file_sep>import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, Events, ViewController, App } from 'ionic-angular'; import { IProfile } from '../../../models/models'; import { AuthanticationServiceProvider, AppStateServiceProvider } from '../../../providers/providers'; import { LoginPage } from '../../auth/auth'; import { PractitionerProfilePage } from '../practitioner'; @IonicPage() @Component({ selector: 'page-practitioner-options', templateUrl: 'practitioner-options.html', }) export class PractitionerOptionsPage { menuItems: Array<any> = []; userProfImage: string = 'assets/imgs/chatterplace.png'; user: IProfile; constructor(public app: App, public navCtrl: NavController, public events: Events, public navParams: NavParams, public viewCtrl: ViewController, private authProvider: AuthanticationServiceProvider, private appState: AppStateServiceProvider) { events.subscribe('profile:recieved', profile => { if (profile !== undefined && profile !== "") { this.user = profile; if (this.user && this.user.profilePicUrl) { this.userProfImage = this.user.profilePicUrl; } } }) this.user = this.appState.userProfile; if (this.user && this.user.profilePicUrl) { this.userProfImage = this.user.profilePicUrl; } this.createMenuItems(); } ionViewDidLoad() { console.log('ionViewDidLoad UserOptionsPage'); } openPage(page) { if (page.type === 'page') { this.updateActive(); page.isActive = true; console.log(page.name); this.viewCtrl.dismiss().then(() => { this.app.getRootNav().push(page.component).catch(err => console.error(err)); //this.navCtrl.push(page.component).catch(err => console.error(err)); }); } else if (page.type.startsWith('action')) { this.doAction(page.type); } } doAction(action: string) { if (action === 'action:logout') { this.authProvider.logoutUser(); //this.navCtrl.popAll(); this.viewCtrl.dismiss().then(() => { this.navCtrl.setRoot(LoginPage).catch(err => console.error(err)); }); } } updateActive() { this.menuItems.forEach(page => { page.isActive = false; }) } createMenuItems() { this.menuItems = [ { icon: 'person', name: 'Profile', component: PractitionerProfilePage, type: 'page', isActive: false }, { icon: 'lock', name: 'Logout', component: '', type: 'action:logout', isActive: false }, ]; } } <file_sep>import { IProfile } from './../../../models/profile'; import { Component } from '@angular/core'; import { NavController, ModalController, FabContainer, MenuController, ToastController, LoadingController, PopoverController } from 'ionic-angular'; import { AngularFireAuth } from 'angularfire2/auth'; import { AuthanticationServiceProvider, AppStateServiceProvider } from '../../../providers/providers'; import { LoginPage } from '../../auth/auth'; import { ProductListPage, RegisterKitPage, UserOptionsPage } from '../consumer'; import { CallControlBoxPage } from '../../shared/shared'; @Component({ selector: 'page-dashboard', templateUrl: 'dashboard.html' }) export class DashboardPage { pageContent: any; userProfile: IProfile; userOrders: any[]; userKits: any; myCallerId: number = 0; private appState: any; incomingCallId; incomingCall: boolean = false; showRegisterKit: boolean = false; showBuyOption: boolean = true; showWaitingMessage: boolean = false; constructor(public navCtrl: NavController, private afAuth: AngularFireAuth, public modalCtrl: ModalController, private loadingCtrl: LoadingController, private toast: ToastController, private toastCtrl: ToastController, private menu: MenuController, private authProvider: AuthanticationServiceProvider, appState: AppStateServiceProvider, private popoverCtrl: PopoverController ) { this.appState = appState; } ionViewWillLoad() { let loadingPopup = this.loadingCtrl.create({ spinner: 'crescent', content: '' }); loadingPopup.present(); let removePop = true; try { this.afAuth.authState.subscribe(userAuth => { if (userAuth) { if (this.appState.userProfile) { this.userProfile = this.appState.userProfile; this.userOrders = this.appState.userOrders; this.userKits = this.appState.userKits; if (this.userOrders.length > 0) { this.showRegisterKit = true; this.showBuyOption = false; this.showWaitingMessage = false; } if (this.userKits) { this.showRegisterKit = false; this.showWaitingMessage = true; this.showBuyOption = true; } if (removePop) { loadingPopup.dismiss() removePop = false; } } else { console.log('User Profile not found'); if (removePop) { loadingPopup.dismiss() removePop = false; } this.navCtrl.setRoot(LoginPage); } } else { console.log('auth false'); if (removePop) { loadingPopup.dismiss() removePop = false; } this.navCtrl.setRoot(LoginPage); } }); } catch (error) { if (removePop) { loadingPopup.dismiss() removePop = false; } this.toast.create({ message: error.message, duration: 3000 }).present(); } } ionViewDidLoad() { this.menu.enable(true); } openModel(pageName, userList) { this.modalCtrl.create(pageName, null, { cssClass: 'inset-modal' }) .present(); } answerCall(inCallerId) { let modal = this.modalCtrl.create(CallControlBoxPage, { incommingCallerId: inCallerId }, { cssClass: 'inset-modal' }); modal.present(); } generateRandom(): number { var min = 11111111; var max = 99999999; return Math.floor(Math.random() * (max - min + 1) + min); } signOut(fab: FabContainer) { fab.close(); this.authProvider.logoutUser() .then(authData => { console.log("Logged out"); // toast message this.presentToast('bottom', 'You are now logged out'); this.navCtrl.setRoot(LoginPage); }, error => { var errorMessage: string = error.message; console.log(errorMessage); }); } presentToast(position: string, message: string) { let toast = this.toastCtrl.create({ message: message, position: position, duration: 3000 }); toast.present(); } openShoping() { this.navCtrl.push(ProductListPage); } registerKit() { this.navCtrl.push(RegisterKitPage) } presentPopover(event) { let popover = this.popoverCtrl.create(UserOptionsPage, { page: this.pageContent }) popover.present({ ev: event }); } } <file_sep>export * from './consumer-signup/consumer-signup'; export * from './consumer-conditions/consumer-conditions' export * from './consumer-profile/consumer-profile' export * from './practitioner-conditions/practitioner-conditions' export * from './practitioner-signup/practitioner-signup' export * from './signup-type/signup-type'
8e2c0b700cca83ddd5a4410fb82e8ccdbfe5be30
[ "Markdown", "TypeScript" ]
61
TypeScript
ashaqmir/SynerOme
6888047b9de603f09a279a8e4fb3ebb6a2ecfd86
7b3e7828afdbc0ca497c56263fac3bfeb62514c2
refs/heads/master
<repo_name>SanjeevKV/algotrading<file_sep>/Scrapers/capital_market_scoreboard.py from selenium import webdriver from selenium.webdriver.common.keys import Keys import numpy as np import pandas as pd import datetime def main(): profile = webdriver.FirefoxProfile() profile.set_preference("browser.download.folderList", 2) profile.set_preference("browser.download.manager.showWhenStarting", False) profile.set_preference("browser.download.dir", '/Users/300006804/Desktop/MyWork/algotrading/Downloads/') profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/csv;application/vnd.ms-excel.sheet.binary.macroenabled.12") driver = webdriver.Firefox(executable_path='/Library/geckodriver',firefox_profile=profile) driver.get('http://subscribers.capitalmarket.com/') userName = driver.find_element_by_name("UN") password = driver.find_element_by_name("PW") submit = driver.find_element_by_xpath("//input[@src='images/submit.gif']") userName.send_keys("SANK186") password.send_keys("<PASSWORD>") submit.click() driver.get('http://subscribers.capitalmarket.com/Index.asp') corporate_scoreboard=driver.find_element_by_xpath("//*[text()='Corporate Scoreboard']") corporate_scoreboard.click() companies = [] for i in range(2,35): driver.get('http://subscribers.capitalmarket.com/Index.asp') corporate_scoreboard=driver.find_element_by_xpath("//*[text()='Corporate Scoreboard']") corporate_scoreboard.click() industry = driver.find_element_by_xpath('/html/body/table/tbody/tr/td/center/table/tbody/tr/td[2]/table/tbody/tr[3]/td[1]/table[1]/tbody/tr[1]/td[2]/table[3]/tbody/tr['+str(i)+']/td[1]/a') print industry.text industry.click() total_rows = len(driver.find_elements_by_xpath('/html/body/table/tbody/tr/td/center/table/tbody/tr/td[2]/table/tbody/tr[3]/td/table/tbody/tr/td[2]/form/table[2]/tbody/tr')) for i in range(1,total_rows+1): if(i%19 < 1 or i%19 > 3): company = [] row = driver.find_elements_by_xpath('/html/body/table/tbody/tr/td/center/table/tbody/tr/td[2]/table/tbody/tr[3]/td/table/tbody/tr/td[2]/form/table[2]/tbody/tr['+str(i)+']/td') for data in row: company.append(data.text) companies.append(company) heads = open('headers.csv','r') columns = heads.readline().split(',') heads.close() df = pd.DataFrame(data=companies,columns=columns) instant = datetime.datetime.now() df.to_csv('CorporateScoreboard_'+instant.strftime("%Y_%m_%d")+'.csv') driver.close() if __name__ == '__main__': main()<file_sep>/Algorithms/InteractiveStepTradingTest.py import StepTrading as st import sys import ConfigParser if __name__ == '__main__': config_file = sys.argv[1] company_list = sys.argv[2] config = ConfigParser.ConfigParser() config.read(config_file) response = 0 while response != 7 : company = raw_input("Enter the symbol of the company:\n") response = input("1.Process LTP\n2.View historical orders\n3.View Buy orders\n4.View Sell orders\n5.Approve Buy orders\n6.Approve Sell orders\n7.Exit\n") if response == 1: st.process_current_price(config,company) elif response == 2: st.view_historical_orders(company) elif response == 3: st.view_pending_order(company,True) elif response == 4: st.view_pending_order(company,False) elif response == 5: price = float(raw_input("Input price\n")) quantity = input("Input quantity\n") st.approve_pending_order(company,True,price,quantity) elif response == 6: price = float(raw_input("Input price\n")) quantity = input("Input quantity\n") st.approve_pending_order(company,False,price,quantity) <file_sep>/Scrapers/bse_bulk_trading.py from selenium import webdriver from selenium.webdriver.common.keys import Keys def main(): profile = webdriver.FirefoxProfile() profile.set_preference("browser.download.folderList", 2) profile.set_preference("browser.download.manager.showWhenStarting", False) profile.set_preference("browser.download.dir", '/Users/300006804/Desktop/MyWork/algotrading/Downloads/') profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/csv;application/vnd.ms-excel.sheet.binary.macroenabled.12") driver = webdriver.Firefox(executable_path='/Library/geckodriver',firefox_profile=profile) driver.get('http://www.bseindia.com/markets/equity/EQReports/BulknBlockDeals.aspx') from_text = driver.find_element_by_id("ctl00_ContentPlaceHolder1_txtDate") to_text = driver.find_element_by_id("ctl00_ContentPlaceHolder1_txtToDate") all_market_tick = driver.find_element_by_id("ctl00_ContentPlaceHolder1_chkAllMarket") from_text.send_keys("23/01/2018") to_text.send_keys("25/01/2018") all_market_tick.click() submit_button = driver.find_element_by_id("ctl00_ContentPlaceHolder1_btnSubmit") submit_button.click() print driver.page_source download_button = driver.find_element_by_id("ctl00_ContentPlaceHolder1_btndownload1") download_button.click() driver.close() if __name__ == '__main__': main()<file_sep>/Tests/IntradayMA.py import os import sys import re import time class Statistics: def __init__(self,val): self.prev_val = val self.simple_mean = val self.simple_ma = val self.last_hour_ma = val self.day_ma = val def simple_statistics(self,val): '''Let us say we are getting the stock value every second we need to maintain a counter 3600 seconds and then update last_hour_average ''' if self.simple_mean == 0: self.simple_mean = val self.simple_mean = (self.simple_mean + val)/2.0 self.prev_val = val if time.localtime().tm_min == 0 and time.localtime().tm_sec==0 and time.localtime().tm_hour == 9: self.simple_mean = self.day_ma if time.localtime().tm_min == 0 and time.localtime().tm_sec==0 and time.localtime().tm_hour >= 9 and time.localtime().tm_hour <= 17: self.last_hour_ma = self.simple_mean if time.localtime().tm_min == 0 and time.localtime().tm_sec==0 and time.localtime().tm_hour == 18: self.day_ma = self.last_hour_ma x = Statistics(0.0) list = [6, 7, 9, 5, 8, 6, 9] for i in list: x.simple_statistics(i) print x.simple_mean, x.last_hour_ma, x.day_ma <file_sep>/Tests/MaxProfit.py import os import sys import re def max_profit(array): mx_profit = 0 min_so_far = array[0] good_sprice = 0 for ind in range(0,len(array)): sprice = array[ind] if sprice < min_so_far: min_so_far = sprice min_so_far_ind = ind mx_profit_here = sprice - min_so_far if mx_profit_here > mx_profit: mx_profit = mx_profit_here good_sprice_ind = ind good_bprice_ind = min_so_far_ind print "Good buy and sell prices indexes",good_bprice_ind, good_sprice_ind return mx_profit if __name__ == '__main__': filename = sys.argv[1] with open(filename) as file: cnt = 0 for line in file: if re.match("Sample",line): cnt += 1 list = [] elif(re.match(" ",line)): pass elif re.match("End",line): print "Sample ",cnt print "Max stock price is ",max(list), print "Min stock price is ",min(list) print "Max profit that can be booked ",max_profit(list) else: list = [int(stk_price) for stk_price in line.split(',')] <file_sep>/README.md # AlgoTrading The main aim of the project is to get a continuous and reliable profit using algorithms for making trading decisions on BSE and NSE. # Naming Convention 1. module_name 2. package_name 3. ClassName 4. method_name 5. ExceptionName 6. function_name 7. GLOBAL_CONSTANT_NAME 8. global_var_name 9. instance_var_name 10. function_parameter_name 11. local_var_name # RoadMap Step 1: Build modules to use kite APIs and make necessary actions possible Step 2: Use a simple testFile to test the functions in the modules Step 3: Implement a simple algorithm to make smart trading decisions Step 4: Test the effectiveness of the algorithm on sample data Step 5: Decide the machine on which the algorithm runs eternally Step 6: Get the API access from Zerodha and deploy the repository on the decided machine and monitor the live trading # Improvements 1. Algorithm used to make the decision can be improved 2. Hack-around the dependency on Zerodha 3. If the algorithms are successful, we can expose some functionalities as FaaS (Functionality as a Service) # Algorithm 1 - StepDeals Step 1: Identify N(potentially successful) companies to invest on Step 2: Divide the initial Principal(P) into N parts Pi Step 3: Let's say Invest-Reserve ratio is Ri Step 4: Buy (Pi * Ri) worth of shares in the company 'i' for delivery with limit order at LTPi Step 5: Define Step % for every company Si 1. Increasing function LTPi 1. A lot Lj is already bought at LTPi and a lot Lj-1 is already bought at LTPi - LTPi * Si / 100 : Sell the lots Lk where 0 < k < j 2. A lot Lj-1 is bought at (L-1)TPi but not Lj at LTPi : Buy the lot Lj at (L-1)TPi + (L-1)TPi * Si / 100 2. Decreasing function LTPi 1. A lot Lj is already bought at LTPi : Sell all the lots Lk where 0 < k < j 2. A lot Lj is not already bought at LTPi : Buy a lot at LTPi<file_sep>/Algorithms/StepTrading.py import ConfigParser import sys import pandas as pd import os import math import random history_location = '../History/' buy_orders_location = '../Orders/Buy/' sell_orders_location = '../Orders/Sell/' bought_orders_location = '../Orders/Bought/' sold_orders_location = '../Orders/Sold/' extension = '.csv' def get_historical_orders_from_file(company): ''' Returns a dataFrame containing all the information about active lots from a file :param company: :return: ''' df = pd.read_csv(history_location+company+extension) if os.path.isfile(history_location + company + extension) else \ pd.DataFrame(columns=["symbol","buy_price","quantity","selling_price_threshold","trigger_price","trigger"]) return df def get_historical_orders(company,storage): ''' Returns a dataFrame containing all the information about active lots from any storage interface :param company: :param storage: :return: ''' if storage == 1: df = get_historical_orders_from_file(company) df.sort_values('buy_price',ascending=True,inplace=True) df['cumulative_quantity'] = df['quantity'].cumsum() return df def get_current_price(company): ''' Returns the LTP of a particular company - Real time :param company: :return: ''' current_price = float(raw_input("LTP of " + company + " :")) return current_price def get_orders_in_range(config,historical_orders,company,current_price): ''' Only active orders within a certain %age of LTP are returned :param config: :param historical_orders: :param company: :param current_price: :return: ''' orders_in_range = historical_orders[(historical_orders['buy_price'] > (current_price - current_price * float(config.get("RANGE",company)))) & (historical_orders['selling_price_threshold'] < (current_price + current_price * float(config.get("RANGE",company))))] return orders_in_range def set_new_global_triggers(historical_orders,current_price): ''' Trigger for a particular lot is set whenever the LTP is greater than the lot's trigger_price :param historical_orders: :param current_price: :return: ''' for i in range(len(historical_orders)): if current_price > historical_orders['trigger_price'][i]: historical_orders.iloc[i,list(historical_orders.columns).index('trigger')] = True def set_new_range_triggers(orders_in_range): ''' 1. Trigger for a lot is set when there are no lots at a lesser price but at least one lot with higher price 2. Trigger for a lot is set when there are at least 2 lots with higher price :param orders_in_range: :return: ''' print orders_in_range print len(orders_in_range) orders_in_range.reset_index(inplace=True) for i in range(len(orders_in_range)): if len(orders_in_range[orders_in_range['selling_price_threshold'] > orders_in_range['selling_price_threshold'][i]]) > 0 and len(orders_in_range[orders_in_range['buy_price'] < orders_in_range['buy_price'][i]]) < 1: orders_in_range.iloc[i,list(orders_in_range.columns).index('trigger')] = True if len(orders_in_range[orders_in_range['selling_price_threshold'] > orders_in_range['selling_price_threshold'][i]]) > 1: orders_in_range.iloc[i,list(orders_in_range.columns).index('trigger')] = True def set_sell_orders(config,company,historical_orders,current_price): ''' Sell orders are placed for a lot only when the lot is triggered to be sold 1. Sell the lot if triggered even if the current_price is lower than the selling_price_threshold 2. If there are lots with selling_price_threshold < current_price place a consolidated single sell order :param historical_orders: :param current_price: :return: ''' if not os.path.isfile(sell_orders_location + company + '.csv'): print "The file for the company " + company + "does not exist, filling with only columns" df = pd.DataFrame(columns=["order_id","quantity","sell_price","sltp"]) df.to_csv(sell_orders_location + company + ".csv" ,index=False) lots_sellable = len(historical_orders[historical_orders['selling_price_threshold'] < current_price]) print "*********************" pending_sell_order = pd.read_csv(sell_orders_location + company + '.csv') pending_sell_price = pending_sell_order['sell_price'][0] if len(pending_sell_order) > 0 else -1 if len(historical_orders) > 0: if lots_sellable == 0: if historical_orders['trigger'][0] == True: print "Sell the first lot with LP : " , historical_orders['selling_price_threshold'][0] , "and SLTP : " , \ historical_orders['trigger_price'][0] if pending_sell_price != historical_orders['selling_price_threshold'][0]: place_new_sell_order(config,company,historical_orders['selling_price_threshold'][0],historical_orders["cumulative_quantity"][0]) else: print "Nothing to sell for now" else: print "Sell the " , lots_sellable , "lots with a cumulative shares of " , historical_orders["cumulative_quantity"][lots_sellable-1] , " at a LP of " , historical_orders['selling_price_threshold'][lots_sellable-1] , " and a SLTP of " , \ historical_orders['trigger_price'][lots_sellable-1] if pending_sell_price != historical_orders['selling_price_threshold'][lots_sellable-1]: place_new_sell_order(config,company,historical_orders['selling_price_threshold'][lots_sellable-1],historical_orders["cumulative_quantity"][lots_sellable-1]) def place_new_buy_order(config,company,buy_price): ''' Erases the existing buy orders of a company and places a new buy order :param config: :param company: :param buy_price: :return: ''' df = pd.DataFrame(columns=["order_id","quantity","buy_price","sltp"]) current_lot_worth = float(config.get("PRINCIPAL",company)) * float(config.get("IRR",company)) current_lot_size = math.floor(current_lot_worth/buy_price) sltp = buy_price - buy_price * float(config.get("TRIGGER_LIMIT",company)) #API call to place order order = [random.randint(0,10),current_lot_size,buy_price,sltp] df.loc[0] = order df.to_csv(buy_orders_location + company + '.csv',index=False) def place_new_sell_order(config,company,sell_price,quantity): ''' Place sell order after removing the existing sell orders :param config: :param company: :param sell_price: :param quantity: :return: ''' df = pd.DataFrame(columns=["order_id","quantity","sell_price","sltp"]) sltp = sell_price + sell_price * float(config.get("TRIGGER_LIMIT",company)) #API call to place sell order and cancel the existing one order = [random.randint(0,10),quantity,sell_price,sltp] df.loc[0] = order df.to_csv(sell_orders_location + company + '.csv',index=False) def set_buy_orders(config,company,orders_in_range,current_price): ''' 1. Do not buy if there are higher as well as lower orders 2. Buy at the current price if there are no higher or lower orders 3. Buy at a lower price if there is only a lot at higher price 4. Buy at a higher price if there is only a lot at lower price :param config: :param company: :param orders_in_range: :param current_price: :return: ''' lower_orders = orders_in_range[orders_in_range["buy_price"] < current_price] higher_orders = orders_in_range[orders_in_range["buy_price"] > current_price] lowest_high = min(higher_orders["buy_price"]) if len(higher_orders) > 0 else -1 highest_low = max(lower_orders["buy_price"]) if len(lower_orders) > 0 else -1 print "###########",lowest_high,highest_low if not os.path.isfile(buy_orders_location + company + '.csv'): print "The file for the company " + company + "does not exist, filling with only columns" df = pd.DataFrame(columns=["order_id","quantity","buy_price","sltp"]) df.to_csv(buy_orders_location + company + ".csv" ,index=False) pending_buy_order = pd.read_csv(buy_orders_location + company + '.csv') pending_buy_price = pending_buy_order['buy_price'][0] if len(pending_buy_order) > 0 else -1 if lowest_high > 0 and highest_low > 0: print "Nothing to buy at the moment" elif highest_low == -1 and lowest_high == -1: print "Buy at current_price as LP" if pending_buy_price != current_price: place_new_buy_order(config,company,current_price) elif highest_low == -1: print "Buy a lot at ", (lowest_high - lowest_high * float(config.get("PRICE_DELTA",company))), " of " , (float(config.get("PRINCIPAL",company)) * float(config.get("IRR",company))) / (lowest_high - lowest_high * float(config.get("PRICE_DELTA",company))) if pending_buy_price != (lowest_high - lowest_high * float(config.get("PRICE_DELTA",company))): place_new_buy_order(config,company,lowest_high - lowest_high * float(config.get("PRICE_DELTA",company))) else: print "Buy a lot at ", (highest_low + highest_low * float(config.get("PRICE_DELTA",company))), " of " , (float(config.get("PRINCIPAL",company)) * float(config.get("IRR",company))) / (highest_low - highest_low * float(config.get("PRICE_DELTA",company))) if pending_buy_price != (highest_low + highest_low * float(config.get("PRICE_DELTA",company))): place_new_buy_order(config,company,highest_low + highest_low * float(config.get("PRICE_DELTA",company))) def process_current_price(config,company): ''' Steps to be taken when LTP is refreshed :param config: :param company: :return: ''' current_price = get_current_price(company) #API call to get the LTP process_approved_buy_orders(config,company) process_approved_sell_orders(company) historical_orders = get_historical_orders(company,1) orders_in_range = get_orders_in_range(config,historical_orders,company,current_price) set_new_global_triggers(historical_orders,current_price) set_new_range_triggers(orders_in_range) historical_orders.to_csv(history_location + company + extension,index=False) #Write after the triggers are set set_sell_orders(config,company,historical_orders,current_price) set_buy_orders(config,company,orders_in_range,current_price) def process_approved_buy_orders(config,company): #API call to check the success of order_id and the following code is executed only in case of success df = pd.read_csv(bought_orders_location + company + extension) if os.path.isfile(bought_orders_location + company + extension) else [] historical_orders = get_historical_orders(company,1) historical_orders = historical_orders[["symbol","buy_price","quantity","selling_price_threshold","trigger_price","trigger"]] if len(df) > 0: buy_price = df["price"][0] quantity = df["quantity"][0] selling_price_threshold = buy_price + buy_price * float(config.get("PRICE_DELTA",company)) trigger_price = selling_price_threshold + selling_price_threshold * float(config.get("TRIGGER_LIMIT",company)) * float(config.get("TRIGGER",company)) historical_orders.loc[len(historical_orders)] = [company,buy_price,quantity,selling_price_threshold,trigger_price,False] historical_orders.to_csv(history_location + company + extension,index=False) df = pd.DataFrame(columns=["symbol","price","quantity"]) df.to_csv(bought_orders_location + company + extension, index=False) def view_pending_order(company,buy): if buy: df = pd.read_csv(buy_orders_location + company + extension) if os.path.isfile(buy_orders_location + company + extension) else \ pd.DataFrame(columns=["order_id","quantity","buy_price","sltp"]) print df else: df = pd.read_csv(sell_orders_location + company + extension) if os.path.isfile(sell_orders_location + company + extension) else \ pd.DataFrame(columns=["order_id","quantity","sell_price","sltp"]) print df def view_historical_orders(company): historical_orders = get_historical_orders(company,1) print historical_orders def approve_pending_order(company,buy,price,quantity): df = pd.DataFrame(data=[[company,price,quantity]],columns=["symbol","price","quantity"]) if buy: df.to_csv(bought_orders_location + company + extension,index=False) df = pd.DataFrame(columns=["order_id","quantity","buy_price","sltp"]) df.to_csv(buy_orders_location + company + ".csv" ,index=False) else: df.to_csv(sold_orders_location + company + extension, index=False) df = pd.DataFrame(columns=["order_id","quantity","sell_price","sltp"]) df.to_csv(sell_orders_location + company + ".csv" ,index=False) def process_approved_sell_orders(company): df = pd.read_csv(sold_orders_location + company + extension) if os.path.isfile(sold_orders_location + company + extension) else [] historical_orders = get_historical_orders(company,1) if len(df) > 0: quantity = df["quantity"][0] historical_orders_to_retain = historical_orders[historical_orders["cumulative_quantity"] > quantity] historical_orders_to_retain = historical_orders_to_retain[["symbol","buy_price","quantity","selling_price_threshold","trigger_price","trigger"]] historical_orders_to_retain.to_csv(history_location + company + extension,index=False) df = pd.DataFrame(columns=["symbol","price","quantity"]) df.to_csv(sold_orders_location + company + extension, index=False) if __name__ == '__main__': ''' Driver Program ''' config_file = sys.argv[1] company_list = sys.argv[2] config = ConfigParser.ConfigParser() config.read(config_file) companies = config.get("COMPANIES",company_list).split(',') for company in companies: process_current_price(config,company)
9541cf55571419fc28a0e89ad625828f94be5ab0
[ "Markdown", "Python" ]
7
Python
SanjeevKV/algotrading
c45053f846a330a45a642031cdb19b1e59ac6278
2bc59248c131e58b48accc8c283747caffd552ab
refs/heads/master
<file_sep>package coroutines.practice.oncompletion import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.* import kotlinx.coroutines.runBlocking fun foo() = flow { emit(1) throw RuntimeException() } /** * onCompletion is just like 'finally' in try/catch block. It's used for executing an action when * the flow collection completes. It can also be used to determine whether flow collection completed * normally or with exception as shown in this example. if the cause is null then that means it * completed normally. The onCompletion operator, unlike catch, does not handle the exception. */ @ExperimentalCoroutinesApi fun main() = runBlocking { foo() .onCompletion { cause -> if (cause != null) println("Completed with exception: $cause") } .catch { cause -> println("Exception occurred $cause") } .collect { println(it) } }<file_sep>package abc.anydiff123.flowOn import log import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext @ExperimentalCoroutinesApi fun fooFlowOn() = flow { log("starting flow") for ( i in 1..3) { log("Emitting $i") emit(i) } }.flowOn(Dispatchers.Default) /** * Since fooFlow().collect() is called from worker thread, the body of the flow is also called * in the worker thread. */ @ExperimentalCoroutinesApi fun main() = runBlocking { log("Before changing the context.") fooFlowOn().collect { log("Collected $it") } }<file_sep>package coroutines.practice.channel.fanout import kotlinx.coroutines.* import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.channels.produce @ExperimentalCoroutinesApi fun CoroutineScope.produceNumbers() = produce { var x = 0 while (true) { send(x++) } } fun CoroutineScope.launchProcessor(id: Int, channel: ReceiveChannel<Int>) = launch { for (message in channel) { println("Processor: $id, received: $message") } } @ExperimentalCoroutinesApi fun main() = runBlocking { val producer = produceNumbers() repeat(5) { launchProcessor(it, producer) } delay(1000) producer.cancel() }<file_sep>package coroutines.practice.debounce import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.delay import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.conflate import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.flow import kotlinx.coroutines.runBlocking import kotlin.system.measureTimeMillis fun foo() = flow { emit(1) delay(1000) emit(2) delay(500) emit(3) delay(600) emit(4) delay(1000) emit(5) delay(1000) emit(6) delay(1000) emit(7) } @FlowPreview @ExperimentalCoroutinesApi fun main() = runBlocking { val time = measureTimeMillis { foo() .debounce(1000) .collect { println("Collected: $it") } } println("Completed in $time ms") }<file_sep>import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.flow import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext fun log(message: String) = println("${Thread.currentThread().name} : $message") fun fooFlow() = flow { log("starting flow") for ( i in 1..3) { emit(i) } } /** * Since fooFlow().collect() is called from worker thread, the body of the flow is also called * in the worker thread. */ fun main() = runBlocking { log("Before changing the context.") withContext(Dispatchers.Default) { fooFlow().collect { log("Collected $it") } } } <file_sep>import kotlinx.coroutines.* /** * runBlocking and coroutineScope may look similar because they both wait for its body and all its * children to complete. The main difference between these two is that the runBlocking method blocks * the current thread for waiting, while coroutineScope just suspends, releasing the underlying * thread for other usages. Because of that difference, runBlocking is a regular function and * coroutineScope is a suspending function. */ fun main() = runBlocking { // this: CoroutineScope launch { delay(50L) println("Task from runBlocking") } coroutineScope { // Creates a coroutine scope launch { delay(75L) println("Task from nested launch") } delay(100L) println("Task from coroutine scope") // This line will be printed before the nested launch } println("Coroutine scope is over") // This line is not printed until the nested launch completes }<file_sep>package generatorfor.controlflow /** * Generator can be used to control the execution of the program flow from outside. * The function allows to pause its execution and pass control(fate) of the remainder of the * function execution to the caller. */ fun controlProgramFlow() = sequence { println("Execution started") yield(0) println("Execution resumed") yield(1) println("Execution resumed") } fun main() { val controlIterator = controlProgramFlow().iterator() println(controlIterator.next()) println(controlIterator.next()) // Throws Exception if no more elements. Use hasNext() to check. // println(controlIterator.next()) }<file_sep>package coroutines.practice.catchoperator import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.InternalCoroutinesApi import kotlinx.coroutines.flow.* import kotlinx.coroutines.runBlocking fun foo() = flow { for (i in 1..3) { println("Emitting $i") emit(i) } } @ExperimentalCoroutinesApi fun main() = runBlocking { foo() .onEach { value -> check(value <= 1) println(value) } .catch { println("Caught $it") } .collect() }<file_sep>import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.delay import kotlinx.coroutines.flow.* import kotlinx.coroutines.runBlocking fun getDetails(id: Int) = flow { emit("<NAME> $id") delay(500) emit("last name $id") } /** * Sometimes you have a situation where you receive a value from a Flow and you have to pass that * value to get another Flow. For example here, from a Flow of IDs 1,2,3, you want to receive * details for each of those IDs. So you pass each ID again to the getDetails function to receive * another Flow of values. In such cases you end up having Flow of Flow i.e. Flow<Flow<String>>. * * In this case you use flatMapConcat { } or flatMapMerge { } to flatten it to receive Flow<String>. * flatMapConcat { } waits for inner flow to complete before starting to collect the next one. * Here getDetails() is the inner Flow. */ @FlowPreview fun main() = runBlocking { val startTime = System.currentTimeMillis() (1..3).asFlow().onEach { delay(100) } .flatMapConcat { getDetails(it) } .collect { println("$it in ${System.currentTimeMillis() - startTime} ms") } }<file_sep>package kotlinx.coroutines.guide.exampleFlow02 /** * The foo() function that we created here is like a generator function in Javascript. * In Kotlin, generator functions are created using [Sequence] and yield(). * yield() is a suspending function. When the next() method is called on the Iterator object, * the function that calls yield() function, returns the value passed to the yield() function * and gets suspended at that point. It is resumed when the next() function is called on Iterator * object again. * * So, think of the yield() function as "return, and next time start from where you stopped". * This is how lazy iterators are created. * These can also be used to create infinite elements unlike collections. */ fun foo(): Sequence<Int> = sequence { // sequence builder for (i in 1..3) { Thread.sleep(100) // pretend we are computing it yield(i) // yield next value } } fun controlProgramFlow() = sequence { println("Execution started") yield(0) println("Execution resumed") yield(1) println("Execution resumed") } fun main() { val iterator = foo().iterator() println(iterator.next()) // 1 println(iterator.next()) // 2 println(iterator.next()) // 3 //foo().forEach { value -> println(value) } val controlIterator = controlProgramFlow().iterator() println(controlIterator.next()) println(controlIterator.next()) }<file_sep>import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.delay import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.conflate import kotlinx.coroutines.flow.flow import kotlinx.coroutines.runBlocking import kotlin.system.measureTimeMillis fun fooConflate() = flow { for (i in 1..3) { delay(100) // Asynchronously waiting emit(i) } } /** * conflate operator can be used to skip the intermediate values, when the collector is slow to process the values. * Only most recent value that's emitted gets collected. */ @ExperimentalCoroutinesApi fun main() = runBlocking { val time = measureTimeMillis { fooConflate() .conflate() .collect { delay(300) // Processing the value slow. println("Collected: $it") } } println("Completed in $time ms") }<file_sep>import kotlinx.coroutines.async import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking import kotlin.system.measureTimeMillis fun main() = runBlocking { val time = measureTimeMillis { // These functions are executed sequentially and execute in 2000 ms, if we don't use async-await. val one = async { doSomethingUsefulOne() } val two = async { doSomethingUsefulTwo() } println("result: ${one.await() + two.await()}") } println("Time taken: $time") } suspend fun doSomethingUsefulOne(): Int { delay(1000L) return 12 } suspend fun doSomethingUsefulTwo(): Int { delay(1000L) return 18 } <file_sep>import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.take import kotlinx.coroutines.runBlocking fun numbers() = flow { try { emit(1) emit(2) println("This line will not be reached.") emit(3) } catch (e: Exception) { println(e.printStackTrace()) } finally { println("Inside finally") } } @ExperimentalCoroutinesApi fun main() = runBlocking { numbers().take(2).collect { println(it) } }<file_sep>package coroutines.practice.flatmaplatest import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.delay import kotlinx.coroutines.flow.* import kotlinx.coroutines.runBlocking fun getDetails(id: Int) = flow { emit("first name $id") delay(500) emit("last name $id") } /** * flatMapLatest { } is similar to the the collectLatest { } but its used for Flow of Flow. * For example Flow<Flow<String>> in this case. It will consider only the latest ID flow and fetch * values for the latest ID. It cancels all the code in its block on a new value. */ @ExperimentalCoroutinesApi @FlowPreview fun main() = runBlocking { val startTime = System.currentTimeMillis() (1..3).asFlow().onEach { delay(100) } .flatMapLatest { delay(300); getDetails(it) } .collect { println("$it in ${System.currentTimeMillis() - startTime} ms") } }<file_sep>package abc.anydiff123.flowmap import kotlinx.coroutines.delay import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.map import kotlinx.coroutines.runBlocking suspend fun performRequest(request: Int): String { delay(1000) return "request: $request" } /** * Just like collections and sequences, flows can be transformed with operators like map(), filter(). * Key difference between operators of sequences and operators of Flows is that the blocks of code inside operators of * Flow can call suspending functions. * * In this example, A Flow of incoming requests is mapped to the results with the map() operator, even when performing * a request is a long running operation. And this long running operation is implemented by a suspending function. */ fun main() = runBlocking { (1..3).asFlow() .map { request -> performRequest(request) } .collect { println(it) } }
36b83251d8749d3d5f0c484ce685a3fd1968b0db
[ "Kotlin" ]
15
Kotlin
YogeshUmeshVaity/kotlin-coroutines-language-guide-practice
f729710a0c7044c20da0e455201bb12b4438e6e3
3d4eea77e74c743d3757dbbfcaf1cd66b0c11511
refs/heads/master
<repo_name>Evolver90/LanguageGenetics<file_sep>/tree/Tag.java package tree; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; public enum Tag { START { @Override public String toString() { return "START"; } }, CC { @Override public String toString() { return "CC"; } }, CD { @Override public String toString() { return "CD"; } }, DT { @Override public String toString() { return "DT"; } }, EX { @Override public String toString() { return "EX"; } }, FW { @Override public String toString() { return "FW"; } }, IN { @Override public String toString() { return "IN"; } }, JJ { @Override public String toString() { return "JJ"; } }, JJR { @Override public String toString() { return "JJR"; } }, JJS { @Override public String toString() { return "JJS"; } }, LS { @Override public String toString() { return "LS"; } }, MD { @Override public String toString() { return "MD"; } }, NN { @Override public String toString() { return "NN"; } }, NNS { @Override public String toString() { return "NNS"; } }, NNP { @Override public String toString() { return "NNP"; } }, NNPS { @Override public String toString() { return "NNPS"; } }, PDT { @Override public String toString() { return "PDT"; } }, POS { @Override public String toString() { return "POS"; } }, PRP { @Override public String toString() { return "PRP"; } }, PRP$ { @Override public String toString() { return "PRP$"; } }, RB { @Override public String toString() { return "RB"; } }, RBR { @Override public String toString() { return "RBR"; } }, RBS { @Override public String toString() { return "RBS"; } }, RP { @Override public String toString() { return "RP"; } }, SYM { @Override public String toString() { return "SYM"; } }, TO { @Override public String toString() { return "TO"; } }, UH { @Override public String toString() { return "UH"; } }, VB { @Override public String toString() { return "VB"; } }, VBD { @Override public String toString() { return "VBD"; } }, VBG { @Override public String toString() { return "VBG"; } }, VBN { @Override public String toString() { return "VBN"; } }, VBP { @Override public String toString() { return "VBP"; } }, VBZ { @Override public String toString() { return "VBZ"; } }, WDT { @Override public String toString() { return "WDT"; } }, WP { @Override public String toString() { return "WP"; } }, WP$ { @Override public String toString() { return "WP$"; } }, WRB { @Override public String toString() { return "WRB"; } }; private static final List<Tag> tags = Collections.unmodifiableList(Arrays.asList(values())); private static final int tagSize = tags.size(); private final static Random random = new Random(); private Tag[] tagGroup; static { START.tagGroup = new Tag[]{}; CC.tagGroup = new Tag[]{Tag.CD}; CD.tagGroup = new Tag[]{Tag.CC}; JJ.tagGroup = new Tag[]{Tag.JJR, Tag.JJS}; JJR.tagGroup = new Tag[]{Tag.JJ, Tag.JJS}; JJS.tagGroup = new Tag[]{Tag.JJ, Tag.JJR}; NN.tagGroup = new Tag[]{Tag.NNS, Tag.NNP, Tag.NNPS}; NNS.tagGroup = new Tag[]{Tag.NN, Tag.NNP, Tag.NNPS}; NNP.tagGroup = new Tag[]{Tag.NN, Tag.NNS, Tag.NNPS}; NNPS.tagGroup = new Tag[]{Tag.NN, Tag.NNS, Tag.NNP}; PDT.tagGroup = new Tag[]{Tag.POS, Tag.PRP, Tag.PRP$}; POS.tagGroup = new Tag[]{Tag.PDT, Tag.PRP, Tag.PRP$}; PRP.tagGroup = new Tag[]{Tag.PDT, Tag.POS, Tag.PRP$}; PRP$.tagGroup = new Tag[]{Tag.PDT, Tag.POS, Tag.PRP}; RB.tagGroup = new Tag[]{Tag.RBR, Tag.RBS, Tag.RP}; RBR.tagGroup = new Tag[]{Tag.RB, Tag.RBS, Tag.RP}; RBS.tagGroup = new Tag[]{Tag.RB, Tag.RBR, Tag.RP}; RP.tagGroup = new Tag[]{Tag.RB, Tag.RBR, Tag.RBS}; VB.tagGroup = new Tag[]{Tag.VBD, Tag.VBG, Tag.VBN, Tag.VBP, Tag.VBZ}; VBD.tagGroup = new Tag[]{Tag.VB, Tag.VBG, Tag.VBN, Tag.VBP, Tag.VBZ}; VBG.tagGroup = new Tag[]{Tag.VB, Tag.VBD, Tag.VBN, Tag.VBP, Tag.VBZ}; VBN.tagGroup = new Tag[]{Tag.VB, Tag.VBD, Tag.VBG, Tag.VBP, Tag.VBZ}; VBP.tagGroup = new Tag[]{Tag.VB, Tag.VBD, Tag.VBG, Tag.VBN, Tag.VBZ}; VBZ.tagGroup = new Tag[]{Tag.VB, Tag.VBD, Tag.VBG, Tag.VBN, Tag.VBP}; WDT.tagGroup = new Tag[]{Tag.WP, Tag.WP$, Tag.WRB}; WP.tagGroup = new Tag[]{Tag.WDT, Tag.WP$, Tag.WRB}; WP$.tagGroup = new Tag[]{Tag.WDT, Tag.WP, Tag.WRB}; WRB.tagGroup = new Tag[]{Tag.WDT, Tag.WP, Tag.WP$}; } public boolean sameGroup(Tag otherTag) { if(Arrays.asList(tagGroup).contains(otherTag) || this == otherTag) { return true; } return false; } public static Tag randomTag(Tag oldTag) { Tag newTag = tags.get(random.nextInt(tagSize)); while(newTag == oldTag || newTag == Tag.START) { newTag = tags.get(random.nextInt(tagSize)); } return newTag; } } <file_sep>/articles/ArticleExtractor.java package articles; import java.io.File; import java.io.IOException; public class ArticleExtractor { private String pathWiki = "C:\\Users\\Milan\\Desktop\\School\\CUHK\\AI\\Paper\\LanguageGenetics\\wikipedia_test.txt"; public ArticleExtractor() { } public void getArticles(ArticleDB articleDB) throws IOException { File file = new File(pathWiki); ArticleParser parser = new ArticleParser(file); while(parser.hasNext()) { Article article = parser.next(); articleDB.addArticle(article.getWeight(), article); } parser.close(); } } <file_sep>/population/Population.java package population; import java.util.ArrayList; import java.util.List; import tree.Tree; public class Population { private List<Tree> population; private static Population instance = null; public static Population getInstance() { if(instance == null) { instance = new Population(); } return instance; } private Population() { population = new ArrayList<Tree>(); } public void removeMember(Tree member) { population.remove(member); } public void addMember(Tree member) { population.add(member); } public List<Tree> getPopulation() { return population; } }
307b3e01a0a1dfc09f95d2ddb57b3a9cd48f57e8
[ "Java" ]
3
Java
Evolver90/LanguageGenetics
e21932cfe717966a11b84d40d9ba17396418a43e
ffaf1ffb1c590858370116ae7acaac4c93b5703b
refs/heads/main
<repo_name>OnlyTense/DiscordJS-Bot<file_sep>/Commands/ping.js module.exports = { name: "ping", description: "This is a ping command!", execute(message, args, Discord, client){ message.channel.send('Pong!') const Embed = new Discord.MessageEmbed() .addField("My Latency is:", `> ${Date.now() - message.createdTimestamp}ms`) .setColor("RANDOM") .setThumbnail('https://media.discordapp.net/attachments/798594125712326737/808933236507017236/ff8c49a85b7fbda0110c66353a9db71e.png') message.channel.send(Embed); } } <file_sep>/Commands/meme.js const { MessageEmbed } = require('discord.js'); const somethingRandom = require('some-random-cat').Random const subreddits = [ "meme", "memes", "dankmemes" ] module.exports = { name: "meme", description: "This is a meme command!", execute(message, args, Discord, client){ let randomSubReddit = subreddits[Math.floor(Math.random() * subreddits.length)] somethingRandom.getMeme(randomSubReddit).then(res => { const embed = new MessageEmbed() .setTitle(res.title) .setURL(`https://www.reddit.com/r/${randomSubReddit}`) .setImage(res.img) .setFooter(`👍 ${res.upvotes} | 💬 ${res.comments}`) .setAuthor(`From u/${res.author}`) .setColor('RANDOM') message.channel.send(embed) console.log(res) }).catch(e => message.channel.send('API Error.')) } }<file_sep>/Commands/coinflip.js module.exports = { name: "coinflip", description: "This is a coinflip command!", execute(message, args, Discord, client){ let choice = Math.floor(Math.random() * 2) if(choice === 0) return message.reply('It was heads!') if(choice === 1) return message.reply('It was tails!') } }<file_sep>/Commands/botstats.js const time = require('ms') let os = require ('os').platform();; let cpu = require ('os').cpus()[0].model;; module.exports = { name: "botstats", description: "This is a botstats command!", execute(message, args, Discord, client){ let inline = true const uptime = time(client.uptime) message.channel.send('These are my statistics.') const Embed = new Discord.MessageEmbed() .addField("My Latency is:", `> ${Date.now() - message.createdTimestamp}ms`) .addField("My API Latency is:", `> ${Math.round(client.ws.ping)}ms`) .addField("My OS is:", `> ${os}`) .setColor("RANDOM") .setThumbnail("https://media.discordapp.net/attachments/798594125712326737/808783195940192296/b67e65c2ab0428da786c1f53ebfd4243.png") .addField('I have been up for:', `> ${uptime}`) .addField("My CPU is:", `> ${cpu}`) message.channel.send(Embed); } } <file_sep>/README.md # Discord.JS, Open-Source, Free to Use Bot ## Introduction > This bot was made with the idea that people should be able to have a great starting point went making a Discord.JS bot. ## Credit > All credit goes to @OnlyTense (me) for this repository although not all code is mine.
35979f6039183658be5ba72646aab537b09af1d1
[ "JavaScript", "Markdown" ]
5
JavaScript
OnlyTense/DiscordJS-Bot
b12ea3762ca01a031175404c2136bb9342207803
b920e723db25c7715fa9cc6e1fce32bad0057b92
refs/heads/master
<repo_name>rmnppt/codeclan<file_sep>/BBall_kNN.R ###-----------------------------------------------------------------------### ### Predicting the salaries of baseball players with k nearest neighbours ### ###-----------------------------------------------------------------------### # "Introduction to statistical learning" # - Fantastic book, must read for machine learning intro # - get the pdf for free! http://www-bcf.usc.edu/~gareth/ISL/ library(ISLR) # extensive and powerful plotting library # find more here http://ggplot2.org/ and countless online tutorials library(ggplot2) # 1. Explore # ---------- # we will analyse a dataset called 'Hitters', # lets explore it and see whats inside ?Hitters class(Hitters) head(Hitters) str(Hitters) summary(Hitters) ?class # we want to predict the salary so lets see what its distribution is hist(log10(Hitters$Salary), breaks = 30) ?hist # note that salary is given in thousands of dollars, # you can check with ?Hitters # a prettier plot with ggplot ggplot(Hitters, aes(x = log10(Salary))) + geom_histogram() # what variables might be correlated with the salary? ggplot(Hitters, aes(x = Years, y = Hits)) + geom_point(aes(colour = log10(Salary))) # 2. Data Munging! # ---------------- # creating a new object, a new df that contains only the # predictors of interest predictors <- data.frame( hits = Hitters$Hits, years = Hitters$Years ) # store the response variable seperately response <- log10(Hitters$Salary) # remove NA's (remove rows containing missing values for salary) to_remove <- which(is.na(response)) predictors <- predictors[-to_remove, ] response <- response[-to_remove] # mean standardise and scale # this trick can be used to bring different numeric variables # onto comparable scales shits <- scale(predictors$hits) syears <- scale(predictors$years) spredictors <- data.frame(shits, syears) ggplot(spredictors, aes(x = syears, y = shits)) + geom_point(aes(colour = log10(response)), size = 3, data = as.data.frame(response)) # 3. Fit a Model # -------------- # fast nearest neighbours library(FNN) # the default calculates 'leave-one-out' predictions model <- knn.reg(train = spredictors, y = response, k = 10) # rsq between real values and predicted values # is an indicator of performance model # k is arbitrarily selected so far, how do we tune K? # lets try by measuring the rsq for predictions when we vary K. # first we need a data.frame to store the results N <- nrow(spredictors) - 1 tuningK <- data.frame( k = 1:N, rsq = NA ) # now lets loop through and extract the rsq for each value of K for(i in 1:N){ tuningK$rsq[i] <- knn.reg( train = spredictors, y = response, k = i )$R2Pred } # the best value of K is the one that results in the highest value of rsq # (possibly) bestK <- which.max(tuningK$rsq) bestK # visualise the tuning of K ggplot(tuningK, aes(x = k, y = rsq)) + geom_line() + geom_vline(xintercept = bestK, colour = "red", lty = 3) # 4. Evaluate model behaviour # --------------------------- # re-calculate LOO predictions with tuned K model <- knn.reg(train = spredictors, y = response, k = bestK) # collect the results results <- data.frame( salary = response, preds = model$pred, resids = model$residuals ) # lets plot the predicted salary over the real salary, # the same as the correlation we have been measuring with rsq. # but visualising allows us to see *where* the model fails ggplot(results, aes(x = preds, y = salary)) + geom_point() + geom_abline(intercept = 0, slope = 1) # the difference between the real values and the predicted values # is called the residuals we can inspect the residuals median(abs(model$residuals)) ggplot(results, aes(x = salary, y = resids)) + geom_point() + geom_hline(yintercept = 0) # we can also examine the predicted values in theoretical space # of the explanatory variables. this allows us to see what the model # has learned. # first we need some new fake variables hits_grid <- seq(min(shits), max(shits), length.out = 50) years_grid <- seq(min(syears), max(syears), length.out = 50) # the very useful expand.grid() function will return a data frame # containing every combination of its arguments grid_data <- expand.grid( years = years_grid, hits = hits_grid ) # now we can calculate predicted values on our theoretical grid grid_results <- knn.reg( train = spredictors, test = grid_data, y = response, k = bestK ) # collect the results grid_data <- cbind(grid_data, preds = grid_results$pred) # and visualise ggplot(grid_data, aes(x = hits, y = years)) + geom_raster(aes(fill = preds)) <file_sep>/README.md # k nearest neighbour tutorial for codeclan During this short data science tutorial students will use a historical dataset of baseball players in the 80’s to predict their salaries. We will consider a few measures of player experience and performance to predict the salary that they earn. We will use the statistical programming language R and to go from data to model to evaluation and inference, a whistle stop tour of the data science journey. We will cover: - R objects, and exploring a dataset e.g. plotting - Data handling and transforming numeric variables - The K nearest neighbour regression approach - Evaluating model performance and behaviour If you have questions or comments after the tutorial then please feel free to get in touch. Also if the data science route appeals to you then likewise get in touch but also keep an eye on our website (www.thedatalab.com) for info on events around Scotland.
6fb988a7c325fced27c7d2c812395be0aab723cc
[ "Markdown", "R" ]
2
R
rmnppt/codeclan
e30f1f208b534efc711eada1120e143603ec4da6
ea5e9e93258554b2201d2122d7e1229c010c48d6
refs/heads/master
<repo_name>himanshi2626/Script_Twoo_Auto_Two<file_sep>/target/site/cucumber-pretty/report.js $(document).ready(function() {var formatter = new CucumberHTML.DOMFormatter($('.cucumber-report'));formatter.uri("src/test/java/Features/a1.0_PDP_Email_Sign_UP_Incorrect_Data_1.feature"); formatter.feature({ "line": 2, "name": "Email Sign UP Incorrect Data", "description": "", "id": "email-sign-up-incorrect-data", "keyword": "Feature", "tags": [ { "line": 1, "name": "@1.0_PDP_Email_Sign_UP_Incorrect_Data_1" } ] }); formatter.scenario({ "line": 3, "name": "Email Sign UP Incorrect Data", "description": "", "id": "email-sign-up-incorrect-data;email-sign-up-incorrect-data", "type": "scenario", "keyword": "Scenario" }); formatter.step({ "line": 5, "name": "user is already on PDP Page FP i", "keyword": "Given " }); formatter.step({ "line": 6, "name": "User click on Download button to download the product i", "keyword": "Then " }); formatter.step({ "line": 7, "name": "user is redirected to sign up page i", "keyword": "Then " }); formatter.step({ "line": 8, "name": "user enter incorrect details to sign up i", "keyword": "Then " }); formatter.step({ "line": 9, "name": "error message is displayed i", "keyword": "Then " }); formatter.step({ "line": 10, "name": "user enter new email and correct details to sign up i", "keyword": "Then " }); formatter.step({ "line": 11, "name": "user is redirected to pricing page And then user navigates to free ppt page i", "keyword": "Then " }); formatter.step({ "line": 12, "name": "user downloads a free product i", "keyword": "Then " }); formatter.step({ "line": 13, "name": "user delete the account i", "keyword": "Then " }); formatter.match({ "location": "pdp_Email_Sign_UP_Incorrect_Data_1.user_is_already_on_PDP_Page_FP_i()" }); formatter.result({ "duration": 7479764600, "status": "passed" }); formatter.match({ "location": "pdp_Email_Sign_UP_Incorrect_Data_1.user_click_on_Download_button_to_download_the_product_i()" }); formatter.result({ "duration": 4150726400, "status": "passed" }); formatter.match({ "location": "pdp_Email_Sign_UP_Incorrect_Data_1.user_is_redirected_to_sign_up_page_i()" }); formatter.result({ "duration": 6405932900, "status": "passed" }); formatter.match({ "location": "pdp_Email_Sign_UP_Incorrect_Data_1.user_enter_incorrect_details_to_sign_up_i()" }); formatter.result({ "duration": 28815336700, "status": "passed" }); formatter.match({ "location": "pdp_Email_Sign_UP_Incorrect_Data_1.error_message_is_displayed_i()" }); formatter.result({ "duration": 22351957000, "status": "passed" }); formatter.match({ "location": "pdp_Email_Sign_UP_Incorrect_Data_1.user_enter_new_email_and_correct_details_to_sign_up_i()" }); formatter.result({ "duration": 32818875600, "status": "passed" }); formatter.match({ "location": "pdp_Email_Sign_UP_Incorrect_Data_1.user_is_redirected_to_pricing_page_And_then_user_navigates_to_free_ppt_page_i()" }); formatter.result({ "duration": 7445896600, "status": "passed" }); formatter.match({ "location": "pdp_Email_Sign_UP_Incorrect_Data_1.user_downloads_a_free_product_i()" }); formatter.result({ "duration": 13244354800, "status": "passed" }); formatter.match({ "location": "pdp_Email_Sign_UP_Incorrect_Data_1.user_delete_the_account_i()" }); formatter.result({ "duration": 20114119500, "status": "passed" }); formatter.uri("src/test/java/Features/b1.1_PDP_Email_Sign_UP_Correct_Data_2.feature"); formatter.feature({ "line": 2, "name": "PDP Email Sign UP Correct Data", "description": "", "id": "pdp-email-sign-up-correct-data", "keyword": "Feature", "tags": [ { "line": 1, "name": "@1.1_PDP_Email_Sign_UP_Correct_Data_2" } ] }); formatter.scenario({ "line": 3, "name": "PDP Email Sign UP Correct Data", "description": "", "id": "pdp-email-sign-up-correct-data;pdp-email-sign-up-correct-data", "type": "scenario", "keyword": "Scenario" }); formatter.step({ "line": 5, "name": "user is already on PDP Page FP ii", "keyword": "Given " }); formatter.step({ "line": 6, "name": "User click on Download button to download the product ii", "keyword": "Then " }); formatter.step({ "line": 7, "name": "user is redirected to sign up page ii", "keyword": "Then " }); formatter.step({ "line": 8, "name": "user enter new email and correct details to sign up ii", "keyword": "Then " }); formatter.step({ "line": 9, "name": "user is redirected to pricing page And then user navigates to free ppt page ii", "keyword": "Then " }); formatter.step({ "line": 10, "name": "user downloads a free product ii", "keyword": "Then " }); formatter.step({ "line": 11, "name": "user delete the account ii", "keyword": "Then " }); formatter.match({ "location": "pdp_Email_Sign_UP_Correct_Data_2.user_is_already_on_PDP_Page_FP_ii()" }); formatter.result({ "duration": 4380780500, "status": "passed" }); formatter.match({ "location": "pdp_Email_Sign_UP_Correct_Data_2.user_click_on_Download_button_to_download_the_product_ii()" }); formatter.result({ "duration": 4103681600, "status": "passed" }); formatter.match({ "location": "pdp_Email_Sign_UP_Correct_Data_2.user_is_redirected_to_sign_up_page_ii()" }); formatter.result({ "duration": 5765621900, "status": "passed" }); formatter.match({ "location": "pdp_Email_Sign_UP_Correct_Data_2.user_enter_new_email_and_correct_details_to_sign_up_ii()" }); formatter.result({ "duration": 31885686400, "status": "passed" }); formatter.match({ "location": "pdp_Email_Sign_UP_Correct_Data_2.user_is_redirected_to_pricing_page_And_then_user_navigates_to_free_ppt_page_ii()" }); formatter.result({ "duration": 6284816400, "status": "passed" }); formatter.match({ "location": "pdp_Email_Sign_UP_Correct_Data_2.user_downloads_a_free_product_ii()" }); formatter.result({ "duration": 12271661500, "status": "passed" }); formatter.match({ "location": "pdp_Email_Sign_UP_Correct_Data_2.user_delete_the_account_ii()" }); formatter.result({ "duration": 12924006200, "status": "passed" }); formatter.uri("src/test/java/Features/c2.1_PDP_Facebook_Sign_UP_3.feature"); formatter.feature({ "line": 2, "name": "PDP Facebook Sign UP", "description": "", "id": "pdp-facebook-sign-up", "keyword": "Feature", "tags": [ { "line": 1, "name": "@2.1_PDP_Facebook_Sign_UP_3" } ] }); formatter.scenario({ "line": 3, "name": "PDP Facebook Sign UP", "description": "", "id": "pdp-facebook-sign-up;pdp-facebook-sign-up", "type": "scenario", "keyword": "Scenario" }); formatter.step({ "line": 5, "name": "user is already on pdp page iii", "keyword": "Given " }); formatter.step({ "line": 6, "name": "User click on Download button to download the product iii", "keyword": "Then " }); formatter.step({ "line": 7, "name": "user is redirected to sign up page iii", "keyword": "Then " }); formatter.step({ "line": 8, "name": "User click on sign in with facebook button iii", "keyword": "Then " }); formatter.step({ "line": 9, "name": "user is redirected to pricing page iii", "keyword": "Then " }); formatter.step({ "line": 10, "name": "user go to free ppts page iii", "keyword": "Then " }); formatter.step({ "line": 11, "name": "user download a free ppt iii", "keyword": "Then " }); formatter.step({ "line": 12, "name": "user delete the account iii", "keyword": "Then " }); formatter.match({ "location": "pdp_Facebook_Sign_UP_3.user_is_already_on_pdp_page_iii()" }); formatter.result({ "duration": 4247666000, "status": "passed" }); formatter.match({ "location": "pdp_Facebook_Sign_UP_3.user_click_on_Download_button_to_download_the_product_iii()" }); formatter.result({ "duration": 4085439800, "status": "passed" }); formatter.match({ "location": "pdp_Facebook_Sign_UP_3.user_is_redirected_to_sign_up_page_iii()" }); formatter.result({ "duration": 58200, "status": "passed" }); formatter.match({ "location": "pdp_Facebook_Sign_UP_3.user_click_on_sign_in_with_facebook_button_iii()" }); formatter.result({ "duration": 24310509400, "status": "passed" }); formatter.match({ "location": "pdp_Facebook_Sign_UP_3.user_is_redirected_to_pricing_page_iii()" }); formatter.result({ "duration": 23900, "status": "passed" }); formatter.match({ "location": "pdp_Facebook_Sign_UP_3.user_go_to_free_ppts_page_iii()" }); formatter.result({ "duration": 26100, "status": "passed" }); formatter.match({ "location": "pdp_Facebook_Sign_UP_3.user_download_a_free_ppt_iii()" }); formatter.result({ "duration": 5155747200, "status": "passed" }); formatter.match({ "location": "pdp_Facebook_Sign_UP_3.user_delete_the_account_iii()" }); formatter.result({ "duration": 36483269900, "status": "passed" }); formatter.uri("src/test/java/Features/e2.2_PDP_Gmail_Sign_UP_5.feature"); formatter.feature({ "line": 2, "name": "PDP Gmail Sign UP", "description": "", "id": "pdp-gmail-sign-up", "keyword": "Feature", "tags": [ { "line": 1, "name": "@2.2_PDP_Gmail_Sign_UP_5" } ] }); formatter.scenario({ "line": 3, "name": "PDP Gmail Sign UP", "description": "", "id": "pdp-gmail-sign-up;pdp-gmail-sign-up", "type": "scenario", "keyword": "Scenario" }); formatter.step({ "line": 5, "name": "user is already on pdp page v", "keyword": "Given " }); formatter.step({ "line": 6, "name": "User click on Download button to download the product v", "keyword": "Then " }); formatter.step({ "line": 7, "name": "user is redirected to sign up page v", "keyword": "Then " }); formatter.step({ "line": 8, "name": "User click on sign in with google button v", "keyword": "Then " }); formatter.step({ "line": 9, "name": "user is redirected to pricing page v", "keyword": "Then " }); formatter.step({ "line": 10, "name": "user go to free ppts page v", "keyword": "Then " }); formatter.step({ "line": 11, "name": "user download a free ppt v", "keyword": "Then " }); formatter.step({ "line": 12, "name": "user delete the account v", "keyword": "Then " }); formatter.match({ "location": "pdp_Gmail_Sign_UP_5.user_is_already_on_pdp_page_v()" }); formatter.result({ "duration": 4207166100, "status": "passed" }); formatter.match({ "location": "pdp_Gmail_Sign_UP_5.user_click_on_Download_button_to_download_the_product_v()" }); formatter.result({ "duration": 4092386300, "status": "passed" }); formatter.match({ "location": "pdp_Gmail_Sign_UP_5.user_is_redirected_to_sign_up_page_v()" }); formatter.result({ "duration": 21700, "status": "passed" }); formatter.match({ "location": "pdp_Gmail_Sign_UP_5.user_click_on_sign_in_with_google_button_v()" }); formatter.result({ "duration": 42051499000, "status": "passed" }); formatter.match({ "location": "pdp_Gmail_Sign_UP_5.user_is_redirected_to_pricing_page_v()" }); formatter.result({ "duration": 20400, "status": "passed" }); formatter.match({ "location": "pdp_Gmail_Sign_UP_5.user_go_to_free_ppts_page_v()" }); formatter.result({ "duration": 5000018200, "status": "passed" }); formatter.match({ "location": "pdp_Gmail_Sign_UP_5.user_download_a_free_ppt_v()" }); formatter.result({ "duration": 11609396300, "status": "passed" }); formatter.match({ "location": "pdp_Gmail_Sign_UP_5.user_delete_the_account_v()" }); formatter.result({ "duration": 47707821500, "status": "passed" }); formatter.uri("src/test/java/Features/g3.1_PDP_Email_Login_Incorrect_Data_Paid_User_7.feature"); formatter.feature({ "line": 2, "name": "PDP Email Login Incorrect Data Paid User", "description": "", "id": "pdp-email-login-incorrect-data-paid-user", "keyword": "Feature", "tags": [ { "line": 1, "name": "@3.1_PDP_Email_Login_Incorrect_Data_Paid_User_7" } ] }); formatter.scenario({ "line": 3, "name": "PDP Email Login Incorrect Data Paid User", "description": "", "id": "pdp-email-login-incorrect-data-paid-user;pdp-email-login-incorrect-data-paid-user", "type": "scenario", "keyword": "Scenario" }); formatter.step({ "line": 5, "name": "user is already on PDP Page MD vii", "keyword": "Given " }); formatter.step({ "line": 6, "name": "User click on Download button to download the product vii", "keyword": "Then " }); formatter.step({ "line": 7, "name": "user is redirected to Login page vii", "keyword": "Then " }); formatter.step({ "line": 8, "name": "user enter incorrect details to login vii", "keyword": "Then " }); formatter.step({ "line": 9, "name": "error message is displayed vii", "keyword": "Then " }); formatter.step({ "line": 10, "name": "user login with correct details vii", "keyword": "Then " }); formatter.step({ "line": 11, "name": "user will be redirected to same pdp page vii", "keyword": "Then " }); formatter.step({ "line": 12, "name": "user download the product vii", "keyword": "Then " }); formatter.step({ "line": 13, "name": "user logout from website vii", "keyword": "Then " }); formatter.match({ "location": "pdp_Email_Login_Incorrect_Data_Paid_User_7.user_is_already_on_PDP_Page_MD_vii()" }); formatter.result({ "duration": 4855406000, "status": "passed" }); formatter.match({ "location": "pdp_Email_Login_Incorrect_Data_Paid_User_7.user_click_on_Download_button_to_download_the_product_vii()" }); formatter.result({ "duration": 4083276900, "status": "passed" }); formatter.match({ "location": "pdp_Email_Login_Incorrect_Data_Paid_User_7.user_is_redirected_to_Login_page_vii()" }); formatter.result({ "duration": 31000, "status": "passed" }); formatter.match({ "location": "pdp_Email_Login_Incorrect_Data_Paid_User_7.user_enter_incorrect_details_to_login_vii()" }); formatter.result({ "duration": 12575372900, "status": "passed" }); formatter.match({ "location": "pdp_Email_Login_Incorrect_Data_Paid_User_7.error_message_is_displayed_vii()" }); formatter.result({ "duration": 8137205600, "status": "passed" }); formatter.match({ "location": "pdp_Email_Login_Incorrect_Data_Paid_User_7.user_login_with_correct_details_vii()" }); formatter.result({ "duration": 16961513400, "status": "passed" }); formatter.match({ "location": "pdp_Email_Login_Incorrect_Data_Paid_User_7.user_will_be_redirected_to_same_pdp_page_vii()" }); formatter.result({ "duration": 2035780600, "status": "passed" }); formatter.match({ "location": "pdp_Email_Login_Incorrect_Data_Paid_User_7.user_download_the_product_vii()" }); formatter.result({ "duration": 4167954400, "status": "passed" }); formatter.match({ "location": "pdp_Email_Login_Incorrect_Data_Paid_User_7.user_logout_from_website_vii()" }); formatter.result({ "duration": 13070180900, "status": "passed" }); formatter.uri("src/test/java/Features/h3.2_PDP_Email_Login_Correct_Data_Paid_User_8.feature"); formatter.feature({ "line": 2, "name": "PDP Email Login Correct Data Paid User", "description": "", "id": "pdp-email-login-correct-data-paid-user", "keyword": "Feature", "tags": [ { "line": 1, "name": "@3.2_PDP_Email_Login_Correct_Data_Paid_User_8" } ] }); formatter.scenario({ "line": 3, "name": "PDP Email Login Correct Data Paid User", "description": "", "id": "pdp-email-login-correct-data-paid-user;pdp-email-login-correct-data-paid-user", "type": "scenario", "keyword": "Scenario" }); formatter.step({ "line": 5, "name": "user is already on PDP Page MD viii", "keyword": "Given " }); formatter.step({ "line": 6, "name": "User click on Download button to download the product viii", "keyword": "Then " }); formatter.step({ "line": 7, "name": "user is redirected to Login page viii", "keyword": "Then " }); formatter.step({ "line": 8, "name": "user login with correct details viii", "keyword": "Then " }); formatter.step({ "line": 9, "name": "user will be redirected to same pdp page viii", "keyword": "Then " }); formatter.step({ "line": 10, "name": "user download the product viii", "keyword": "Then " }); formatter.step({ "line": 11, "name": "user logout from website viii", "keyword": "Then " }); formatter.match({ "location": "pdp_Email_Login_Correct_Data_Paid_User_8.user_is_already_on_PDP_Page_MD_viii()" }); formatter.result({ "duration": 4555163200, "status": "passed" }); formatter.match({ "location": "pdp_Email_Login_Correct_Data_Paid_User_8.user_click_on_Download_button_to_download_the_product_viii()" }); formatter.result({ "duration": 4108401400, "status": "passed" }); formatter.match({ "location": "pdp_Email_Login_Correct_Data_Paid_User_8.user_is_redirected_to_Login_page_viii()" }); formatter.result({ "duration": 23400, "status": "passed" }); formatter.match({ "location": "pdp_Email_Login_Correct_Data_Paid_User_8.user_login_with_correct_details_viii()" }); formatter.result({ "duration": 16090764100, "status": "passed" }); formatter.match({ "location": "pdp_Email_Login_Correct_Data_Paid_User_8.user_will_be_redirected_to_same_pdp_page_viii()" }); formatter.result({ "duration": 25000, "status": "passed" }); formatter.match({ "location": "pdp_Email_Login_Correct_Data_Paid_User_8.user_download_the_product_viii()" }); formatter.result({ "duration": 6410298000, "status": "passed" }); formatter.match({ "location": "pdp_Email_Login_Correct_Data_Paid_User_8.user_logout_from_website_viii()" }); formatter.result({ "duration": 12626775200, "status": "passed" }); formatter.uri("src/test/java/Features/i4.1_PDP_Facebook_Login_Paid_User_9.feature"); formatter.feature({ "line": 2, "name": "PDP Facebook Login Paid User", "description": "", "id": "pdp-facebook-login-paid-user", "keyword": "Feature", "tags": [ { "line": 1, "name": "@4.1_PDP_Facebook_Login_Paid_User_9" } ] }); formatter.scenario({ "line": 3, "name": "PDP Facebook Login Paid User", "description": "", "id": "pdp-facebook-login-paid-user;pdp-facebook-login-paid-user", "type": "scenario", "keyword": "Scenario" }); formatter.step({ "line": 5, "name": "user is already on pdp page CD ix", "keyword": "Given " }); formatter.step({ "line": 6, "name": "User click on Download button to download the product ix", "keyword": "Then " }); formatter.step({ "line": 7, "name": "user is redirected to Login page ix", "keyword": "Then " }); formatter.step({ "line": 8, "name": "User click on sign in with facebook button ix", "keyword": "Then " }); formatter.step({ "line": 9, "name": "user will be redirected to same page pdpd ix", "keyword": "Then " }); formatter.step({ "line": 10, "name": "user download the product ix", "keyword": "Then " }); formatter.step({ "line": 11, "name": "user logout from website ix", "keyword": "Then " }); formatter.match({ "location": "pdp_Facebook_Login_Paid_User_9.user_is_already_on_pdp_page_CD_ix()" }); formatter.result({ "duration": 3670811100, "status": "passed" }); formatter.match({ "location": "pdp_Facebook_Login_Paid_User_9.user_click_on_Download_button_to_download_the_product_ix()" }); formatter.result({ "duration": 4116467700, "status": "passed" }); formatter.match({ "location": "pdp_Facebook_Login_Paid_User_9.user_is_redirected_to_Login_page_ix()" }); formatter.result({ "duration": 40500, "status": "passed" }); formatter.match({ "location": "pdp_Facebook_Login_Paid_User_9.user_click_on_sign_in_with_facebook_button_ix()" }); formatter.result({ "duration": 22256326900, "status": "passed" }); formatter.match({ "location": "pdp_Facebook_Login_Paid_User_9.user_will_be_redirected_to_same_page_pdpd_ix()" }); formatter.result({ "duration": 26100, "status": "passed" }); formatter.match({ "location": "pdp_Facebook_Login_Paid_User_9.user_download_the_product_ix()" }); formatter.result({ "duration": 4099209400, "status": "passed" }); formatter.match({ "location": "pdp_Facebook_Login_Paid_User_9.user_logout_from_website_ix()" }); formatter.result({ "duration": 13269903900, "status": "passed" }); formatter.uri("src/test/java/Features/j4.1.1_Facebook_Logout_10.feature"); formatter.feature({ "line": 2, "name": "Facebook Logout", "description": "", "id": "facebook-logout", "keyword": "Feature", "tags": [ { "line": 1, "name": "@4.1.1_Facebook_Logout_10" } ] }); formatter.scenario({ "line": 3, "name": "Facebook Logout", "description": "", "id": "facebook-logout;facebook-logout", "type": "scenario", "keyword": "Scenario" }); formatter.step({ "line": 4, "name": "navigate to the facebook url x", "keyword": "Given " }); formatter.match({ "location": "pdp_Facebook_Logout_10.navigate_to_the_facebook_url_x()" }); formatter.result({ "duration": 18221712700, "status": "passed" }); formatter.uri("src/test/java/Features/k4.2_PDP_Gmail_Login_Paid_User_11.feature"); formatter.feature({ "line": 3, "name": "PDP Gmail Login Paid User", "description": "", "id": "pdp-gmail-login-paid-user", "keyword": "Feature", "tags": [ { "line": 1, "name": "@4.2_PDP_Gmail_Login_Paid_User_11" } ] }); formatter.scenario({ "line": 4, "name": "PDP Gmail Login Paid User", "description": "", "id": "pdp-gmail-login-paid-user;pdp-gmail-login-paid-user", "type": "scenario", "keyword": "Scenario" }); formatter.step({ "line": 6, "name": "user is already on pdp page CD xi", "keyword": "Given " }); formatter.step({ "line": 7, "name": "User click on Download button to download the product xi", "keyword": "Then " }); formatter.step({ "line": 8, "name": "user is redirected to Login page xi", "keyword": "Then " }); formatter.step({ "line": 9, "name": "User click on sign in with google button xi", "keyword": "Then " }); formatter.step({ "line": 10, "name": "user will be redirected to same page pdpd xi", "keyword": "Then " }); formatter.step({ "line": 11, "name": "user download the product xi", "keyword": "Then " }); formatter.step({ "line": 12, "name": "user logout from website xi", "keyword": "Then " }); formatter.match({ "location": "pdp_Gmail_Login_Paid_User_11.user_is_already_on_pdp_page_CD_xi()" }); formatter.result({ "duration": 3826331800, "status": "passed" }); formatter.match({ "location": "pdp_Gmail_Login_Paid_User_11.user_click_on_Download_button_to_download_the_product_xi()" }); formatter.result({ "duration": 6125070300, "status": "passed" }); formatter.match({ "location": "pdp_Gmail_Login_Paid_User_11.user_is_redirected_to_Login_page_xi()" }); formatter.result({ "duration": 20600, "status": "passed" }); formatter.match({ "location": "pdp_Gmail_Login_Paid_User_11.user_click_on_sign_in_with_google_button_xi()" }); formatter.result({ "duration": 27984071400, "status": "passed" }); formatter.match({ "location": "pdp_Gmail_Login_Paid_User_11.user_will_be_redirected_to_same_page_pdpd_xi()" }); formatter.result({ "duration": 1999956300, "status": "passed" }); formatter.match({ "location": "pdp_Gmail_Login_Paid_User_11.user_download_the_product_xi()" }); formatter.result({ "duration": 8334377100, "status": "passed" }); formatter.match({ "location": "pdp_Gmail_Login_Paid_User_11.user_logout_from_website_xi()" }); formatter.result({ "duration": 15898405600, "status": "passed" }); formatter.uri("src/test/java/Features/l4.2.1_Gmail_Logout_12.feature"); formatter.feature({ "line": 2, "name": "Gmail Logout", "description": "", "id": "gmail-logout", "keyword": "Feature", "tags": [ { "line": 1, "name": "@4.2.1_Gmail_Logout_12" } ] }); formatter.scenario({ "line": 3, "name": "Gmail Logout", "description": "", "id": "gmail-logout;gmail-logout", "type": "scenario", "keyword": "Scenario" }); formatter.step({ "line": 4, "name": "navigate to the gmail url xii", "keyword": "Given " }); formatter.match({ "location": "pdp_Gmail_Logout_12.navigate_to_the_gmail_url_xii()" }); formatter.result({ "duration": 23890331800, "status": "passed" }); formatter.uri("src/test/java/Features/m5.1_PDP_Email_Login_Incorrect_Data_Free_User_13.feature"); formatter.feature({ "line": 2, "name": "PDP Email Login Incorrect Data Free User", "description": "", "id": "pdp-email-login-incorrect-data-free-user", "keyword": "Feature", "tags": [ { "line": 1, "name": "@5.1_PDP_Email_Login_Incorrect_Data_Free_User_13" } ] }); formatter.scenario({ "line": 3, "name": "PDP Email Login Incorrect Data Free User", "description": "", "id": "pdp-email-login-incorrect-data-free-user;pdp-email-login-incorrect-data-free-user", "type": "scenario", "keyword": "Scenario" }); formatter.step({ "line": 5, "name": "user is already on PDP Page NA xiii", "keyword": "Given " }); formatter.step({ "line": 6, "name": "User click on Download button to download the product xiii", "keyword": "Then " }); formatter.step({ "line": 7, "name": "user is redirected to Login page xiii", "keyword": "Then " }); formatter.step({ "line": 8, "name": "user enter incorrect details to login xiii", "keyword": "Then " }); formatter.step({ "line": 9, "name": "error message is displayed xiii", "keyword": "Then " }); formatter.step({ "line": 10, "name": "user login with correct details xiii", "keyword": "Then " }); formatter.step({ "line": 11, "name": "user is reedirected to pricing page xiii", "keyword": "Then " }); formatter.step({ "line": 12, "name": "user logout from website xiii", "keyword": "Then " }); formatter.match({ "location": "pdp_Email_Login_Incorrect_Data_Free_User_13.user_is_already_on_PDP_Page_NA_xiii()" }); formatter.result({ "duration": 5463180800, "status": "passed" }); formatter.match({ "location": "pdp_Email_Login_Incorrect_Data_Free_User_13.user_click_on_Download_button_to_download_the_product_xiii()" }); formatter.result({ "duration": 4096964100, "status": "passed" }); formatter.match({ "location": "pdp_Email_Login_Incorrect_Data_Free_User_13.user_is_redirected_to_Login_page_xiii()" }); formatter.result({ "duration": 999999600, "status": "passed" }); formatter.match({ "location": "pdp_Email_Login_Incorrect_Data_Free_User_13.user_enter_incorrect_details_to_login_xiii()" }); formatter.result({ "duration": 12446716300, "status": "passed" }); formatter.match({ "location": "pdp_Email_Login_Incorrect_Data_Free_User_13.error_message_is_displayed_xiii()" }); formatter.result({ "duration": 10131419000, "status": "passed" }); formatter.match({ "location": "pdp_Email_Login_Incorrect_Data_Free_User_13.user_login_with_correct_details_xiii()" }); formatter.result({ "duration": 14540764700, "status": "passed" }); formatter.match({ "location": "pdp_Email_Login_Incorrect_Data_Free_User_13.user_is_reedirected_to_pricing_page_xiii()" }); formatter.result({ "duration": 999944400, "status": "passed" }); formatter.match({ "location": "pdp_Email_Login_Incorrect_Data_Free_User_13.user_logout_from_website_xiii()" }); formatter.result({ "duration": 13619378100, "status": "passed" }); formatter.uri("src/test/java/Features/n5.2_PDP_Email_Login_Correct_Data_Free_User_14.feature"); formatter.feature({ "line": 2, "name": "PDP Email Login Correct Data Free User", "description": "", "id": "pdp-email-login-correct-data-free-user", "keyword": "Feature", "tags": [ { "line": 1, "name": "@5.2_PDP_Email_Login_Correct_Data_Free_User_14" } ] }); formatter.scenario({ "line": 3, "name": "PDP Email Login Correct Data Free User", "description": "", "id": "pdp-email-login-correct-data-free-user;pdp-email-login-correct-data-free-user", "type": "scenario", "keyword": "Scenario" }); formatter.step({ "line": 5, "name": "user is already on PDP Page MD xiv", "keyword": "Given " }); formatter.step({ "line": 6, "name": "User click on Download button to download the product xiv", "keyword": "Then " }); formatter.step({ "line": 7, "name": "user is redirected to Login page xiv", "keyword": "Then " }); formatter.step({ "line": 8, "name": "user login with correct details xiv", "keyword": "Then " }); formatter.step({ "line": 9, "name": "user is reedirected to same pdp page and download the product xiv", "keyword": "Then " }); formatter.step({ "line": 10, "name": "user logout from website xiv", "keyword": "Then " }); formatter.match({ "location": "pdp_Email_Login_Correct_Data_Free_User_14.user_is_already_on_PDP_Page_MD_xiv()" }); formatter.result({ "duration": 5500554400, "status": "passed" }); formatter.match({ "location": "pdp_Email_Login_Correct_Data_Free_User_14.user_click_on_Download_button_to_download_the_product_xiv()" }); formatter.result({ "duration": 4092602600, "status": "passed" }); formatter.match({ "location": "pdp_Email_Login_Correct_Data_Free_User_14.user_is_redirected_to_Login_page_xiv()" }); formatter.result({ "duration": 999984000, "status": "passed" }); formatter.match({ "location": "pdp_Email_Login_Correct_Data_Free_User_14.user_login_with_correct_details_xiv()" }); formatter.result({ "duration": 15563016100, "status": "passed" }); formatter.match({ "location": "pdp_Email_Login_Correct_Data_Free_User_14.user_is_reedirected_to_same_pdp_page_and_download_the_product_xiv()" }); formatter.result({ "duration": 6610412900, "status": "passed" }); formatter.match({ "location": "pdp_Email_Login_Correct_Data_Free_User_14.user_logout_from_website_xiv()" }); formatter.result({ "duration": 13174210400, "status": "passed" }); formatter.uri("src/test/java/Features/o5.3_PDP_Facebook_Login_Free_User_15.feature"); formatter.feature({ "line": 2, "name": "PDP Facebook Login Free User", "description": "", "id": "pdp-facebook-login-free-user", "keyword": "Feature", "tags": [ { "line": 1, "name": "@5.3_PDP_Facebook_Login_Free_User_15" } ] }); formatter.scenario({ "line": 3, "name": "PDP Facebook Login Free User", "description": "", "id": "pdp-facebook-login-free-user;pdp-facebook-login-free-user", "type": "scenario", "keyword": "Scenario" }); formatter.step({ "line": 5, "name": "user is already on pdp page FP xv", "keyword": "Given " }); formatter.step({ "line": 6, "name": "User click on Download button to download the product xv", "keyword": "Then " }); formatter.step({ "line": 7, "name": "user is redirected to Login page xv", "keyword": "Then " }); formatter.step({ "line": 8, "name": "User click on sign in with facebook button xv", "keyword": "Then " }); formatter.step({ "line": 9, "name": "user will be redirected to same page xv", "keyword": "Then " }); formatter.step({ "line": 10, "name": "user download the product xv", "keyword": "Then " }); formatter.step({ "line": 11, "name": "user logout from website xv", "keyword": "Then " }); formatter.match({ "location": "pdp_Facebook_Login_Free_User_15.user_is_already_on_pdp_page_FP_xv()" }); formatter.result({ "duration": 4392908000, "status": "passed" }); formatter.match({ "location": "pdp_Facebook_Login_Free_User_15.user_click_on_Download_button_to_download_the_product_xv()" }); formatter.result({ "duration": 4099422300, "status": "passed" }); formatter.match({ "location": "pdp_Facebook_Login_Free_User_15.user_is_redirected_to_Login_page_xv()" }); formatter.result({ "duration": 67600, "status": "passed" }); formatter.match({ "location": "pdp_Facebook_Login_Free_User_15.user_click_on_sign_in_with_facebook_button_xv()" }); formatter.result({ "duration": 23260101900, "status": "passed" }); formatter.match({ "location": "pdp_Facebook_Login_Free_User_15.user_will_be_redirected_to_same_page_xv()" }); formatter.result({ "duration": 1000015800, "status": "passed" }); formatter.match({ "location": "pdp_Facebook_Login_Free_User_15.user_download_the_product_xv()" }); formatter.result({ "duration": 6208197400, "status": "passed" }); formatter.match({ "location": "pdp_Facebook_Login_Free_User_15.user_logout_from_website_xv()" }); formatter.result({ "duration": 29913644800, "status": "passed" }); formatter.uri("src/test/java/Features/q5.4_PDP_Gmail_Login_Free_User_17.feature"); formatter.feature({ "line": 2, "name": "PDP Gmail Login Free User", "description": "", "id": "pdp-gmail-login-free-user", "keyword": "Feature", "tags": [ { "line": 1, "name": "@5.4_PDP_Gmail_Login_Free_User_17" } ] }); formatter.scenario({ "line": 3, "name": "PDP Gmail Login Free User", "description": "", "id": "pdp-gmail-login-free-user;pdp-gmail-login-free-user", "type": "scenario", "keyword": "Scenario" }); formatter.step({ "line": 5, "name": "user is already on pdp page FP xvii", "keyword": "Given " }); formatter.step({ "line": 6, "name": "User click on Download button to download the product xvii", "keyword": "Then " }); formatter.step({ "line": 7, "name": "user is redirected to Login page xvii", "keyword": "Then " }); formatter.step({ "line": 8, "name": "User click on sign in with google button xvii", "keyword": "Then " }); formatter.step({ "line": 9, "name": "user will be redirected to same page xvii", "keyword": "Then " }); formatter.step({ "line": 10, "name": "user download the product xvii", "keyword": "Then " }); formatter.step({ "line": 11, "name": "user logout from website xvii", "keyword": "Then " }); formatter.match({ "location": "pdp_Gmail_Login_Free_User_17.user_is_already_on_pdp_page_FP_xvii()" }); formatter.result({ "duration": 5249264300, "status": "passed" }); formatter.match({ "location": "pdp_Gmail_Login_Free_User_17.user_click_on_Download_button_to_download_the_product_xvii()" }); formatter.result({ "duration": 6201917100, "status": "passed" }); formatter.match({ "location": "pdp_Gmail_Login_Free_User_17.user_is_redirected_to_Login_page_xvii()" }); formatter.result({ "duration": 999389400, "status": "passed" }); formatter.match({ "location": "pdp_Gmail_Login_Free_User_17.user_click_on_sign_in_with_google_button_xvii()" }); formatter.result({ "duration": 27703438200, "status": "passed" }); formatter.match({ "location": "pdp_Gmail_Login_Free_User_17.user_will_be_redirected_to_same_page_xvii()" }); formatter.result({ "duration": 999526300, "status": "passed" }); formatter.match({ "location": "pdp_Gmail_Login_Free_User_17.user_download_the_product_xvii()" }); formatter.result({ "duration": 10900482200, "status": "passed" }); formatter.match({ "location": "pdp_Gmail_Login_Free_User_17.user_logout_from_website_xvii()" }); formatter.result({ "duration": 36264830600, "status": "passed" }); });
fc9c9e07d0638eb5c97c7461ee24bfb967686404
[ "JavaScript" ]
1
JavaScript
himanshi2626/Script_Twoo_Auto_Two
14cf73de333857c5e7f3635d4c41ff5d750a8dab
ebff333a3c8f9ce7026718a9e41b1cfbe78d8a22
refs/heads/main
<file_sep>img2pdf==0.4.0 lxml==4.6.2 pikepdf==2.8.0.post2 Pillow==8.1.2 PyPDF2==1.26.0 <file_sep>import glob import img2pdf from PyPDF2 import PdfFileReader, PdfFileWriter def convert_all(regex="*.jpg"): images = glob.glob(regex) images.sort() convert_list(images) def convert_list(images): for image in images: with open(image.split('.')[0] + '.pdf', 'wb') as target, open(image, 'rb') as source: target.write(img2pdf.convert(source)) def concatenate_all(target, regex="*.pdf"): pdfs = glob.glob(regex) pdfs.sort() with open(target, 'wb') as output: concatenate_list(pdfs, output) def concatenate_list(pdfs, target): input_streams = [] try: for pdf in pdfs: input_streams.append(open(pdf, 'rb')) writer = PdfFileWriter() for reader in map(PdfFileReader, input_streams): for n in range(reader.getNumPages()): writer.addPage(reader.getPage(n)) writer.write(target) finally: for f in input_streams: f.close() if __name__ == '__main__': convert_all() concatenate_all('Termo de Compromisso.pdf', 'tc*.pdf')
e8551d5f94bf53f0822cd3633483b136cc8f67b5
[ "Python", "Text" ]
2
Text
aless-ishy/common_life_utilities
9df67aa86b14a74c526e910d695bc08e3019bc50
4b9419eaa66287309c2e26b7e4496642ac740eab
refs/heads/master
<file_sep>package report; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; @Entity @Table(name="Record") public class Record { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; private String invoiceNo; private String stockCode; private String description; private Integer quantity; @Temporal(TemporalType.TIMESTAMP) private Date invoiceDate; private Float unitPrice; @Column(name = "customer_id" ) private Integer customerID; private String country; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getInvoiceNo() { return invoiceNo; } public void setInvoiceNo(String invoiceNo) { this.invoiceNo = invoiceNo; } public String getStockCode() { return stockCode; } public void setStockCode(String stockCode) { this.stockCode = stockCode; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } public Date getInvoiceDate() { return invoiceDate; } public void setInvoiceDate(Date invoiceDate) { this.invoiceDate = invoiceDate; } public Float getUnitPrice() { return unitPrice; } public void setUnitPrice(Float unitPrice) { this.unitPrice = unitPrice; } public Integer getCustomerID() { return customerID; } public void setCustomerID(Integer customerID) { this.customerID = customerID; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } } <file_sep>import { AppPage } from './app.po'; describe('report App', () => { let page: AppPage; beforeEach(() => { page = new AppPage(); page.navigateTo(); }); it('should redirect to table page', () => { expect(page.getURL()).toContain('#/pages/table'); }); it('should display a table', () => { expect(page.getTable()).toBeTruthy(); }); it('should have 50 tuples ', () => { page.getTableItems().then( data => { expect(data.length).toBe(50); } ) }); it('should dispaly a summary like \'50 of 3999\'', () => { expect(page.getSummaryText()).toBe('50 of 3999'); }); it('should redirect to charts page', () => { page.getChartsMenu().click(); expect(page.getURL()).toContain('#/pages/charts'); }); }); <file_sep>import { TestBed, inject } from '@angular/core/testing'; import { HttpClientModule } from '@angular/common/http'; import { ReportService } from './report.service'; describe('ReportService', () => { beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientModule], providers: [ReportService] }); }); it('should be created', inject([ReportService], (service: ReportService) => { expect(service).toBeTruthy(); })); it('should get 20 elements', inject([ReportService], (service: ReportService) => { const page: number = 0; const size: number = 20; service.getDemo(page, size, undefined).subscribe(data => { expect(data.numberOfElements).toBe(size); }) })); }); <file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { SpinnerComponent } from '../../@theme/spinner/spinner.component'; import { HttpClientModule } from '@angular/common/http'; import { InfiniteScrollModule } from 'ngx-infinite-scroll'; import { FormsModule } from '@angular/forms'; import { DemoTableComponent } from './demo-table.component'; import { SearchBarComponent } from './search-bar/search-bar.component'; import { ReportService } from '../../@core/data/report.service'; import { Observable } from 'rxjs/Observable'; import { Data } from '../../@core/data/data'; import 'rxjs/add/observable/of'; describe('DemoTableComponent', () => { let component: DemoTableComponent; let fixture: ComponentFixture<DemoTableComponent>; let service: ReportService; let spy: jasmine.Spy; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ DemoTableComponent, SpinnerComponent, SearchBarComponent ], imports: [InfiniteScrollModule, HttpClientModule, FormsModule], providers: [ReportService] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(DemoTableComponent); component = fixture.componentInstance; service = fixture.debugElement.injector.get(ReportService); spy = spyOn(service, 'getDemo').and.returnValue(Observable.of({content:[], totalElements: 0, numberOfElements: 0} as Data)); fixture.detectChanges(); }); it('should create demo table', () => { expect(component).toBeTruthy(); }); it('should get \'0 of 0\' on the Card footer by Spy function', async(() => { fixture.whenStable().then(() => { const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('.card-footer').textContent).toBe("0 of 0"); }); })); }); <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { PagesComponent } from './pages.component'; import { ChartsModule } from './charts/charts.module' import { DemoTableModule } from './demo-table/demo-table.module'; import { PagesRoutingModule } from './pages-routing.module'; import { NbThemeModule, NbSidebarModule, NbMenuModule, NbLayoutModule, NbSidebarService, NbMenuService } from '@nebular/theme'; @NgModule({ imports: [ CommonModule, NbThemeModule.forRoot({ name: 'default' }), NbMenuModule.forRoot(), NbLayoutModule, NbSidebarModule, PagesRoutingModule, ChartsModule, DemoTableModule ], declarations: [PagesComponent], providers: [NbSidebarService] }) export class PagesModule { } <file_sep>import { Component, OnInit, Input, ViewChild, ElementRef } from '@angular/core'; import { HttpErrorResponse } from '@angular/common/http'; import { ReportService } from '../../@core/data/report.service'; @Component({ selector: 'demo-table', templateUrl: './demo-table.component.html', styleUrls: ['./demo-table.component.css'] }) export class DemoTableComponent implements OnInit { @Input() size: number; @ViewChild('table') table: ElementRef; records: Array<any>; page: number = 0; subTotal: number = 0; total: number = 0; throttle: number = 300; scrollDistance: number = 1; isLoadingResults: boolean = false; customerID: string; searchBarPlaceholder: string = "Type Customer ID..."; constructor(private reportService: ReportService) {} ngOnInit() { this.refresh(); } refresh(customerID: string = undefined) { this.customerID = customerID; this.appendRecords(true); } appendRecords(needRefresh: boolean = false) { if ( !needRefresh && (this.subTotal === this.total)) { return; } this.isLoadingResults = true; this.size = this.size || 50; if (needRefresh) { this.page = 0; this.subTotal = 0; this.table.nativeElement.scrollTop = 0; } this.reportService.getDemo(this.page, this.size, this.customerID).subscribe( data => { if(!this.records || needRefresh){ this.records = data.content; }else { this.records = this.records.concat(data.content); } this.page++; this.subTotal += data.numberOfElements; this.total = data.totalElements this.isLoadingResults = false; }, (err: HttpErrorResponse) => { if(err.error instanceof Error) { console.error('An error occured:', err.error.message); } else { console.error(`Backend returned code ${err.status}, body was: ${err.error}`); } } ); } } <file_sep>import { browser, by, element } from 'protractor'; export class AppPage { navigateTo() { return browser.get('/'); } navigateToCharts() { return browser.get('#/pages/charts'); } getURL() { return browser.getCurrentUrl(); } getTable() { return element(by.css('table')); } getTableItems() { return element.all(by.css('table tbody tr')); } getSummaryText() { return element(by.css('.card-footer')).getText(); } getChartsMenu() { return element(by.css('.menu-items .menu-item:nth-child(2)')); } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { InfiniteScrollModule } from 'ngx-infinite-scroll'; import { FormsModule } from '@angular/forms'; import { ReportService } from '../../@core/data/report.service'; import { DemoTableComponent } from './demo-table.component'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { SpinnerComponent } from '../../@theme/spinner/spinner.component'; import {DatePipe} from '@angular/common'; import { SearchBarComponent } from './search-bar/search-bar.component'; @NgModule({ imports: [ CommonModule, InfiniteScrollModule, MatProgressSpinnerModule, FormsModule ], declarations: [DemoTableComponent, SpinnerComponent, SearchBarComponent], providers: [ReportService] }) export class DemoTableModule { } <file_sep>import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { Data } from './data'; @Injectable() export class ReportService { constructor(private http: HttpClient) { } getDemo(page: number = 0, size: number = 15, customerID: string): Observable<Data> { let url = `http://192.168.3.11:8080/demo/find?page=${page}&size=${size}`; if(customerID) { url += `&customer_id=${customerID}`; } return this.http.get<Data>(url); } } <file_sep>import { NbMenuItem } from '@nebular/theme'; export const MENU_ITEMS: NbMenuItem[] = [ { title: 'Table', icon: 'nb-tables', link: '/pages/table', home: true, }, { title: 'Charts', icon: 'nb-bar-chart', link: '/pages/charts', } ]; <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule, Routes } from '@angular/router'; import {PagesComponent} from './pages.component'; import {ChartsComponent} from './charts/charts.component'; import {DemoTableComponent} from './demo-table/demo-table.component'; const routes: Routes = [{ path: '', component: PagesComponent, children: [{ path: 'charts', component: ChartsComponent, }, { path: 'table', component: DemoTableComponent, }, { path: '', redirectTo: 'table', pathMatch: 'full', }], }]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule], declarations: [] }) export class PagesRoutingModule { } <file_sep># demo This demo contains the codes of frontend and backend. [Live Demo](http://my-demo.cf/)<file_sep>export class Data { content: Array<any>; totalElements: number; numberOfElements: number; }
3ea278590fb1079b36e02bba7e59a434079b13f0
[ "Markdown", "Java", "TypeScript" ]
13
Java
wjchwygood/demo
6ce761a9e5871fc7385eedd438bb39469f08536e
f5aec3f3f0bb8d0371dcde43e937e9910d254e27
refs/heads/master
<file_sep>""" Compared with model_baseline, do not use correlation output for skip link Compared to model_baseline_fixed, added return values to test whether nsample is set reasonably. """ import tensorflow as tf import numpy as np import math import sys import os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(BASE_DIR, '../utils')) sys.path.append(os.path.join(BASE_DIR, '..')) sys.path.append(os.path.join(BASE_DIR, '../tf_ops/sampling')) sys.path.append(os.path.join(BASE_DIR, '../tf_ops/grouping')) from tf_sampling import farthest_point_sample, gather_point #from tf_grouping import query_ball_point, query_ball_point_var_rad, group_point, knn_point from tf_grouping import query_ball_point, group_point, knn_point import tf_util from net_utils_GAT import * def gating_process(inputs,num_output_channels,scope,stride=1,padding='VALID',bn_decay=None,is_training=None): with tf.variable_scope(scope) as sc: num_in_channels = inputs.get_shape()[-1].value kernel_shape = [1, num_in_channels, num_output_channels] with tf.device("/cpu:0"): kernel = tf.get_variable('weights', kernel_shape, initializer= tf.contrib.layers.xavier_initializer(), dtype=tf.float32) biases = tf.get_variable('biases', [num_output_channels], initializer=tf.constant_initializer(0.0), dtype=tf.float32) df='NHWC' outputs = tf.nn.conv1d(inputs, kernel, stride=stride, padding=padding, data_format=df) outputs = tf.nn.bias_add(outputs, biases, data_format=df) outputs =tf.contrib.layers.batch_norm(outputs, center=True, scale=True, is_training=is_training, decay=bn_decay,updates_collections=None, scope='bn', data_format=df) outputs = tf.nn.relu(outputs) return outputs def placeholder_inputs(batch_size, num_point, num_frames): pointclouds_pl = tf.placeholder(tf.float32, shape=(batch_size, num_point * num_frames, 3 + 3)) labels_pl = tf.placeholder(tf.int32, shape=(batch_size, num_point * num_frames)) labelweights_pl = tf.placeholder(tf.float32, shape=(batch_size, num_point * num_frames)) masks_pl = tf.placeholder(tf.float32, shape=(batch_size, num_point * num_frames)) return pointclouds_pl, labels_pl, labelweights_pl, masks_pl def get_model(point_cloud, num_frames, is_training, bn_decay=None): """ Semantic segmentation PointNet, input is BxNx3, output Bxnum_class """ end_points = {} batch_size = point_cloud.get_shape()[0].value num_point = point_cloud.get_shape()[1].value // num_frames l0_xyz = point_cloud[:, :, 0:3] #l0_time = tf.concat([tf.ones([batch_size, num_point, 1]) * i for i in range(num_frames)], \ # axis=-2) #l0_points = tf.concat([point_cloud[:, :, 3:], l0_time], axis=-1) l0_points = point_cloud[:, :, 3:] #######Contextual representation farthest_distance=0.6 num_neighbors=4 new_xyz = l0_xyz # (batch_size, npoint, 3) idx, pts_cnt = query_ball_point(farthest_distance, num_neighbors, l0_xyz, new_xyz) neighbor_xyz = group_point(l0_xyz, idx) neighbor_xyz -= tf.tile(tf.expand_dims(new_xyz, 2), [1,1,num_neighbors,1]) neighbor_points = group_point(l0_points, idx) neighbor_representation = tf.concat([neighbor_xyz, neighbor_points], axis=-1) neighbor_representation=tf.reshape(neighbor_representation, (batch_size, point_cloud.get_shape()[1].value, -1)) num_channel=neighbor_representation.get_shape()[2].value points= tf_util.conv1d(point_cloud, num_channel, 1, padding='VALID', bn=True, is_training=is_training, scope='points_fc', bn_decay=bn_decay) neighbor_representation_gp= gating_process(neighbor_representation, num_channel, padding='VALID', is_training=is_training, scope='neighbor_representation_gp', bn_decay=bn_decay) points_gp= gating_process(points, num_channel, padding='VALID', is_training=is_training, scope='points_gp', bn_decay=bn_decay) l0_points_CR=tf.concat([neighbor_representation_gp*points, points_gp*neighbor_representation], axis=-1) ########## Positional Representation idx, pts_cnt = query_ball_point(0.6, 32, l0_xyz, l0_xyz) neighbor_xyz = group_point(l0_xyz, idx) # neighbor_xyz = self.gather_neighbour(xyz, neigh_idx) xyz_tile = tf.tile(tf.expand_dims(l0_xyz, axis=2), [1, 1, tf.shape(idx)[-1], 1]) relative_xyz = xyz_tile - neighbor_xyz #relative_xyz =neighbor_xyz relative_dis = tf.reduce_sum(tf.square(relative_xyz), axis=-1, keepdims=True) encoded_position= tf.concat([relative_dis, relative_xyz, xyz_tile, neighbor_xyz], axis=-1) encoded_position = tf_util.conv2d(encoded_position, num_channel*2, [1, 1], padding='VALID', stride=[1, 1], bn=True, is_training=is_training, scope='conv011' , bn_decay=bn_decay ) positional_representation= tf.reduce_mean(encoded_position, axis=[2], keep_dims=True, name='avgpool') l0_points = tf_util.conv2d(tf.concat([positional_representation, tf.expand_dims(l0_points_CR, 2)], axis=-1),num_channel*2, [1,1], padding='VALID', stride=[1,1], bn=True, is_training=is_training, scope='attp', bn_decay=bn_decay) l0_points= tf.squeeze(l0_points, [2]) l1_xyz, l1_points, l1_indices = pointnet_sa_module_withgab(l0_xyz, l0_points, npoint=2048, radius=1.0, nsample=32, mlp=[32,32,64], mlp2=None, group_all=False,knn=False, is_training=is_training, bn_decay=bn_decay, scope='layer1',gab=True) l2_xyz, l2_points, l2_indices = pointnet_sa_module(l1_xyz, l1_points, npoint=512, radius=2.0, nsample=32, mlp=[64,64,128], mlp2=None, group_all=False,knn=False, is_training=is_training, bn_decay=bn_decay, scope='layer2') l3_xyz, l3_points, l3_indices = pointnet_sa_module(l2_xyz, l2_points, npoint=128, radius=4.0, nsample=32, mlp=[128,128,256], mlp2=None, group_all=False, knn=False, is_training=is_training, bn_decay=bn_decay, scope='layer3') l4_xyz, l4_points, l4_indices = pointnet_sa_module(l3_xyz, l3_points, npoint=64, radius=8.0, nsample=32, mlp=[256,256,512], mlp2=None, group_all=False, knn=False, is_training=is_training, bn_decay=bn_decay, scope='layer4') # Feature Propagation layers l3_points = pointnet_fp_module(l3_xyz, l4_xyz, l3_points, l4_points, [256,256], is_training, bn_decay, scope='fa_layer1') l2_points = pointnet_fp_module(l2_xyz, l3_xyz, l2_points, l3_points, [256,256], is_training, bn_decay, scope='fa_layer2') l1_points = pointnet_fp_module(l1_xyz, l2_xyz, l1_points, l2_points, [256,128], is_training, bn_decay, scope='fa_layer3') l0_points = pointnet_fp_module(l0_xyz, l1_xyz, l0_points, l1_points, [128,128], is_training, bn_decay, scope='fa_layer4') ##### debug net = tf_util.conv1d(l0_points, 128, 1, padding='VALID', bn=True, is_training=is_training, scope='fc1', bn_decay=bn_decay) ########## Channel-wise Attention input = net output_f = tf.transpose(input, [0, 2, 1]) energy = tf.matmul(output_f, input) D = tf.reduce_max(energy, -1) D = tf.expand_dims(D, -1) energy_new = tf.tile(D, multiples=[1, 1, energy.shape[2]]) - energy attention = tf.nn.softmax(energy_new, axis=-1) output_CA = tf.matmul(input, attention) gamma2 = tf_util._variable_with_weight_decay('weightsgamma2m', shape=[1], use_xavier=True, stddev=1e-3, wd=0.0) output_CA = output_CA * gamma2 + input output_CA=tf_util.conv1d(output_CA, 2, 1, padding='VALID', activation_fn=None, scope='cpm') end_points['feats'] =output_CA ########## Squeeze-and-Excitation ex1 = tf.reduce_mean(input, axis=[1], keep_dims=True, name='avgpool1') print(ex1 .get_shape()) ex1 = tf_util.conv1d(ex1,64, 1, padding='VALID', scope='ex1') print(ex1 .get_shape()) ex1 = tf_util.conv1d(ex1,128, 1, padding='VALID', scope='ex2') print(ex1 .get_shape()) output=input*ex1 net = tf_util.dropout(output, keep_prob=0.5, is_training=is_training, scope='dp1') net = tf_util.conv1d(net, 12, 1, padding='VALID', activation_fn=None, scope='fc2') return net, end_points def get_loss(pred, label, mask, end_points, label_weights): """ pred: BxNx3, label: BxN, mask: BxN """ classify_loss = tf.losses.sparse_softmax_cross_entropy( labels=label, \ logits=pred, \ weights=label_weights, \ reduction=tf.losses.Reduction.NONE) classify_loss = tf.reduce_sum(classify_loss * mask) / (tf.reduce_sum(mask) + 1) tf.summary.scalar('classify loss', classify_loss) tf.add_to_collection('losses', classify_loss) tf.add_to_collection('losses1', classify_loss) return classify_loss if __name__=='__main__': with tf.Graph().as_default(): inputs = tf.zeros((32,1024*2,6)) outputs = get_model(inputs, tf.constant(True)) print(outputs) <file_sep>import argparse import math from datetime import datetime #import h5py import numpy as np import tensorflow as tf import socket import importlib import os import sys import pickle BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(BASE_DIR) # model sys.path.append(os.path.join(BASE_DIR, 'models')) # model sys.path.append(os.path.join(BASE_DIR, '../utils')) sys.path.append(os.path.join(BASE_DIR, '../data')) import synthia_dataset import class_mapping parser = argparse.ArgumentParser() parser.add_argument('--num_gpus', type=int, default=1, help='How many gpus to use [default: 1]') parser.add_argument('--data', default='/data/hejingming/PCL/meteornet-master/processed_pc', help='Dataset dir [default: model_basic]') parser.add_argument('--model', default='dy_seg_model', help='Model name [default: model_basic]') parser.add_argument('--model_path', default=None, help='Model path to restore [default: None]') parser.add_argument('--log_dir', default='log', help='Log dir [default: log]') parser.add_argument('--num_point', type=int, default=16384, help='Point Number [default: 2048]') parser.add_argument('--num_frame', type=int, default=1, help='Number of frames [default: 1]') parser.add_argument('--max_epoch', type=int, default=150, help='Epoch to run [default: 100]') parser.add_argument('--batch_size', type=int, default=12, help='Batch Size during training [default: 32]') parser.add_argument('--learning_rate', type=float, default=0.0016, help='Initial learning rate [default: 0.001]') parser.add_argument('--command_file', default=None, help='Name of command file [default: None]') parser.add_argument('--momentum', type=float, default=0.9, help='Initial learning rate [default: 0.9]') parser.add_argument('--optimizer', default='adam', help='adam or momentum [default: adam]') parser.add_argument('--decay_step', type=int, default=200000, help='Decay step for lr decay [default: 200000]') parser.add_argument('--decay_rate', type=float, default=0.7, help='Decay rate for lr decay [default: 0.7]') parser.add_argument('--visu', type=bool, default=False, help='Whether to dump visualization results.') FLAGS = parser.parse_args() #os.environ['CUDA_VISIBLE_DEVICES'] = str(FLAGS.gpu) NUM_GPUS = FLAGS.num_gpus BATCH_SIZE = FLAGS.batch_size DATA = FLAGS.data NUM_POINT = FLAGS.num_point NUM_FRAME = FLAGS.num_frame MAX_EPOCH = FLAGS.max_epoch BASE_LEARNING_RATE = FLAGS.learning_rate #GPU_INDEX = FLAGS.gpu MOMENTUM = FLAGS.momentum OPTIMIZER = FLAGS.optimizer DECAY_STEP = FLAGS.decay_step DECAY_RATE = FLAGS.decay_rate COMMAND_FILE = FLAGS.command_file assert(BATCH_SIZE % NUM_GPUS == 0) DEVICE_BATCH_SIZE = BATCH_SIZE / NUM_GPUS MODEL = importlib.import_module(FLAGS.model) # import network module MODEL_FILE = os.path.join(BASE_DIR, 'models', FLAGS.model+'.py') MODEL_PATH = FLAGS.model_path LOG_DIR = FLAGS.log_dir if not os.path.exists(LOG_DIR): os.mkdir(LOG_DIR) os.system('cp %s %s' % (MODEL_FILE, LOG_DIR)) # bkp of model def os.system('cp %s %s' % (__file__, LOG_DIR)) # bkp of train procedure os.system('cp %s %s' % (COMMAND_FILE, LOG_DIR)) # bkp of command file os.system('cp %s %s' % ('synthia_dataset.py', LOG_DIR)) # bkp of command file os.system('cp ../utils/net_utils.py %s' % (LOG_DIR)) # bkp of train procedure LOG_FOUT = open(os.path.join(LOG_DIR, 'log_train.txt'), 'w') LOG_FOUT.write(str(FLAGS)+'\n') BN_INIT_DECAY = 0.5 BN_DECAY_DECAY_RATE = 0.5 BN_DECAY_DECAY_STEP = float(DECAY_STEP) BN_DECAY_CLIP = 0.99 NUM_CLASSES = 12 TRAINVAL_DATASET = synthia_dataset.SegDataset(DATA, filelist_name='data_prep/trainval_raw.txt', npoints=NUM_POINT, num_nonkey=NUM_FRAME-1, train=True) TEST_DATASET = synthia_dataset.SegDataset(DATA, filelist_name='data_prep/test_raw.txt', npoints=NUM_POINT, num_nonkey=NUM_FRAME-1, train=False) def log_string(out_str): LOG_FOUT.write(out_str+'\n') LOG_FOUT.flush() print(out_str) def average_gradients(tower_grads): """Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. From tensorflow tutorial: cifar10/cifar10_multi_gpu_train.py Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradients. The inner list is over the gradient calculation for each tower. Returns: List of pairs of (gradient, variable) where the gradient has been averaged across all towers. """ average_grads = [] for grad_and_vars in zip(*tower_grads): # Note that each grad_and_vars looks like the following: # ((grad0_gpu0, var0_gpu0), ... , (grad0_gpuN, var0_gpuN)) grads = [] #for g, _ in grad_and_vars: for g, v in grad_and_vars: # Add 0 dimension to the gradients to represent the tower. expanded_g = tf.expand_dims(g, 0) # Append on a 'tower' dimension which we will average over below. grads.append(expanded_g) # Average over the 'tower' dimension. grad = tf.concat(axis=0, values=grads) grad = tf.reduce_mean(grad, 0) # Keep in mind that the Variables are redundant because they are shared # across towers. So .. we will just return the first tower's pointer to # the Variable. v = grad_and_vars[0][1] grad_and_var = (grad, v) average_grads.append(grad_and_var) return average_grads def get_learning_rate(batch): learning_rate = tf.train.exponential_decay( BASE_LEARNING_RATE, # Base learning rate. batch * BATCH_SIZE, # Current index into the dataset. DECAY_STEP, # Decay step. DECAY_RATE, # Decay rate. staircase=True) learing_rate = tf.maximum(learning_rate, 0.00001) # CLIP THE LEARNING RATE! return learning_rate def get_bn_decay(batch): bn_momentum = tf.train.exponential_decay( BN_INIT_DECAY, batch*BATCH_SIZE, BN_DECAY_DECAY_STEP, BN_DECAY_DECAY_RATE, staircase=True) bn_decay = tf.minimum(BN_DECAY_CLIP, 1 - bn_momentum) return bn_decay def train(): with tf.Graph().as_default(): with tf.device('/cpu:0'): pointclouds_pl, labels_pl, labelweights_pl, masks_pl = MODEL.placeholder_inputs(BATCH_SIZE, NUM_POINT, NUM_FRAME) is_training_pl = tf.placeholder(tf.bool, shape=()) #print(is_training_pl) # Note the global_step=batch parameter to minimize. # That tells the optimizer to helpfully increment the 'batch' parameter for you every time it trains. batch = tf.get_variable('batch', [], initializer=tf.constant_initializer(0), trainable=False) bn_decay = get_bn_decay(batch) tf.summary.scalar('bn_decay', bn_decay) print("--- Get training operator") # Get training operator learning_rate = get_learning_rate(batch) tf.summary.scalar('learning_rate', learning_rate) if OPTIMIZER == 'momentum': optimizer = tf.train.MomentumOptimizer(learning_rate, momentum=MOMENTUM) elif OPTIMIZER == 'adam': optimizer = tf.train.AdamOptimizer(learning_rate) print("--- Get model and loss") MODEL.get_model(pointclouds_pl, NUM_FRAME, is_training_pl, bn_decay=bn_decay) tower_grads = [] pred_gpu = [] total_loss_gpu = [] for i in range(NUM_GPUS): with tf.variable_scope(tf.get_variable_scope(), reuse=True): with tf.device('/gpu:%d'%(i)), tf.name_scope('gpu_%d'%(i)) as scope: # Get model and loss pc_batch = tf.slice(pointclouds_pl, [i*DEVICE_BATCH_SIZE,0,0], [DEVICE_BATCH_SIZE,-1,-1]) label_batch = tf.slice(labels_pl, [i*DEVICE_BATCH_SIZE,0], [DEVICE_BATCH_SIZE,-1]) labelweights_batch = tf.slice(labelweights_pl, [i*DEVICE_BATCH_SIZE,0], [DEVICE_BATCH_SIZE,-1]) masks_batch = tf.slice(masks_pl, [i*DEVICE_BATCH_SIZE,0], [DEVICE_BATCH_SIZE,-1]) pred, end_points = MODEL.get_model(pc_batch, NUM_FRAME, is_training_pl, bn_decay=bn_decay) MODEL.get_loss(pred, label_batch, masks_batch, end_points, labelweights_batch) losses = tf.get_collection('losses1', scope) total_loss = tf.add_n(losses, name='total_loss') for l in losses + [total_loss]: tf.summary.scalar(l.op.name, l) #tf.summary.scalar('loss', loss) grads = optimizer.compute_gradients(total_loss) tower_grads.append(grads) pred_gpu.append(pred) total_loss_gpu.append(total_loss) pred = tf.concat(pred_gpu, 0) total_loss = tf.reduce_mean(total_loss_gpu) # Get training operator grads = average_gradients(tower_grads) train_op = optimizer.apply_gradients(grads, global_step=batch) correct = tf.equal(tf.argmax(pred, 2), tf.to_int64(labels_pl)) accuracy = tf.reduce_sum(tf.cast(correct, tf.float32)) / float(BATCH_SIZE*NUM_POINT) tf.summary.scalar('accuracy', accuracy) # Add ops to save and restore all the variables. saver = tf.train.Saver() # Create a session config = tf.ConfigProto() config.gpu_options.allow_growth = True config.allow_soft_placement = True config.log_device_placement = False sess = tf.Session(config=config) # Add summary writers merged = tf.summary.merge_all() train_writer = tf.summary.FileWriter(os.path.join(LOG_DIR, 'train'), sess.graph) test_writer = tf.summary.FileWriter(os.path.join(LOG_DIR, 'test'), sess.graph) # Init variables init = tf.global_variables_initializer() sess.run(init) #sess.run(init, {is_training_pl: True}) if (MODEL_PATH is not None) and (MODEL_PATH != 'None'): saver = tf.train.Saver() saver.restore(sess, MODEL_PATH) log_string('Model restored.') ops = {'pointclouds_pl': pointclouds_pl, 'labels_pl': labels_pl, 'labelweights_pl': labelweights_pl, 'masks_pl': masks_pl, 'is_training_pl': is_training_pl, 'pred': pred, 'loss':total_loss, 'train_op': train_op, 'merged': merged, 'step': batch, 'end_points': end_points} for epoch in range(MAX_EPOCH): log_string('**** EPOCH %03d ****' % (epoch)) log_string('learning_rate: {}'.format(sess.run(learning_rate))) sys.stdout.flush() train_one_epoch(sess, ops, train_writer) # Save the variables to disk. if (epoch+1) % 1 == 0: save_path = saver.save(sess, os.path.join(LOG_DIR, "model-{}.ckpt".format(epoch))) log_string("Model saved in file: %s" % save_path) log_string('---- EPOCH %03d TEST ----'%(epoch)) eval_one_epoch(sess, ops, test_writer, dataset=TEST_DATASET, epoch_cnt=epoch) def get_batch(dataset, idxs, start_idx, end_idx, half=0): bsize = end_idx - start_idx batch_data = np.zeros((bsize, NUM_POINT * NUM_FRAME, 3 + 3)) batch_label = np.zeros((bsize, NUM_POINT * NUM_FRAME), dtype='int32') batch_mask = np.zeros((bsize, NUM_POINT * NUM_FRAME), dtype=np.bool) for i in range(bsize): pc, rgb, label, labelweights, loss_mask, valid_pred_idx_in_full = dataset.get(idxs[i+start_idx], half) batch_data[i, :, :3] = pc batch_data[i, :, 3:] = rgb batch_label[i] = label batch_mask[i] = loss_mask batch_labelweights = labelweights[batch_label] return batch_data, batch_label, batch_labelweights, batch_mask def train_one_epoch(sess, ops, train_writer): """ ops: dict mapping from string to tf ops """ is_training = True # Shuffle train samples train_idxs = np.arange(0, len(TRAINVAL_DATASET)) np.random.shuffle(train_idxs) num_batches = len(TRAINVAL_DATASET) // BATCH_SIZE log_string(str(datetime.now())) loss_sum = 0 for batch_idx in range(num_batches): #for half in [0, 1]: for half in [0]: start_idx = batch_idx * BATCH_SIZE end_idx = (batch_idx+1) * BATCH_SIZE batch_data, batch_label, batch_labelweights, batch_mask = \ get_batch(TRAINVAL_DATASET, train_idxs, start_idx, end_idx, half) #print(half) #print(batch_data.shape) #ply1=batch_data[0] #for i in range(ply1.shape[0]): # print('v '+str(ply1[i][0])+' '+str(ply1[i][1])+' '+str(ply1[i][2])+' 6') feed_dict = {ops['pointclouds_pl']: batch_data, ops['labels_pl']: batch_label, ops['labelweights_pl']: batch_labelweights, ops['masks_pl']: batch_mask, ops['is_training_pl']: is_training,} summary, step, _, loss_val, pred_val = sess.run([ops['merged'], ops['step'], ops['train_op'], ops['loss'], ops['pred']], feed_dict=feed_dict) train_writer.add_summary(summary, step) loss_sum += loss_val if (batch_idx+1)%10 == 0: log_string(' -- %03d / %03d --' % (batch_idx+1, num_batches)) log_string('mean loss: %f' % (loss_sum / 10 / 2)) loss_sum = 0 def eval_one_epoch(sess, ops, test_writer, dataset, epoch_cnt): """ ops: dict mapping from string to tf ops """ is_training = False test_idxs = np.arange(0, len(dataset)) # Test on all data: last batch might be smaller than BATCH_SIZE num_batches = (len(dataset)+BATCH_SIZE-1) // BATCH_SIZE loss_sum = 0 total_correct = 0 total_seen = 0 total_pred_label_class = [0 for _ in range(NUM_CLASSES)] total_correct_class = [0 for _ in range(NUM_CLASSES)] total_class = [0 for _ in range(NUM_CLASSES)] log_string(str(datetime.now())) log_string('---- EPOCH %03d EVALUATION ----'%(epoch_cnt)) batch_data = np.zeros((BATCH_SIZE, NUM_POINT*NUM_FRAME, 3 + 3)) batch_label = np.zeros((BATCH_SIZE, NUM_POINT*NUM_FRAME)) batch_mask = np.zeros((BATCH_SIZE, NUM_POINT*NUM_FRAME)) batch_labelweights = np.zeros((BATCH_SIZE, NUM_POINT*NUM_FRAME)) for batch_idx in range(num_batches): if batch_idx %20==0: log_string('%03d/%03d'%(batch_idx, num_batches)) start_idx = batch_idx * BATCH_SIZE end_idx = min(len(dataset), (batch_idx+1) * BATCH_SIZE) cur_batch_size = end_idx-start_idx #for half in [0, 1]: for half in [0]: cur_batch_data, cur_batch_label, cur_batch_labelweights, cur_batch_mask = \ get_batch(dataset, test_idxs, start_idx, end_idx, half) if cur_batch_size == BATCH_SIZE: batch_data = cur_batch_data batch_label = cur_batch_label batch_mask = cur_batch_mask batch_labelweights = cur_batch_labelweights else: batch_data[0:(cur_batch_size)] = cur_batch_data batch_label[0:(cur_batch_size)] = cur_batch_label batch_mask[0:(cur_batch_size)] = cur_batch_mask batch_labelweights[0:(cur_batch_size)] = cur_batch_labelweights # --------------------------------------------------------------------- # ---- INFERENCE BELOW ---- feed_dict = {ops['pointclouds_pl']: batch_data, ops['labels_pl']: batch_label, ops['labelweights_pl']: batch_labelweights, ops['masks_pl']: batch_mask, ops['is_training_pl']: is_training} summary, step, loss_val, pred_val = sess.run([ops['merged'], ops['step'], ops['loss'], ops['pred']], feed_dict=feed_dict) test_writer.add_summary(summary, step) # ---- INFERENCE ABOVE ---- # --------------------------------------------------------------------- pred_val = np.argmax(pred_val, 2) # BxN cur_pred_val = pred_val[0:cur_batch_size] correct = np.sum((cur_pred_val == cur_batch_label) * cur_batch_mask) # evaluate only on 20 categories but not unknown total_correct += correct total_seen += np.sum(cur_batch_mask) if cur_batch_size == BATCH_SIZE: loss_sum += loss_val for l in range(NUM_CLASSES): total_pred_label_class[l] += np.sum(((cur_pred_val==l) | (cur_batch_label==l)) & cur_batch_mask) total_correct_class[l] += np.sum((cur_pred_val==l) & (cur_batch_label==l) & cur_batch_mask) total_class[l] += np.sum((cur_batch_label==l) & cur_batch_mask) log_string('eval mean loss: %f' % (loss_sum / float(len(dataset)/BATCH_SIZE))) ACCs = [] for i in range(NUM_CLASSES): acc = total_correct_class[i] / float(total_class[i]) if total_class[i] == 0: acc = 0 log_string('eval acc of %s:\t %f'%(class_mapping.index_to_class[class_mapping.label_to_index[i]], acc)) ACCs.append(acc) log_string('eval accuracy: %f'% (np.mean(np.array(ACCs)))) IoUs = [] for i in range(NUM_CLASSES): iou = total_correct_class[i] / float(total_pred_label_class[i]) if total_pred_label_class[i] == 0: iou = 0 log_string('eval mIoU of %s:\t %f'%(class_mapping.index_to_class[class_mapping.label_to_index[i]], iou)) IoUs.append(iou) log_string('eval mIoU:\t %f'%(np.mean(np.array(IoUs)))) return loss_sum/float(len(dataset)/BATCH_SIZE) if __name__ == "__main__": log_string('pid: %s'%(str(os.getpid()))) train() LOG_FOUT.close() <file_sep>import os import sys BASE_DIR = os.path.dirname(__file__) ROOT_DIR = os.path.dirname(BASE_DIR) sys.path.append(BASE_DIR) sys.path.append(os.path.join(BASE_DIR, '../utils')) sys.path.append(os.path.join(ROOT_DIR, 'tf_ops/sampling')) sys.path.append(os.path.join(ROOT_DIR, 'tf_ops/grouping')) from tf_sampling import farthest_point_sample, gather_point from tf_grouping import query_ball_point, group_point, knn_point import tensorflow as tf import numpy as np import tf_util from pointnet_gab_util import pointnet_sa_module_withgab, pointnet_fp_module def gating_process(inputs,num_output_channels,scope,stride=1,padding='VALID',bn_decay=None,is_training=None): with tf.variable_scope(scope) as sc: num_in_channels = inputs.get_shape()[-1].value kernel_shape = [1, num_in_channels, num_output_channels] with tf.device("/cpu:0"): kernel = tf.get_variable('weights', kernel_shape, initializer= tf.contrib.layers.xavier_initializer(), dtype=tf.float32) biases = tf.get_variable('biases', [num_output_channels], initializer=tf.constant_initializer(0.0), dtype=tf.float32) df='NHWC' outputs = tf.nn.conv1d(inputs, kernel, stride=stride, padding=padding, data_format=df) outputs = tf.nn.bias_add(outputs, biases, data_format=df) outputs =tf.contrib.layers.batch_norm(outputs, center=True, scale=True, is_training=is_training, decay=bn_decay,updates_collections=None, scope='bn', data_format=df) outputs = tf.nn.relu(outputs) return outputs def placeholder_inputs(batch_size, num_point): pointclouds_pl = tf.placeholder(tf.float32, shape=(batch_size, num_point, 9)) labels_pl = tf.placeholder(tf.int32, shape=(batch_size, num_point)) return pointclouds_pl, labels_pl def get_model(point_cloud, is_training, num_neighbors, farthest_distance, bn_decay=None): """ Semantic segmentation PointNet, input is BxNx9, output Bxnum_class """ batch_size = point_cloud.get_shape()[0].value num_point = point_cloud.get_shape()[1].value end_points = {} l0_xyz = point_cloud[:, :, 0:3] l0_points = point_cloud[:, :, 3:9] #######Contextual representation new_xyz = l0_xyz # (batch_size, npoint, 3) idx, pts_cnt = query_ball_point(farthest_distance, num_neighbors, l0_xyz, new_xyz) neighbor_xyz = group_point(l0_xyz, idx) neighbor_xyz -= tf.tile(tf.expand_dims(new_xyz, 2), [1,1,num_neighbors,1]) neighbor_points = group_point(l0_points, idx) neighbor_representation = tf.concat([neighbor_xyz, neighbor_points], axis=-1) neighbor_representation=tf.reshape(neighbor_representation, (batch_size, num_point, -1)) num_channel=neighbor_representation.get_shape()[2].value points= tf_util.conv1d(point_cloud, num_channel, 1, padding='VALID', bn=True, is_training=is_training, scope='points_fc', bn_decay=bn_decay) neighbor_representation_gp= gating_process(neighbor_representation, num_channel, padding='VALID', is_training=is_training, scope='neighbor_representation_gp', bn_decay=bn_decay) points_gp= gating_process(points, num_channel, padding='VALID', is_training=is_training, scope='points_gp', bn_decay=bn_decay) l0_points_CR=tf.concat([neighbor_representation_gp*points, points_gp*neighbor_representation], axis=-1) ########## Positional Representation idx, pts_cnt = query_ball_point(0.06, 16, l0_xyz, l0_xyz) neighbor_xyz = group_point(l0_xyz, idx) # neighbor_xyz = self.gather_neighbour(xyz, neigh_idx) xyz_tile = tf.tile(tf.expand_dims(l0_xyz, axis=2), [1, 1, tf.shape(idx)[-1], 1]) relative_xyz = xyz_tile - neighbor_xyz # relative_xyz =neighbor_xyz relative_dis = tf.reduce_sum(tf.square(relative_xyz), axis=-1, keepdims=True) encoded_position = tf.concat([relative_dis, relative_xyz, xyz_tile, neighbor_xyz], axis=-1) encoded_position = tf_util.conv2d(encoded_position, num_channel * 2, [1, 1], padding='VALID', stride=[1, 1], bn=True, is_training=is_training, scope='conv011', bn_decay=bn_decay ) encoded_neighbours = group_point(l0_points, idx) positional_representation = tf.concat([encoded_neighbours, encoded_position], axis=-1) positional_representation = tf.reduce_mean(positional_representation, axis=[2], keep_dims=True, name='avgpool') points = tf_util.conv2d(positional_representation, num_channel * 2, [1, 1], padding='VALID', stride=[1, 1], bn=True, is_training=is_training, scope='attp', bn_decay=bn_decay) points = tf.squeeze(points, [2]) l0_points = points + l0_points_CR # Layer 1 l1_xyz, l1_points, l1_indices = pointnet_sa_module_withgab( l0_xyz, l0_points, npoint=1024, radius=0.1, nsample=32, mlp=[32,32,64], mlp2=[64,64], group_all=False, is_training=is_training, bn_decay=bn_decay, scope='layer1',gab=True) l2_xyz, l2_points, l2_indices = pointnet_sa_module_withgab( l1_xyz, l1_points, npoint=256, radius=0.2, nsample=32, mlp=[64,64,128], mlp2=None, group_all=False, is_training=is_training, bn_decay=bn_decay, scope='layer2') l3_xyz, l3_points, l3_indices = pointnet_sa_module_withgab( l2_xyz, l2_points, npoint=64, radius=0.4, nsample=32, mlp=[128,128,256], mlp2=None, group_all=False, is_training=is_training, bn_decay=bn_decay, scope='layer3') l4_xyz, l4_points, l4_indices = pointnet_sa_module_withgab(l3_xyz, l3_points, npoint=16, radius=0.8, nsample=32, mlp=[256,256,512], mlp2=None, group_all=False, is_training=is_training, bn_decay=bn_decay, scope='layer4') # Feature Propagation layers l3_points = pointnet_fp_module(l3_xyz, l4_xyz, l3_points, l4_points, [256,256], is_training, bn_decay, scope='fa_layer1') l2_points = pointnet_fp_module(l2_xyz, l3_xyz, l2_points, l3_points, [256,256], is_training, bn_decay, scope='fa_layer2') l1_points = pointnet_fp_module(l1_xyz, l2_xyz, l1_points, l2_points, [256,128], is_training, bn_decay, scope='fa_layer3') l0_points = pointnet_fp_module(l0_xyz, l1_xyz, l0_points, l1_points, [128,128,128], is_training, bn_decay, scope='fa_layer4') # FC layers net = tf_util.conv1d(l0_points, 128, 1, padding='VALID', bn=True, is_training=is_training, scope='fc1', bn_decay=bn_decay) ########## Channel-wise Attention input = net output_a = tf_util.conv2d(tf.expand_dims(input, 1), 128, [1, 1], padding='VALID', stride=[1, 1], bn=True, is_training=is_training, scope='conv_output_a', bn_decay=bn_decay) output_b = tf_util.conv2d(tf.expand_dims(input, 1), 128, [1, 1], padding='VALID', stride=[1, 1], bn=True, is_training=is_training, scope='conv_output_b', bn_decay=bn_decay) output_b = tf.transpose(output_b, [0, 1, 3, 2]) output_a = tf.squeeze(output_a, [1]) output_b = tf.squeeze(output_b, [1]) energy = tf.matmul(output_b, output_a) D = tf.reduce_max(energy, -1) D = tf.expand_dims(D, -1) energy_new = tf.tile(D, multiples=[1, 1, energy.shape[2]]) - energy attention = tf.nn.softmax(energy_new, axis=-1) output_d = tf_util.conv2d(tf.expand_dims(input, 1), 128, [1, 1], padding='VALID', stride=[1, 1], bn=True, is_training=is_training, scope='conv_output_d', bn_decay=bn_decay) output_d = tf.squeeze(output_d, [1]) output_CA = tf.matmul(output_d, attention) gamma2 = tf_util._variable_with_weight_decay('weightsgamma2m', shape=[1], use_xavier=True, stddev=1e-3, wd=0.0) output_CA = output_CA * gamma2 + input output = output_CA ########## Squeeze-and-Excitation ex1 = tf.reduce_mean(input, axis=[1], keep_dims=True, name='avgpool1') print(ex1.get_shape()) ex1 = tf_util.conv1d(ex1, 64, 1, padding='VALID', scope='ex1') print(ex1.get_shape()) ex1 = tf_util.conv1d(ex1, 128, 1, padding='VALID', scope='ex2') print(ex1.get_shape()) output2 = input * ex1 # output=output+output2 output = tf.concat([output, output2], axis=-1) end_points['feats'] = output net = tf_util.dropout(output, keep_prob=0.5, is_training=is_training, scope='dp1') net = tf_util.conv1d(net,13, 1, padding='VALID', activation_fn=None, scope='fc2') return net, end_points def get_loss(pred, label): """ pred: BxNxC, label: BxN, smpw: BxN """ classify_loss = tf.losses.sparse_softmax_cross_entropy(labels=label, logits=pred) tf.summary.scalar('classify loss', classify_loss) tf.add_to_collection('losses', classify_loss) return classify_loss if __name__=='__main__': with tf.Graph().as_default(): inputs = tf.zeros((32,2048,3)) net, _ = get_model(inputs, tf.constant(True), 10) print(net) <file_sep>import os import sys BASE_DIR = os.path.dirname(__file__) ROOT_DIR = os.path.dirname(BASE_DIR) sys.path.append(BASE_DIR) sys.path.append(os.path.join(BASE_DIR, '../utils')) sys.path.append(os.path.join(ROOT_DIR, 'tf_ops/sampling')) sys.path.append(os.path.join(ROOT_DIR, 'tf_ops/grouping')) from tf_sampling import farthest_point_sample, gather_point from tf_grouping import query_ball_point, group_point, knn_point import tensorflow as tf import numpy as np import tf_util from pointnet_util import pointnet_sa_module, pointnet_sa_module_msg, pointnet_fp_module def placeholder_inputs(batch_size, num_point): pointclouds_pl = tf.placeholder(tf.float32, shape=(batch_size, num_point, 6)) labels_pl = tf.placeholder(tf.int32, shape=(batch_size, num_point)) cls_labels_pl = tf.placeholder(tf.int32, shape=(batch_size)) return pointclouds_pl, labels_pl, cls_labels_pl NUM_CATEGORIES = 16 def gating_process(inputs,num_output_channels,scope,stride=1,padding='VALID',bn_decay=None,is_training=None): with tf.variable_scope(scope) as sc: num_in_channels = inputs.get_shape()[-1].value kernel_shape = [1, num_in_channels, num_output_channels] with tf.device("/cpu:0"): kernel = tf.get_variable('weights', kernel_shape, initializer= tf.contrib.layers.xavier_initializer(), dtype=tf.float32) biases = tf.get_variable('biases', [num_output_channels], initializer=tf.constant_initializer(0.0), dtype=tf.float32) df='NHWC' outputs = tf.nn.conv1d(inputs, kernel, stride=stride, padding=padding, data_format=df) outputs = tf.nn.bias_add(outputs, biases, data_format=df) outputs =tf.contrib.layers.batch_norm(outputs, center=True, scale=True, is_training=is_training, decay=bn_decay,updates_collections=None, scope='bn', data_format=df) outputs = tf.nn.relu(outputs) return outputs def get_model(point_cloud, cls_label, is_training, bn_decay=None): """ Classification PointNet, input is BxNx3, output Bx40 """ batch_size = point_cloud.get_shape()[0].value num_point = point_cloud.get_shape()[1].value end_points = {} l0_xyz = tf.slice(point_cloud, [0,0,0], [-1,-1,3]) l0_points = tf.slice(point_cloud, [0,0,3], [-1,-1,3]) farthest_distance=0.15 num_neighbors=4 #######Contextual representation new_xyz = l0_xyz # (batch_size, npoint, 3) idx, pts_cnt = query_ball_point(farthest_distance, num_neighbors, l0_xyz, new_xyz) neighbor_xyz = group_point(l0_xyz, idx) neighbor_xyz -= tf.tile(tf.expand_dims(new_xyz, 2), [1,1,num_neighbors,1]) neighbor_points = group_point(l0_points, idx) neighbor_representation = tf.concat([neighbor_xyz, neighbor_points], axis=-1) neighbor_representation=tf.reshape(neighbor_representation, (batch_size, num_point, -1)) num_channel=neighbor_representation.get_shape()[2].value points= tf_util.conv1d(point_cloud, num_channel, 1, padding='VALID', bn=True, is_training=is_training, scope='points_fc', bn_decay=bn_decay) neighbor_representation_gp= gating_process(neighbor_representation, num_channel, padding='VALID', is_training=is_training, scope='neighbor_representation_gp', bn_decay=bn_decay) points_gp= gating_process(points, num_channel, padding='VALID', is_training=is_training, scope='points_gp', bn_decay=bn_decay) l0_points_CR=tf.concat([neighbor_representation_gp*points, points_gp*neighbor_representation], axis=-1) l0_points=l0_points_CR ########## Positional Representation #num_channel=K idx, pts_cnt = query_ball_point(0.2, 16, l0_xyz, l0_xyz) neighbor_xyz = group_point(l0_xyz, idx) # neighbor_xyz = self.gather_neighbour(xyz, neigh_idx) xyz_tile = tf.tile(tf.expand_dims(l0_xyz, axis=2), [1, 1, tf.shape(idx)[-1], 1]) relative_xyz = xyz_tile - neighbor_xyz #relative_xyz =neighbor_xyz relative_dis = tf.reduce_sum(tf.square(relative_xyz), axis=-1, keepdims=True) encoded_position= tf.concat([relative_dis, relative_xyz, xyz_tile, neighbor_xyz], axis=-1) encoded_position = tf_util.conv2d(encoded_position, 16, [1, 1], padding='VALID', stride=[1, 1], bn=True, is_training=is_training, scope='conv011', bn_decay=bn_decay ) encoded_neighbours = group_point(l0_points, idx) positional_representation = tf.concat([encoded_neighbours, encoded_position], axis=-1) positional_representation= tf.reduce_mean(positional_representation, axis=[2], keep_dims=True, name='avgpool') points = tf_util.conv2d(tf.concat([positional_representation, tf.expand_dims(l0_points_CR, 2)], axis=-1),num_channel*2, [1,1], padding='VALID', stride=[1,1], bn=True, is_training=is_training, scope='attp', bn_decay=bn_decay) points= tf.squeeze(points, [2]) end_points['points'] = points # Set abstraction layers l1_xyz, l1_points = pointnet_sa_module_msg(l0_xyz, l0_points, 512, [0.1,0.2,0.4], [32,64,128], [[32,32,64], [64,64,128], [64,96,128]], is_training, bn_decay, scope='layer1') l2_xyz, l2_points = pointnet_sa_module_msg(l1_xyz, l1_points, 128, [0.4,0.8], [64,128], [[128,128,256],[128,196,256]], is_training, bn_decay, scope='layer2') l3_xyz, l3_points, l3_indices = pointnet_sa_module(l2_xyz, l2_points, npoint=None, radius=None, nsample=None, mlp=[256,512,1024], mlp2=None, group_all=True, is_training=is_training, bn_decay=bn_decay, scope='layer3') # Feature propagation layers l2_points = pointnet_fp_module(l2_xyz, l3_xyz, l2_points, l3_points, [256,256], is_training, bn_decay, scope='fa_layer1') l1_points = pointnet_fp_module(l1_xyz, l2_xyz, l1_points, l2_points, [256,128], is_training, bn_decay, scope='fa_layer2') cls_label_one_hot = tf.one_hot(cls_label, depth=NUM_CATEGORIES, on_value=1.0, off_value=0.0) cls_label_one_hot = tf.reshape(cls_label_one_hot, [batch_size, 1, NUM_CATEGORIES]) cls_label_one_hot = tf.tile(cls_label_one_hot, [1,num_point,1]) l0_points = pointnet_fp_module(l0_xyz, l1_xyz, tf.concat([cls_label_one_hot, l0_xyz, l0_points],axis=-1), l1_points, [128,128], is_training, bn_decay, scope='fp_layer3') # FC layers net = tf_util.conv1d(l0_points, 128, 1, padding='VALID', bn=True, is_training=is_training, scope='fc1', bn_decay=bn_decay) ########## Channel-wise Attention input = net output_a = tf_util.conv2d(tf.expand_dims(input, 1),128, [1,1], padding='VALID', stride=[1,1], bn=True, is_training=is_training, scope='conv_output_a', bn_decay=bn_decay) output_b= tf_util.conv2d(tf.expand_dims(input, 1),128, [1,1], padding='VALID', stride=[1,1], bn=True, is_training=is_training, scope='conv_output_b', bn_decay=bn_decay) output_b = tf.transpose(output_b, [0,1,3,2]) output_a = tf.squeeze(output_a,[1]) output_b = tf.squeeze(output_b,[1]) energy=tf.matmul(output_b,output_a) D=tf.reduce_max(energy, -1) D=tf.expand_dims(D, -1) energy_new=tf.tile(D, multiples=[1, 1,energy.shape[2]])-energy attention=tf.nn.softmax(energy_new,axis=-1) output_d= tf_util.conv2d(tf.expand_dims(input, 1),128, [1,1], padding='VALID', stride=[1,1], bn=True, is_training=is_training, scope='conv_output_d', bn_decay=bn_decay) output_d= tf.squeeze(output_d,[1]) output_CA=tf.matmul(output_d,attention) gamma2 = tf_util._variable_with_weight_decay('weightsgamma2m', shape=[1], use_xavier=True, stddev=1e-3, wd=0.0) output_CA=output_CA*gamma2+input ########## Squeeze-and-Excitation ex1 = tf.reduce_mean(input, axis=[1], keep_dims=True, name='avgpool1') print(ex1 .get_shape()) ex1 = tf_util.conv1d(ex1,64, 1, padding='VALID', bn=True, is_training=is_training, scope='ex1', bn_decay=bn_decay) print(ex1 .get_shape()) ex1 = tf_util.conv1d(ex1,128, 1, padding='VALID', bn=True, is_training=is_training, scope='ex2', bn_decay=bn_decay) print(ex1 .get_shape()) output2=input*ex1 output=tf.concat([output_CA, output2], axis=-1) end_points['feats'] = output net = tf_util.dropout(net, keep_prob=0.5, is_training=is_training, scope='dp1') net = tf_util.conv1d(net, 50, 1, padding='VALID', activation_fn=None, scope='fc2') return net, end_points def get_loss(pred, label): """ pred: BxNxC, label: BxN, """ loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=pred, labels=label) classify_loss = tf.reduce_mean(loss) tf.summary.scalar('classify loss', classify_loss) tf.add_to_collection('losses', classify_loss) return classify_loss if __name__=='__main__': with tf.Graph().as_default(): inputs = tf.zeros((32,2048,6)) cls_labels = tf.zeros((32),dtype=tf.int32) output, ep = get_model(inputs, cls_labels, tf.constant(True)) print(output)
f54c9b519b2f7348d092fab169ef9e45cd3ebc09
[ "Python" ]
4
Python
fly519/ELGS2
88de170dfcab167776f47ebc5e4c5cffab91ed92
b9d694785be6323f0aeff0ea0d14a230e5fd4000
refs/heads/master
<repo_name>homam/android-landingpages-apps<file_sep>/maFeaturePhoneHtml/localhost_7645/Special/Scripts/Babelbay/Dumb/FlashAudioPlayer.js var __extends = this.__extends || function (d, b) { function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var FlashAudioPlayer = (function (_super) { __extends(FlashAudioPlayer, _super); function FlashAudioPlayer() { _super.call(this); this._queryStringCacheReset = 2; this._container = (function () { var e = document.createElement("div"); e.id = 'FlashAudioPlayer-container'; document.body.appendChild(e); return e; })(); } FlashAudioPlayer.prototype._reMake = function () { var swf = "special/scripts/Babelbay/Dumb/FlashAudioPlayer2a3b.swf?r=" + this._queryStringCacheReset; var html = "<span id='DefaultAudioPlayer-container' style='display: block; width: 1px; height: 1px; position: fixed; top: 100px; left: 2px; z-index:1000'>" + "<object width='1' height='1' id='DefaultAudioPlayer-player' type='application/x-shockwave-flash' data='" + swf + "'>" + "<param name='movie' value='" + swf + "' />" + "<param name='quality' value='high' />" + "<param name='allowfullscreen' value='true' />" + "<param name='bgcolor' value='#ffffff' />" + "<param name='play' value='true' />" + "<param name='loop' value='true' />" + "<param name='scale' value='showall' />" + "<param name='devicefont' value='false' />" + "<param name='salign' value='' />" + "<param name='allowScriptAccess' value='always' />" + "<param name='FlashVars' value='foo=" + escape(this.url) + "' />" + "</object>" + "</span>"; this._container.innerHTML = html; }; FlashAudioPlayer.prototype.start = function () { this._reMake(); document.getElementById('DefaultAudioPlayer-container').style.display = "block"; _super.prototype.start.call(this); }; FlashAudioPlayer.prototype.stop = function () { document.getElementById('DefaultAudioPlayer-container').style.display = "none"; _super.prototype.stop.call(this); }; FlashAudioPlayer._supported = null; FlashAudioPlayer.supported = function supported() { if(FlashAudioPlayer._supported == null) { if(!!window.navigator) { FlashAudioPlayer._supported = (typeof navigator.plugins == "undefined" || navigator.plugins.length == 0) ? ("undefined" != typeof ActiveXObject) : true; } else { FlashAudioPlayer._supported = false; } } return FlashAudioPlayer._supported; } return FlashAudioPlayer; })(AudioPlayerBase); <file_sep>/vipgames/README.md API documentaiton: https://docs.google.com/document/d/<KEY>edit<file_sep>/vipgames/Games/spacem.hypergunner/vipgames.api.js var vipgames = vipgames || {}; // vipgames.utils vipgames.utils = vipgames.utils || {}; // Extends original with extension and returns the newly extended original object. vipgames.utils.extend = vipgames.utils.extend || (function () { return function (original, extension, override) { var ov = !!override; if (!original) throw 'original object expected'; for (var p in extension) if (ov || !original[p]) original[p] = extension[p]; return original; }; })(); vipgames.utils = vipgames.utils.extend({ log: function () { if (!!console && !!console.log) console.log.apply(console, arguments); } }, vipgames.utils); vipgames.utils = vipgames.utils.extend({ error: function (message) { vipgames.utils.log("ERR: ", message); throw message; } }, vipgames.utils); vipgames.utils = vipgames.utils.extend({ // Returns a random string rndstr: function (L) { var s = ''; var randomchar = function () { var n = Math.floor(Math.random() * 62); if (n < 10) return n; //1-10 if (n < 36) return String.fromCharCode(n + 55); //A-Z return String.fromCharCode(n + 61); //a-z } while (s.length < L) s += randomchar(); return s; } }, vipgames.utils); vipgames.utils = vipgames.utils.extend({ // Creates a delegate for {func}. delegate: function (func, _this) { return function () { func.apply(_this, arguments); }; } }, vipgames.utils); // end vipgames.utils vipgames.ui = vipgames.ui || {}; vipgames.ui._documentLoaded = false; // true: if document is already loaded vipgames.api = vipgames.api || {}; vipgames.api._internals = { current_game: null, current_player_id: 1, // override this value in real games games: [], // override this function to actually handlle the game_event. on_game_event_handler: function (modifiedEventArgs, originalEventArgs, callback) { // simulate an AJAX call setTimeout(function () { var data = {}; if (modifiedEventArgs.event_name == "game_start") data.play_session_id = parseInt(Math.random() * 100000); // simulate a play_session_id callback(data, modifiedEventArgs, originalEventArgs); if ('game_quit' == modifiedEventArgs.event_name) alert('Quit!'); }, 100); }, loadCurrentGame: function (gameStartArgs) { // on is a static method that tracks events and returns play_session_id in game_start callback. var on = function (modifiedEventArgs, originalEventArgs, callback) { (function () { // log: var loggableObject = vipgames.utils.extend({}, modifiedEventArgs); delete loggableObject["session_id"]; delete loggableObject["player_id"]; delete loggableObject["play_session_id"]; delete loggableObject["event_name"]; delete loggableObject["game_id"]; vipgames.utils.log(modifiedEventArgs.game_id + " on " + modifiedEventArgs.event_name + '()', JSON.stringify(loggableObject)); })(); vipgames.api._internals.on_game_event_handler.apply(this, arguments); }; // returns a delegate for game_load, game_start, level_start, level_end, game_end API functions // note more functionalities can be added using // 3.speicalFunc (async, in callback) works after AJAX call on the received data, before callback() is called. // 2.speicalCheckFunc (checks the current state and throws exceptions if the game is in an invalid state) // 1.eventArgsAmpifier (amplify eventArgs and perfom operations prior to making modifiedEventArgs and calling on function) - used in game_load var getOn = function (name, specialFunc, specialCheckFunc, eventArgsAmplifier) { return function (eventArgs, callback) { // this: api object if (!!eventArgsAmplifier) vipgames.utils.delegate(eventArgsAmplifier, this)(eventArgs); // if the first argument is a callback function, then this on function must have been called by one argument. if ((typeof eventArgs == 'function') && !callback) { callback = eventArgs; eventArgs = null; } modifiedEventArgs = vipgames.utils.extend({ event_name: name, game_id: this._game.game_id, scores: this._game.getScores(), session_id: this._session_id, player_id: this._player_id, play_session_id: this._play_session_id }, eventArgs, false); // validate the state var speicalCheckFuncDelegate = !!specialCheckFunc ? vipgames.utils.delegate(specialCheckFunc, this) : null; if (speicalCheckFuncDelegate) { speicalCheckFuncDelegate(modifiedEventArgs); } var speicalFuncDelegate = !!specialFunc ? vipgames.utils.delegate(specialFunc, this) : null; on(modifiedEventArgs, eventArgs, function (data, modifiedEventArgs, eventArgs) { if (!!speicalFuncDelegate) speicalFuncDelegate(data); if (!!callback) callback(data, modifiedEventArgs, eventArgs); }); }; }; // create the API object and pass it to the game.load() var api_instance = { _session_id: gameStartArgs.session_id, _player_id: gameStartArgs.player_id, _play_session_id: null, _play_sessions: [], _game: null, _original_game_handler: this.current_game, _getLastPlaySession: function () { var length = this._play_sessions.length; return length > 0 ? this._play_sessions[length - 1] : null; }, _checkPlaySession: function (forceExisted, forceStarted, forceEnded, functionName) { var playSession = this._getLastPlaySession(); var ended = !playSession || !!playSession.end_date; var started = !!playSession && !playSession.end_date; if ((forceStarted && !started) || (forceExisted && !playSession)) { vipgames.utils.error('game_start() must have been called, before ' + functionName + '()'); } if (forceEnded && !ended) { vipgames.utils.error('game_end() must have been called, before ' + functionName + '()'); } return playSession; }, getScene: function () { return document.getElementById('vipgames_game_scene'); }, game_load: getOn('game_load', null, null, function (eventArgs) { this._game = eventArgs; this._game.game_id = this._original_game_handler.game_id; vipgames.api._internals.current_game._interface = this._game; }), game_start: getOn('game_start', function (data) { this._play_session_id = data.play_session_id; this._play_sessions.push({ play_sessoin_id: data.play_session_id, start_date: new Date() }); }, function () { this._checkPlaySession(false, false, true, 'game_start'); }), level_start: getOn('level_start', null, function () { this._checkPlaySession(true, true, false, 'level_start'); }), level_end: getOn('level_end', null, function () { this._checkPlaySession(true, true, false, 'level_end'); }), game_end: getOn('game_end', null, function () { var playSession = this._checkPlaySession(true, true, false, 'game_end'); playSession.end_date = new Date(); playSession.scores = this._game.getScores(); }), game_quit: getOn('game_quit', function () { }, function () { this._checkPlaySession(false, false, false, 'game_quit'); }, null) }; this.current_game.load(api_instance); vipgames.api._internals.current_api_instance = api_instance; } }; vipgames.api.register = function (game) { vipgames.api._internals.games.push(game); vipgames.api._internals.current_game = game; // starts the currently registered game // in this test version, the game loads immediately after document.load var f = function () { vipgames.api._internals.loadCurrentGame({ session_id: vipgames.utils.rndstr(9), player_id: vipgames.api._internals.current_player_id }); }; if (vipgames.ui._documentLoaded) f(); else window.addEventListener('load', function () { f(); }, false); }; window.addEventListener('load', function () { vipgames.ui._documentLoaded = true; }, false); <file_sep>/maFeaturePhoneHtml/localhost_7645/UserlessCourse/FlashCards8add.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <!-- Mirrored from localhost:7645/UserlessCourse/FlashCards?levelId=5&courseId=16&stepId=4&x-lang=en by HTTrack Website Copier/3.x [XR&CO'2013], Mon, 16 Sep 2013 19:24:23 GMT --> <!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=utf-8" /><!-- /Added by HTTrack --> <head> <title>Tame your Temper</title> <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0"/> <link href="../shared/css/dumb/main.css" rel="stylesheet" /> <link href="../shared/css/dumb/reset.css" rel="stylesheet" /> <link href="../shared/css/dumb/settings.css" rel="stylesheet" /> <link href="../Shared/css/dumb/home-page.css" rel="stylesheet" /> <link href="../shared/css/dumb/chapters.css" rel="stylesheet" /> <link href="../shared/css/dumb/courseinfo.css" rel="stylesheet" /> <link href="../shared/css/dumb/footer.css" rel="stylesheet" /> <link href="../shared/css/dumb/header.css" rel="stylesheet" /> <link href="../shared/css/dumb/welcome-language.css" rel="stylesheet" /> <link href="../Special/css/BodyLanguage/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/BodyLanguage/dumb/flashcards-page.css" rel="stylesheet"/> <link href="../Special/css/Textbook/dumb/flashcards-page.css" rel="stylesheet"/> <link href="../Special/css/Textbook/MobilePhotography/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Textbook/MobilePhotography/dumb/flashcards-page.css" rel="stylesheet"/> <link href="../Special/css/Textbook/NegotiationSkills/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Textbook/NegotiationSkills/dumb/flashcards-page.css" rel="stylesheet"/> <link href="../Special/css/Textbook/CareerSuccess/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Textbook/CareerSuccess/dumb/flashcards-page.css" rel="stylesheet"/> <link href="../Special/css/Textbook/PresentationSkills/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Textbook/PresentationSkills/dumb/flashcards-page.css" rel="stylesheet"/> <link href="../Special/css/Textbook/TameYourTamper/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Textbook/TameYourTamper/dumb/flashcards-page.css" rel="stylesheet"/> <link href="../Special/css/Textbook/Leadership/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Textbook/Leadership/dumb/flashcards-page.css" rel="stylesheet"/> <link href="../Special/css/Babelbay/dumb/flashcards-page.css" rel="stylesheet"/> <link href="../Special/css/Babelbay/Babelbay-ar/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Babelbay/Babelbay-fr/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Babelbay/Babelbay-es/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Babelbay/Babelbay-de/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Babelbay/Babelbay-ru/dumb/theme.css" rel="stylesheet"/> <script type="text/javascript" src="../Special/Scripts/Babelbay/Dumb/AudioPlayerBase.js"></script> <script type="text/javascript" src="../Special/Scripts/Babelbay/Dumb/Html5AudioPlayer.js"></script> <script type="text/javascript" src="../Special/Scripts/Babelbay/Dumb/FlashAudioPlayer.js"></script> </head> <body class="p320 userless "> <div id="wrap" class="course-TameYourTamper viewType-Textbook page-NewFlashCards "> <div id="header"> <a href="../UserlessHome2fc2.html?x-lang=en" class="current"><span class="icons cap"></span><span class="title">Home</span></a> &rsaquo; <a href="../UserlessCourseeaf7.html?courseId=16&amp;x-lang=en" class="current"><span class="icons book"></span><span class="title">Tame your Temper</span></a> &rsaquo; <a name="top"></a> </div> <div class="content"> <div class="header">3. Do not yell</div> <div class="content-container layout-Flow"> <p>Do not yell at your child. It will get you nowhere except towards being even angrier. Here are some tips to prevent you from screaming:</p> <div class="accordion"> <p> <strong>Be an active listener</strong> </p> <div class="content"> <p>If you are in a &#39;situation&#39; , try to figure out how the child really feels. Avoid being judgemental, which makes your child feel criticised and will cause him to become defensive.</p> </div> </div> <div class="accordion"> <p> <strong>Lower your expectations</strong> </p> <div class="content"> <p>If you find yourself in a conflict with your children all the time, you may simply be expecting too much of them. For instance, if the child starts nagging or crying when walking in the mall for hours, adjust your expectations and actions.</p> </div> </div> <div class="accordion"> <p> <strong>Just whisper</strong> </p> <div class="content"> <p>Children often tune out yelling. Try speaking softly and see what happens.</p> </div> </div> <div class="accordion"> <p> <strong>Be strategic</strong> </p> <div class="content"> <p>Find ways to accomplish stressful tasks without your children. For instance, if all of you lose it in the supermarket try shopping online or have someone look after them while you do the shopping.</p> </div> </div> <div class="accordion"> <p> <strong>Adopt a mantra</strong> </p> <div class="content"> <p>Find a word or phrase to distract yourself from yelling and try to remind yourself of the fact that your child is only a child. Your mantra can be something like: &quot;He&#39;s only 2, he&#39;s only 2!&quot;</p> </div> </div> <div class="accordion"> <p> <strong>Get physical</strong> </p> <div class="content"> <p>Yelling is a form of physical release. So why don&#39;t you take up some real physical exercise? Jogging in place or doing a jumping jack or two will distract you from yelling. You probably won&#39;t do this in a public place, but at home you can. You may even lose a few pounds.</p> </div> </div> <div class="accordion"> <p> <strong>Ask for help</strong> </p> <div class="content"> <p>Yelling is a sign of stress and fatigue. So, ask for help. Have your partner or a trusted babysitter help you out for half a day so you will get some time to recover.</p> </div> </div> <p></p> </div> </div> <div id="footer"> <a href="FlashCards3ab6.html?levelId=5&amp;courseId=16&amp;stepId=3&amp;x-lang=en" class="left">&lsaquo; Prev</a> <a href="#top" class="center">&uarr; Back to Top</a> <a href="FlashCards9b33.html?levelId=5&amp;courseId=16&amp;stepId=5&amp;x-lang=en" class="right">Next &rsaquo;</a> </div> </div> </body> <!-- Mirrored from localhost:7645/UserlessCourse/FlashCards?levelId=5&courseId=16&stepId=4&x-lang=en by HTTrack Website Copier/3.x [XR&CO'2013], Mon, 16 Sep 2013 19:24:23 GMT --> </html> <file_sep>/vipgames/Games/HexWars/html5game/uph_vipapi.js var vi_started = false; vi_score = 0, vi_state = 0, vi_handler = { getScores: function() { return vi_score }, stop: function() { vi_state |= 1 }, restart: function() { vi_state |= 2 }, unload: function() { vi_state |= 4 }, }; function vi_init() { if (vi_started) return; window._vi.game_load(vi_handler); vi_started = true } function vi_game_start() { window._vi.game_start() } function vi_game_end() { window._vi.game_end() } function vi_game_quit() { window._vi.game_quit() } function vi_level_start() { window._vi.level_start() } function vi_level_end() { window._vi.level_end() } function vi_set_score(value) { vi_score = value } function vi_get_state() { var o = vi_state; vi_state = 0; return o }<file_sep>/vipgames/Games/spacem.wizardwars/script/resources.js (function () { var imglib = [ { "sheetname": "playersheet", "type": "player", "src": "library/playersheet.png", "width": 384, "height": 48, "framewidth": 48, "frameheight": 48, "framedelay": 2, "framesperdirection": 2, "deathframe": 0, "deathframecount": 0, "attackframe": 0, "attackframecount": 0, "painframe": 0, "painframecount": 0 }, { "sheetname": "monstersheet", "type": "monster", "src": "library/monstersheet.png", "width": 256, "height": 128, "framewidth": 32, "frameheight": 32, "framedelay": 4, "framesperdirection": 2, "deathframe": 0, "deathframecount": 0, "attackframe": 0, "attackframecount": 0, "painframe": 0, "painframecount": 0 }, { "sheetname": "numberssheet", "type": "numbers", "src": "library/numbers.png", "width": 240, "height": 48, "framewidth": 24, "frameheight": 48, "framedelay": 0, "framesperdirection": 0, "deathframe": 0, "deathframecount": 0, "attackframe": 0, "attackframecount": 0, "painframe": 0, "painframecount": 0 }, { "sheetname": "explosionsheet", "type": "explosion", "src": "library/explosion.png", "width": 96, "height": 16, "framewidth": 16, "frameheight": 16, "framedelay": 4, "framesperdirection": 5, "deathframe": 0, "deathframecount": 0, "attackframe": 0, "attackframecount": 0, "painframe": 0, "painframecount": 0 }, { "sheetname": "playermissilesheet", "type": "playermissile", "src": "library/playermissile.png", "width": 16, "height": 16, "framewidth": 16, "frameheight": 16, "framedelay": 0, "framesperdirection": 1, "deathframe": 0, "deathframecount": 0, "attackframe": 0, "attackframecount": 0, "painframe": 0, "painframecount": 0 }, { "sheetname": "sparksheet", "type": "spark", "src": "library/spark.png", "width": 16, "height": 16, "framewidth": 16, "frameheight": 16, "framedelay": 0, "framesperdirection": 1, "deathframe": 0, "deathframecount": 0, "attackframe": 0, "attackframecount": 0, "painframe": 0, "painframecount": 0 }, { "sheetname": "entitysheet", "type": "entity", "src": "library/entities.png", "width": 64, "height": 160, "framewidth": 32, "frameheight": 32, "framedelay": 4, "framesperdirection": 2, "deathframe": 0, "deathframecount": 0, "attackframe": 0, "attackframecount": 0, "painframe": 0, "painframecount": 0 }, { "sheetname": "zoltarsheet", "type": "zoltar", "src": "library/zoltarsheet.png", "width": 384, "height": 48, "framewidth": 48, "frameheight": 48, "framedelay": 2, "framesperdirection": 2, "deathframe": 0, "deathframecount": 0, "attackframe": 0, "attackframecount": 0, "painframe": 0, "painframecount": 0 }, { "sheetname": "markersheet", "type": "marker", "src": "library/marker.png", "width": 128, "height": 32, "framewidth": 32, "frameheight": 32, "framedelay": 1, "framesperdirection": 3, "deathframe": 0, "deathframecount": 0, "attackframe": 0, "attackframecount": 0, "painframe": 0, "painframecount": 0 } ]; window.wizardwars = window.wizardwars || {}; window.wizardwars.imglib = imglib; })();<file_sep>/maFeaturePhoneHtml/localhost_7645/UserlessCourse/CourseInfo5f6e.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <!-- Mirrored from localhost:7645/UserlessCourse/CourseInfo?CourseId=20&x-lang=en by HTTrack Website Copier/3.x [XR&CO'2013], Mon, 16 Sep 2013 19:18:23 GMT --> <!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=utf-8" /><!-- /Added by HTTrack --> <head> <title>Learn to Lead</title> <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0"/> <link href="../shared/css/dumb/main.css" rel="stylesheet" /> <link href="../shared/css/dumb/reset.css" rel="stylesheet" /> <link href="../shared/css/dumb/settings.css" rel="stylesheet" /> <link href="../Shared/css/dumb/home-page.css" rel="stylesheet" /> <link href="../shared/css/dumb/chapters.css" rel="stylesheet" /> <link href="../shared/css/dumb/courseinfo.css" rel="stylesheet" /> <link href="../shared/css/dumb/footer.css" rel="stylesheet" /> <link href="../shared/css/dumb/header.css" rel="stylesheet" /> <link href="../shared/css/dumb/welcome-language.css" rel="stylesheet" /> <link href="../Special/css/BodyLanguage/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/BodyLanguage/dumb/flashcards-page.css" rel="stylesheet"/> <link href="../Special/css/Textbook/dumb/flashcards-page.css" rel="stylesheet"/> <link href="../Special/css/Textbook/MobilePhotography/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Textbook/MobilePhotography/dumb/flashcards-page.css" rel="stylesheet"/> <link href="../Special/css/Textbook/NegotiationSkills/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Textbook/NegotiationSkills/dumb/flashcards-page.css" rel="stylesheet"/> <link href="../Special/css/Textbook/CareerSuccess/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Textbook/CareerSuccess/dumb/flashcards-page.css" rel="stylesheet"/> <link href="../Special/css/Textbook/PresentationSkills/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Textbook/PresentationSkills/dumb/flashcards-page.css" rel="stylesheet"/> <link href="../Special/css/Textbook/TameYourTamper/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Textbook/TameYourTamper/dumb/flashcards-page.css" rel="stylesheet"/> <link href="../Special/css/Textbook/Leadership/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Textbook/Leadership/dumb/flashcards-page.css" rel="stylesheet"/> <link href="../Special/css/Babelbay/dumb/flashcards-page.css" rel="stylesheet"/> <link href="../Special/css/Babelbay/Babelbay-ar/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Babelbay/Babelbay-fr/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Babelbay/Babelbay-es/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Babelbay/Babelbay-de/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Babelbay/Babelbay-ru/dumb/theme.css" rel="stylesheet"/> <script type="text/javascript" src="../Special/Scripts/Babelbay/Dumb/AudioPlayerBase.js"></script> <script type="text/javascript" src="../Special/Scripts/Babelbay/Dumb/Html5AudioPlayer.js"></script> <script type="text/javascript" src="../Special/Scripts/Babelbay/Dumb/FlashAudioPlayer.js"></script> </head> <body class="p320 userless "> <div id="wrap" class="course-Leadership viewType-Textbook page-CourseInfo "> <div id="header"> <a href="../UserlessHome2fc2.html?x-lang=en" class="current"><span class="icons cap"></span><span class="title">Home</span></a> &rsaquo; <span class="icons book"></span><span class="title">Learn to Lead</span> &rsaquo; <a name="top"></a> </div> <div id="courseinfo"> <div class="header-wrap"> <div class="title">Learn to Lead</div> <img src="../Special/images/Leadership/intro-dumb/intro.jpg" /> </div> <a href="../UserlessCourse5f6e.html?CourseId=20&amp;x-lang=en" class="startcourse_btn">Start Course</a> <p></p> <div class="panel Quote"> <span class="text">A boss creates fear, a leader confidence. A boss fixes blame, a leader corrects mistakes. A boss knows all, a leader asks questions. A boss makes work drudgery, a leader makes it interesting. A boss is interested in themselves, a leader is interested in the group.</span> <span class="quote-by"><NAME></span> <span class="quote-date">1885-1976</span> </div> <p>Leadership helps a nation pull through in tough times, it makes a failing business the greatest thing ever, it helps others see things in ways they didn&#39;t see it before, it empowers young minds to achieve the impossible. If you have the willpower and desire to lead, you can become a leader.</p> <p></p> <p>Leadership is the process by which one person is able to empower, inspire and motivate another person or group of people in achieving their goals. A leader helps us see what we can&#39;t. He shows the path to follow and has the ability to visualize what we can achieve.</p> <p></p> <p>Leaders are not necessarily born as one; they can be molded, trained and improvised. Do you have what it takes to be a leader? Do you want to help other people in achieving their goals? Do you want to change the thought process of your peer group? Do you want to climb the ladder of promotions at your workplace? Do you want to be a leader?</p> <p></p> <p>Then, let&#39;s get started!</p> <p></p> <p>* In this course we are referring to a leader as a &#39;he&#39;. Of course the he-word can easily be replaced by &#39;she&#39;.</p> </div> </div> </body> <!-- Mirrored from localhost:7645/UserlessCourse/CourseInfo?CourseId=20&x-lang=en by HTTrack Website Copier/3.x [XR&CO'2013], Mon, 16 Sep 2013 19:18:23 GMT --> </html> <file_sep>/maFeaturePhoneHtml/localhost_7645/Special/Scripts/Babelbay/Dumb/Html5AudioPlayer.js var __extends = this.__extends || function (d, b) { function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var Html5AudioPlayer = (function (_super) { __extends(Html5AudioPlayer, _super); function Html5AudioPlayer() { _super.call(this); this._container = (function () { var e = document.createElement("div"); e.id = 'Html5AudioPlayer-container'; document.body.appendChild(e); return e; })(); } Html5AudioPlayer.prototype._reMake = function () { if(!!this.audio) { this.audio.pause(); } else { this.audio = document.createElement("audio"); this._container.appendChild(this.audio); } this.audio.src = this.url; this.audio.load(); try { this.audio.volume = 1; } catch (ex) { } }; Html5AudioPlayer.prototype.start = function () { this._reMake(); this.audio.play(); _super.prototype.start.call(this); }; Html5AudioPlayer.prototype.stop = function () { this.audio.pause(); this._container.removeChild(this.audio); this.audio = null; _super.prototype.stop.call(this); }; Html5AudioPlayer._supported = null; Html5AudioPlayer.supported = function supported() { if(Html5AudioPlayer._supported == null) { var e = document.createElement("audio"); Html5AudioPlayer._supported = (!!e && !!e.play); } return Html5AudioPlayer._supported; } return Html5AudioPlayer; })(AudioPlayerBase); <file_sep>/maFeaturePhoneHtml/localhost_7645/Special/Scripts/Babelbay/Dumb/AudioPlayerBase.js var AudioPlayerState; (function (AudioPlayerState) { AudioPlayerState._map = []; AudioPlayerState.Playing = 2; AudioPlayerState.Stopped = 1; })(AudioPlayerState || (AudioPlayerState = {})); var PageEvent = (function () { function PageEvent() { } PageEvent.prototype.addHandler = function (f) { var arr = (this._handlers || []); arr.push(f); this._handlers = arr; }; PageEvent.prototype.execute = function () { var args = []; for (var _i = 0; _i < (arguments.length - 0); _i++) { args[_i] = arguments[_i + 0]; } var arr = this._handlers; var self = this; if(!!arr && arr.length > 0) { arr.forEach(function (f) { return f.apply(self, arguments); }); } }; return PageEvent; })(); var AudioPlayerBase = (function () { function AudioPlayerBase() { this.state = AudioPlayerState.Stopped; this.startEvent = new PageEvent(); } AudioPlayerBase.prototype.setAudio = function (url, length) { this.url = url; this.length = length; return this; }; AudioPlayerBase.prototype.start = function () { this._lastPlay = new Date(); this.state = AudioPlayerState.Playing; this.startEvent.execute(); }; AudioPlayerBase.prototype.stop = function () { this.state = AudioPlayerState.Stopped; }; AudioPlayerBase.prototype.toggle = function () { if(AudioPlayerState.Stopped == this.state) { this.start(); } else { var now = new Date(); if((now.getTime() - this._lastPlay.getTime()) > this.length) { this.stop(); var self = this; setTimeout(function () { return self.start(); }, 500); } else { this.stop(); } } }; AudioPlayerBase.create = function create() { if(Html5AudioPlayer.supported()) { return new Html5AudioPlayer(); } else { return new FlashAudioPlayer(); } } return AudioPlayerBase; })(); <file_sep>/maFeaturePhoneHtml/localhost_7645/UserlessCourse/FlashCards400d.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <!-- Mirrored from localhost:7645/UserlessCourse/FlashCards?levelId=2&courseId=3&stepId=3&x-lang=en by HTTrack Website Copier/3.x [XR&CO'2013], Mon, 16 Sep 2013 19:22:45 GMT --> <!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=utf-8" /><!-- /Added by HTTrack --> <head> <title>Successful Negotiating</title> <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0"/> <link href="../shared/css/dumb/main.css" rel="stylesheet" /> <link href="../shared/css/dumb/reset.css" rel="stylesheet" /> <link href="../shared/css/dumb/settings.css" rel="stylesheet" /> <link href="../Shared/css/dumb/home-page.css" rel="stylesheet" /> <link href="../shared/css/dumb/chapters.css" rel="stylesheet" /> <link href="../shared/css/dumb/courseinfo.css" rel="stylesheet" /> <link href="../shared/css/dumb/footer.css" rel="stylesheet" /> <link href="../shared/css/dumb/header.css" rel="stylesheet" /> <link href="../shared/css/dumb/welcome-language.css" rel="stylesheet" /> <link href="../Special/css/BodyLanguage/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/BodyLanguage/dumb/flashcards-page.css" rel="stylesheet"/> <link href="../Special/css/Textbook/dumb/flashcards-page.css" rel="stylesheet"/> <link href="../Special/css/Textbook/MobilePhotography/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Textbook/MobilePhotography/dumb/flashcards-page.css" rel="stylesheet"/> <link href="../Special/css/Textbook/NegotiationSkills/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Textbook/NegotiationSkills/dumb/flashcards-page.css" rel="stylesheet"/> <link href="../Special/css/Textbook/CareerSuccess/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Textbook/CareerSuccess/dumb/flashcards-page.css" rel="stylesheet"/> <link href="../Special/css/Textbook/PresentationSkills/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Textbook/PresentationSkills/dumb/flashcards-page.css" rel="stylesheet"/> <link href="../Special/css/Textbook/TameYourTamper/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Textbook/TameYourTamper/dumb/flashcards-page.css" rel="stylesheet"/> <link href="../Special/css/Textbook/Leadership/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Textbook/Leadership/dumb/flashcards-page.css" rel="stylesheet"/> <link href="../Special/css/Babelbay/dumb/flashcards-page.css" rel="stylesheet"/> <link href="../Special/css/Babelbay/Babelbay-ar/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Babelbay/Babelbay-fr/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Babelbay/Babelbay-es/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Babelbay/Babelbay-de/dumb/theme.css" rel="stylesheet"/> <link href="../Special/css/Babelbay/Babelbay-ru/dumb/theme.css" rel="stylesheet"/> <script type="text/javascript" src="../Special/Scripts/Babelbay/Dumb/AudioPlayerBase.js"></script> <script type="text/javascript" src="../Special/Scripts/Babelbay/Dumb/Html5AudioPlayer.js"></script> <script type="text/javascript" src="../Special/Scripts/Babelbay/Dumb/FlashAudioPlayer.js"></script> </head> <body class="p320 userless "> <div id="wrap" class="course-NegotiationSkills viewType-Textbook page-NewFlashCards "> <div id="header"> <a href="../UserlessHome2fc2.html?x-lang=en" class="current"><span class="icons cap"></span><span class="title">Home</span></a> &rsaquo; <a href="../UserlessCoursef0c2.html?courseId=3&amp;x-lang=en" class="current"><span class="icons book"></span><span class="title">Successful Negotiating</span></a> &rsaquo; <a name="top"></a> </div> <div class="content"> <div class="header">2. Ask questions</div> <div class="content-container layout-Flow"> <p>Your questions should have two goals:</p> <p>1. to get more and specific information</p> <p>2. to uncover the other party&#39;s needs</p> <p></p> <p>Questions may be open-ended and expansive or closed-ended and restrictive.</p> <div class="list Paragraph ordered"> <ol> <li> <div> <span class="title">Closed-ended questions</span> <span class="text">These questions can be answered either as yes or no. You use this method of questioning to get specific information that guides the discussion or conversation more to your favour.</span> </div> </li> <li> <div> <span class="title">Open-ended questions</span> <span class="text">They do not lead the other party in any specific direction. Generally speaking, they reveal much more about the counterpart&#39;s feelings and needs than restrictive questions do.</span> </div> </li> </ol> </div> <p>Explore five keys of proper questioning:</p> <div class="accordion"> <p> <strong>1. Have a plan</strong> </p> <div class="content"> <p>Ask yourself what type of information will help you make the right decision. Do you have to be more direct or indirect?</p> </div> </div> <div class="accordion"> <p> <strong>2. Know the other person</strong> </p> <div class="content"> <p>The more you know about your negotiation partner, the better you can frame your questions.</p> </div> </div> <div class="accordion"> <p> <strong>3. Broad to narrow</strong> </p> <div class="content"> <p>Begin your questioning with broad questions and gradually bring it down to more specific answers.</p> </div> </div> <div class="accordion"> <p> <strong>4. Sense of timing</strong> </p> <div class="content"> <p>Be aware of your counterpart&#39;s feelings. If he finds a question offensive, you won&#39;t get any answers. Asking someone how his or her diet is going while she is eating a piece of pie is a good example of bad timing.</p> </div> </div> <div class="accordion"> <p> <strong>5. Ask for permission</strong> </p> <div class="content"> <p>Ask permission before asking a question. You counterpart is more likely to give you a complete answer if you ask him politely.</p> </div> </div> </div> </div> <div id="footer"> <a href="FlashCardscc85.html?levelId=2&amp;courseId=3&amp;stepId=2&amp;x-lang=en" class="left">&lsaquo; Prev</a> <a href="#top" class="center">&uarr; Back to Top</a> <a href="FlashCards59c0.html?levelId=2&amp;courseId=3&amp;stepId=4&amp;x-lang=en" class="right">Next &rsaquo;</a> </div> </div> </body> <!-- Mirrored from localhost:7645/UserlessCourse/FlashCards?levelId=2&courseId=3&stepId=3&x-lang=en by HTTrack Website Copier/3.x [XR&CO'2013], Mon, 16 Sep 2013 19:22:45 GMT --> </html>
1021af75f89d797039c28192225cff18d055b478
[ "JavaScript", "HTML", "Markdown" ]
10
JavaScript
homam/android-landingpages-apps
4420df6bba38ef5e68cf3fc5953890842c7580c5
6a3df39aac6102ed46ec7e43a7307bb8a9f0ac95
refs/heads/master
<repo_name>liu1234/perceptron<file_sep>/cpu/testers/traffic_gen/traffic_gen.cc /* * Copyright (c) 2012 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: <NAME> * <NAME> * <NAME> */ #include <sstream> #include "base/random.hh" #include "cpu/testers/traffic_gen/traffic_gen.hh" #include "debug/Checkpoint.hh" #include "debug/TrafficGen.hh" #include "sim/stats.hh" #include "sim/system.hh" using namespace std; TrafficGen::TrafficGen(const TrafficGenParams* p) : MemObject(p), system(p->system), masterID(system->getMasterId(name())), port(name() + ".port", *this), stateGraph(*this, port, p->config_file, masterID), updateStateGraphEvent(this) { } TrafficGen* TrafficGenParams::create() { return new TrafficGen(this); } MasterPort& TrafficGen::getMasterPort(const string& if_name, int idx) { if (if_name == "port") { return port; } else { return MemObject::getMasterPort(if_name, idx); } } void TrafficGen::init() { if (!port.isConnected()) fatal("The port of %s is not connected!\n", name()); Enums::MemoryMode mode = system->getMemoryMode(); // if the system is in timing mode active the request generator if (mode == Enums::timing) { DPRINTF(TrafficGen, "Timing mode, activating request generator\n"); // enter initial state stateGraph.enterState(stateGraph.currState); } else { DPRINTF(TrafficGen, "Traffic generator is only active in timing mode\n"); } } void TrafficGen::initState() { // when not restoring from a checkpoint, make sure we kick things off if (system->getMemoryMode() == Enums::timing) { Tick nextStateGraphEvent = stateGraph.nextEventTick(); schedule(updateStateGraphEvent, nextStateGraphEvent); } else { DPRINTF(TrafficGen, "Traffic generator is only active in timing mode\n"); } } unsigned int TrafficGen::drain(Event* drain_event) { // @todo we should also stop putting new requests in the queue and // either interrupt the current state or wait for a transition return port.drain(drain_event); } void TrafficGen::serialize(ostream &os) { DPRINTF(Checkpoint, "Serializing TrafficGen\n"); // save ticks of the graph event if it is scheduled Tick nextStateGraphEvent = updateStateGraphEvent.scheduled() ? updateStateGraphEvent.when() : 0; DPRINTF(TrafficGen, "Saving nextStateGraphEvent=%llu\n", nextStateGraphEvent); SERIALIZE_SCALAR(nextStateGraphEvent); Tick nextTransitionTick = stateGraph.nextTransitionTick; SERIALIZE_SCALAR(nextTransitionTick); // @todo: also serialise the current state, figure out the best // way to drain and restore } void TrafficGen::unserialize(Checkpoint* cp, const string& section) { // restore scheduled events Tick nextStateGraphEvent; UNSERIALIZE_SCALAR(nextStateGraphEvent); if (nextStateGraphEvent != 0) { schedule(updateStateGraphEvent, nextStateGraphEvent); } Tick nextTransitionTick; UNSERIALIZE_SCALAR(nextTransitionTick); stateGraph.nextTransitionTick = nextTransitionTick; } void TrafficGen::updateStateGraph() { // schedule next update event based on either the next execute // tick or the next transition, which ever comes first Tick nextStateGraphEvent = stateGraph.nextEventTick(); DPRINTF(TrafficGen, "Updating state graph, next event at %lld\n", nextStateGraphEvent); schedule(updateStateGraphEvent, nextStateGraphEvent); // perform the update associated with the current update event stateGraph.update(); } void TrafficGen::StateGraph::parseConfig(const string& file_name, MasterID master_id) { // keep track of the transitions parsed to create the matrix when // done vector<Transition> transitions; // open input file ifstream infile; infile.open(file_name.c_str(), ifstream::in); if (!infile.is_open()) { fatal("Traffic generator %s config file not found at %s\n", owner.name(), file_name); } // read line by line and determine the action based on the first // keyword string keyword; string line; while (getline(infile, line).good()) { // see if this line is a comment line, and if so skip it if (line.find('#') != 1) { // create an input stream for the tokenization istringstream is(line); // determine the keyword is >> keyword; if (keyword == "STATE") { // parse the behaviour of this state uint32_t id; Tick duration; string mode; is >> id >> duration >> mode; if (mode == "TRACE") { string traceFile; Addr addrOffset; is >> traceFile >> addrOffset; states[id] = new TraceGen(port, master_id, duration, traceFile, addrOffset); DPRINTF(TrafficGen, "State: %d TraceGen\n", id); } else if (mode == "IDLE") { states[id] = new IdleGen(port, master_id, duration); DPRINTF(TrafficGen, "State: %d IdleGen\n", id); } else if (mode == "LINEAR" || mode == "RANDOM") { uint32_t read_percent; Addr start_addr; Addr end_addr; Addr blocksize; Tick min_period; Tick max_period; Addr data_limit; is >> read_percent >> start_addr >> end_addr >> blocksize >> min_period >> max_period >> data_limit; DPRINTF(TrafficGen, "%s, addr %x to %x, size %d," " period %d to %d, %d%% reads\n", mode, start_addr, end_addr, blocksize, min_period, max_period, read_percent); if (read_percent > 100) panic("%s cannot have more than 100% reads", name()); if (mode == "LINEAR") { states[id] = new LinearGen(port, master_id, duration, start_addr, end_addr, blocksize, min_period, max_period, read_percent, data_limit); DPRINTF(TrafficGen, "State: %d LinearGen\n", id); } else if (mode == "RANDOM") { states[id] = new RandomGen(port, master_id, duration, start_addr, end_addr, blocksize, min_period, max_period, read_percent, data_limit); DPRINTF(TrafficGen, "State: %d RandomGen\n", id); } } else { fatal("%s: Unknown traffic generator mode: %s", name(), mode); } } else if (keyword == "TRANSITION") { Transition transition; is >> transition.from >> transition.to >> transition.p; transitions.push_back(transition); DPRINTF(TrafficGen, "Transition: %d -> %d\n", transition.from, transition.to); } else if (keyword == "INIT") { // set the initial state as the active state is >> currState; DPRINTF(TrafficGen, "Initial state: %d\n", currState); } } } // resize and populate state transition matrix transitionMatrix.resize(transitions.size()); for (size_t i = 0; i < transitions.size(); i++) { transitionMatrix[i].resize(transitions.size()); } for (vector<Transition>::iterator t = transitions.begin(); t != transitions.end(); ++t) { transitionMatrix[t->from][t->to] = t->p; } // ensure the egress edges do not have a probability larger than // one for (size_t i = 0; i < transitions.size(); i++) { double sum = 0; for (size_t j = 0; j < transitions.size(); j++) { sum += transitionMatrix[i][j]; } // avoid comparing floating point numbers if (abs(sum - 1.0) > 0.001) fatal("%s has transition probability != 1 for state %d\n", name(), i); } // close input file infile.close(); } void TrafficGen::StateGraph::update() { // if we have reached the time for the next state transition, then // perform the transition if (curTick() >= nextTransitionTick) { transition(); } else { // we are still in the current state and should execute it states[currState]->execute(); } } void TrafficGen::StateGraph::transition() { // exit the current state states[currState]->exit(); // determine next state double p = random_mt.gen_real1(); assert(currState < transitionMatrix.size()); double cumulative = transitionMatrix[currState][0]; size_t i = 1; while (p < cumulative && i != transitionMatrix[currState].size()) { cumulative += transitionMatrix[currState][i]; ++i; } enterState(i); } void TrafficGen::StateGraph::enterState(uint32_t newState) { DPRINTF(TrafficGen, "Transition to state %d\n", newState); currState = newState; nextTransitionTick += states[currState]->duration; states[currState]->enter(); } TrafficGen::StateGraph::BaseGen::BaseGen(QueuedMasterPort& _port, MasterID master_id, Tick _duration) : port(_port), masterID(master_id), duration(_duration) { } void TrafficGen::StateGraph::LinearGen::enter() { // reset the address and the data counter nextAddr = startAddr; dataManipulated = 0; // this test only needs to happen once, but cannot be performed // before init() is called and the ports are connected if (port.deviceBlockSize() && blocksize > port.deviceBlockSize()) fatal("TrafficGen %s block size (%d) is larger than port" " block size (%d)\n", blocksize, port.deviceBlockSize()); } void TrafficGen::StateGraph::LinearGen::execute() { // choose if we generate a read or a write here bool isRead = random_mt.random<uint8_t>(0, 100) < readPercent; if (readPercent == 0) assert(!isRead); DPRINTF(TrafficGen, "LinearGen::execute: %c to addr %x, size %d\n", isRead ? 'r' : 'w', nextAddr, blocksize); // Create new request Request::Flags flags; Request *req = new Request(nextAddr, blocksize, flags, masterID); PacketPtr pkt = new Packet(req, isRead ? MemCmd::ReadReq : MemCmd::WriteReq); uint8_t* pkt_data = new uint8_t[req->getSize()]; pkt->dataDynamicArray(pkt_data); if (!isRead) { memset(pkt_data, 0xA, req->getSize()); } port.schedTimingReq(pkt, curTick()); // increment the address nextAddr += blocksize; // Add the amount of data manipulated to the total dataManipulated += blocksize; } Tick TrafficGen::StateGraph::LinearGen::nextExecuteTick() { // If we have reached the end of the address space, reset the // address to the start of the range if (nextAddr + blocksize > endAddr) { DPRINTF(TrafficGen, "Wrapping address to the start of " "the range\n"); nextAddr = startAddr; } // Check to see if we have reached the data limit. If dataLimit is // zero we do not have a data limit and therefore we will keep // generating requests for the entire residency in this state. if (dataLimit && dataManipulated >= dataLimit) { DPRINTF(TrafficGen, "Data limit for LinearGen reached.\n"); // there are no more requests, therefore return MaxTick return MaxTick; } else { // return the time when the next request should take place return curTick() + random_mt.random<Tick>(minPeriod, maxPeriod); } } void TrafficGen::StateGraph::RandomGen::enter() { // reset the counter to zero dataManipulated = 0; // this test only needs to happen once, but cannot be performed // before init() is called and the ports are connected if (port.deviceBlockSize() && blocksize > port.deviceBlockSize()) fatal("TrafficGen %s block size (%d) is larger than port" " block size (%d)\n", name(), blocksize, port.deviceBlockSize()); } void TrafficGen::StateGraph::RandomGen::execute() { // choose if we generate a read or a write here bool isRead = random_mt.random<uint8_t>(0, 100) < readPercent; if (readPercent == 0) assert(!isRead); // address of the request Addr addr = random_mt.random<Addr>(startAddr, endAddr - 1); // round down to start address of block addr -= addr % blocksize; DPRINTF(TrafficGen, "RandomGen::execute: %c to addr %x, size %d\n", isRead ? 'r' : 'w', addr, blocksize); // create new request packet Request::Flags flags; Request *req = new Request(addr, blocksize, flags, masterID); PacketPtr pkt = new Packet(req, isRead ? MemCmd::ReadReq : MemCmd::WriteReq); uint8_t* pkt_data = new uint8_t[req->getSize()]; pkt->dataDynamicArray(pkt_data); if (!isRead) { memset(pkt_data, 0xA, req->getSize()); } port.schedTimingReq(pkt, curTick()); // Add the amount of data manipulated to the total dataManipulated += blocksize; } Tick TrafficGen::StateGraph::RandomGen::nextExecuteTick() { // Check to see if we have reached the data limit. If dataLimit is // zero we do not have a data limit and therefore we will keep // generating requests for the entire residency in this state. if (dataLimit && dataManipulated >= dataLimit) { DPRINTF(TrafficGen, "Data limit for RandomGen reached.\n"); // No more requests. Return MaxTick. return MaxTick; } else { // Return the time when the next request should take place. return curTick() + random_mt.random<Tick>(minPeriod, maxPeriod); } } Tick TrafficGen::StateGraph::TraceGen::nextExecuteTick() { // We need to look at the next line to calculate the next time an // event occurs, or potentially return MaxTick to signal that // nothing has to be done. string buffer; if (!traceComplete && trace.good()){ getline(trace, buffer); DPRINTF(TrafficGen, "Input trace: %s\n", buffer); } else { // We are at the end of the file, thus we have no more data in // the trace Return MaxTick to signal that there will be no // more transactions in this active period for the state. return MaxTick; } //Reset the nextElement to the default values currElement = nextElement; nextElement.clear(); // Check that we have something to process. This assume no EOF at // the end of the line. if (buffer.size() > 0 && !trace.eof()) { istringstream iss(buffer); char rOrW, ch; iss >> rOrW; iss >> ch; assert(ch == ','); iss >> nextElement.addr; iss >> ch; assert(ch == ','); iss >> nextElement.blocksize; iss >> ch; assert(ch == ','); iss >> nextElement.tick; if (rOrW == 'r') { nextElement.cmd = MemCmd::ReadReq; } else if (rOrW == 'w') { nextElement.cmd = MemCmd::WriteReq; } else { fatal("Incorrect trace file format!\n"); } } // Check that we have a valid request if (!nextElement.isValid()) { // If it is not valid, assume that we have reached the end of // the trace. Even if this is not the case, we do not know // what to do with the request as it makes no sense. if (trace.good()) { // Trace is good, therefore we are not at the end of the // file. This means that the input trace cannot be read // correctly or it contains data that makes no sense. warn("Unable to read the trace file format\n"); warn("%s", buffer); } traceComplete = true; return MaxTick; } DPRINTF(TrafficGen, "currElement: %c addr %d size %d tick %d (%d)\n", currElement.cmd.isRead() ? 'r' : 'w', currElement.addr, currElement.blocksize, currElement.tick + tickOffset, currElement.tick); DPRINTF(TrafficGen, "nextElement: %c addr %d size %d tick %d (%d)\n", nextElement.cmd.isRead() ? 'r' : 'w', nextElement.addr, nextElement.blocksize, nextElement.tick + tickOffset, nextElement.tick); return tickOffset + nextElement.tick; } void TrafficGen::StateGraph::TraceGen::enter() { // update the trace offset to the time where the state was entered. tickOffset = curTick(); // seek to the start of the input trace file trace.seekg(0, ifstream::beg); trace.clear(); // clear everything nextElement.clear(); currElement.clear(); traceComplete = false; } void TrafficGen::StateGraph::TraceGen::execute() { // it is the responsibility of nextExecuteTick to prevent the // state graph from executing the state if it should not assert(currElement.isValid()); DPRINTF(TrafficGen, "TraceGen::execute: %c %d %d %d\n", currElement.cmd.isRead() ? 'r' : 'w', currElement.addr, currElement.blocksize, currElement.tick); Request::Flags flags; Request *req = new Request(currElement.addr + addrOffset, currElement.blocksize, flags, masterID); PacketPtr pkt = new Packet(req, currElement.cmd); uint8_t* pkt_data = new uint8_t[req->getSize()]; pkt->dataDynamicArray(pkt_data); if (currElement.cmd.isWrite()) { memset(pkt_data, 0xA, req->getSize()); } port.schedTimingReq(pkt, curTick()); } void TrafficGen::StateGraph::TraceGen::exit() { // Check if we reached the end of the trace file. If we did not // then we want to generate a warning stating that not the entire // trace was played. if (!trace.eof()) { warn("Trace player %s was unable to replay the entire trace!\n", name()); } // clear any previous error flags for the input trace file trace.clear(); } bool TrafficGen::TrafficGenPort::recvTimingResp(PacketPtr pkt) { delete pkt->req; delete pkt; return true; } <file_sep>/cpu/pred/bpdebugger_impl.hh #include <bitset> #include <type_traits> #include <iostream> #include <fstream> #include <algorithm> #include "cpu/pred/bpdebugger.hh" #include "debug/DebugInfo.hh" #include "debug/Pattern.hh" #include "base/trace.hh" #define LOG 1 template<typename History> void DebugInfo<History>::printDebugInfo(std::ofstream& file, const Addr& addr) { DPRINTF(DebugInfo, "Branch Addr(%i): \t\t\t\t\t%i\n", unCondBr, addr); DPRINTF(DebugInfo, "Execution times: \t\t\t\t\t%i\n", count); DPRINTF(DebugInfo, "Branch Missprediction rate: \t\t\t%f\n", (double)miss/(double)count); DPRINTF(DebugInfo, "Branch Hit times: \t\t\t\t\t%i\n", hit); DPRINTF(DebugInfo, "Correct prediction(taken): \t\t\t%i\n", hitTaken); DPRINTF(DebugInfo, "Correct prediction(taken) Avg weight: \t\t%i\n", hitTakenWeight/(int)(hitTaken+1)); DPRINTF(DebugInfo, "Correct prediction(not taken): \t\t\t%i\n", hitNotTaken); DPRINTF(DebugInfo, "Correct prediction(not taken) Avg weight: \t\t%i\n", hitNotTakenWeight/(int)(hitNotTaken+1)); DPRINTF(DebugInfo, "Branch Miss times: \t\t\t\t%i\n", miss); DPRINTF(DebugInfo, "Miss prediction(taken): \t\t\t\t%i\n", missTaken); DPRINTF(DebugInfo, "Miss prediction(taken) Avg weight: \t\t%i\n", missTakenWeight/(int)(missTaken+1)); DPRINTF(DebugInfo, "Miss prediction(not taken): \t\t\t%i\n", missNotTaken); DPRINTF(DebugInfo, "Miss prediction(not taken) Avg weight: \t\t%i\n", missNotTakenWeight/(int)(missNotTaken+1)); DPRINTF(DebugInfo, "Branch Taken times: \t\t\t\t%i\n", taken); DPRINTF(DebugInfo, "Branch Taken Avg weight: \t\t\t\t%i\n", takenWeight/(int)(taken+1)); DPRINTF(DebugInfo, "Branch Not Taken times: \t\t\t\t%i\n", notTaken); DPRINTF(DebugInfo, "Branch Not Taken Avg weight: \t\t\t%i\n", notTakenWeight/(int)(notTaken+1)); DPRINTF(DebugInfo, "Branch history pattern #: \t\t\t\t%i\n", histPattern.size()); DPRINTF(DebugInfo, "Branch conflicts \t\t\t\t\t%i\n", conflictSet.size()); DPRINTF(DebugInfo, "Global History Used: \t\t\t\t%i\n", globalCount); DPRINTF(DebugInfo, "Local History Used: \t\t\t\t%i\n", localCount); #ifdef LOG if(!histPattern.empty()) printPatternInfo(file, 5); if(!conflictSet.empty()) printConflictInfo(file, addr); #endif } template<typename A, typename B> std::pair<B,A> flipPair(const std::pair<A,B>& ele) { return std::pair<B,A>(ele.second, ele.first); } template<typename History> void DebugInfo<History>::printHistoryPattern(std::ofstream& file, History history) { std::bitset<64> historyBits; for(int i = 0; i < history.size(); i++) { historyBits[i] = history[i]; } file.setf(std::ios::hex, std::ios::basefield); file.setf(std::ios::showbase); file << historyBits.to_ulong() << ", "; file.unsetf(std::ios::hex); file.unsetf(std::ios::showbase); } template<> void DebugInfo<unsigned int>::printHistoryPattern(std::ofstream& file, unsigned int history) { file.setf(std::ios::hex, std::ios::basefield); file.setf(std::ios::showbase); file << history << ", "; file.unsetf(std::ios::hex); file.unsetf(std::ios::showbase); } template<typename History> void DebugInfo<History>::printPatternInfo(std::ofstream& file, int maxCount) { file << '\n' << "-------------Start of Pattern Info---------------" << '\n'; std::multimap<unsigned int, History> reverseMap; std::transform(histPattern.begin(), histPattern.end(), std::inserter(reverseMap, reverseMap.begin()),flipPair<History, unsigned int>); int i = 0; auto rIt = reverseMap.rbegin(); while(i < maxCount && rIt != reverseMap.rend()) { auto key = rIt->first; file << "#" << i+1 << " access pattern(" << key << " times): "<< '\n'; auto it_pair = reverseMap.equal_range(key); for(auto it = it_pair.first; it != it_pair.second; it++, rIt++) { printHistoryPattern(file, it->second); if(histTaken.find(it->second) != histTaken.end()) file << "this pattern suggests taken: " << histTaken[it->second] << " times\n"; } i++; } file << '\n' << "-------------End of Pattern Info---------------" << '\n'; } template<typename History> void DebugInfo<History>::printCorrelationInfo(std::ofstream& file, const Addr& addr) { file << "Addr: " << addr << '\n'; file << '\n' << "-------------Start of Correlation Info---------------" << '\n'; for(auto it = correlator.begin(); it != correlator.end(); it++) { file << "----------New record----------" << '\n'; auto& histVec = (*it)->histVec; for(auto br = histVec.begin(); br != histVec.end(); br++) { file << br->addr << '\t' << br->weights << '\t' << br->taken << '\n'; } printHistoryPattern(file, (*it)->pattern); file << "Pattern suggests " << (*it)->result << '\n'; } for(auto it = correlator.begin(); it != correlator.end(); it++) { delete *it; } file << '\n' << "-------------End of Correlation Info---------------" << '\n'; } template<typename History> void DebugInfo<History>::printConflictInfo(std::ofstream& file, const Addr& addr) { file << '\n' << "-------------Start of Conflict Info---------------" << '\n'; file << "conflict addr:" << '\n'; for(auto it = conflictSet.begin() ; it != conflictSet.end(); it++) { if(*it != addr) file << *it << '\n'; } file <<'\n' << "-------------End of Conflict Info---------------" << '\n'; } <file_sep>/cpu/pred/bpdebugger.cc #include <deque> //#include "bpdebugger.hh" #include "bpdebugger_impl.hh" template class DebugInfo<unsigned int>; template class DebugInfo<std::deque<bool>>; <file_sep>/cpu/testers/traffic_gen/traffic_gen.hh /* * Copyright (c) 2012 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: <NAME> * <NAME> * <NAME> */ #ifndef __MEM_TRAFFIC_GEN_HH__ #define __MEM_TRAFFIC_GEN_HH__ #include <fstream> #include "base/hashmap.hh" #include "mem/mem_object.hh" #include "mem/qport.hh" #include "params/TrafficGen.hh" /** * The traffic generator is a master module that generates stimuli for * the memory system, based on a collection of simple behaviours that * are either probabilistic or based on traces. It can be used stand * alone for creating test cases for interconnect and memory * controllers, or function as a black box replacement for system * components that are not yet modelled in detail, e.g. a video engine * or baseband subsystem. */ class TrafficGen : public MemObject { private: /** * The system used to determine which mode we are currently operating * in. */ System* system; /** * MasterID used in generated requests. */ MasterID masterID; protected: /** * The state graph is responsible for instantiating and keeping * track of the various generator states and also perform the * transitions and call the appropriate functions when entering, * executing and exiting a state. */ class StateGraph { public: /** * Create a state graph from an input file. * * @param _owner used solely for the name * @param _port port used to send requests * @param file_name configuration description to read in * @param master_id the unique id used for all requests */ StateGraph(TrafficGen& _owner, QueuedMasterPort& _port, const std::string& file_name, MasterID master_id) : nextTransitionTick(0), owner(_owner), port(_port) { parseConfig(file_name, master_id); } /** * Get the name, used for DPRINTFs. * * @return the owner's name */ std::string name() const { return owner.name(); } /** * Either perform a state transition or execute the current * state, depending on the current time. */ void update(); /** * Determine next state and perform the transition. */ void transition(); /** * Enter a new state. * * @param newState identifier of state to enter */ void enterState(uint32_t newState); /** * Get the tick of the next event, either an execution or a * transition. * * @return tick of the next state graph event */ Tick nextEventTick() { return std::min(states[currState]->nextExecuteTick(), nextTransitionTick); } /** Time of next transition */ Tick nextTransitionTick; private: /** * Parse the config file and build the state map and * transition matrix. * * @param file_name Config file name to parse * @param master_id MasterID to use for generated requests */ void parseConfig(const std::string& file_name, MasterID master_id); /** Struct to represent a probabilistic transition during parsing. */ struct Transition { uint32_t from; uint32_t to; double p; }; /** Base class for all generator states */ class BaseGen { protected: /** Port used to send requests */ QueuedMasterPort& port; /** The MasterID used for generating requests */ const MasterID masterID; public: /** Time to spend in this state */ const Tick duration; /** * Create a base generator. * * @param _port port used to send requests * @param master_id MasterID set on each request * @param _duration duration of this state before transitioning */ BaseGen(QueuedMasterPort& _port, MasterID master_id, Tick _duration); virtual ~BaseGen() { } /** * Get the name, useful for DPRINTFs. * * @return the port name */ std::string name() const { return port.name(); } /** * Enter this generator state. */ virtual void enter() = 0; /** * Execute this generator state. */ virtual void execute() = 0; /** * Exit this generator state. By default do nothing. */ virtual void exit() { }; /** * Determine the next execute tick. MaxTick means that * there will not be any further event in the current * activation cycle of the state. * * @return next tick when the state should be executed */ virtual Tick nextExecuteTick() = 0; }; /** * The idle generator does nothing. */ class IdleGen : public BaseGen { public: IdleGen(QueuedMasterPort& _port, MasterID master_id, Tick _duration) : BaseGen(_port, master_id, _duration) { } void enter() { } void execute() { } Tick nextExecuteTick() { return MaxTick; } }; /** * The linear generator generates sequential requests from a * start to an end address, with a fixed block size. A * fraction of the requests are reads, as determined by the * read percent. There is an optional data limit for when to * stop generating new requests. */ class LinearGen : public BaseGen { public: /** * Create a linear address sequence generator. Set * min_period == max_period for a fixed inter-transaction * time. * * @param _port port used to send requests * @param master_id MasterID set on each request * @param _duration duration of this state before transitioning * @param start_addr Start address * @param end_addr End address * @param _blocksize Size used for transactions injected * @param min_period Lower limit of random inter-transaction time * @param max_period Upper limit of random inter-transaction time * @param read_percent Percent of transactions that are reads * @param data_limit Upper limit on how much data to read/write */ LinearGen(QueuedMasterPort& _port, MasterID master_id, Tick _duration, Addr start_addr, Addr end_addr, Addr _blocksize, Tick min_period, Tick max_period, uint8_t read_percent, Addr data_limit) : BaseGen(_port, master_id, _duration), startAddr(start_addr), endAddr(end_addr), blocksize(_blocksize), minPeriod(min_period), maxPeriod(max_period), readPercent(read_percent), dataLimit(data_limit) { } void enter(); void execute(); Tick nextExecuteTick(); private: /** Start of address range */ const Addr startAddr; /** End of address range */ const Addr endAddr; /** Blocksize and address increment */ const Addr blocksize; /** Request generation period */ const Tick minPeriod; const Tick maxPeriod; /** * Percent of generated transactions that should be reads */ const uint8_t readPercent; /** Maximum amount of data to manipulate */ const Addr dataLimit; /** Address of next request */ Addr nextAddr; /** * Counter to determine the amount of data * manipulated. Used to determine if we should continue * generating requests. */ Addr dataManipulated; }; /** * The random generator is similar to the linear one, but does * not generate sequential addresses. Instead it randomly * picks an address in the range, aligned to the block size. */ class RandomGen : public BaseGen { public: /** * Create a random address sequence generator. Set * min_period == max_period for a fixed inter-transaction * time. * * @param _port port used to send requests * @param master_id MasterID set on each request * @param _duration duration of this state before transitioning * @param start_addr Start address * @param end_addr End address * @param _blocksize Size used for transactions injected * @param min_period Lower limit of random inter-transaction time * @param max_period Upper limit of random inter-transaction time * @param read_percent Percent of transactions that are reads * @param data_limit Upper limit on how much data to read/write */ RandomGen(QueuedMasterPort& _port, MasterID master_id, Tick _duration, Addr start_addr, Addr end_addr, Addr _blocksize, Tick min_period, Tick max_period, uint8_t read_percent, Addr data_limit) : BaseGen(_port, master_id, _duration), startAddr(start_addr), endAddr(end_addr), blocksize(_blocksize), minPeriod(min_period), maxPeriod(max_period), readPercent(read_percent), dataLimit(data_limit) { } void enter(); void execute(); Tick nextExecuteTick(); private: /** Start of address range */ const Addr startAddr; /** End of address range */ const Addr endAddr; /** Block size */ const Addr blocksize; /** Request generation period */ const Tick minPeriod; const Tick maxPeriod; /** * Percent of generated transactions that should be reads */ const uint8_t readPercent; /** Maximum amount of data to manipulate */ const Addr dataLimit; /** * Counter to determine the amount of data * manipulated. Used to determine if we should continue * generating requests. */ Addr dataManipulated; }; /** * The trace replay generator reads a trace file and plays * back the transactions. The trace is offset with respect to * the time when the state was entered. */ class TraceGen : public BaseGen { private: /** * This struct stores a line in the trace file. */ struct TraceElement { /** Specifies if the request is to be a read or a write */ MemCmd cmd; /** The address for the request */ Addr addr; /** The size of the access for the request */ Addr blocksize; /** The time at which the request should be sent */ Tick tick; /** * Check validity of this element. * * @return if this element is valid */ bool isValid() const { return cmd != MemCmd::InvalidCmd; } /** * Make this element invalid. */ void clear() { cmd = MemCmd::InvalidCmd; } }; public: /** * Create a trace generator. * * @param _port port used to send requests * @param master_id MasterID set on each request * @param _duration duration of this state before transitioning * @param trace_file File to read the transactions from * @param addr_offset Positive offset to add to trace address */ TraceGen(QueuedMasterPort& _port, MasterID master_id, Tick _duration, const std::string& trace_file, Addr addr_offset) : BaseGen(_port, master_id, _duration), traceFile(trace_file), addrOffset(addr_offset), traceComplete(false) { /** * Create a 4MB read buffer for the input trace * file. This is to reduce the number of disk accesses * and thereby speed up the execution of the code. */ readBuffer = new char[4 * 1024 * 1024]; trace.rdbuf()->pubsetbuf(readBuffer, 4 * 1024 * 1024); trace.open(traceFile.c_str(), std::ifstream::in); if (!trace.is_open()) { fatal("Traffic generator %s trace file could not be" " opened: %s\n", name(), traceFile); } } ~TraceGen() { // free the memory used by the readBuffer delete[] readBuffer; } void enter(); void execute(); void exit(); /** * Read a line of the trace file. Returns the raw tick * when the next request should be generated. If the end * of the file has been reached, it returns MaxTick to * indicate that there will be no more requests. */ Tick nextExecuteTick(); private: /** Path to the trace file */ std::string traceFile; /** Input stream used for reading the input trace file */ std::ifstream trace; /** Larger buffer used for reading from the stream */ char* readBuffer; /** Store the current and next element in the trace */ TraceElement currElement; TraceElement nextElement; /** * Stores the time when the state was entered. This is to add an * offset to the times stored in the trace file. */ Tick tickOffset; /** * Offset for memory requests. Used to shift the trace * away from the CPU address space. */ Addr addrOffset; /** * Set to true when the trace replay for one instance of * state is complete. */ bool traceComplete; /** * Used to store the Tick when the next generate should * occur. It is to remove a transaction as soon as we * enter the state. */ Tick oldEmitTime; }; /** Pointer to owner of request handler */ TrafficGen& owner; /** Pointer to request handler */ QueuedMasterPort& port; /** State transition matrix */ std::vector<std::vector<double> > transitionMatrix; public: /** Index of the current state */ uint32_t currState; /** Map of states */ m5::hash_map<uint32_t, BaseGen*> states; }; /** Queued handler */ class TrafficGenPort : public QueuedMasterPort { public: TrafficGenPort(const std::string& name, TrafficGen& _owner) : QueuedMasterPort(name, &_owner, queue), queue(_owner, *this), owner(_owner) { } protected: bool recvTimingResp(PacketPtr pkt); private: MasterPacketQueue queue; // Owner of the port TrafficGen& owner; }; TrafficGenPort port; /** Request generator state graph */ StateGraph stateGraph; /** * Schedules event for next update and executes an update on the * state graph. */ void updateStateGraph(); /** Event for updating the state graph */ EventWrapper<TrafficGen, &TrafficGen::updateStateGraph> updateStateGraphEvent; public: TrafficGen(const TrafficGenParams* p); ~TrafficGen() {} virtual MasterPort& getMasterPort(const std::string &if_name, int idx = InvalidPortID); void init(); void initState(); unsigned int drain(Event *drain_event); void serialize(std::ostream &os); void unserialize(Checkpoint* cp, const std::string& section); }; #endif //__MEM_TRAFFIC_GEN_HH__ <file_sep>/cpu/inorder/resources/bpred_unit.cc /* * Copyright (c) 2004-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: <NAME> */ #include <list> #include <vector> #include "arch/utility.hh" #include "base/trace.hh" #include "config/the_isa.hh" #include "cpu/inorder/resources/bpred_unit.hh" #include "debug/InOrderBPred.hh" #include "debug/Resource.hh" using namespace std; using namespace ThePipeline; BPredUnit::BPredUnit(Resource *_res, ThePipeline::Params *params) : res(_res), BTB(params->BTBEntries, params->BTBTagSize, params->instShiftAmt) { // Setup the selected predictor. if (params->predType == "local") { localBP = new LocalBP(params->localPredictorSize, params->localCtrBits, params->instShiftAmt); predictor = Local; } else if (params->predType == "tournament") { tournamentBP = new TournamentBP(params->localPredictorSize, params->localCtrBits, params->localHistoryTableSize, params->localHistoryBits, params->globalPredictorSize, params->globalHistoryBits, params->globalCtrBits, params->choicePredictorSize, params->choiceCtrBits, params->instShiftAmt); predictor = Tournament; } else if (params->predType == "perceptron") { perceptronBP = new PerceptronBP(params->perceptronPredictorSize, params->perceptronHistoryBits, params->instShiftAmt, params->branchAddr); predictor = Perceptron; } else if (params->predType == "gshare") { gshareBP = new GshareBP(params->gshareHistoryBits, params->gshareHistoryTableSize, params->gshareCtrBits, params->instShiftAmt); predictor = Gshare; } else { fatal("Invalid BP selected!"); } for (int i=0; i < ThePipeline::MaxThreads; i++) RAS[i].init(params->RASSize); instSize = sizeof(TheISA::MachInst); } std::string BPredUnit::name() { return res->name(); } void BPredUnit::regStats() { lookups .name(name() + ".lookups") .desc("Number of BP lookups") ; condPredicted .name(name() + ".condPredicted") .desc("Number of conditional branches predicted") ; condIncorrect .name(name() + ".condIncorrect") .desc("Number of conditional branches incorrect") ; BTBLookups .name(name() + ".BTBLookups") .desc("Number of BTB lookups") ; BTBHits .name(name() + ".BTBHits") .desc("Number of BTB hits") ; BTBHitPct .name(name() + ".BTBHitPct") .desc("BTB Hit Percentage") .precision(6); BTBHitPct = (BTBHits / BTBLookups) * 100; usedRAS .name(name() + ".usedRAS") .desc("Number of times the RAS was used to get a target.") ; RASIncorrect .name(name() + ".RASInCorrect") .desc("Number of incorrect RAS predictions.") ; } void BPredUnit::switchOut() { // Clear any state upon switch out. for (int i = 0; i < ThePipeline::MaxThreads; ++i) { squash(0, i); } } void BPredUnit::takeOverFrom() { // Can reset all predictor state, but it's not necessarily better // than leaving it be. /* for (int i = 0; i < ThePipeline::MaxThreads; ++i) RAS[i].reset(); BP.reset(); BTB.reset(); */ } bool BPredUnit::predict(DynInstPtr &inst, TheISA::PCState &predPC, ThreadID tid) { // See if branch predictor predicts taken. // If so, get its target addr either from the BTB or the RAS. // Save off record of branch stuff so the RAS can be fixed // up once it's done. using TheISA::MachInst; int asid = inst->asid; bool pred_taken = false; TheISA::PCState target; ++lookups; DPRINTF(InOrderBPred, "[tid:%i] [sn:%i] %s(%s) ... PC %s doing branch " "prediction\n", tid, inst->seqNum, inst->staticInst->disassemble(inst->instAddr()), predPC.instAddr(), inst->pcState()); void *bp_history = NULL; if (inst->isUncondCtrl()) { DPRINTF(InOrderBPred, "[tid:%i] Unconditional control.\n", tid); pred_taken = true; // Tell the BP there was an unconditional branch. BPUncond(bp_history); if (inst->isReturn() && RAS[tid].empty()) { DPRINTF(InOrderBPred, "[tid:%i] RAS is empty, predicting " "false.\n", tid); pred_taken = false; } } else { ++condPredicted; pred_taken = BPLookup(predPC.instAddr(), bp_history); } PredictorHistory predict_record(inst->seqNum, predPC, pred_taken, bp_history, tid); // Now lookup in the BTB or RAS. if (pred_taken) { if (inst->isReturn()) { ++usedRAS; // If it's a function return call, then look up the address // in the RAS. TheISA::PCState rasTop = RAS[tid].top(); //target = TheISA::buildRetPC(inst->pcState(), rasTop); target = rasTop; // Record the top entry of the RAS, and its index. predict_record.usedRAS = true; predict_record.RASIndex = RAS[tid].topIdx(); predict_record.rasTarget = rasTop; assert(predict_record.RASIndex < 16); RAS[tid].pop(); DPRINTF(InOrderBPred, "[tid:%i]: Instruction %s is a return, " "RAS predicted target: %s, RAS index: %i.\n", tid, inst->pcState(), target, predict_record.RASIndex); } else { ++BTBLookups; if (inst->isCall()) { RAS[tid].push(inst->pcState()); // Record that it was a call so that the top RAS entry can // be popped off if the speculation is incorrect. predict_record.wasCall = true; DPRINTF(InOrderBPred, "[tid:%i]: Instruction %s was a call" ", adding %s to the RAS index: %i.\n", tid, inst->pcState(), predPC, RAS[tid].topIdx()); } if (inst->isCall() && inst->isUncondCtrl() && inst->isDirectCtrl()) { target = inst->branchTarget(); } else if (BTB.valid(predPC.instAddr(), asid)) { ++BTBHits; // If it's not a return, use the BTB to get the target addr. target = BTB.lookup(predPC.instAddr(), asid); DPRINTF(InOrderBPred, "[tid:%i]: [asid:%i] Instruction %s " "predicted target is %s.\n", tid, asid, inst->pcState(), target); } else { DPRINTF(InOrderBPred, "[tid:%i]: BTB doesn't have a " "valid entry, predicting false.\n",tid); pred_taken = false; predict_record.predTaken = false; if(!inst->isCall() && !inst->isReturn()) { BPBTBUpdate(predPC.instAddr(), bp_history); } else if(inst->isCall() && !inst->isUncondCtrl()) { RAS[tid].pop(); } } } } if (pred_taken) { // Set the PC and the instruction's predicted target. predPC = target; //TheISA::advancePC(predPC, inst->staticInst); } TheISA::advancePC(predPC, inst->staticInst); DPRINTF(InOrderBPred, "[tid:%i]: [sn:%i]: Setting Predicted PC to %s.\n", tid, inst->seqNum, predPC); predHist[tid].push_front(predict_record); DPRINTF(InOrderBPred, "[tid:%i] [sn:%i] pushed onto front of predHist " "...predHist.size(): %i\n", tid, inst->seqNum, predHist[tid].size()); return pred_taken; } void BPredUnit::update(const InstSeqNum &done_sn, ThreadID tid) { DPRINTF(Resource, "BranchPred: [tid:%i]: Commiting branches until sequence" "number %lli.\n", tid, done_sn); while (!predHist[tid].empty() && predHist[tid].back().seqNum <= done_sn) { // Update the branch predictor with the correct results. BPUpdate(predHist[tid].back().pc.instAddr(), predHist[tid].back().predTaken, predHist[tid].back().bpHistory, false); predHist[tid].pop_back(); } } void BPredUnit::squash(const InstSeqNum &squashed_sn, ThreadID tid, ThreadID asid) { History &pred_hist = predHist[tid]; while (!pred_hist.empty() && pred_hist.front().seqNum > squashed_sn) { if (pred_hist.front().usedRAS) { DPRINTF(InOrderBPred, "BranchPred: [tid:%i]: Restoring top of RAS " "to: %i, target: %s.\n", tid, pred_hist.front().RASIndex, pred_hist.front().rasTarget); RAS[tid].restore(pred_hist.front().RASIndex, pred_hist.front().rasTarget); } else if (pred_hist.front().wasCall) { DPRINTF(InOrderBPred, "BranchPred: [tid:%i]: Removing speculative " "entry added to the RAS.\n",tid); RAS[tid].pop(); } // This call should delete the bpHistory. BPSquash(pred_hist.front().bpHistory); pred_hist.pop_front(); } } void BPredUnit::squash(const InstSeqNum &squashed_sn, const TheISA::PCState &corrTarget, bool actually_taken, ThreadID tid, ThreadID asid) { // Now that we know that a branch was mispredicted, we need to undo // all the branches that have been seen up until this branch and // fix up everything. History &pred_hist = predHist[tid]; ++condIncorrect; DPRINTF(InOrderBPred, "[tid:%i]: Squashing from sequence number %i, " "setting target to %s.\n", tid, squashed_sn, corrTarget); squash(squashed_sn, tid); // If there's a squash due to a syscall, there may not be an entry // corresponding to the squash. In that case, don't bother trying to // fix up the entry. if (!pred_hist.empty()) { HistoryIt hist_it = pred_hist.begin(); //HistoryIt hist_it = find(pred_hist.begin(), pred_hist.end(), // squashed_sn); //assert(hist_it != pred_hist.end()); if (pred_hist.front().seqNum != squashed_sn) { DPRINTF(InOrderBPred, "Front sn %i != Squash sn %i\n", pred_hist.front().seqNum, squashed_sn); assert(pred_hist.front().seqNum == squashed_sn); } if ((*hist_it).usedRAS) { ++RASIncorrect; } BPUpdate((*hist_it).pc.instAddr(), actually_taken, pred_hist.front().bpHistory, true); // only update BTB on branch taken right??? if (actually_taken) BTB.update((*hist_it).pc.instAddr(), corrTarget, asid); DPRINTF(InOrderBPred, "[tid:%i]: Removing history for [sn:%i] " "PC %s.\n", tid, (*hist_it).seqNum, (*hist_it).pc); pred_hist.erase(hist_it); DPRINTF(InOrderBPred, "[tid:%i]: predHist.size(): %i\n", tid, predHist[tid].size()); } else { DPRINTF(InOrderBPred, "[tid:%i]: [sn:%i] pred_hist empty, can't " "update.\n", tid, squashed_sn); } } void BPredUnit::BPUncond(void * &bp_history) { // Only the tournament predictor cares about unconditional branches. if (predictor == Tournament) { tournamentBP->uncondBr(bp_history); } else if(predictor == Perceptron) { perceptronBP->uncondBr(bp_history); } else if(predictor == Gshare) { gshareBP->uncondBr(bp_history); } } void BPredUnit::BPSquash(void *bp_history) { if (predictor == Local) { localBP->squash(bp_history); } else if (predictor == Tournament) { tournamentBP->squash(bp_history); } else if (predictor == Perceptron) { perceptronBP->squash(bp_history); } else if (predictor == Gshare) { gshareBP->squash(bp_history); } else { panic("Predictor type is unexpected value!"); } } bool BPredUnit::BPLookup(Addr inst_PC, void * &bp_history) { if (predictor == Local) { return localBP->lookup(inst_PC, bp_history); } else if (predictor == Tournament) { return tournamentBP->lookup(inst_PC, bp_history); } else if (predictor == Perceptron) { return perceptronBP->lookup(inst_PC, bp_history); } else if (predictor == Gshare) { return gshareBP->lookup(inst_PC, bp_history); } else { panic("Predictor type is unexpected value!"); } } void BPredUnit::BPBTBUpdate(Addr inst_PC, void* &bp_history) { if(predictor == Local) { localBP->BTBUpdate(inst_PC, bp_history); } else if(predictor == Tournament) { tournamentBP->BTBUpdate(inst_PC, bp_history); } else if(predictor == Perceptron) { perceptronBP->BTBUpdate(inst_PC, bp_history); } else if(predictor == Gshare) { gshareBP->BTBUpdate(inst_PC, bp_history); } else { panic("Predictor type is unexpected value!"); } } void BPredUnit::BPUpdate(Addr inst_PC, bool taken, void *bp_history, bool squashed) { if (predictor == Local) { localBP->update(inst_PC, taken, bp_history); } else if (predictor == Tournament) { tournamentBP->update(inst_PC, taken, bp_history, squashed); } else if (predictor == Perceptron) { perceptronBP->update(inst_PC, taken, bp_history, squashed); } else if (predictor == Gshare) { gshareBP->update(inst_PC, taken, bp_history, squashed); } else { panic("Predictor type is unexpected value!"); } } void BPredUnit::dump() { /*typename History::iterator pred_hist_it; for (int i = 0; i < ThePipeline::MaxThreads; ++i) { if (!predHist[i].empty()) { pred_hist_it = predHist[i].begin(); cprintf("predHist[%i].size(): %i\n", i, predHist[i].size()); while (pred_hist_it != predHist[i].end()) { cprintf("[sn:%lli], PC:%#x, tid:%i, predTaken:%i, " "bpHistory:%#x\n", (*pred_hist_it).seqNum, (*pred_hist_it).PC, (*pred_hist_it).tid, (*pred_hist_it).predTaken, (*pred_hist_it).bpHistory); pred_hist_it++; } cprintf("\n"); } }*/ } <file_sep>/cpu/pred/bpdebugger.hh #ifndef __CPU_O3_BPDEBUGGER_PRED_HH__ #define __CPU_O3_BPDEBUGGER_PRED_HH__ #include <map> #include <vector> #include <set> #include <deque> #include <fstream> #include <memory> #include "base/types.hh" //#include "cpu/pred/perceptron.hh" //#include "cpu/pred/gshare.hh" //#include "cpu/pred/tournament.hh" class PerceptronBP; class GshareBP; class TournamentBP; template<typename A, typename B> std::pair<B,A> flipPair(const std::pair<A,B>& ele); template<typename History> class DebugInfo { friend class PerceptronBP; friend class GshareBP; friend class TournamentBP; void printDebugInfo(std::ofstream&, const Addr&); private: unsigned int count; unsigned int threshold; unsigned int squashed; unsigned int hit; // total weight when branch predicts correct, this value should be high unsigned int hitTaken; int hitTakenWeight; unsigned int hitNotTaken; int hitNotTakenWeight; // These three value could potentially reveal the reason for the misprediction unsigned int miss; // total weight when branch predicts wrong unsigned int missTaken; // total weight when branch predicts wrong(should be taken) int missTakenWeight; unsigned int missNotTaken; // total weight when branch predicts wrong(should be not taken) int missNotTakenWeight; unsigned int taken; int takenWeight; unsigned int notTaken; int notTakenWeight; unsigned int globalCount; unsigned int localCount; std::map<History, unsigned int> histPattern; // If linear separable std::map<History, unsigned int> histTaken; public: struct Correlation { struct RelatedBr { RelatedBr() {} RelatedBr(const Addr& _addr, const int& _weights, const bool& _taken) : addr(_addr), weights(_weights), taken(_taken) {} Addr addr; int weights; bool taken; }; Correlation() {} std::vector<RelatedBr> histVec; History pattern; bool result; }; private: std::vector<Correlation*> correlator; unsigned int coflict; std::set<Addr> conflictSet; bool unCondBr; bool stablized; void printPatternInfo(std::ofstream&, int maxCount); void printHistoryPattern(std::ofstream&, History); void printCorrelationInfo(std::ofstream&, const Addr&); void printConflictInfo(std::ofstream&, const Addr&); }; #endif <file_sep>/cpu/pred/gshare.cc #include "base/callback.hh" #include "base/intmath.hh" #include "debug/Predictor.hh" #include "debug/FreeList.hh" #include "debug/DebugInfo.hh" #include "base/trace.hh" #include "cpu/pred/gshare.hh" #include <fstream> GshareBP::GshareBP(unsigned int _gshareHistoryBits, unsigned int _gshareHistoryTableSize, unsigned int _gshareGlobalCtrBits, unsigned int _instShiftAmt) : gshareHistoryBits(_gshareHistoryBits), gshareHistoryTableSize(_gshareHistoryTableSize), gshareGlobalCtrBits(_gshareGlobalCtrBits), instShiftAmt(_instShiftAmt) { globalCtrsTable.resize(gshareHistoryTableSize); for (int i = 0; i < gshareHistoryTableSize; ++i) globalCtrsTable[i].setBits(gshareGlobalCtrBits); globalHistMask = gshareHistoryTableSize-1; threshold = (1 << (gshareGlobalCtrBits - 1)) - 1; Callback* cb = new MakeCallback<GshareBP, &GshareBP::writeDebugInfo>(this); registerExitCallback(cb); } inline unsigned int GshareBP::calGlobalHistIdx(Addr& addr) { return ((addr >> instShiftAmt) & globalHistMask) ^ globalHistory; } void GshareBP::updateGlobalHistoryTaken() { globalHistory = globalHistory << 1 | 1; globalHistory = globalHistory & globalHistMask; } void GshareBP::updateGlobalHistoryNotTaken() { globalHistory = globalHistory << 1; globalHistory = globalHistory & globalHistMask; } void GshareBP::uncondBr(void*& bp_history) { BPHistory* history = new BPHistory(); history->gshareGlobalHist = globalHistory; history->gsharePred = true; bp_history = (void*)history; } void GshareBP::BTBUpdate(Addr& branch_addr, void*& bp_history) { } bool GshareBP::lookup(Addr& branch_addr, void*& bp_history) { auto& record = debugMap[branch_addr]; record.count++; unsigned int globalCtrsTableIdx = calGlobalHistIdx(branch_addr); assert(globalCtrsTableIdx < globalCtrsTable.size()); idxMap[globalCtrsTableIdx].insert(branch_addr); record.conflictSet = idxMap[globalCtrsTableIdx]; bool gsharePrediction = globalCtrsTable[globalCtrsTableIdx].read() > threshold; BPHistory* history = new BPHistory(); history->gsharePred = gsharePrediction; history->gshareGlobalHist = globalHistory; bp_history = (void*)history; return gsharePrediction; } void GshareBP::update(Addr& branch_addr, bool taken, void*& bp_history, bool squashed) { if(!bp_history) return; BPHistory* history = (BPHistory*)bp_history; updateDebugInfo(branch_addr, taken, bp_history); unsigned int globalCtrsTableIdx = calGlobalHistIdx(branch_addr); if(taken) { updateGlobalHistoryTaken(); globalCtrsTable[globalCtrsTableIdx].increment(); } else { updateGlobalHistoryNotTaken(); globalCtrsTable[globalCtrsTableIdx].decrement(); } delete history; } void GshareBP::updateDebugInfo(Addr& addr, bool taken, void*& bp_history) { BPHistory* history = (BPHistory*)bp_history; if(debugMap.find(addr) == debugMap.end()) { auto& record = debugMap[addr]; record.unCondBr = true; } auto& record = debugMap[addr]; if(record.unCondBr) record.count++; record.globalCount++; if(taken == history->gsharePred) { record.hit++; if(taken) { record.hitTaken++; } else { record.hitNotTaken++; } } else { record.miss++; if(taken) { record.missTaken++; } else { record.missNotTaken++; } } if(taken) { record.taken++; } else { record.notTaken++; } } void GshareBP::squash(void*& bp_history) { if(!bp_history) return; DPRINTF(FreeList, "In flight branch is squashed due to last branch misprediction\n"); BPHistory* history = (BPHistory*)bp_history; delete history; /* TODO: if speculatively update history, we need to recover history */ } void GshareBP::writeDebugInfo() { std::ofstream file("/home/min/a/liu1234/gem5/log.txt"); for(auto it = debugMap.begin(); it != debugMap.end(); it++) { auto& addr = it->first; auto& record = it->second; if(record.unCondBr || record.count < 10 || (double)(record.hit)/(double)(record.count) > 0.8) continue; //if(record.unCondBr || record.count < 10) continue; DPRINTF(DebugInfo, "-------------------new record-----------------\n"); record.printDebugInfo(file, addr); DPRINTF(DebugInfo, "-------------------record end-----------------\n"); } file.close(); } <file_sep>/README.md # perceptron 1. Copy the cpu/ directory to your workspace. In case things get wrong, you'd better move your directory to somewhere else first, and then move this one to the place. Don not use copy, cp can't do things recursively. 2. Update the files in configs/ in correponding place(Simulation.py in common/ and run.py in spec2k6/). Do not move directory here because here are the only changed files. For other not changed ones, leave them there. However, you can mv files around in case bad things happen. 3. Command line for running is: ./build/ALPHA_MESI_CMP_directory/gem5.opt -d gcc/ configs/spec2k6/run.py -b gcc --cpu-type=atomic -I 1000000000 --at-instruction --take-checkpoints=1000000000 --checkpoint-dir=checkpoint This will take the checkpoint at 1 billion insts by using atomic cpu, and save the checkpoint file in checkpoint/. ./build/ALPHA_MESI_CMP_directory/gem5.opt -d gcc/ configs/spec2k6/run.py -b gcc --cpu-type=detailed -I 100000000 --at-instruction -r 1000000000 -s 1 --checkpoint-dir=checkpoint --restore-with-cpu=atomic --caches --predtype=perceptron --historylen=60 This will restore the checkpoint at 1 billion insts using checkpoint in checkpoint/ and run 100 million insts using o3 cpu with 60 bits perceptron branch predictor. P.S. If you find the benchmark doesn't work, go for the email sent by TA and check details. Plus, better check the correct simpoints place with TA to make sure we are using the right one. I sent an email to TA yesterday but get no response. <file_sep>/cpu/pred/perceptron.cc #include "base/callback.hh" #include "base/intmath.hh" #include "cpu/pred/perceptron.hh" #include "debug/Predictor.hh" #include "debug/FreeList.hh" #include "debug/DebugInfo.hh" #include "base/trace.hh" #include <cmath> #include <fstream> PerceptronBP::PerceptronBP(unsigned _perceptronPredictorSize, unsigned _perceptronHistoryBits, unsigned _instShiftAmt, unsigned long _branchAddr) : perceptronPredictorSize(_perceptronPredictorSize), perceptronHistoryBits(_perceptronHistoryBits), instShiftAmt(_instShiftAmt), debugAddr(_branchAddr) { perceptronTable.resize(perceptronPredictorSize); for(int i = 0; i < perceptronPredictorSize; i++) perceptronTable[i].resize(perceptronHistoryBits+1); //globalHistory.resize(perceptronHistoryBits-1); threshold = 1.93*perceptronHistoryBits+14; DPRINTF(Predictor, "Perceptron branch predictor threshold: %i\n", threshold); DPRINTF(Predictor, "Tracking branch: %x\n", debugAddr); Callback* cb = new MakeCallback<PerceptronBP, &PerceptronBP::writeDebugInfo>(this); registerExitCallback(cb); } inline unsigned int PerceptronBP::calHistIdx(Addr& addr) { return (addr >> instShiftAmt) & (perceptronPredictorSize-1); } inline void PerceptronBP::updateGlobalHistoryTaken(Addr& addr) { globalHistory.push_back(1); if(globalHistory.size() > perceptronHistoryBits) globalHistory.pop_front(); // This is for debug debugGlobalHist.historyAddr.push_back(addr); if(debugGlobalHist.historyAddr.size() > perceptronHistoryBits) debugGlobalHist.historyAddr.pop_front(); } inline void PerceptronBP::updateGlobalHistoryNotTaken(Addr& addr) { globalHistory.push_back(0); if(globalHistory.size() > perceptronHistoryBits) globalHistory.pop_front(); // This is for debug debugGlobalHist.historyAddr.push_back(addr); if(debugGlobalHist.historyAddr.size() > perceptronHistoryBits) debugGlobalHist.historyAddr.pop_front(); } bool PerceptronBP::lookup(Addr& branch_addr, void*& bp_history) { // DPRINTF(Predictor, "PerceptronBP looking up addr %s\n", branch_addr); auto& record = debugMap[branch_addr]; record.count++; unsigned int perceptronTableIdx = calHistIdx(branch_addr); assert(perceptronTableIdx < perceptronTable.size()); idxMap[perceptronTableIdx].insert(branch_addr); record.conflictSet = idxMap[perceptronTableIdx]; if(record.conflictSet.size() > 1) { // DPRINTF(Predictor, "This address conflicts with other %i addresses\n", conflictSet.size()-1); } WeightVector& weightVec = perceptronTable[perceptronTableIdx]; //unsigned int maxWeightIdx = 1; //DPRINTF(Predictor, "Global history 1 length: %i\n", globalHistory.size()); auto histLen = globalHistory.size(); int result = weightVec[0]; for(int i = 0; i < histLen; i++) { if(globalHistory[histLen-i-1]) { result += weightVec[i+1]; } else { result -= weightVec[i+1]; } /*if(conflictSet.size() > 1 && (conflictSet.find(debugGlobalHist.historyAddr[histLen-i-1]) != conflictSet.end()) && debugGlobalHist.historyAddr[histLen-i-1] != branch_addr)*/ //{ //DPRINTF(Predictor, "Conflict Addr %s also in the history, bad things can happen\n", debugGlobalHist.historyAddr[histLen-i-1]); //} //DPRINTF(Predictor, "Correlation factor with #%i history %i is: %i\n", histLen-i-1, globalHistory[histLen-i-1], weightVec[i+1]); } bool predTaken = (result > 0) ? true : false; DebugInfo<HistRegister>::Correlation* cptr = new DebugInfo<HistRegister>::Correlation(); for(int i = 1; i < histLen+1; i++) { cptr->histVec.emplace_back(debugGlobalHist.historyAddr[histLen-i], weightVec[i], globalHistory[histLen-i]); } cptr->pattern = globalHistory; cptr->result = predTaken; record.correlator.push_back(cptr); // DPRINTF(Predictor, "Branch bias itself is %i\n", weightVec[0]); // DPRINTF(Predictor, "PerceptronBP result: %i, predict: %i\n", result, predTaken); BPHistory* history = new BPHistory(); history->globalHistory = globalHistory; history->perceptronOutput = result; history->perceptronPredTaken = predTaken; bp_history = (void*)history; /* TODO: speculatively update history to support more in-flight branches */ return predTaken; } void PerceptronBP::uncondBr(void*& bp_history) { BPHistory* history = new BPHistory(); history->globalHistory = globalHistory; history->perceptronOutput = threshold+1; history->perceptronPredTaken = true; bp_history = (void*)history; } void PerceptronBP::BTBUpdate(Addr& branch_addr, void*& bp_history) { } void PerceptronBP::update(Addr& branch_addr, bool taken, void*& bp_history, bool squashed) { // DPRINTF(Predictor, "Perceptron updating %s\n", branch_addr); if(!bp_history) return; // update debug info updateDebugInfo(branch_addr, taken, bp_history); unsigned int perceptronTableIdx = calHistIdx(branch_addr); assert(perceptronTableIdx < perceptronTable.size()); WeightVector& weightVec = perceptronTable[perceptronTableIdx]; BPHistory* history = (BPHistory*)bp_history; auto& histQueue = history->globalHistory; if(taken != history->perceptronPredTaken || abs(history->perceptronOutput) <= threshold) { if(taken != history->perceptronPredTaken) { DPRINTF(Predictor, "update due to misprediction\n"); } else { DPRINTF(Predictor, "update due to threshold\n"); } if(taken) weightVec[0] += 1; else weightVec[0] -= 1; auto histLen = globalHistory.size(); for(int i = 0; i < histLen; i++) { if(taken == histQueue[histLen-i-1]) weightVec[i+1] += 1; else weightVec[i+1] -= 1; } } else { // DPRINTF(Predictor, "%s looks like stablized\n", branch_addr); /* TODO: can still mispredict after stablized */ //if(!record.stablized) //{ //printoutStats(branch_addr, record); //record.stablized = true; //} } /* TODO: this can be done speculatively when looking up */ if(taken) { updateGlobalHistoryTaken(branch_addr); } else { updateGlobalHistoryNotTaken(branch_addr); } // DPRINTF(Predictor, "Update global history %s to %i\n", branch_addr, taken); //DPRINTF(Predictor, "Global history 2 length: %i\n", globalHistory.size()); delete history; } void PerceptronBP::squash(void*& bp_history) { if(!bp_history) return; DPRINTF(FreeList, "In flight branch is squashed due to last branch misprediction\n"); BPHistory* history = (BPHistory*)bp_history; delete history; /* TODO: if speculatively update history, we need to recover history */ } void PerceptronBP::updateDebugInfo(Addr& addr, bool taken, void*& bp_history) { BPHistory* history = (BPHistory*)bp_history; if(debugMap.find(addr) == debugMap.end()) { auto& record = debugMap[addr]; record.unCondBr = true; } auto& record = debugMap[addr]; if(record.unCondBr) record.count++; record.histPattern[history->globalHistory]++; record.globalCount++; if(taken == history->perceptronPredTaken) { record.hit++; if(taken) { record.hitTaken++; record.hitTakenWeight += history->perceptronOutput; } else { record.hitNotTaken++; record.hitNotTakenWeight += history->perceptronOutput; } } else { record.miss++; if(taken) { record.missTaken++; record.missTakenWeight += history->perceptronOutput; } else { record.missNotTaken++; record.missNotTakenWeight += history->perceptronOutput; } } if(taken) { record.taken++; record.takenWeight += history->perceptronOutput; record.histTaken[history->globalHistory]++; } else { record.notTaken++; record.notTakenWeight += history->perceptronOutput; } } /* void PerceptronBP::printoutStats(Addr& addr, DebugInfo& record) { if(record.unCondBr) { DPRINTF(Predictor, "This is an unconditional branch, should be always correct, ignore it\n"); return; } DPRINTF(Predictor, "-------------------new record-----------------\n"); DPRINTF(Predictor, "%s has been executed for %i times and stablized\n", addr, record.count); //DPRINTF(Predictor, "After %i times, it stablized(seemingly)\n", record.threshold); DPRINTF(Predictor, "Branch Hit times: %i; Miss times: %i\n", record.hit, record.miss); DPRINTF(Predictor, "In branch correct prediction, %i is taken\n", record.hitTaken); DPRINTF(Predictor, "Avg weight for this prediction is %i\n", record.hitTakenWeight/(int)(record.hitTaken+1)); DPRINTF(Predictor, "In branch correct prediction, %i is not taken\n", record.hitNotTaken); DPRINTF(Predictor, "Avg weight for this prediction is %i\n", record.hitNotTakenWeight/(int)(record.hitNotTaken+1)); if(record.miss > 0) { DPRINTF(Predictor, "In branch missprediction, %i should be taken but predicted as not taken\n",record.missTaken); DPRINTF(Predictor, "Avg weight for this missprediction is %i\n",record.missTakenWeight/(int)(record.missTaken+1)); DPRINTF(Predictor, "In branch missprediction, %i should be not taken but predicted as taken\n",record.missNotTaken); DPRINTF(Predictor, "Avg weight for this missprediction is %i\n",record.missNotTakenWeight/(int)(record.missNotTaken+1)); } DPRINTF(Predictor, "Branch taken %i times avg weight: %i; not taken %i times avg weight: %i\n", record.taken, record.takenWeight/(int)(record.taken+1), record.notTaken, record.notTakenWeight/(int)(record.notTaken+1)); DPRINTF(Predictor, "-------------------record end-----------------\n"); } */ void PerceptronBP::writeDebugInfo() { std::ofstream file_all("/home/min/a/liu1234/gem5/log.txt"); std::ofstream file_single("/home/min/a/liu1234/gem5/single.txt"); for(auto it = debugMap.begin(); it != debugMap.end(); it++) { auto& addr = it->first; auto& record = it->second; if(addr == debugAddr) { DPRINTF(DebugInfo, "-------Traced One-------\n"); record.printCorrelationInfo(file_single, addr); } if(record.unCondBr || record.count < 10 || (double)(record.hit)/(double)(record.count) > 0.8) continue; //if(record.unCondBr || record.count < 10) continue; DPRINTF(DebugInfo, "-------------------new record-----------------\n"); file_all << "Addr: " << addr << " hist pattern" << '\n'; record.printDebugInfo(file_all, addr); DPRINTF(DebugInfo, "-------------------record end-----------------\n"); file_all << '\n'; } file_single.close(); file_all.close(); } <file_sep>/cpu/pred/perceptron.hh #ifndef __CPU_O3_PERCEPTRON_PRED_HH__ #define __CPU_O3_PERCEPTRON_PRED_HH__ #include <vector> #include <deque> #include <map> #include <set> #include "base/types.hh" #include "cpu/pred/bpdebugger.hh" /* class PerceptronBPBase { PerceptronBP(unsigned perceptronPredictorSize, unsigned perceptronHistoryBits) {} public: bool lookup(Addr& branch_addr, void*& bp_history) = 0; void update(Addr& branch_addr, bool taken, void*& bp_history, bool squashed) = 0; void squash(Addr& branch_addr, void*& bp_history) = 0; }; */ class PerceptronBP { public: PerceptronBP(unsigned _perceptronPredictorSize, unsigned _perceptronHistoryBits, unsigned _instShiftAmt, unsigned long _branchAddr); bool lookup(Addr& branch_addr, void*& bp_history); void update(Addr& branch_addr, bool taken, void*& bp_history, bool squashed); void squash(void*& bp_history); void BTBUpdate(Addr& branch_addr, void*& bp_history); void uncondBr(void*& bp_history); protected: unsigned int calHistIdx(Addr& addr); void updateGlobalHistoryTaken(Addr&); void updateGlobalHistoryNotTaken(Addr&); typedef std::deque<bool> HistRegister; typedef std::vector<int> WeightVector; struct BPHistory { HistRegister globalHistory; int perceptronOutput; bool perceptronPredTaken; }; HistRegister globalHistory; std::vector<WeightVector> perceptronTable; unsigned perceptronPredictorSize; unsigned perceptronHistoryBits; unsigned int threshold; unsigned int instShiftAmt; std::map<Addr, unsigned int> addrMap; std::map<unsigned int, std::set<Addr>> idxMap; // This is for debugging /* typedef struct { unsigned int count; unsigned int threshold; unsigned int squashed; unsigned int hit; // total weight when branch predicts correct, this value should be high unsigned int hitTaken; int hitTakenWeight; unsigned int hitNotTaken; int hitNotTakenWeight; // These three value could potentially reveal the reason for the misprediction unsigned int miss; // total weight when branch predicts wrong unsigned int missTaken; // total weight when branch predicts wrong(should be taken) int missTakenWeight; unsigned int missNotTaken; // total weight when branch predicts wrong(should be not taken) int missNotTakenWeight; unsigned int taken; int takenWeight; unsigned int notTaken; int notTakenWeight; std::map<std::deque<bool>, int> histPattern; unsigned int coflict; std::set<Addr> conflictSet; bool unCondBr; bool stablized; }DebugInfo; */ Addr debugAddr; std::map<Addr, DebugInfo<HistRegister>> debugMap; void updateDebugInfo(Addr&, bool, void*&); // void printoutStats(Addr&, DebugInfo<HistRegister>&); void writeDebugInfo(); typedef std::deque<Addr> HistAddress; typedef struct { HistRegister globalHistory; HistAddress historyAddr; // unsigned int size() {return globalHistory.size()}; // bool operator[](int idx) {return globalHistory[idx];} }DebugGlobalHist; DebugGlobalHist debugGlobalHist; // unsigned int weightBits; }; #endif <file_sep>/configs/run.py # Copyright (c) 2012 Purdue University # All rights reserved. # # Redistribution and use in source and binary forms, with o without # modification, are permitted provided that the following coditions are # met: redistributions of source code must retain the above cpyright # notice, this list of conditions and the following disclaimer # redistributions in binary form must reproduce the above copyrght # notice, this list of conditions and the following disclaimer i the # documentation and/or other materials provided with the distribuion; # neither the name of the copyright holders nor the names of its # contributors may be used to endorse or promote products derived fom # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Authors: <NAME> ### The following file was referenced from the following site: ### http://www.m5sim.org/SPEC_CPU2006_benchmarks ### ### and subsequent changes were made import os import optparse import sys import m5 from m5.defines import buildEnv from m5.objects import * from m5.util import addToPath, fatal addToPath('../common') addToPath('../ruby') addToPath('../topologies') import Options import Ruby import Simulation import CacheConfig from Caches import * from cpu2000 import * import spec2k6 from Ruby import * # Get paths we might need. It's expected this file is in m5/configs/example. config_path = os.path.dirname(os.path.abspath(__file__)) print config_path config_root = os.path.dirname(config_path) print config_root m5_root = os.path.dirname(config_root) print m5_root execfile(os.path.join(config_root, "ruby", "Ruby.py")) parser = optparse.OptionParser() Options.addCommonOptions(parser) Options.addSEOptions(parser) Ruby.define_options(parser) # Benchmark options parser.add_option("-b", "--benchmark", default="", help="The benchmark to be loaded.") parser.add_option("--bypassing", action="store_true", help="Enable bypassing") parser.add_option("--predtype", default="perceptron", help="Predictor type") parser.add_option("--brdegrade", action="store_true", help="Branch degrade") parser.add_option("--praccurate", type="int", default=0, help="Branch degrade percentage") parser.add_option("--historylen", type="int", default=10, help="Perceptron history size") parser.add_option("--branchaddr", type="long", default=0, help="trace one branch in debugging") (options, args) = parser.parse_args() if args: print "Error: script doesn't take any positional arguments" sys.exit(1) if options.benchmark == 'perlbench': process = spec2k6.perlbench elif options.benchmark == 'bzip2': process = spec2k6.bzip2 elif options.benchmark == 'gcc': process = spec2k6.gcc elif options.benchmark == 'bwaves': process = spec2k6.bwaves elif options.benchmark == 'gamess': process = spec2k6.gamess elif options.benchmark == 'mcf': process = spec2k6.mcf elif options.benchmark == 'milc': process = spec2k6.milc elif options.benchmark == 'zeusmp': process = spec2k6.zeusmp elif options.benchmark == 'gromacs': process = spec2k6.gromacs elif options.benchmark == 'cactusADM': process = spec2k6.cactusADM elif options.benchmark == 'leslie3d': process = spec2k6.leslie3d elif options.benchmark == 'namd': process = spec2k6.namd elif options.benchmark == 'gobmk': process = spec2k6.gobmk; elif options.benchmark == 'dealII': process = spec2k6.dealII elif options.benchmark == 'soplex': process = spec2k6.soplex elif options.benchmark == 'povray': process = spec2k6.povray elif options.benchmark == 'calculix': process = spec2k6.calculix elif options.benchmark == 'hmmer': process = spec2k6.hmmer elif options.benchmark == 'sjeng': process = spec2k6.sjeng elif options.benchmark == 'GemsFDTD': process = spec2k6.GemsFDTD elif options.benchmark == 'libquantum': process = spec2k6.libquantum elif options.benchmark == 'h264ref': process = spec2k6.h264ref elif options.benchmark == 'tonto': process = spec2k6.tonto elif options.benchmark == 'lbm': process = spec2k6.lbm elif options.benchmark == 'omnetpp': process = spec2k6.omnetpp elif options.benchmark == 'astar': process = spec2k6.astar elif options.benchmark == 'wrf': process = spec2k6.wrf elif options.benchmark == 'sphinx3': process = spec2k6.sphinx3 elif options.benchmark == 'xalancbmk': process = spec2k6.xalancbmk elif options.benchmark == 'specrand_i': process = spec2k6.specrand_i elif options.benchmark == 'specrand_f': process = spec2k6.specrand_f multiprocesses = [] numThreads = 1 (CPUClass, test_mem_mode, FutureClass) = Simulation.setCPUClass(options) CPUClass.clock = '1.0GHz' CPUClass.numThreads = numThreads if options.cpu_type == "inorder" or options.cpu_type == "detailed": if options.restore_with_cpu == None: # if options.bypassing: # CPUClass.bypassing = True # if options.brdegrade: # CPUClass.predAccuracy = options.praccurate CPUClass.predType = options.predtype CPUClass.perceptronHistoryBits = options.historylen CPUClass.branchAddr = options.branchaddr else: FutureClass.predType = options.predtype FutureClass.perceptronHistoryBits = options.historylen FutureClass.branchAddr = options.branchaddr #CPUClass.predType = options.predtype #CPUClass.perceptronHistoryBits = options.historylen #CPUClass.branchAddr = options.branchaddr multiprocesses.append(process) np = options.num_cpus system = System(cpu = [CPUClass(cpu_id=i) for i in xrange(np)], physmem = SimpleMemory(range=AddrRange("512MB")), membus = CoherentBus(), mem_mode = test_mem_mode) for i in xrange(np): if options.smt: system.cpu[i].workload = multiprocesses elif len(multiprocesses) == 1: system.cpu[i].workload = multiprocesses[0] else: system.cpu[i].workload = multiprocesses[i] if options.ruby: options.use_map = True Ruby.create_system(options, system) assert(options.num_cpus == len(system.ruby._cpu_ruby_ports)) for i in xrange(np): ruby_port = system.ruby._cpu_ruby_ports[i] # Create the interrupt controller and connect its ports to Ruby system.cpu[i].createInterruptController() # Connect the cpu's cache ports to Ruby system.cpu[i].icache_port = ruby_port.slave system.cpu[i].dcache_port = ruby_port.slave if buildEnv['TARGET_ISA'] == 'x86': system.cpu[i].interrupts.pio = ruby_port.master system.cpu[i].interrupts.int_master = ruby_port.slave system.cpu[i].interrupts.int_slave = ruby_port.master system.cpu[i].itb.walker.port = ruby_port.slave system.cpu[i].dtb.walker.port = ruby_port.slave else: system.system_port = system.membus.slave system.physmem.port = system.membus.master CacheConfig.config_cache(options,system) root = Root(full_system = False, system = system) Simulation.run(options, root, system, FutureClass) <file_sep>/cpu/pred/gshare.hh #ifndef _CPU_O3_GSHARE_PRED_HH #define _CPU_O3_GSHARE_PRED_HH #include <map> #include <vector> #include <set> #include "base/types.hh" #include "cpu/o3/sat_counter.hh" #include "cpu/pred/bpdebugger.hh" class GshareBP { public: GshareBP(unsigned int _gshareHistoryBits, unsigned int _gshareHistoryTableSize, unsigned int _gshareGlobalCtrBits, unsigned int _instShiftAmt); bool lookup(Addr& branch_addr, void*& bp_history); void update(Addr& branch_addr, bool taken, void*& bp_history, bool squashed); void squash(void*& bp_history); void BTBUpdate(Addr& branch_addr, void*& bp_history); void uncondBr(void*& bp_history); protected: unsigned int calGlobalHistIdx(Addr& addr); void updateGlobalHistoryTaken(); void updateGlobalHistoryNotTaken(); struct BPHistory { bool gsharePred; unsigned int gshareGlobalHist; }; unsigned int gshareHistoryBits; unsigned int gshareHistoryTableSize; unsigned int gshareGlobalCtrBits; unsigned int globalHistory; unsigned int globalHistMask; unsigned int threshold; int instShiftAmt; std::vector<SatCounter> globalCtrsTable; std::map<unsigned int, std::set<Addr>> idxMap; std::map<Addr, DebugInfo<unsigned int>> debugMap; void updateDebugInfo(Addr&, bool, void*&); void writeDebugInfo(); }; #endif
6e5fbb0af54311e70fdaba8732ab59124873af0a
[ "Markdown", "Python", "C++" ]
12
C++
liu1234/perceptron
4a427cd252cd40f2cafb96acc18db8f1ca4ac939
05c24eaada5720e7cacd178b20fec71cbec471ae
refs/heads/master
<repo_name>stephenmussel/weekend-react-gallery<file_sep>/notes.txt Strategies to not panic: - Build the easy setup stuff first, build moment - kicking it off Fri while it's fresh - caffeine - take breaks Todo Provided [x] server-side GET to retrieve data [x] server-side PUT to update (like) photo [] no DB needed for base Setup [x] npm install dependencies [x] sandbox.js [x] add test images to public/images [x] wireframe [] App.jsx (start with everything in here first, then break into components if there's time) [] GalleryList component [x] GalleryItem component [] use axios to GET data from /gallery and store in App.jsx [x] loop over list of gallery data with .map [x] make GalleryItem [x] include like button [] description when clicked [] use axios to PUT (update) the like count /gallery/like/:id [] update GalleryList when like button clicked [] GalleryList to display GalleryItem Features [] Render all images as a gallery [] Visitor [] clicks image to see description [] clicks button to like image Styling [ ] tbd Stretch Goals ....worry about these later.<file_sep>/src/components/GalleryList/GalleryList.jsx import GalleryItem from "../GalleryItem/GalleryItem"; import { useState } from 'react'; function GalleryList({list, updateLove}) { const[description, setDescription] = useState(false); return( <> <div className="gallery-list-container"> <h2>Gallery List</h2> {/* loops thru {list} to display each image in gallery.data.js */} {list.map(item => (<> <img key={item.id} src={item.path} alt={item.description}/> <br /> <GalleryItem item={item} updateLove={updateLove} /> {/* <p key={item.id}><img src={item.path} alt={item.description}/></p> */} {/* <p>{item.description}</p> */} {/* <GalleryItem /> */} </>) )} </div> </> ) } export default GalleryList;<file_sep>/src/components/App/App.jsx import React from 'react'; import './App.css'; import Header from '../Header/Header'; import axios from 'axios'; import { useState, useEffect } from 'react'; import galleryItems from '../../modules/gallery.data'; import GalleryList from '../GalleryList/GalleryList'; function App() { const [galleryList, setGalleryList] = useState(galleryItems); // const [likeCounter, setLikeCounter] = useState(0); const fetchGallery = () => { axios({ method: 'GET', url: '/gallery', }).then((response) => { console.log(response.data); setGalleryList(response.data); }).catch((error) => { console.log('error in fetchGallery', error); }); } const updateLove = (galleryId) => { console.log(galleryId); axios({ method: 'PUT', url: `/like/${galleryId}`, }).then((response) => { fetchGallery(); }).catch((error) => { alert('error in updateLove'); console.log(error); }) } useEffect(() => { fetchGallery(); }, []); return ( <div className="App"> <Header /> <GalleryList list={galleryList} updateLove={updateLove} /> </div> ); } export default App;<file_sep>/src/modules/gallery.data.js const galleryItems = [ { id: 1, path: 'images/climbing-2.jpg', description: 'My wife and I in our happy place, the forest of Fontainebleau.', likes: 0 }, { id: 2, path: 'images/food-3.jpg', description: 'One of our summer pastimes.', likes: 0 }, { id: 3, path: 'images/nature-2.jpg', description: 'The North Shore during peak fall colors.', likes: 0 }, { id: 4, path: 'images/climbing-3.jpg', description: 'Sandstone textures dusted with snow.', likes: 0 }, { id: 5, path: 'images/food-5.jpg', description: 'Rotisserie chicken from the local boucherie in Milly-la-Foret.', likes: 0 }, { id: 6, path: 'images/travel-3.jpg', description: 'Hiking from Kotor to Tivat.', likes: 0 }, ]; module.exports = galleryItems;<file_sep>/src/components/GalleryItem/GalleryItem.jsx import { useState } from 'react'; // this is the button and counter for each image // provides ability to track `love` for each image separately function GalleryItem ({item, updateLove}) { const [loveCounter, setLoveCounter] = useState(0); const [description, setDescription] =useState(false); const handleLove = (galleryId) => { console.log('in handleLove', galleryId); // setLoveCounter(loveCounter + 1); updateLove(galleryId) setDescription(true); } return( <> {/* {description && <p>My wife and I in our happy place, the forest of Fontainebleau.</p>} */} <button className="love-button" onClick={ () => handleLove(item) }>love it!</button> {/* <button className="love-button" onClick={ () => setLoveCounter(loveCounter + 1) }>love it!</button> */} <p>&#10084;&#65039;&nbsp; {loveCounter}</p> {/* {description && <div>{item.description}</div>}<br /> */} </> ) } export default GalleryItem;
767c7bade8308610049dfe699c3e7def2ff4a52f
[ "JavaScript", "Text" ]
5
Text
stephenmussel/weekend-react-gallery
8e5729c636ca01fb8d6d2a52bbe0eaaee3e73dc8
0cbd06a2ec4d6e2f1e9a17070f478cd01eb56d73
refs/heads/master
<repo_name>quocdatt8/week2-assignment<file_sep>/baseProject/BaseRN-master/App/Config/ScreenConfig.ts import { Color } from 'App/Theme'; const ScreenConfig = { headerColor: Color.headerSafe, safeAreaColor: Color.headerSafe, }; export default ScreenConfig; <file_sep>/demoHook/AppNavigation.js import React, { useState, useEffect } from 'react'; import { View, Text, TouchableOpacity } from 'react-native'; import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; function HomeScreen({navigation, route}) { console.log(navigation); const [count, setCount] = useState(0); useEffect(() => { if (route.params?.value) { setCount(route.params?.value); } }, route.params?.value) const updateCountValue = (value) => { setCount(value); } return ( <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}> <Text>Home Screen</Text> <TouchableOpacity onPress={() => navigation.navigate('Detail1', { userName: '<NAME>', updateCountValue: updateCountValue, })}> <Text>{`Count is: ${count}`}</Text> <Text>Go To Detail 1</Text> </TouchableOpacity> </View> ); } function DetailsScreen1({navigation, route}) { // const {userName, updateCountValue} = route.params; const userName = route.params?.userName; const updateCountValue = route.params?.updateCountValue; return ( <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}> <Text>Details Screen 1</Text> <Text>{`userName: ${userName}`}</Text> <TouchableOpacity onPress={() => updateCountValue(3)}> <Text> Update value of HOmeScreen </Text> </TouchableOpacity> <TouchableOpacity onPress={() => navigation.push('Detail2')}> <Text>Go to Detail 2</Text> </TouchableOpacity> </View> ); } function DetailsScreen2({navigation}) { return ( <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}> <Text>Details Screen 2</Text> <TouchableOpacity onPress={() => navigation.push('Detail1')}> <Text>Go to Detail 1</Text> </TouchableOpacity> </View> ); } const Stack = createStackNavigator(); function App() { return ( <NavigationContainer> <Stack.Navigator> <Stack.Screen name="Home" component={HomeScreen} options={{title: 'Home screen'}}/> <Stack.Screen name="Detail1" component={DetailsScreen1} options={{title: 'Message screen 1'}} /> <Stack.Screen name="Detail2" component={DetailsScreen2} options={{title: 'Message screen 2'}} /> </Stack.Navigator> </NavigationContainer> ); } export default App;<file_sep>/baseProject/BaseRN-master/__tests__/__mocks__/base-screen.mock.ts import { BaseScreenProps } from 'App/@types/screen-type'; import { ScreenMap } from 'App/Config/NavigationConfig'; export const mockBaseScreenProps: BaseScreenProps<ScreenMap.Home> = { navigation: { navigate: jest.fn(), dispatch: jest.fn(), pop: jest.fn(), goBack: jest.fn(), push: jest.fn(), addListener: jest.fn(), popToTop: jest.fn(), canGoBack: jest.fn(), replace: jest.fn(), reset: jest.fn(), removeListener: jest.fn(), setParams: jest.fn(), setOptions: jest.fn(), dangerouslyGetParent: jest.fn(), isFocused: jest.fn(), dangerouslyGetState: jest.fn(), }, route: { key: '', name: ScreenMap.Home, params: {}, }, }; <file_sep>/baseProject/BaseRN-master/App/Redux/HomeRedux.ts import { createAction, createActionTypeOnSuccess, UnfoldSagaActionType } from 'redux-unfold-saga'; import { produce } from 'immer'; export const REDUX_KEY = 'Home'; export enum ActionTypes { GET_HOME_DATA = 'GET_HOME_DATA', } export const Actions = { getHomeData: createAction(ActionTypes.GET_HOME_DATA), }; export interface HomeState { data: {}; } export const defaultState: HomeState = { data: {}, }; export const reducer = (state = defaultState, action: UnfoldSagaActionType): HomeState => { const { type, payload } = action; return produce(state, (draftState: HomeState) => { switch (type) { case createActionTypeOnSuccess(ActionTypes.GET_HOME_DATA): draftState.data = payload; break; } }); }; <file_sep>/baseProject/BaseRN-master/App/Config/NavigationConfig.ts import { ParamListBase } from '@react-navigation/native'; export enum ScreenMap { Home = 'Home', Detail = 'Detail', } export interface ScreenParams extends ParamListBase { [ScreenMap.Home]: {}; [ScreenMap.Detail]: { userName: string }; } <file_sep>/baseProject/BaseRN-master/App/Lib/apiMap.ts export const apiMap = { getHomeData: 'users/kienlv58', }; <file_sep>/baseProject/BaseRN-master/App/Lib/fetchHelpers.ts import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'; import { merge } from 'lodash'; // import Config from 'react-native-config'; import env from 'App/Config/Enviroment/env'; import { throwErrorIfEmpty, throwErrorIfMalformed } from './errorHelpers'; const API_ENDPOINT = env.API_ENDPOINT; /** * Universal user object * This user object is used throughout the app */ interface User { accessToken: string; } let user: User | undefined; /** * Update access token into universal user object * @param authorizedUser */ export function updateAccessTokenToHeader(authorizedUser: User | undefined): void { if (authorizedUser) { user = { ...user, ...authorizedUser, }; } } /** * Configure default request config * @param requestConfig */ export const configure = (requestConfig: AxiosRequestConfig = {}): AxiosRequestConfig => { const targetConfig = { headers: { 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json', }, timeout: 30000, }; if (user && user.accessToken) { merge(targetConfig, { headers: { Authorization: `Bearer ${user.accessToken}`, }, }); } return merge(targetConfig, requestConfig); }; /** * app API instance */ export const appApi = axios.create({ baseURL: API_ENDPOINT, }); appApi.interceptors.request.use( (config: AxiosRequestConfig): AxiosRequestConfig => { return configure(config); }, (error): Promise<Error> => { return Promise.reject(error); }, ); appApi.interceptors.response.use( (response: AxiosResponse): AxiosResponse => { throwErrorIfMalformed(response); throwErrorIfEmpty(response); return response; }, (error): Promise<Error> => { return Promise.reject(error); }, ); export default { appApi, }; <file_sep>/baseProject/BaseRN-master/__tests__/__mocks__/async-storage.ts // @ts-ignore import MockAsyncStorage from 'mock-async-storage'; const mockImpl = new MockAsyncStorage(); jest.mock('@react-native-community/async-storage', () => mockImpl); <file_sep>/baseProject/BaseRN-master/__tests__/__mocks__/reactotron-react-native.ts const reactotron = { configure: jest.fn(), useReactNative: jest.fn(), use: jest.fn(), connect: jest.fn(), }; export default reactotron; <file_sep>/baseProject/BaseRN-master/.eslintrc.js module.exports = { env: { browser: true, es6: true, jest: true, node: true, }, extends: [ '@react-native-community', 'eslint:recommended', 'plugin:import/recommended', 'plugin:import/typescript', 'plugin:react/recommended', // Uses the recommended rules from @eslint-plugin-react 'plugin:react-native/all', 'plugin:jsx-a11y/strict', 'plugin:lodash/recommended', 'plugin:prettier/recommended', // Enables eslint-plugin-prettier and displays prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array. 'plugin:@typescript-eslint/recommended', // Uses the recommended rules from @typescript-eslint/eslint-plugin ], plugins: ['@typescript-eslint'], parser: '@typescript-eslint/parser', // Specifies the ESLint parser parserOptions: { ecmaFeatures: { jsx: true, // Allows for the parsing of JSX }, ecmaVersion: 2018, // Allows for the parsing of modern ECMAScript features sourceType: 'module', // Allows for the use of imports }, rules: { // Place to specify ESLint rules. Can be used to overwrite rules specified from the extended configs '@typescript-eslint/indent': ['off', 2], '@typescript-eslint/explicit-member-accessibility': ['off'], '@typescript-eslint/no-var-requires': 'off', 'import/named': 'warn', // This rule should be removed after @typescript-eslint/parser fix 'import/newline-after-import': 'error', 'import/no-unresolved': 'off', // Let typescript decide whether a module path is resolved 'import/order': 'error', '@typescript-eslint/no-unused-vars': 'error', '@typescript-eslint/no-use-before-define': 'off', indent: 'off', 'no-console': 'warn', 'lodash/import-scope': 'off', 'lodash/prefer-noop': 'off', 'react/display-name': 'off', 'react/jsx-max-depth': ['error', { max: 6 }], 'max-lines': ['error', { max: 300, skipBlankLines: true, skipComments: true }], 'max-lines-per-function': ['error', { max: 50 }], 'react-native/no-raw-text': 'off', 'react/jsx-no-bind': 'off', '@typescript-eslint/no-explicit-any': 'error', '@typescript-eslint/ban-ts-ignore': 'warn', }, settings: { react: { version: 'detect', // Tells eslint-plugin-react to automatically detect the version of React to use }, }, }; <file_sep>/baseProject/BaseRN-master/App/Selector/HomeSelector.ts import { get } from 'lodash'; import { createSelector } from 'reselect'; import { RootState } from 'App/Redux'; import { HomeState, REDUX_KEY } from 'App/Redux/HomeRedux'; export const selectHome = (state: RootState): HomeState => get(state, REDUX_KEY); export const selectHomeData = createSelector(selectHome, (homeState: HomeState): {} => homeState.data); export default { selectHomeData, }; <file_sep>/baseProject/BaseRN-master/App/Redux/index.ts import { combineReducers } from 'redux'; import { REDUX_KEY as HomeKey, reducer as HomeReducer, defaultState as homeDefaultState, HomeState } from './HomeRedux'; import { REDUX_KEY as GlobalKey, reducer as GlobalReducer, defaultState as globalDefaultState, GlobalState, } from './GlobalRedux'; export interface RootState { [HomeKey]: HomeState; [GlobalKey]: GlobalState; } export const RootStateDefault: RootState = { [HomeKey]: homeDefaultState, [GlobalKey]: globalDefaultState, }; export default combineReducers<RootState>({ [HomeKey]: HomeReducer, [GlobalKey]: GlobalReducer, }); <file_sep>/baseProject/BaseRN-master/App/Containers/HomeScreen/styles.ts import { StyleSheet } from 'react-native'; import { Palette } from 'App/Theme/Palette'; const styles = StyleSheet.create({ viewToScroll: { backgroundColor: Palette.angry, height: 400, }, }); export default styles; <file_sep>/baseProject/BaseRN-master/jest.config.js module.exports = { testEnvironment: 'node', preset: 'react-native', // moduleNameMapper: { // '^[./a-zA-Z0-9$_-]+\\.(bmp|gif|jpg|jpeg|png|psd|svg|webp|ttf|otf)$': 'RelativeImageStub', // '^React$': '<rootDir>/node_modules/react', // }, setupFiles: ['<rootDir>/node_modules/react-native/jest/setup.js', './__tests__/jestSetup.js'], moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], transform: { // '^.+\\.(js)$': 'babel-jest', // '\\.(ts|tsx)$': 'ts-jest', // '^.+\\.tsx?$': 'ts-jest', // '^[./a-zA-Z0-9$_-]+\\.(bmp|gif|jpg|jpeg|png|psd|svg|webp)$': './mediaFileTransformer.js', }, testRegex: '(/tests/.*|\\.(test|spec))\\.(ts|tsx|js)$', testPathIgnorePatterns: ['\\.snap$', '/node_modules/'], transformIgnorePatterns: [ 'node_modules/(?!(jest-)?react-native|react-native|react-navigation|@react-navigation|@storybook|@react-native-community)', ], setupFilesAfterEnv: ['<rootDir>setup-tests.js'], // cacheDirectory: '.jest/cache', }; <file_sep>/baseProject/BaseRN-master/App/Sagas/HomeSaga.ts import { SagaIterator } from 'redux-saga'; import { takeLatest } from 'redux-saga/effects'; import { unfoldSaga, UnfoldSagaActionType } from 'redux-unfold-saga'; import { ActionTypes } from 'App/Redux/HomeRedux'; import { appApi } from 'App/Lib/fetchHelpers'; import { apiMap } from 'App/Lib/apiMap'; export function* takeGetHomeData({ callbacks, type }: UnfoldSagaActionType): Iterable<SagaIterator> { yield unfoldSaga( { handler: async (): Promise<{}> => { const { data } = await appApi.get(apiMap.getHomeData); return data; }, key: type, }, callbacks, ); } export default function*(): SagaIterator { yield takeLatest(ActionTypes.GET_HOME_DATA, takeGetHomeData); } <file_sep>/baseProject/BaseRN-master/App/Selector/GlobalSelector.ts import { get } from 'lodash'; import { createSelector } from 'reselect'; import { RootState } from 'App/Redux'; import { GlobalState, REDUX_KEY } from 'App/Redux/GlobalRedux'; export const selectGlobal = (state: RootState): GlobalState => get(state, REDUX_KEY); export const selectGlobalLoading = createSelector( selectGlobal, (gloabalState: GlobalState): boolean => gloabalState.isLoading, ); export default { selectGlobal, }; <file_sep>/baseProject/BaseRN-master/App/@types/screen-type.d.ts import { ParamListBase, RouteProp } from '@react-navigation/native'; import { StackNavigationProp } from '@react-navigation/stack'; import { ScreenParams } from 'App/Config/NavigationConfig'; interface BaseScreenProps<RouteName extends keyof ParamList, ParamList extends ParamListBase = ScreenParams> { navigation: StackNavigationProp<ParamList, RouteName>; route: RouteProp<ParamList, RouteName>; } type RouteScreenProps<RouteName extends keyof ParamList, ParamList extends ParamListBase = ScreenParams> = RouteProp< ParamList, RouteName >; type NavigationScreenProps< RouteName extends keyof ParamList, ParamList extends ParamListBase = ScreenParams > = StackNavigationProp<ParamList, RouteName>; <file_sep>/baseProject/BaseRN-master/App/Sagas/index.ts import { SagaIterator } from 'redux-saga'; import { all, call } from 'redux-saga/effects'; import home from './HomeSaga'; export default function* rootSaga(): SagaIterator { yield all([call(home)]); } <file_sep>/baseProject/BaseRN-master/App/Config/Enviroment/env.ts import EnvDev from './env.dev'; import EnvProd from './env.prod'; const env = __DEV__ ? EnvDev : EnvProd; export default env; <file_sep>/demoHook/App.js /** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow strict-local */ import React, {useState, useEffect} from 'react'; import { SafeAreaView, StyleSheet, ScrollView, View, Text, StatusBar, TouchableOpacity, Alert, } from 'react-native'; import { Header, LearnMoreLinks, Colors, DebugInstructions, ReloadInstructions, } from 'react-native/Libraries/NewAppScreen'; const DEFAULT_COUNT = 0; const TRACK_VALUE = 3; const App: () => React$Node = () => { const [count, setCount] = useState(DEFAULT_COUNT); // Component did mount useEffect(() => { Alert.alert('Component did mount'); // Component will unmount return () => { console.warn('Component will unmount.') } }, []); // Call when count updated. useEffect(() => { if ( count === TRACK_VALUE) { Alert.alert('Track value'); } }, [count]); // Called every time when function called useEffect(() => { console.warn("useEffect called with count: ", count); }) return ( <SafeAreaView style={styles.container}> <Text style={styles.title}>{`Bạn đã click ${count} lần`} </Text> <TouchableOpacity onPress={() => setCount(count + 1)} style={styles.btn}> <Text>Click me</Text> </TouchableOpacity> <TouchableOpacity onPress={() => setCount(DEFAULT_COUNT)} style={styles.btn} > <Text>Reset</Text> </TouchableOpacity> </SafeAreaView> ); }; const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center', }, btn: { width: 100, height: 50, alignItems: 'center', justifyContent: 'center', borderColor: 'gray', borderWidth: 1, marginTop: 20, }, title: { fontSize: 16, fontWeight: 'bold' } }); export default App; <file_sep>/baseProject/BaseRN-master/App/Lib/errorHelpers.ts import { AxiosResponse } from 'axios'; import { isEmpty, get, toNumber } from 'lodash'; const COMMON_ERROR_MESSAGE = 'Có lỗi xảy ra!'; export function throwErrorIfEmpty(response: Partial<AxiosResponse>): void { if (isEmpty(get(response, 'data'))) { throw new Error(COMMON_ERROR_MESSAGE); } } export function throwErrorIfMalformed(response: Partial<ErrorResponseType>): void { throwErrorIfEmpty(response); if (toNumber(get(response, 'data.status')) === 0) { throw new Error(get(response, 'data.message') || COMMON_ERROR_MESSAGE); } } <file_sep>/baseProject/BaseRN-master/App/Config/Enviroment/env.dev.ts export default { API_ENDPOINT: 'https://api.github.com/', };
aa1e1bb0bb7c7d0dc84b2c24fb8468b2bca6ee9f
[ "JavaScript", "TypeScript" ]
22
TypeScript
quocdatt8/week2-assignment
6f02bf360999e4842195d9c654d2b5210f2e8a78
b4747538cb21fecb5a70b93891806bbd8878e5b1
refs/heads/master
<repo_name>vanh17/panthrMath<file_sep>/test/finite.spec.js var chai = require('chai'); var expect = chai.expect; var precision = 1e-10; var utils = require('../panthrMath/utils'); var main = require('..'); describe('finite distribution', function() { it('specified via list of values and probabilities', function() { var d; d = main.finite({ xs: [2, 5, 7], ws: [1, 2, 1] }); ['d', 'p', 'q', 'r'].forEach(function(s) { expect(d).to.respondTo(s); }); [[1, 0], [2, 0.25], [5, 0.5], [6, 0], [7, 0.25], [8, 0]].forEach( function(pair) { expect(d.d(pair[0])).to.equal(pair[1]); expect(d.d(pair[0], true)).to.equal(Math.log(pair[1])); }); [[1, 0], [2, 0.25], [3, 0.25], [5, 0.75], [6, 0.75], [7, 1], [8, 1]].forEach(function(pair) { expect(d.p(pair[0])).to.equal(pair[1]); expect(d.p(pair[0], true, true)).to.equal(Math.log(pair[1])); expect(d.p(pair[0], false)).to.equal(1 - pair[1]); expect(d.p(pair[0], false, true)).to.equal(Math.log(1 - pair[1])); }); [[0, 2], [0.2, 2], [0.25, 2], [0.3, 5], [0.45, 5], [0.7, 5], [0.75, 5], [0.8, 7], [1, 7]].forEach(function(pair) { expect(d.q(pair[0])).to.equal(pair[1]); expect(d.q(Math.log(pair[0]), true, true)).to.equal(pair[1]); expect(d.q(1-pair[0], false)).to.equal(pair[1]); expect(d.q(Math.log(1-pair[0]), false, true)).to.equal(pair[1]); }); }); it('understands non-integer xs', function() { var d; d = main.finite({ xs: [-0.2, 5.1, 7], ws: [1, 2, 1] }); ['d', 'p', 'q', 'r'].forEach(function(s) { expect(d).to.respondTo(s); }); [[-1, 0], [-0.2, 0.25], [5.1, 0.5], [6, 0], [7, 0.25], [8, 0]].forEach(function(p) { expect(d.d(p[0])).to.equal(p[1]); expect(d.d(p[0], true)).to.equal(Math.log(p[1])); }); [[-1, 0], [-0.2, 0.25], [3, 0.25], [5.1, 0.75], [6, 0.75], [7, 1], [8, 1]].forEach(function(p) { expect(d.p(p[0])).to.equal(p[1]); expect(d.p(p[0], true, true)).to.equal(Math.log(p[1])); expect(d.p(p[0], false)).to.equal(1 - p[1]); expect(d.p(p[0], false, true)).to.equal(Math.log(1 - p[1])); }); [[0, -0.2], [0.2, -0.2], [0.25, -0.2], [0.3, 5.1], [0.45, 5.1], [0.7, 5.1], [0.75, 5.1], [0.8, 7], [1, 7]].forEach(function(p) { expect(d.q(p[0])).to.equal(p[1]); expect(d.q(Math.log(p[0]), true, true)).to.equal(p[1]); expect(d.q(1-p[0], false)).to.equal(p[1]); expect(d.q(Math.log(1-p[0]), false, true)).to.equal(p[1]); }); }); it('specified via a function', function() { var n, p, f, cdf, d, i, q; n = 20; for (var times = 0; times < 20; times += 1) { p = Math.random(); f = main.dbinom(n, p); cdf = main.pbinom(n, p); d = main.finite({ f: f, min: 0, max: n }); for (i = 0; i <= n; i += 1) { expect(utils.relativelyCloseTo(d.d(i), f(i))).to.be.ok; expect(utils.relativelyCloseTo(d.p(i), cdf(i))).to.be.ok; expect(utils.relativelyCloseTo(d.p(i, false), main.pbinom(n, p, false)(i))).to.be.ok; if (d.p(i, false) > 1e-8) { expect(d.q(d.p(i))).to.equal(i); } q = main.pbinom(n, p, false)(i); if (d.p(i, true) > 1e-8) { expect(d.q(d.p(i, false), false)).to.equal(i); } } } }); }); <file_sep>/panthrMath/distributions/chisq.js (function(define) { 'use strict'; define(function(require) { /** * Provides density function, cumulative distribution function, * quantile function, and random number generator * for the chi square distribution ... TODO * * @module distributions.chisq * @memberof distributions * @author <NAME> <<EMAIL>>, <NAME> <<EMAIL>> */ var gamma; gamma = require('./gamma'); /** * TODO * * @fullName dchisq(df, logp)(x) * @memberof chisq */ function dchisq(df, logp) { return gamma.dgamma(df / 2, 2, logp); } /** * TODO * * @fullName pchisq(df, lowerTail, logp)(x) * @memberof chisq */ function pchisq(df, lowerTail, logp) { return gamma.pgamma(df / 2, 2, lowerTail, logp); } /** * TODO * * @fullName qchisq(df, lowerTail, logp)(p) * @memberof chisq */ function qchisq(df, lowerTail, logp) { return gamma.qgamma(df / 2, 2, lowerTail, logp); } /** * TODO * * @memberof chisq */ function rchisq(df) { return gamma.rgamma(df / 2, 2); } return { /** * Returns an object representing a chi squared distribution for `df` degrees * of freedom, with properties `d`, `p`, `q`, `r`. * ``` * chisq(df).d(x, logp) // same as dchisq(df, logp)(x) * chisq(df).p(x, lowerTail, logp) // same as pchisq(df, lowerTail, logp)(x) * chisq(df).q(x, lowerTail, logp) // same as qchisq(df, lowerTail, logp)(x) * chisq(df).r() // same as rchisq(df)() * ``` * @memberof chisq */ chisq: function(df) { return { d: function(x, logp) { return dchisq(df, logp)(x); }, p: function(q, lowerTail, logp) { return pchisq(df, lowerTail, logp)(q); }, q: function(p, lowerTail, logp) { return qchisq(df, lowerTail, logp)(p); }, r: function() { return rchisq(df)(); } }; }, dchisq: dchisq, pchisq: pchisq, qchisq: qchisq, rchisq: rchisq }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { 'use strict'; module.exports = factory(require); }));
99043deee789cf0984ff1d4bdef29aed0bb114b4
[ "JavaScript" ]
2
JavaScript
vanh17/panthrMath
9521f899b7c494e787da37759974203a889073cb
cc3d967fc1d6ec5df96f4be5ed656fd4a1c70134
refs/heads/master
<file_sep>//CREATE A ROTATING CUBE AND ALSO A CAMERA WITH A RIGID BODY var scene, camera, renderer, clock; var keyboard = {}; var player = { height: 3.0, speed: 0.2, turnSpeed: Math.PI * 0.02 }; var geometry = new THREE.BoxGeometry(1, 1, 1); var material = new THREE.MeshBasicMaterial({ color: 'blue' }); var cube = new THREE.Mesh(geometry, material); var geometry = new THREE.PlaneGeometry(30, 30, 30); var material = new THREE.MeshBasicMaterial({ color: 'grey', side: THREE.DoubleSide }); var plane = new THREE.Mesh(geometry, material); var axesHelper = new THREE.AxesHelper(100); var renderer = new THREE.WebGLRenderer({ antialias: true }) var stats; var rigidBodies = [], tmpTrans; let physicsWorld; Ammo().then(start) function setupPhysicsWorld() { let collisionConfiguration = new Ammo.btDefaultCollisionConfiguration(), dispatcher = new Ammo.btCollisionDispatcher(collisionConfiguration), overlappingPairCache = new Ammo.btDbvtBroadphase(), solver = new Ammo.btSequentialImpulseConstraintSolver(); physicsWorld = new Ammo.btDiscreteDynamicsWorld(dispatcher, overlappingPairCache, solver, collisionConfiguration); physicsWorld.setGravity(new Ammo.btVector3(0, -10, 0)); } function setupGraphics() { //create clock for timing clock = new THREE.Clock(); //create the scene scene = new THREE.Scene(); scene.background = new THREE.Color(0xbfd1e5); //create camera camera = new THREE.PerspectiveCamera(90, 1280 / 720, 0.1, 1000); camera.position.set(0, player.height, -5); camera.lookAt(new THREE.Vector3(0, player.height, 0)); //Add hemisphere light let hemiLight = new THREE.HemisphereLight(0xffffff, 0xffffff, 0.1); hemiLight.color.setHSL(0.6, 0.6, 0.6); hemiLight.groundColor.setHSL(0.1, 1, 0.4); hemiLight.position.set(0, 50, 0); scene.add(hemiLight); //Add directional light let dirLight = new THREE.DirectionalLight(0xffffff, 1); dirLight.color.setHSL(0.1, 1, 0.95); dirLight.position.set(-1, 1.75, 1); dirLight.position.multiplyScalar(100); scene.add(dirLight); dirLight.castShadow = true; dirLight.shadow.mapSize.width = 2048; dirLight.shadow.mapSize.height = 2048; let d = 50; dirLight.shadow.camera.left = -d; dirLight.shadow.camera.right = d; dirLight.shadow.camera.top = d; dirLight.shadow.camera.bottom = -d; dirLight.shadow.camera.far = 13500; //Setup the renderer renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setClearColor(0xbfd1e5); renderer.setPixelRatio(window.devicePixelRatio); renderer.setSize(1280, 720); document.body.appendChild(renderer.domElement); renderer.gammaInput = true; renderer.gammaOutput = true; renderer.shadowMap.enabled = true; } function createCube() { //TODO create a rotating cube with collision } function createBall() { let pos = { x: 0, y: 20, z: 0 }; let radius = 2; let quat = { x: 0, y: 0, z: 0, w: 1 }; let mass = 1; //threeJS Section let ball = new THREE.Mesh(new THREE.SphereBufferGeometry(radius), new THREE.MeshPhongMaterial({ color: 0xff0505 })); ball.position.set(pos.x, pos.y, pos.z); ball.castShadow = true; ball.receiveShadow = true; scene.add(ball); //Ammojs Section let transform = new Ammo.btTransform(); transform.setIdentity(); transform.setOrigin(new Ammo.btVector3(pos.x, pos.y, pos.z)); transform.setRotation(new Ammo.btQuaternion(quat.x, quat.y, quat.z, quat.w)); let motionState = new Ammo.btDefaultMotionState(transform); let colShape = new Ammo.btSphereShape(radius); colShape.setMargin(0.05); let localInertia = new Ammo.btVector3(0, 0, 0); colShape.calculateLocalInertia(mass, localInertia); let rbInfo = new Ammo.btRigidBodyConstructionInfo(mass, motionState, colShape, localInertia); let body = new Ammo.btRigidBody(rbInfo); physicsWorld.addRigidBody(body); ball.userData.physicsBody = body; rigidBodies.push(ball); } function createBlock() { let pos = { x: 0, y: 0, z: 0 }; let scale = { x: 50, y: 2, z: 50 }; let quat = { x: 0, y: 0, z: 0, w: 1 }; let mass = 0; //threeJS Section let blockPlane = new THREE.Mesh(new THREE.BoxBufferGeometry(), new THREE.MeshPhongMaterial({ color: 0xa0afa4 })); blockPlane.position.set(pos.x, pos.y, pos.z); blockPlane.scale.set(scale.x, scale.y, scale.z); blockPlane.castShadow = true; blockPlane.receiveShadow = true; scene.add(blockPlane); //Ammojs Section let transform = new Ammo.btTransform(); transform.setIdentity(); transform.setOrigin(new Ammo.btVector3(pos.x, pos.y, pos.z)); transform.setRotation(new Ammo.btQuaternion(quat.x, quat.y, quat.z, quat.w)); let motionState = new Ammo.btDefaultMotionState(transform); let colShape = new Ammo.btBoxShape(new Ammo.btVector3(scale.x * 0.5, scale.y * 0.5, scale.z * 0.5)); colShape.setMargin(0.05); let localInertia = new Ammo.btVector3(0, 0, 0); colShape.calculateLocalInertia(mass, localInertia); let rbInfo = new Ammo.btRigidBodyConstructionInfo(mass, motionState, colShape, localInertia); let body = new Ammo.btRigidBody(rbInfo); physicsWorld.addRigidBody(body); } function updatePhysics(deltaTime) { // Step world physicsWorld.stepSimulation(deltaTime, 10); // Update rigid bodies for (let i = 0; i < rigidBodies.length; i++) { let objThree = rigidBodies[i]; let objAmmo = objThree.userData.physicsBody; let ms = objAmmo.getMotionState(); if (ms) { ms.getWorldTransform(tmpTrans); let p = tmpTrans.getOrigin(); let q = tmpTrans.getRotation(); objThree.position.set(p.x(), p.y(), p.z()); objThree.quaternion.set(q.x(), q.y(), q.z(), q.w()); } } } function setupStats() { stats = new Stats(); stats.domElement.style.position = 'absolute'; stats.domElement.style.top = '0px'; container.appendChild(stats.domElement); } function start() { tmpTrans = new Ammo.btTransform(); setupGraphics(); setupPhysicsWorld(); setupStats(); createBlock(); createBall(); animate(); } function animate() { //console.log stats.update() requestAnimationFrame(animate); let deltaTime = clock.getDelta(); updatePhysics(deltaTime); updateControls(); renderer.render(scene, camera); } function keyDown(event) { keyboard[event.keyCode] = true; } function keyUp(event) { keyboard[event.keyCode] = false; } function updateControls() { if (keyboard[87]) { // W key camera.position.x -= Math.sin(camera.rotation.y) * player.speed; camera.position.z -= -Math.cos(camera.rotation.y) * player.speed; } if (keyboard[83]) { // S key camera.position.x += Math.sin(camera.rotation.y) * player.speed; camera.position.z += -Math.cos(camera.rotation.y) * player.speed; } if (keyboard[65]) { // A key camera.position.x += Math.sin(camera.rotation.y + Math.PI / 2) * player.speed; camera.position.z += -Math.cos(camera.rotation.y + Math.PI / 2) * player.speed; } if (keyboard[68]) { // D key camera.position.x += Math.sin(camera.rotation.y - Math.PI / 2) * player.speed; camera.position.z += -Math.cos(camera.rotation.y - Math.PI / 2) * player.speed; } if (keyboard[37]) { // left arrow key camera.rotation.y -= player.turnSpeed; } if (keyboard[39]) { // right arrow key camera.rotation.y += player.turnSpeed; } } window.addEventListener('keydown', keyDown); window.addEventListener('keyup', keyUp); <file_sep># My-Little-Universe Building my personal space in ThreeJS. # Usage with Live Server Live server offers many features like Auto Refresh of the Browser and watches for changes in your server folder and automatically restarts itself. First install Live-server using the command `npm install -g live-server` Issue `live-server` in your local directory to start the server. For other information about live-server visit its official page (https://www.npmjs.com/package/live-server) # Join me? I'm a newbie but I'm willing to learn, want to join me on this adventure ? Contact me and we might work together on it. # Copyrights No copyrights, you can do whatever you want with this code but I'd like to know how you'd use it.
78cfdc730c386340ef03db32d6c08b7d2ac4fbc2
[ "JavaScript", "Markdown" ]
2
JavaScript
Cesarsk/My-Little-Universe
466825bfb75db02a1a68a84ab056be6b3132e71b
160a66030ae5fc77d8987978aae284595a217fc0
refs/heads/master
<file_sep>/** * <NAME>, 107, Assignment 2 */ import java.util.Arrays; import java.util.stream.Collectors; /** * SimpleList class implements methods to create and use a custom ArrayList */ public class SimpleList { private int[] list; private int count; /** * creates an array called list and a counter int */ public SimpleList() { list = new int[10]; count = 0; } /** * push a variable to the array and increment count * @param a the integer to add to the beginning of the list */ public void add(int a) { if (count == list.length) { double len = list.length * 1.5; int[] newlist = new int[(int)len]; for (int i = 0; i < list.length; i++){ newlist[i] = list[i]; } list = newlist; } for (int i = list.length - 1; i > 0; i--) { list[i] = list[i - 1]; } count++; list[0] = a; } /** * search for a variable in the list and remove it if found, decrement count * @param a the int to search for and remove from the list. */ public void remove(int a) { for (int i = 0; i < list.length; i++) { if (list[i] == a) { for (int j = i; j < list.length - 1; j++) { list[j] = list[j + 1]; } count--; } } double len = list.length * 0.75; if (count < (int)len){ int[] newlist = new int[(int)len]; for (int i = 0; i < (int)len; i++){ newlist[i] = list[i]; } list = newlist; } } /** * return the value of count * @return return the int count */ public int count() { return count; } /** * search a variable in the list and return its index * @param a the int to search for. * @return return the inndex of the searched variable */ public int search(int a) { for (int i = 0; i < list.length; i++) { if (list[i] == a) { return i; } } return -1; } /** * return the list as a string delimited by spaces * @return return a concatenated string of the array */ public String toString(){ String result = Arrays.stream(list) .mapToObj(String::valueOf) .collect(Collectors.joining(" ")); return result; } /** * adds an element to the end of the array * @param a the int to add to the end of the list. */ public void append(int a) { if (count == list.length) { double len = list.length * 1.5; int[] newlist = new int[(int) len]; for (int i = 0; i < list.length; i++) { newlist[i] = list[i]; } list = newlist; } list[count] = a; count++; } /** * returns the first element of the array * @return return the first value in the list */ public int first(){ return list[0]; } /** * returns the size of the array * @return return the size of the array */ public int size(){ return list.length; } } <file_sep>import static org.junit.Assert.*; public class SimpleListTest { @org.junit.Test public void simpleList() { //testing constructor of SimpleList to make sure it initiates the list to zeroes SimpleList list1 = new SimpleList(); assertNotNull("not null", list1); assertEquals(0, list1.count()); } @org.junit.Test public void add() { //testing the add function such to make sure it does not add more than one instance SimpleList list1 = new SimpleList(); list1.add(2); list1.add(1); assertEquals(0, list1.search(1)); assertEquals(1, list1.search(2)); assertNotEquals(2, list1.search(3)); list1.add(1); list1.add(1); list1.add(1); list1.add(1); list1.add(1); list1.add(1); list1.add(1); list1.add(1); list1.add(1); assertEquals(15, list1.size()); } @org.junit.Test public void remove() { //testing the remove function, to make sure it does not remove all instances SimpleList list1 = new SimpleList(); list1.add(2); list1.add(1); list1.add(1); list1.remove(1); assertEquals("1 2 0 0 0 0 0", list1.toString()); assertEquals(7, list1.size()); } @org.junit.Test public void countTest() { //testing count function to make sure it returns the correct count regardless of adds or removes SimpleList list1 = new SimpleList(); list1.add(2); list1.add(1); list1.remove(1); assertEquals(1, list1.count()); } @org.junit.Test public void searchTest() { //testing search function to make sure it returns the correct index of the number and -1 if the number isnt in the list SimpleList list1 = new SimpleList(); list1.add(2); list1.add(1); list1.remove(1); assertEquals(0, list1.search(2)); assertEquals(-1, list1.search(5)); } @org.junit.Test public void arrayToString() { //testing toString function to see if it correctly turns the array into a string SimpleList list1 = new SimpleList(); list1.add(2); list1.add(1); list1.remove(1); assertEquals("2 0 0 0 0 0 0", list1.toString()); } @org.junit.Test public void appendTest(){ SimpleList list1 = new SimpleList(); list1.add(2); list1.add(1); list1.append(8); assertEquals("1 2 8 0 0 0 0 0 0 0", list1.toString()); list1.append(1); list1.append(1); list1.append(1); list1.append(1); list1.append(1); list1.append(1); list1.append(1); list1.append(1); assertEquals(15, list1.size()); } @org.junit.Test public void firstTest(){ SimpleList list1 = new SimpleList(); list1.add(2); list1.add(1); list1.append(8); assertEquals(1, list1.first()); } @org.junit.Test public void sizeTest(){ SimpleList list1 = new SimpleList(); list1.add(2); list1.add(1); list1.append(8); assertEquals(10, list1.size()); list1.add(2); list1.add(2); list1.add(2); list1.add(2); list1.add(2); list1.add(2); list1.add(2); list1.add(2); assertEquals(15, list1.size()); } }
e1d7e5533e0a281692949ca43e904ab67377a5b1
[ "Java" ]
2
Java
ahomais/360-Assignment-2
436fd2cb615125199d7a62ffbcafd530e4bbe976
b9589171a2592dd0f63e4396b91a6996bba918d2
refs/heads/master
<repo_name>alwaysleep/aki-sample<file_sep>/src/main/java/com/aki/sample/service/impl/OnlyForTestServiceImpl.java package com.aki.sample.service.impl; import com.aki.sample.service.OnlyForTestService; public class OnlyForTestServiceImpl implements OnlyForTestService { } <file_sep>/src/main/java/com/aki/sample/mapper/OnlyForTestMapper.java package com.aki.sample.mapper; import java.util.List; import org.springframework.stereotype.Repository; import com.aki.sample.domain.OnlyForTest; @Repository public interface OnlyForTestMapper { public Integer insert(OnlyForTest entity); public List<OnlyForTest> query(OnlyForTest entity); public int delete(Integer id); } <file_sep>/src/main/java/com/aki/sample/config/DataSourceConfig.java package com.aki.sample.config; import java.io.IOException; import javax.sql.DataSource; import org.mybatis.spring.SqlSessionFactoryBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.TransactionManagementConfigurer; /** * * <pre> * </pre> * @createAt 2018-09-01 03:12:43 * @author vikingblackey <EMAIL> */ @Configuration @EnableTransactionManagement public class DataSourceConfig implements TransactionManagementConfigurer { @Autowired DataSource dataSource; @Bean @ConfigurationProperties(prefix="spring.datasource") public DataSource sqliteDataSource() { return DataSourceBuilder.create().build(); } @Bean public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) throws IOException { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(dataSource); factoryBean.setConfigLocation(new ClassPathResource("mybatis/config.xml")); ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); factoryBean.setMapperLocations(resolver.getResources("classpath*:mybatis/mappers/*.xml")); factoryBean.setTypeAliasesPackage("com.aki.sample.domain"); return factoryBean; } @Bean @Override public PlatformTransactionManager annotationDrivenTransactionManager() { return new DataSourceTransactionManager(dataSource); } } <file_sep>/src/main/java/com/aki/sample/service/OnlyForTestService.java package com.aki.sample.service; public interface OnlyForTestService { } <file_sep>/src/main/resources/sql/only_for_test.sql create table only_for_test ( id integer primary key autoincrement, name text not null, age integer not null, address char(50), salary real, image blob );<file_sep>/README.md # Spring Boot 2 Sample Project > 一个简单的Spring Boot 2工程样板,旨在提供一个简单便捷的Web开发框架。 > > 前端基于Vue实现前后端分离方案,后端精简化只添加必要组件,便于快速填充业务代码实现业务需求。 ## 基础组件 此样板工程封版于2018年08月31日,各类组件的版本更新也基于此时间线。 后端基于[Spring Boot 2.0.4.RELEASE](https://spring.io/projects/spring-boot),可通过[Spring Initializr](https://github.com/spring-io/initializr)生成和更新,内含Web和MyBatista模块。 前端基于[Vue 2.5.17](https://github.com/vuejs/vue),可通过[vue-cli 3](https://github.com/vuejs/vue-cli)创建,工程结构与vue-cli 2略有不同,详见[官网](https://cn.vuejs.org)。主要是Vuex、Vue-Router等基础模块。 ## SQLite数据库 通常Java开源框架会选用MySQL作为数据库,选SQLite主要是更简单。 其实有Spring加持,换数据源也就是改行配置的事情,切换数据源并不影响模板工程。 ## Vue-CLI 3 Vue-CLi 3 带来了不少新的改动。简化之前webpack的配置项(这点得两看),提供了更为友好的UI管理。 初始化的工程结构和上个版本基本一致,新项目使用没有太大问题。老项目就不要再升级了。 ## PS 个人项目,博君一笑。不承担任何风险,也没责任解答任何问题。我再去睡会zzZ~~
c5707c81405c04f690f0721d63502f8cea3d072d
[ "Markdown", "Java", "SQL" ]
6
Java
alwaysleep/aki-sample
12d6daf844d74b4edbcfe1fb15c907c833d3045c
19c7cd04a42d3d28040516448cfd7671d0c89a47
refs/heads/master
<repo_name>Mr-Jess/color-converter<file_sep>/README.md # Color Converter Color converter app is a digital color flow-chart that is simple and easy, targeted towards children based learning. ## Objectives / Usage * When any **two** primary colors are mixed together the outcome will result in its secondary color. * When using the app entering any **one** secondary color will produce its **two** primary colors. ## Example show below * Below is example (1.a). * Enter any color inside the text box.("Green" is used below). * The outcome is: **Yellow and Blue** make up the color **Green**. * The following example (1.b) shows two colors input to result in one mixture outcome color. 1.a <a href="https://ibb.co/P1NnW9Y"><img src="https://i.ibb.co/HGVsPx2/Screen-Shot-2019-10-07-at-8-53-25-PM.png" alt="Screen-Shot-2019-10-07-at-8-53-25-PM" border="0"></a> 1.b <a href="https://ibb.co/tcYzZDL"><img src="https://i.ibb.co/FJ8XszH/Screen-Shot-2019-10-07-at-10-03-37-PM.png" alt="Screen-Shot-2019-10-07-at-10-03-37-PM" border="0"></a> ### How to download on your computer The link below provides instant access to the Fork and Git Clone process. Color Converter link below * [Color Converter App](https://github.com/Mr-Jess/color-converter) To learn how to Fork and Git Clone see link below * [Fork & Git Clone info](https://guides.github.com/activities/forking/)<file_sep>/color-converter.js //Input two Primary colors to get its secondary color outcome. function toCombined(Prim1, Prim2) { if (color1==='red' && color2==='yellow'|| color1==='yellow' && color2==='red') { return 'Orange' } else if (color1==='red' && color2==='blue' || color1==='blue' && color2==='red') { return 'Purple' } else if (color1==='yellow' && color2==='blue' || color1==='blue' && color2==='yellow') { return 'Green' } else if (color1===undefined || color2===undefined) { return 'Enter two primary colors!' } return; } //Breaks down one secondary color to its two primary colors. function toBreakDown(Sec1) { if (color3==='orange') { return 'Red & Yellow' } else if (color3==='purple') { return 'Red & Blue' } else if (color3==='green') { return 'Yellow & Blue' } else if (color3===undefined) { return 'Must enter two primary colors or one secondary color!' } return; } let color1 = process.argv[2] let color2 = process.argv[3] let color3 = process.argv[2] console.log('Color1: ', color1) console.log('Color2: ', color2) console.log(toCombined(color1, color2)); console.log('Color3:', color3) console.log(toBreakDown(color3));
f79f7b7c0033667e3c56362cd1cf8ab172b74df6
[ "Markdown", "JavaScript" ]
2
Markdown
Mr-Jess/color-converter
2be0569acd3d424a12c6e9e8360412d3b86907dd
059cb812e7ccf4ff6d44f236b487c8993d1a6ff7
refs/heads/master
<repo_name>Gharibw/RTBD<file_sep>/CarMate/mcslptds.1/README.txt Cars are equipped with various types of sensors that notify the current status the car. Moreover, new automotive technologies exist, such as Connected Cars, Android Auto, and CarPlay, which are built to provide some effective solutions like automatic notification of crashes, speed notifications, in addition to entertainment purposes. However, to our knowledge, there is no system that prevent emergencies based on the current situation of the car. Thus, we combined the use of sensors’ functions with the new car technologies to read sensory data from the car, apply machine learning algorithms on it, and prevent possible emergency situations. Moreover, our system provides a platform for automatic maintenance scheduling and monitoring. # Node.js Starter Application Bluemix provides a Node.js starter application as a template so that you can add your code and push the changes back to the Bluemix environment. ## Files The Node.js starter application has files as below: * instructions.md This file describes the Next Steps for getting started with this template. * app.js This file contains the server side JavaScript code for your application written using the Node.js API * views/ This directory contains the views of the application. It is required by the express framework and jade template engine in this sample application. * public/ This directory contains public resources of the application. It is required by the express framework in this sample application. * package.json This file is required by the Node.js environment. It specifies this Node.js project name, dependencies, and other configurations of your Node.js application. <file_sep>/README.md Real-time Big Data Analysis small Project: - MapReduce (wordCount example) in Andriod application - HBase functions (create, Insert, View, Delete) implemented using Android application Repository is updated periodically! ==== University of Missouri-Kansas City <file_sep>/CarMate/mcslptds.1/app.js /*jshint node:true*/ // app.js // This file contains the server side JavaScript code for your application. // This sample application uses express as web application framework (http://expressjs.com/), // and jade as template engine (http://jade-lang.com/). var express = require('express'); // setup middleware var app = express(); var fs = require('fs'); app.use(app.router); app.use(express.errorHandler()); app.use(express.static(__dirname + '/public')); //setup static public directory app.set('view engine', 'jade'); app.set('views', __dirname + '/views'); //optional since express defaults to CWD/views // render index page app.get('/', function(req, res){ res.render('index'); }); // There are many useful environment variables available in process.env. // VCAP_APPLICATION contains useful information about a deployed application. var appInfo = JSON.parse(process.env.VCAP_APPLICATION || "{}"); // TODO: Get application information and use it in your app. // VCAP_SERVICES contains all the credentials of services bound to // this application. For details of its content, please refer to // the document or sample of each service. var services = JSON.parse(process.env.VCAP_SERVICES || "{}"); // TODO: Get service credentials and communicate with bluemix services. // The IP address of the Cloud Foundry DEA (Droplet Execution Agent) that hosts this application: var host = (process.env.VCAP_APP_HOST || 'localhost'); // The port on the DEA for communication with the application: var port = (process.env.VCAP_APP_PORT || 3000); var create_datapoint = function(req, res) { console.log("Recording a datapoint"); require('mongodb').connect(services.timeseriesdatabase[0].credentials.json_url, function(err, conn) { if (err) { res.write(err.stack); } console.log("Extracting values"); var collection = conn.collection('ts_data_v'); var parsedUrl = require('url').parse(req.url, true); var queryObject = parsedUrl.query; var name = (queryObject["name"] || 'lounge'); var temppoint = parseFloat((queryObject["temp"] || 0)); var tsdate = new Date(); var datestring = tsdate.getUTCFullYear() + '-'; if (parseInt(tsdate.getUTCMonth() + 1) < 10) { datestring = datestring + '0' + (tsdate.getUTCMonth()+1) + '-'; } else { datestring = datestring + (tsdate.getUTCMonth()+1) + '-'; } if (parseInt(tsdate.getUTCDate()) < 10) { datestring = datestring + '0' + tsdate.getUTCDate() + ' '; } else { datestring = datestring + tsdate.getUTCDate() + ' '; } if (parseInt(tsdate.getUTCHours()) < 10) { datestring = datestring + '0' + tsdate.getUTCHours() + ':'; } else { datestring = datestring + tsdate.getUTCHours() + ':'; } if (parseInt(tsdate.getUTCMinutes()) < 10) { datestring = datestring + '0' + tsdate.getUTCMinutes() + ':'; } else { datestring = datestring + tsdate.getUTCMinutes() + ':'; } if (parseInt(tsdate.getUTCSeconds()) < 10) { datestring = datestring + '0' + tsdate.getUTCSeconds() + ':00000'; } else { datestring = datestring + tsdate.getUTCSeconds() + ':00000'; } console.log(datestring); var message = { 'loc_esi_id': name, 'measure_unit' : 'C', 'direction' : 'P', 'value': temppoint, 'tstamp': datestring}; console.log("Constructed record"); console.log(JSON.stringify(message)); collection.insert(message, {safe:true}, function(err){ if (err) { console.log(err.stack); } res.write(JSON.stringify(message)); }); }); res.end(); }; var list_datapoint = function(req, res) { var parsedUrl = require('url').parse(req.url, true); var queryObject = parsedUrl.query; var name = (queryObject["name"] || 'lounge'); res.writeHead(200, {'Content-Type': 'text/plain'}); require('mongodb').connect(services.timeseriesdatabase[0].credentials.json_url, function(err, conn) { var collection = conn.collection('ts_data_v'); res.write("Reading from collection ts_data_v"); collection.find({"loc_esi_id":"lounge"}, {limit:100, sort:[['loc_esi_id','ascending'],['tstamp','ascending']]}, function(err, cursor) { cursor.toArray(function(err, items) { if (err) { res.write(err.stack); } for (i=0; i < items.length; i++) { res.write(JSON.stringify(items[i]) + "\n"); } res.end(); }); }); }); }; var list_time_datapoint = function(req, res) { var parsedUrl = require('url').parse(req.url, true); var queryObject = parsedUrl.query; var name = (queryObject["name"] || 'lounge'); res.writeHead(200, {'Content-Type': 'text/plain'}); require('mongodb').connect(services.timeseriesdatabase[0].credentials.json_url, function(err, conn) { var collection = conn.collection('ts_data_v'); collection.find({"loc_esi_id":"lounge"}, {limit:100, sort:[['tstamp','descending']]}, function(err, cursor) { cursor.toArray(function(err, items) { if (err) { res.write(err.stack); } for (i=0; i < items.length; i++) { res.write(JSON.stringify(items[i]) + "\n"); } res.end(); }); }); }); }; var graph_datapoints = function(req, res) { var parsedUrl = require('url').parse(req.url, true); var queryObject = parsedUrl.query; var name = (queryObject["name"] || 'lounge'); res.writeHead(200, {'Content-Type': 'application/json'}); require('mongodb').connect(services.timeseriesdatabase[0].credentials.json_url, function(err, conn) { var collection = conn.collection('ts_data_v'); var dataseries = new Array(); collection.find({"loc_esi_id": name}, {limit:100, sort:[['tstamp','descending']]}, function(err, cursor) { cursor.toArray(function(err, items) { if (err) { res.write(err.stack); } for (i=0; i < items.length; i++) { timeint = (new Date(items[i].tstamp).getTime())/1000; dataseries.push([timeint,items[i].value]); console.log(JSON.stringify(dataseries)); } console.log("Final: " + JSON.stringify(dataseries)); res.write(JSON.stringify(dataseries)); res.end(); }); }); }); } var delete_data = function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); require('mongodb').connect(services.timeseriesdatabase[0].credentials.json_url, function(err, conn) { var collection = conn.collection('ts_data_v'); collection.remove({"measure_unit":"KWH"}, {}, function(err, results) { if (err) { res.write(err.stack); } res.write("Data reset"); }); }); res.end(); }; var graph_view = function(req, res) { fs.readFile('./public/graph.html', function(err, data) { res.end(data); }); } var graph_view_old = function(req, res) { fs.readFile('./public/graphold.html', function(err, data) { res.end(data); }); } var show_speed = function(req, res) { fs.readFile('./public/speedometer.html', function(err, data) { res.end(data); }); } var my_dash = function(req, res) { fs.readFile('./public/myEZdash.html', function(err, data) { res.end(data); }); } app.get("/reading", function (req, res) { create_datapoint(req,res); }); app.get("/dumplist", function (req, res) { list_datapoint(req,res); }); app.get("/dumplisttime", function (req, res) { list_time_datapoint(req,res); }); app.get("/reset", function (req, res) { delete_data(req,res); }); app.get("/graphpoints", function (req, res) { graph_datapoints(req,res); }); app.get("/graph", function (req, res) { graph_view(req,res); }); app.get("/graphold", function (req, res) { graph_view_old(req,res); }); app.get("/showspeed", function (req, res) { show_speed(req,res); }); app.get("/showdash", function (req, res) { my_dash(req,res); }); // Start server app.listen(port, host); console.log('App started on port ' + port);
d0047d1f70fa593a55815764154209b7245ac8c6
[ "Markdown", "JavaScript", "Text" ]
3
Text
Gharibw/RTBD
3c57c753b209b7ff88e54a1f4645f727b1c01d22
a520eb8ea2ebd9412155970cf6c3f1933393f969
refs/heads/master
<file_sep>library("Phenoflow") library("dplyr") library("ggplot2") library("grid") library("gridExtra") library("egg") library("qdapRegex") library("scales") library("cluster") library("factoextra") library("flowClean") library("nlme") library("mgcv") source("functions.R") my.settings <- list( strip.background=list(col="transparent"), strip.border=list(col="transparent", cex=5), gate=list(col="black", fill="lightblue", alpha=0.2,border=NA,lwd=2), panel.background=list(col="lightgray"), background=list(col="white")) # # Bin the data # # # Import original data # original_data <- read.flowSet(path = "original_data") # # # We then extract the total analysis time for each sample in seconds # analysis_length <- c() # for(i in 1:length(original_data)) analysis_length[i] <- as.numeric(original_data[[i]]@description$`#ACQUISITIONTIMEMILLI`)/1000 # analysis_length <- data.frame(time=analysis_length); rownames(analysis_length) <- flowCore::sampleNames(original_data) # # # Choose the size of your time-gate (in seconds) # time_interval <- c(10, 30, 60, 120, 180, 240, 300, 600, # 1200, 1800, 2400, 3000, 3600) # time.step = 0.1 # # # Bin the data and export into new directories # setwd("binned_data/") # for(i in time_interval){ # time_discretization(x = original_data, analysis.length = analysis_length, create=TRUE, # time.interval = i, height = c(0,200000000), # start = 0, time.step = 0.1) # } # setwd("..") set.seed(777) # Import binned data stability_FCS <- read.flowSet(path = "binned_data/Stability_tap1_60") bacteria_FCS <- read.flowSet(path = "binned_data/Bacteria_Run_60") mixed_FCS <- read.flowSet(path = "binned_data/Mixed_Run_60") # Remove last sample as this is a null observation (no or little cells). stability_FCS <- stability_FCS[-58] bacteria_FCS <- bacteria_FCS[-86] mixed_FCS <- mixed_FCS[-74] # Transform parameters by asinh transformation and select primary parameters of interest param=c("FL1-H", "FL3-H", "SSC-H", "FSC-H") stability_FCS <- stability_FCS[,param] bacteria_FCS <- bacteria_FCS[,param] mixed_FCS <- mixed_FCS[,param] stability_FCS <- transform(stability_FCS,`FL1-H`=asinh(`FL1-H`), `SSC-H`=asinh(`SSC-H`), `FL3-H`=asinh(`FL3-H`), `FSC-H`=asinh(`FSC-H`)) bacteria_FCS <- transform(bacteria_FCS,`FL1-H`=asinh(`FL1-H`), `SSC-H`=asinh(`SSC-H`), `FL3-H`=asinh(`FL3-H`), `FSC-H`=asinh(`FSC-H`)) mixed_FCS <- transform(mixed_FCS,`FL1-H`=asinh(`FL1-H`), `SSC-H`=asinh(`SSC-H`), `FL3-H`=asinh(`FL3-H`), `FSC-H`=asinh(`FSC-H`)) # Create a PolygonGate for extracting the single-cell information sqrcut1 <- matrix(c(8.5,8.5,16,16,3,7.25,16,3),ncol=2, nrow=4) colnames(sqrcut1) <- c("FL1-H","FL3-H") polyGate1 <- polygonGate(.gate=sqrcut1, filterId = "Total Cells") ### Creating a rectangle gate, set correct threshold here for FL1 sqrcut2 <- matrix(c(asinh(20000),asinh(20000),20,20, 0,20,20,0),ncol=2, nrow=4) colnames(sqrcut2) <- c("FL1-H","FL3-H") rGate_HNA <- polygonGate(.gate=sqrcut2, filterId = "HNA bacteria") # Check if gate is correct for all data xyplot(`FL3-H` ~ `FL1-H`, data=stability_FCS[1], filter=polyGate1, scales=list(y=list(limits=c(0,15)), x=list(limits=c(6,15))), axis = axis.default, nbin=125, par.strip.text=list(col="white", font=2, cex=2), smooth=FALSE) xyplot(`FL3-H` ~ `FL1-H`, data=bacteria_FCS[1], filter=polyGate1, scales=list(y=list(limits=c(0,15)), x=list(limits=c(6,15))), axis = axis.default, nbin=125, par.strip.text=list(col="white", font=2, cex=2), smooth=FALSE) xyplot(`FL3-H` ~ `FL1-H`, data=mixed_FCS[1], filter=polyGate1, scales=list(y=list(limits=c(0,15)), x=list(limits=c(6,15))), axis = axis.default, nbin=125, par.strip.text=list(col="white", font=2, cex=2), smooth=FALSE) # Proceed only with the bacterial information for fingerprinting stability_FCS <- Subset(stability_FCS, polyGate1) bacteria_FCS <- Subset(bacteria_FCS, polyGate1) mixed_FCS <- Subset(mixed_FCS, polyGate1) # Extract the cell counts # 1. Stability data a <- flowCore::filter(stability_FCS, rGate_HNA) HNACount <- summary(a);HNACount <- toTable(HNACount) s <- flowCore::filter(stability_FCS, polyGate1) TotalCount <- summary(s);TotalCount <- toTable(TotalCount) vol <- c() for(i in 1:length(stability_FCS)) vol[i] <- as.numeric(stability_FCS[[i]]@description$`$VOL`)/1000 counts_stability <- data.frame(Sample = flowCore::sampleNames(stability_FCS), Total_cells = TotalCount$true/vol, HNA_cells = HNACount$true/vol, LNA_cells = (TotalCount$true - HNACount$true)/vol) # 2. Bacteria data a <- flowCore::filter(bacteria_FCS, rGate_HNA) HNACount <- summary(a);HNACount <- toTable(HNACount) s <- flowCore::filter(bacteria_FCS, polyGate1) TotalCount <- summary(s);TotalCount <- toTable(TotalCount) vol <- c() for(i in 1:length(bacteria_FCS)) vol[i] <- as.numeric(bacteria_FCS[[i]]@description$`$VOL`)/1000 counts_bacteria <- data.frame(Sample = flowCore::sampleNames(bacteria_FCS), Total_cells = TotalCount$true/vol, HNA_cells = HNACount$true/vol, LNA_cells = (TotalCount$true - HNACount$true)/vol) # 3. Mixed data a <- flowCore::filter(mixed_FCS, rGate_HNA) HNACount <- summary(a);HNACount <- toTable(HNACount) s <- flowCore::filter(mixed_FCS, polyGate1) TotalCount <- summary(s);TotalCount <- toTable(TotalCount) vol <- c() for(i in 1:length(mixed_FCS)) vol[i] <- as.numeric(mixed_FCS[[i]]@description$`$VOL`)/1000 counts_mixed <- data.frame(Sample = flowCore::sampleNames(mixed_FCS), Total_cells = TotalCount$true/vol, HNA_cells = HNACount$true/vol, LNA_cells = (TotalCount$true - HNACount$true)/vol) # Normalize the signals based on the maximum FL1-H fluorescence summary <- fsApply(x=stability_FCS ,FUN=function(x) apply(x,2,max),use.exprs=TRUE) stability_FCS <- stability_FCS[!is.infinite(summary[,1])] summary <- summary[!is.infinite(summary[,1]),] max = max(summary[,1]) mytrans <- function(x) x/max stability_FCS <- transform(stability_FCS ,`FL1-H`=mytrans(`FL1-H`), `FL3-H`=mytrans(`FL3-H`), `SSC-H`=mytrans(`SSC-H`), `FSC-H`=mytrans(`FSC-H`)) summary <- fsApply(x=bacteria_FCS ,FUN=function(x) apply(x,2,max),use.exprs=TRUE) bacteria_FCS <- bacteria_FCS[!is.infinite(summary[,1])] summary <- summary[!is.infinite(summary[,1]),] max = max(summary[,1]) mytrans <- function(x) x/max bacteria_FCS <- transform(bacteria_FCS ,`FL1-H`=mytrans(`FL1-H`), `FL3-H`=mytrans(`FL3-H`), `SSC-H`=mytrans(`SSC-H`), `FSC-H`=mytrans(`FSC-H`)) summary <- fsApply(x=mixed_FCS, FUN=function(x) apply(x,2,max),use.exprs=TRUE) mixed_FCS <- mixed_FCS[!is.infinite(summary[,1])] max = max(summary[,1]) mytrans <- function(x) x/max mixed_FCS <- transform(mixed_FCS ,`FL1-H`=mytrans(`FL1-H`), `FL3-H`=mytrans(`FL3-H`), `SSC-H`=mytrans(`SSC-H`), `FSC-H`=mytrans(`FSC-H`)) # Resample to minimum sample size: # stability_FCS <- FCS_resample(stability_FCS, replace = TRUE) # bacteria_FCS <- FCS_resample(bacteria_FCS, replace = TRUE) # mixed_FCS <- FCS_resample(mixed_FCS, replace = TRUE) # Run phenotypic diversity analysis diversity_stability <- Diversity_rf(stability_FCS, R = 100, param = param, d = 3) diversity_bacteria <- Diversity_rf(bacteria_FCS, R = 100, param = param, d = 3) diversity_mixed <- Diversity_rf(mixed_FCS, R = 100, param = param, d = 3) # Cluster analysis with 100 bootstraps for(R in 1:100){ bacteria_FCS_resample <- FCS_resample(bacteria_FCS, replace = TRUE, rarefy = TRUE, progress = FALSE) mixed_FCS_resample <- FCS_resample(mixed_FCS, replace = TRUE, rarefy = TRUE, progress = FALSE) fp_bacteria <- flowBasis(bacteria_FCS_resample, param=param, nbin = 128, bw = 0.01, normalize = function(x) x) fp_mixed <- flowBasis(mixed_FCS_resample, param=param, nbin = 128, bw = 0.01, normalize = function(x) x) # Perform PCA to reduce number of features in fingerprint pca_bacteria <- prcomp(fp_bacteria@basis) pca_mixed <- prcomp(fp_mixed@basis) # Only retain PC which explain x% of the variance thresh <- 0.9 nr_pc_bacteria <- min(which((cumsum(vegan::eigenvals(pca_bacteria)/sum(vegan::eigenvals(pca_bacteria)))>thresh)==TRUE)) nr_pc_mixed <- min(which((cumsum(vegan::eigenvals(pca_mixed)/sum(vegan::eigenvals(pca_mixed)))>thresh)==TRUE)) pc_cluster_bacteria <- pca_bacteria$x[, 1:nr_pc_bacteria] pc_cluster_mixed <- pca_mixed$x[, 1:nr_pc_mixed] # Evaluate number of robust clusters by means of silhouette index tmp.si <- c() for(i in 2:(nrow(pc_cluster_bacteria)-1)){ tmp.si[i] <- pam(pc_cluster_bacteria, k=i)$silinfo$avg.width } nr_clusters_bacteria <- which(tmp.si == max(tmp.si, na.rm = TRUE)) tmp.si <- c() for(i in 2:(nrow(pc_cluster_mixed)-1)){ tmp.si[i] <- pam(pc_cluster_mixed, k=i)$silinfo$avg.width } nr_clusters_mixed <- which(tmp.si == max(tmp.si, na.rm = TRUE)) # Cluster samples and export cluster labels clusters_bacteria <- pam(pc_cluster_bacteria, k=nr_clusters_bacteria) clusters_mixed <- pam(pc_cluster_mixed, k=nr_clusters_mixed) # Extract cluster labels if(R == 1){ cluster_labels_bacteria <- data.frame(Sample = names(clusters_bacteria$clustering), cluster_label = clusters_bacteria$clustering) cluster_labels_mixed <- data.frame(Sample = names(clusters_mixed$clustering), cluster_label = clusters_mixed$clustering) } else{ cluster_labels_bacteria <- cbind(cluster_labels_bacteria, clusters_bacteria$clustering) cluster_labels_mixed <- cbind(cluster_labels_mixed, clusters_mixed$clustering) } cat("At bootstrap run - ", R, "/100 \n", sep = "") } # Extract median cluster_labels_bacteria_med <- apply(cluster_labels_bacteria[, 2:101], 1, FUN = function(x) data.frame(table(x))$x[which.max(table(x))]) cluster_labels_mixed_med <- apply(cluster_labels_mixed[2:101], 1, FUN = function(x) median(x)) cluster_labels_bacteria_med <- data.frame(Sample = names(cluster_labels_bacteria_med), median_cluster_label = cluster_labels_bacteria_med) cluster_labels_bacteria_med$interaction <- interaction(cluster_labels_bacteria_med$Sample, cluster_labels_bacteria_med$median_cluster_label) cluster_labels_mixed_med <- data.frame(Sample = names(cluster_labels_mixed_med), median_cluster_label = cluster_labels_mixed_med) cluster_labels_mixed_med$interaction <- interaction(cluster_labels_mixed_med$Sample, cluster_labels_mixed_med$median_cluster_label) # Extract bootstrap confidence cluster_labels_bacteria_boot <- apply(cluster_labels_bacteria[, 2:101], 1, FUN = function(x) table(x)) cluster_labels_mixed_boot <- apply(cluster_labels_mixed[, 2:101], 1, FUN = function(x) table(x)) cluster_labels_bacteria_boot <- lapply(cluster_labels_bacteria_boot, FUN = function(x) data.frame(x)) cluster_labels_bacteria_boot <- reshape2::melt(cluster_labels_bacteria_boot) cluster_labels_bacteria_boot <- cluster_labels_bacteria_boot[, c(1,3,4)] colnames(cluster_labels_bacteria_boot) <- c("cluster_label", "bootstrap_value", "Sample") cluster_labels_bacteria_boot$interaction <- interaction(cluster_labels_bacteria_boot$Sample, cluster_labels_bacteria_boot$cluster_label) cluster_labels_mixed_boot <- lapply(cluster_labels_mixed_boot, FUN = function(x) data.frame(x)) cluster_labels_mixed_boot <- reshape2::melt(cluster_labels_mixed_boot) cluster_labels_mixed_boot <- cluster_labels_mixed_boot[, c(1,3,4)] colnames(cluster_labels_mixed_boot) <- c("cluster_label", "bootstrap_value", "Sample") cluster_labels_mixed_boot$interaction <- interaction(cluster_labels_mixed_boot$Sample, cluster_labels_mixed_boot$cluster_label) # Merge dataframes cluster_labels_bacteria_med <- left_join(cluster_labels_bacteria_med, cluster_labels_bacteria_boot[, -3], by = "interaction") cluster_labels_mixed_med <- left_join(cluster_labels_mixed_med, cluster_labels_mixed_boot[, -3], by = "interaction") # Merge count and phenotypic diversity data in one file results_stability <- left_join(counts_stability, diversity_stability, by = c("Sample" = "Sample_names")) results_stability <- results_stability[results_stability$Total_cells > 0, ] results_bacteria <- left_join(counts_bacteria, diversity_bacteria, by = c("Sample" = "Sample_names")) results_bacteria <- results_bacteria[results_bacteria$Total_cells > 0, ] results_mixed <- left_join(counts_mixed, diversity_mixed, by = c("Sample" = "Sample_names")) results_mixed <- results_mixed[results_mixed$Total_cells > 0, ] # Merge results with cluster labels results_bacteria <- left_join(results_bacteria, cluster_labels_bacteria_med, by = "Sample") results_mixed <- left_join(results_mixed, cluster_labels_mixed_med, by = "Sample") # Add time points meta_stability <- data.frame(do.call(rbind, lapply(strsplit(flowCore::sampleNames(stability_FCS),"_"), rbind))) meta_bacteria <- data.frame(do.call(rbind, lapply(strsplit(flowCore::sampleNames(bacteria_FCS),"_"), rbind))) meta_mixed <- data.frame(do.call(rbind, lapply(strsplit(flowCore::sampleNames(mixed_FCS),"_"), rbind))) results_stability <- data.frame(results_stability, Time = as.numeric(as.character(meta_stability$X1))) results_bacteria <- data.frame(results_bacteria, Time = as.numeric(as.character(meta_bacteria$X1))) results_mixed <- data.frame(results_mixed, Time = as.numeric(as.character(meta_mixed$X1))) # Calculate mean and sd of HNA, count and diversity based on first 15 minutes of run time # For the bacteria and mixed contaminations. Consider the entire run for the stability # experiment. mean_stab_HNA_s <- mean(results_stability$HNA_cells/results_stability$Total_cells) mean_stab_count_s <- mean(results_stability$Total_cells) mean_stab_D2_s <- mean(results_stability$D2) sd_stab_HNA_s <- sd(results_stability$HNA_cells/results_stability$Total_cells) sd_stab_count_s <- sd(results_stability$Total_cells) sd_stab_D2_s <- sd(results_stability$D2) mean_stab_HNA_b <- mean(results_bacteria$HNA_cells[results_bacteria$Time<16]/results_bacteria$Total_cells[results_bacteria$Time<16]) mean_stab_count_b <- mean(results_bacteria$Total_cells[results_bacteria$Time<16]) mean_stab_D2_b <- mean(results_bacteria$D2[results_bacteria$Time<16]) sd_stab_HNA_b <- sd(results_bacteria$HNA_cells[results_bacteria$Time<16]/results_bacteria$Total_cells[results_bacteria$Time<16]) sd_stab_count_b <- sd(results_bacteria$Total_cells[results_bacteria$Time<16]) sd_stab_D2_b <- sd(results_bacteria$D2[results_bacteria$Time<16]) mean_stab_HNA_m <- mean(results_mixed$HNA_cells[results_mixed$Time<16]/results_mixed$Total_cells[results_mixed$Time<16]) mean_stab_count_m <- mean(results_mixed$Total_cells[results_mixed$Time<16]) mean_stab_D2_m <- mean(results_mixed$D2[results_mixed$Time<16]) sd_stab_HNA_m <- sd(results_mixed$HNA_cells[results_mixed$Time<16]/results_mixed$Total_cells[results_mixed$Time<16]) sd_stab_count_m <- sd(results_mixed$Total_cells[results_mixed$Time<16]) sd_stab_D2_m <- sd(results_mixed$D2[results_mixed$Time<16]) # Add column to results indicating difference between stability run and observed values results_stability <- data.frame(results_stability, diff_HNA = abs(results_stability$HNA_cells/results_stability$Total_cells-mean_stab_HNA_s)/sd_stab_HNA_s, diff_count = abs(results_stability$Total_cells-mean_stab_count_s)/sd_stab_count_s, diff_D2 = abs(results_stability$D2-mean_stab_D2_s)/sd_stab_D2_s) results_bacteria <- data.frame(results_bacteria, diff_HNA = abs(results_bacteria$HNA_cells/results_bacteria$Total_cells-mean_stab_HNA_b)/sd_stab_HNA_b, diff_count = abs(results_bacteria$Total_cells-mean_stab_count_b)/sd_stab_count_b, diff_D2 = abs(results_bacteria$D2-mean_stab_D2_b)/sd_stab_D2_b) results_mixed <- data.frame(results_mixed, diff_HNA = abs(results_mixed$HNA_cells/results_mixed$Total_cells-mean_stab_HNA_m)/sd_stab_HNA_m, diff_count = abs(results_mixed$Total_cells-mean_stab_count_m)/sd_stab_count_m, diff_D2 = abs(results_mixed$D2-mean_stab_D2_m)/sd_stab_D2_m) # Create stability plots original_data <- read.flowSet(path = "original_data") FL1_stability <- data.frame(FL1 = asinh(exprs(original_data[[4]])[,9]), Time = exprs(original_data[[4]])[,14]) p_FL1 <- ggplot(FL1_stability, aes(x = Time, y = FL1))+ stat_density_2d(geom = "raster", aes(fill = ..density..), contour = FALSE, n = 100)+ ggplot2::scale_fill_distiller(palette="Greens", na.value="white", direction = 1, type ="div")+ labs(y = "")+ theme_bw()+ theme(axis.title.x = element_blank(), axis.text.x = element_blank(), axis.text.y=element_text(size=14), plot.title = element_text(hjust = 0,size=18))+ ggtitle("(A) Green fluorescence intensity (FL1-H)")+ ylim(8,13)+ guides(fill=FALSE)+ xlim(0,max(results_stability$Time*60/0.1))+ scale_x_continuous(breaks=c(0, 20, 40, 60, 80)*60/0.1) p_density <- ggplot(results_stability, aes(x = as.numeric(Time), y = Total_cells, fill = diff_count))+ geom_point(shape=21, size = 4, alpha = 0.5)+ scale_fill_distiller(palette="RdBu", limits = c(0,3), breaks=c(0,1,2,3), oob=squish)+ theme_bw()+ labs(y="", fill = "Deviation (s.d.)")+ theme(axis.title.x = element_blank(), axis.text.x = element_blank(), axis.text.y=element_text(size=14), plot.title = element_text(hjust = 0, size=18))+ ggtitle(bquote("(B) Total cell density (cells µL"^{-1}*")") )+ geom_line(color="black", alpha = 0.9)+ xlim(0,max(results_stability$Time))+ scale_x_continuous(breaks=c(0, 20, 40, 60, 80))+ scale_y_continuous(breaks=c(0, 25, 50, 75), limits = c(0,75)) p_diversity <- ggplot(results_stability, aes(x = as.numeric(Time), y = D2, fill = diff_D2))+ geom_point(shape=21, size = 4, alpha = 0.5)+ scale_fill_distiller(palette="RdBu", limits = c(0,3), breaks=c(0,1,2,3), oob=squish)+ theme_bw()+ ylim(900,3350)+ labs(y="", fill = "Deviation (s.d.)")+ theme(axis.title.x = element_blank(), axis.text.x = element_blank(), axis.text=element_text(size=14), plot.title = element_text(hjust = 0, size=18))+ labs(y="", x = "Time (min.)")+ ggtitle("(C) Phenotypic diversity index (a.u.)")+ geom_line(color="black", alpha = 0.9)+ geom_errorbar(aes(ymin=D2-sd.D2, ymax=D2+sd.D2), width=0.01)+ xlim(0,max(results_stability$Time))+ scale_x_continuous(breaks=c(0, 20, 40, 60, 80)) p_HNA <- ggplot(results_stability, aes(x = as.numeric(Time), y = 100*HNA_cells/Total_cells, fill = diff_HNA))+ geom_point(shape=21, size = 4, alpha = 0.5)+ scale_fill_distiller(palette="RdBu", limits = c(0,3), breaks=c(0,1,2,3), oob=squish)+ theme_bw()+ labs(y="", fill = "Deviation (s.d.)", x = "Time (min.)")+ ggtitle("(D) % HNA cells")+ theme(axis.text=element_text(size=14), axis.title=element_text(size=16), plot.title = element_text(hjust = 0, size=18))+ geom_line(color="black", alpha = 0.9)+ xlim(0,max(results_stability$Time))+ scale_x_continuous(breaks=c(0, 20, 40, 60, 80))+ scale_y_continuous(breaks=c(0, 25, 50, 75), limits = c(0,75)) pdf("Fig2.pdf", height = 10, width = 10) cowplot::plot_grid(p_FL1, p_density, p_diversity, p_HNA, ncol=1) dev.off() # Create bacteria contamination plots FL1_bacteria <- data.frame(FL1 = asinh(exprs(original_data[[1]])[,9]), Time = exprs(original_data[[1]])[,14]) p_FL1_b <- ggplot(FL1_bacteria, aes(x = Time, y = FL1))+ stat_density_2d(geom = "raster", aes(fill = ..density..), contour = FALSE, n = 100)+ ggplot2::scale_fill_distiller(palette="Greens", na.value="white", direction = 1, type ="div")+ labs(y = "")+ theme_bw()+ theme(axis.title.x = element_blank(), axis.text.x = element_blank(), axis.text.y=element_text(size=14), plot.title = element_text(hjust = 0,size=18))+ ggtitle("Green fluorescence intensity (FL1-H)")+ ylim(8,13)+ guides(fill=FALSE)+ xlim(0,max(results_bacteria$Time*60/0.1))+ scale_x_continuous(breaks=c(0, 20, 40, 60, 80)*60/0.1) p_density_b <- ggplot(results_bacteria, aes(x = as.numeric(Time), y = Total_cells, fill = diff_count))+ geom_point(shape=21, size = 4, alpha = 0.5)+ scale_fill_distiller(palette="RdBu", limits = c(0,3), breaks=c(0,1,2,3), oob=squish)+ theme_bw()+ ylim(0,225)+ labs(y="", fill = "Deviation (s.d.)")+ theme(axis.title.x = element_blank(), axis.text.x = element_blank(), axis.text.y=element_text(size=14), plot.title = element_text(hjust = 0, size=18))+ ggtitle(bquote("(A) Total cell concentration (cells µL"^{-1}*")") )+ geom_line(color="black", alpha = 0.9)+ xlim(0,max(results_bacteria$Time))+ scale_x_continuous(breaks=c(0, 20, 40, 60, 80))+ guides(fill = FALSE) p_HNA_b <- ggplot(results_bacteria, aes(x = as.numeric(Time), y = 100*HNA_cells/Total_cells, fill = diff_HNA))+ geom_point(shape=21, size = 4, alpha = 0.5)+ scale_fill_distiller(palette="RdBu", limits = c(0,3), breaks=c(0,1,2,3), oob=squish)+ theme_bw()+ ylim(0,100)+ labs(y="", fill = "Deviation (s.d.)",x = "Time (min.)")+ theme(axis.text.x = element_text(size=14), axis.text.y=element_text(size=14), plot.title = element_text(hjust = 0, size=18), axis.title=element_text(size=16))+ ggtitle(bquote("(B) % HNA cells") )+ geom_line(color="black", alpha = 0.9)+ scale_x_continuous(breaks=c(0, 20, 40, 60, 80))+ # xlim(0,max(results_bacteria$Time))+ guides(fill = FALSE) p_diversity_b <- ggplot(results_bacteria, aes(x = as.numeric(Time), y = D2, fill = diff_D2))+ geom_point(shape=21, size = 4, alpha = 0.5)+ scale_fill_distiller(palette="RdBu", limits = c(0,3), breaks=c(0,1,2,3), oob=squish)+ theme_bw()+ ylim(900,3000)+ labs(y="", fill = "Deviation (s.d.)")+ theme(axis.title.x = element_blank(), axis.text.x = element_blank(), axis.text.y=element_text(size=14), plot.title = element_text(hjust = 0, size=18))+ ggtitle("(C) Phenotypic diversity index (a.u.)")+ geom_line(color="black", alpha = 0.9)+ geom_errorbar(aes(ymin=D2-sd.D2, ymax=D2+sd.D2), width=0.01)+ xlim(0,max(results_bacteria$Time))+ scale_x_continuous(breaks=c(0, 20, 40, 60, 80))+ guides(fill = FALSE) # Add factor for visualizing bootsrap confidence results_bacteria$bootstrap_value_factor <- results_bacteria$bootstrap_value > 90 p_cluster_b <- ggplot(results_bacteria, aes(x = as.numeric(Time), y = as.numeric(as.character(median_cluster_label))))+ geom_point(shape = 21, size = 4, color = "black", aes(fill = factor(median_cluster_label), alpha = bootstrap_value_factor))+ scale_fill_manual(values = c("#2166AC","#33A02C","#6A3D9A"))+ scale_alpha_manual(values = c(0.5, 0.9))+ scale_color_manual(values = c("black","black","black"))+ theme_bw()+ theme(axis.text=element_text(size=14), axis.title=element_text(size=16), plot.title = element_text(hjust = 0, size=18))+ labs(y="", x = "Time (min.)")+ ggtitle("(D) Phenotypic community type")+ ylim(0,3.5)+ geom_line(color="black", alpha = 0.9)+ guides(fill = FALSE, alpha = FALSE)+ xlim(0,max(results_bacteria$Time))+ scale_x_continuous(breaks=c(0, 20, 40, 60, 80)) pdf("Fig3.pdf", height = 8, width = 12) p1 <- cowplot::plot_grid(p_density_b, p_diversity_b, p_HNA_b, p_cluster_b, ncol=2, align = "hv") print(p1) dev.off() # Create mixed contamination plots FL1_mixed <- data.frame(FL1 = asinh(exprs(original_data[[2]])[,9]), Time = exprs(original_data[[2]])[,14]) p_FL1_mixed <- ggplot(FL1_mixed, aes(x = Time, y = FL1))+ stat_density_2d(geom = "raster", aes(fill = ..density..), contour = FALSE, n = 100)+ ggplot2::scale_fill_distiller(palette="Greens", na.value="white", direction = 1, type ="div")+ labs(y = "")+ theme_bw()+ theme(axis.title.x = element_blank(), axis.text.x = element_blank(), axis.text.y=element_text(size=14), plot.title = element_text(hjust = 0,size=18))+ ggtitle("(A) Green fluorescence intensity (FL1-H)")+ ylim(8, 13)+ guides(fill=FALSE)+ xlim(0, 80*60/0.1)+ scale_x_continuous(breaks=c(0, 20, 40, 60, 80)*60/0.1) p_density_mixed <- ggplot(results_mixed, aes(x = as.numeric(Time), y = Total_cells, fill = diff_count))+ geom_point(shape=21, size = 4, alpha = 0.5)+ scale_fill_distiller(palette="RdBu", limits = c(0,3), breaks=c(0,1,2,3), oob=squish)+ theme_bw()+ ylim(0,225)+ labs(y="", fill = "Deviation (s.d.)")+ theme(axis.title.x = element_blank(), axis.text.x = element_blank(), axis.text.y=element_text(size=14), plot.title = element_text(hjust = 0, size=18))+ ggtitle(bquote("(A) Total cell concentration (cells µL"^{-1}*")") )+ geom_line(color="black", alpha = 0.9)+ xlim(0, 80)+ guides(fill = FALSE) # geom_vline(xintercept = c(10,20,30,40,50,60), linetype =2) p_HNA_mixed <- ggplot(results_mixed, aes(x = as.numeric(Time), y = 100*HNA_cells/Total_cells, fill = diff_HNA))+ geom_point(shape=21, size = 4, alpha = 0.5)+ scale_fill_distiller(palette="RdBu", limits = c(0,3), breaks=c(0,1,2,3), oob=squish)+ theme_bw()+ ylim(0,100)+ labs(y="", fill = "Deviation (s.d.)",x = "Time (min.)")+ theme(axis.text.x = element_text(size=14), axis.text.y=element_text(size=14), plot.title = element_text(hjust = 0, size=18), axis.title=element_text(size=16))+ ggtitle(bquote("(B) % HNA cells") )+ geom_line(color="black", alpha = 0.9)+ xlim(0, 80)+ guides(fill = FALSE) p_diversity_mixed <- ggplot(results_mixed, aes(x = as.numeric(Time), y = D2, fill = diff_D2))+ geom_point(shape=21, size = 4, alpha = 0.5)+ scale_fill_distiller(palette="RdBu", limits = c(0,3), breaks=c(0,1,2,3), oob=squish)+ theme_bw()+ labs(y="", fill = "Deviation (s.d.)")+ theme(axis.title.x = element_blank(), axis.text.x = element_blank(), axis.text.y=element_text(size=14), plot.title = element_text(hjust = 0, size=18))+ ggtitle("(C) Phenotypic diversity index (a.u.)")+ geom_line(color="black", alpha = 0.9)+ geom_errorbar(aes(ymin=D2-sd.D2, ymax=D2+sd.D2), width=0.01)+ xlim(0,80)+ ylim(900,3000)+ guides(fill = FALSE) results_mixed$bootstrap_value_factor <- results_mixed$bootstrap_value > 90 p_cluster_mixed <- ggplot(results_mixed, aes(x = as.numeric(Time), y = median_cluster_label))+ geom_point(shape=21, size = 4, aes(fill = factor(median_cluster_label), alpha = bootstrap_value_factor))+ scale_fill_manual(values = c("#2166AC","#33A02C","#E31A1C","#FF7F00","#6A3D9A"))+ scale_alpha_manual(values = c(0.5, 0.9))+ scale_color_manual(values = c("black", "black", "black", "black", "black"))+ theme_bw()+ theme(axis.text=element_text(size=14), axis.title=element_text(size=16), plot.title = element_text(hjust = 0, size=18) #, panel.background = element_rect(fill = "lightblue", # colour = "lightblue", # size = 0.5, linetype = "solid"), # panel.grid.major = element_line(size = 0.5, linetype = 'solid', # colour = "white"), # panel.grid.minor = element_line(size = 0.25, linetype = 'solid', # colour = "white") )+ labs(y="", x = "Time (min.)")+ ggtitle("(D) Phenotypic community type")+ geom_line(color="black", alpha = 0.9)+ guides(fill = FALSE, alpha = FALSE)+ xlim(0,80)+ scale_y_continuous(breaks=c(0:5), limits = c(0,5.5)) ggplot(results_bacteria, aes(x = as.numeric(Time), y = median_cluster_label))+ geom_point(shape = 21, size = 4, color = "black", aes(fill = factor(median_cluster_label), alpha = bootstrap_value_factor))+ scale_fill_manual(values = c("#2166AC","#33A02C","#6A3D9A"))+ scale_alpha_manual(values = c(0.5, 0.9))+ scale_color_manual(values = c("black","black","black")) pdf("Fig4.pdf", height = 8, width = 12) cowplot::plot_grid(p_density_mixed, p_diversity_mixed, p_HNA_mixed, p_cluster_mixed, ncol=2, align = "hv") dev.off() # Phase 2: Evaluate temporal resolution required for robust estimate of # cells / HNA / phenotypic diversity # Import data dirs <- list.dirs("binned_data", recursive = FALSE) dirs <- dirs[grep(dirs, pattern = "Stability")] dirs <- dirs[1:26] # Merge all flowData for(i in dirs){ flowSum <- read.flowSet(path = i) param=c("FL1-H", "FL3-H", "SSC-H", "FSC-H") flowSum <- flowSum[,param] # Transform parameters flowSum <- transform(flowSum,`FL1-H`=asinh(`FL1-H`), `SSC-H`=asinh(`SSC-H`), `FL3-H`=asinh(`FL3-H`), `FSC-H`=asinh(`FSC-H`)) # Create a PolygonGate for extracting the single-cell information sqrcut1 <- matrix(c(8.5,8.5,16,16,3,7.25,16,3),ncol=2, nrow=4) colnames(sqrcut1) <- c("FL1-H","FL3-H") polyGate1 <- polygonGate(.gate=sqrcut1, filterId = "Total Cells") ### Creating a rectangle gate, set correct threshold here for FL1 sqrcut2 <- matrix(c(asinh(20000),asinh(20000),20,20, 0,20,20,0),ncol=2, nrow=4) colnames(sqrcut2) <- c("FL1-H","FL3-H") rGate_HNA <- polygonGate(.gate=sqrcut2, filterId = "HNA bacteria") # Extract counts a <- flowCore::filter(flowSum, rGate_HNA) HNACount <- summary(a);HNACount <- toTable(HNACount) s <- flowCore::filter(flowSum, polyGate1) TotalCount <- summary(s);TotalCount <- toTable(TotalCount) vol <- c() for(j in 1:length(flowSum)){ vol[j] <- as.numeric(flowSum[[j]]@description$`$VOL`)/1000 } counts_flowSum <- data.frame(Sample = flowCore::sampleNames(flowSum), Total_cells = TotalCount$true, HNA_cells = HNACount$true, LNA_cells = (TotalCount$true - HNACount$true), volume = vol) # Normalize parameters summary <- fsApply(x=flowSum ,FUN=function(x) apply(x,2,max),use.exprs=TRUE) flowSum <- flowSum[!is.infinite(summary[,1])] max = max(summary[,1]) mytrans <- function(x) x/17 flowSum <- transform(flowSum ,`FL1-H`=mytrans(`FL1-H`), `FL3-H`=mytrans(`FL3-H`), `SSC-H`=mytrans(`SSC-H`), `FSC-H`=mytrans(`FSC-H`)) # Run phenotypic diversity analysis diversity_flowSum <- Diversity_rf(flowSum, R = 3, R.b = 100, param = param, d = 3) # Extract metadata metadata_flowSum <- data.frame(Sample_names = flowCore::sampleNames(flowSum), do.call(rbind, lapply(strsplit(flowCore::sampleNames(flowSum),"_"), rbind)))[,1:5] colnames(metadata_flowSum)[2:5] <- c("Time", "Resolution", "Experiment", "Replicate") metadata_flowSum$Replicate <- gsub(metadata_flowSum$Replicate, pattern = ".fcs", replacement = "") # Merge dataframes results_flowSum <- left_join(diversity_flowSum, counts_flowSum, by = c("Sample_names" = "Sample")) results_flowSum <- left_join(results_flowSum, metadata_flowSum, by = "Sample_names") if(i == dirs[1]) results_final <- results_flowSum else results_final <- rbind(results_final, results_flowSum) } # Filter out some binning sizes results_final <- results_final[results_final$Resolution != '3600' & results_final$Resolution != '3000' & results_final$Resolution !='2400',] results_final$Resolution <- droplevels(results_final$Resolution) # Filter out outliers at 10 second resolution results_final_river <- filter(results_final, Total_cells/volume > 100 & Replicate == "river") results_final_tap <- filter(results_final, Replicate == "tap1") # Order resolution factor level results_final_river$Resolution <- factor(results_final_river$Resolution, levels = c("10", "30", "60", "120", "180", "240", "300", "600", "1200", "1800")) results_final_tap$Resolution <- factor(results_final_tap$Resolution, levels = c("10", "30", "60", "120", "180", "240", "300", "600", "1200", "1800")) # Calculate coefficient of variation for each temporal resolution # remove outliers by replacing the ones larger than 1.5*IQR by the 95% and 5% quantiles // called capping x <- results_final_river$Total_cells/results_final_river$volume qnt <- quantile(x, probs=c(.25, .75), na.rm = T) caps <- quantile(x, probs=c(.05, .95), na.rm = T) H <- 1.5 * IQR(x, na.rm = T) x[x < (qnt[1] - H)] <- caps[1] x[x > (qnt[2] + H)] <- caps[2] results_final_river$Total_cells <- x*results_final_river$volume results_final_river <- results_final_river %>% group_by(Resolution) %>% mutate(CV_dens = 100*sd(Total_cells/volume)/mean(Total_cells/volume), CV_D2 = 100*sd(D2)/mean(D2)) CV_river <- do.call(rbind,by(results_final_river[,c(13,15,16,17)], INDICES = factor(results_final_river$Resolution), FUN = unique)) CV_river <- data.frame(CV_river, Total_cells = do.call(rbind,by(results_final_river[,c(8,9)], INDICES = factor(results_final_river$Resolution), FUN = colMeans))[,1]) results_final_tap <- results_final_tap %>% group_by(Resolution) %>% mutate(CV_dens = 100*sd(Total_cells/volume)/mean(Total_cells/volume), CV_D2 = 100*sd(D2)/mean(D2)) CV_tap <- do.call(rbind,by(results_final_tap[,c(13,15,16,17)], INDICES = factor(results_final_tap$Resolution), FUN = unique)) CV_tap <- data.frame(CV_tap, Total_cells = do.call(rbind,by(results_final_tap[,c(8,9)], INDICES = factor(results_final_tap$Resolution), FUN = colMeans))[,1]) # Combine both CV_total <- rbind(CV_river, CV_tap) # Make plots p_stab_density_tap <- ggplot(data = results_final_tap, aes(x = Total_cells, y = Total_cells/volume, fill = Resolution))+ geom_point(shape = 21, size = 4, alpha = 0.5)+ scale_fill_brewer(palette = "Paired")+ scale_x_log10( breaks = scales::trans_breaks("log10", function(x) 10^x), labels = scales::trans_format("log10", scales::math_format(10^.x)) ) + theme_bw()+ theme(axis.text=element_text(size=14), axis.title=element_text(size=16), plot.title = element_text(hjust = 0, size=18), panel.grid.minor = element_blank(), legend.text=element_text(size=15),legend.title=element_text(size=16))+ # ylim(10,50)+ geom_smooth(fill="gray", color = "black", span = 1)+ annotation_logticks(sides = "b")+ labs(y = bquote("Total cell density (cells µL"^{-1}*")"), x = "Cells measured", fill = "Resolution (s)")+ ggtitle("(A)") p_stab_diversity_tap <- ggplot(data = results_final_tap, aes(x = Total_cells, y = D2, fill = Resolution))+ geom_point(shape = 21, size = 4, alpha = 0.5)+ scale_fill_brewer(palette = "Paired")+ scale_x_log10( breaks = scales::trans_breaks("log10", function(x) 10^x), labels = scales::trans_format("log10", scales::math_format(10^.x)) ) + theme_bw()+ theme(axis.text=element_text(size=14), axis.title=element_text(size=16), plot.title = element_text(hjust = 0, size=18), panel.grid.minor = element_blank(), legend.text=element_text(size=15),legend.title=element_text(size=16))+ ylim(1750,2750)+ geom_smooth(fill="gray", color = "black", span = 1)+ annotation_logticks(sides = "b")+ labs(y = bquote("Phenotypic diversity (a.u.)"), x = "Cells measured", fill = "Resolution (s)")+ ggtitle("(B)") p_stab_density_river <- ggplot(data = results_final_river, aes(x = Total_cells, y = Total_cells/volume, fill = Resolution))+ geom_point(shape = 21, size = 4, alpha = 0.5)+ scale_fill_brewer(palette = "Paired")+ scale_x_log10( breaks = scales::trans_breaks("log10", function(x) 10^x), labels = scales::trans_format("log10", scales::math_format(10^.x)) ) + theme_bw()+ theme(axis.text=element_text(size=14), axis.title=element_text(size=16), plot.title = element_text(hjust = 0, size=18), panel.grid.minor = element_blank(), legend.text=element_text(size=15),legend.title=element_text(size=16))+ # ylim(10,50)+ geom_smooth(fill="gray", color = "black", span = 1)+ annotation_logticks(sides = "b")+ labs(y = bquote("Total cell density (cells µL"^{-1}*")"), x = "Cells measured", fill = "Resolution (s)")+ ggtitle("(C)")+ ylim(200,500) p_stab_diversity_river <- ggplot(data = results_final_river, aes(x = Total_cells, y = D2, fill = Resolution))+ geom_point(shape = 21, size = 4, alpha = 0.5)+ scale_fill_brewer(palette = "Paired")+ scale_x_log10( breaks = scales::trans_breaks("log10", function(x) 10^x), labels = scales::trans_format("log10", scales::math_format(10^.x)) ) + theme_bw()+ theme(axis.text=element_text(size=14), axis.title=element_text(size=16), plot.title = element_text(hjust = 0, size=18), panel.grid.minor = element_blank(), legend.text=element_text(size=15),legend.title=element_text(size=16))+ ylim(3000,4000)+ geom_smooth(fill="gray", color = "black", span = 1)+ annotation_logticks(sides = "b")+ labs(y = bquote("Phenotypic diversity (a.u.)"), x = "Cells measured", fill = "Resolution (s)")+ ggtitle("(D)") pdf("Fig5.pdf", height = 10, width = 10) grid_arrange_shared_legend(p_stab_density_tap, p_stab_diversity_tap, p_stab_density_river, p_stab_diversity_river, ncol = 2, nrow = 2) dev.off() # Plots for coefficient of variation CV_total$Replicate <- gsub(CV_total$Replicate, pattern = "tap1", replacement = "Tap water") CV_total$Replicate <- gsub(CV_total$Replicate, pattern = "river", replacement = "River water") p_CV_D2 <- ggplot(data = CV_total, aes(x = Total_cells, y = CV_D2, fill = Resolution))+ geom_point(size = 4, aes(fill = Resolution, shape = Replicate), alpha = 0.9)+ scale_fill_brewer(palette = "Paired")+ scale_x_log10( breaks = scales::trans_breaks("log10", function(x) 10^x), labels = scales::trans_format("log10", scales::math_format(10^.x)) ) + theme_bw()+ scale_shape_manual(values=c(21,22))+ theme(axis.text=element_text(size=14), axis.title=element_text(size=14), plot.title = element_text(hjust = 0, size=18), panel.grid.minor = element_blank(), legend.text=element_text(size=15),legend.title=element_text(size=16))+ # geom_smooth(fill="gray", color = "black", span = 1,formula=y~x)+ geom_smooth(method="lm",color="black",fill="gray",formula=y~x)+ annotation_logticks(sides = "b")+ labs(y = "CV on phenotypic diversity (%)", x = "Cells measured", fill = "Resolution (s)", shape = "")+ ggtitle("(A)")+ guides(fill = guide_legend(override.aes = list(shape = 21)), ncol=1)+ ylim(0,5)+ geom_hline(yintercept = 5, linetype = 2) p_CV_dens <- ggplot(data = CV_total, aes(x = Total_cells, y = CV_dens, fill = Resolution))+ geom_point(size = 4, aes(fill = Resolution, shape = Replicate), alpha = 0.9)+ scale_fill_brewer(palette = "Paired")+ scale_x_log10( breaks = scales::trans_breaks("log10", function(x) 10^x), labels = scales::trans_format("log10", scales::math_format(10^.x)) ) + theme_bw()+ scale_shape_manual(values=c(21,22))+ theme(axis.text=element_text(size=14), axis.title=element_text(size=14), plot.title = element_text(hjust = 0, size=18), panel.grid.minor = element_blank(), legend.text=element_text(size=15),legend.title=element_text(size=16))+ # geom_smooth(fill="gray", color = "black", span = 1,formula=y~x)+ geom_smooth(color="black",fill="gray",formula=y~x)+ annotation_logticks(sides = "b")+ labs(y = "CV on cell density (%)", x = "Cells measured", fill = "Resolution (s)", shape = "")+ ggtitle("(B)")+ guides(fill = guide_legend(override.aes = list(shape = 21)), ncol=1)+ ylim(0,15)+ geom_hline(yintercept = 5, linetype = 2) pdf("Fig6_run2.pdf", height = 5, width = 10) grid_arrange_shared_legend(p_CV_D2, p_CV_dens, ncol = 2, nrow = 1) dev.off() # Autocorrelation check and gam analysis for tap water results_final_tap_60 <- results_stability ### GAMs for stability inference on phenotypic diversity index gam.D2 <- gamm(D2~s(Time, k=60), data=results_final_tap_60, correlation=corCAR1(form =~Time, value = 0.5)) plot(gam.D2$gam,residuals=TRUE) plot(residuals.gam(gam.D2$gam), type = "l") acf(residuals.gam(gam.D2$gam)) # Check for normality in model residuals car::qqPlot(residuals.gam(gam.D2$gam)) plot(D2~Time, data = results_final_tap_60, ylim = c(1000,3000)) points(predict(gam.D2$gam), x = results_final_tap_60$Time, col ="red") # Check for significant autocorrelation Box.test(residuals.gam(gam.D2$gam), lag=15, type="Ljung-Box") # Check for significance of slope anova(gam.D2$gam) ### GAMs for stability inference on total cell density gam.TC <- gamm(Total_cells~s(Time, k=60), data=results_final_tap_60, correlation=corCAR1(form =~Time, value = 0.5)) plot(gam.TC$gam,residuals=TRUE) plot(residuals.gam(gam.TC$gam), type = "l") acf(residuals.gam(gam.TC$gam)) qqPlot(residuals.gam(gam.TC$gam)) plot(Total_cells~Time, data = results_final_tap_60) points(predict(gam.TC$gam), x = results_final_tap_60$Time, col ="red") # Check for significant autocorrelation Box.test(residuals.gam(gam.TC$gam), lag=15, type="Ljung-Box") # Check for significance of slope anova(gam.TC$gam) # Autocorrelation check and gam analysis for river water results_final_river_60 <- results_final_river[results_final_river$Resolution ==60,] results_final_river_60$Time <- as.numeric(as.character(results_final_river_60$Time)) ### GAMs for stability inference on phenotypic diversity index gam.D2 <- gamm(D2~s(Time, k=60), data=results_final_river_60, correlation=corCAR1(form =~Time, value = 0.5)) plot(gam.D2$gam,residuals=TRUE) plot(residuals.gam(gam.D2$gam), type = "l") acf(residuals.gam(gam.D2$gam)) # Check for normality in model residuals qqPlot(residuals.gam(gam.D2$gam)) plot(D2~Time, data = results_final_river_60, ylim = c(1000,5000)) points(predict(gam.D2$gam), x = results_final_river_60$Time, col ="red") # Check for significant autocorrelation Box.test(residuals.gam(gam.D2$gam), lag=15, type="Ljung-Box") # Check for significance of slope anova(gam.D2$gam) ### GAMs for stability inference on total cell density gam.TC <- gamm(Total_cells/volume~s(Time, k=60), data=results_final_river_60, correlation=corCAR1(form =~Time, value = 0.5)) plot(gam.TC$gam,residuals=TRUE) plot(residuals.gam(gam.TC$gam), type = "l") # Check for normality in model residuals qqPlot(residuals.gam(gam.TC$gam)) plot(Total_cells/volume~Time, data = results_final_river_60, ylim = c(0,320)) points(predict(gam.TC$gam), x = results_final_river_60$Time, col ="red") # Check for significant autocorrelation acf(residuals.gam(gam.TC$gam)) Box.test(residuals.gam(gam.TC$gam), lag=15, type="Ljung-Box") # Check for significance of slope anova(gam.TC$gam) ### Fig S1 fs_S1 <- transform(original_data[1],`FL1-H`=asinh(`FL1-H`), `SSC-H`=asinh(`SSC-H`), `FL3-H`=asinh(`FL3-H`), `FSC-H`=asinh(`FSC-H`)) sqrcut1 <- matrix(c(asinh(20000),asinh(20000),16,16, 3,9.55,16,3),ncol=2, nrow=4) colnames(sqrcut1) <- c("FL1-H","FL3-H") rGate_HNA <- polygonGate(.gate=sqrcut1, filterId = "HNA") sqrcut1 <- matrix(c(8.5,8.5,asinh(20000),asinh(20000), 3,7.25,9.55,3),ncol=2, nrow=4) colnames(sqrcut1) <- c("FL1-H","FL3-H") rGate_LNA <- polygonGate(.gate=sqrcut1, filterId = "LNA") sqrcut1 <- matrix(c(8.5,8.5,16,16, 3,7.25,16,3),ncol=2, nrow=4) colnames(sqrcut1) <- c("FL1-H","FL3-H") polyGate1 <- polygonGate(.gate=sqrcut1, filterId = "Total Cells") ### Creating a rectangle gate, set correct threshold here for FL1 sqrcut2 <- matrix(c(asinh(20000),asinh(20000),20,20, 0,20,20,0),ncol=2, nrow=4) filters <- filters(list(rGate_LNA, rGate_HNA)) flist <- list(filters) names(flist) <- flowCore::sampleNames(fs_S1) pdf("FigS1.pdf", height = 5, width = 6) print(xyplot(`FL3-H`~`FL1-H`, data=fs_S1, filter=flist, xbins=500,nbin=128, par.strip.text=list(col="black", font=3,cex=1), smooth=FALSE, xlim = c(7.5,15), ylim = c(2.5,15), xlab=list(label="Green fluorescence intensity (FL1-H)",cex=1.35),ylab=list(label="Red fluorescence intensity (FL3-H)",cex=1.35), par.settings=my.settings, scales=list(x=list(at=seq(from=0, to=15, by=2.5),cex=1), y=list(at=seq(from=0, to=15, by=2.5),cex=1)), layout=c(1,1), margin=TRUE, binTrans="log", strip=strip.custom(factor.levels="") ) ) dev.off() ### Calculate coefficient of variation for each bin in each experiment and visualize ### this fingerprint for Figure 6 cv_fp_bacteria <- apply(fp_bacteria@basis[, 1:16384], 2, function(x) sd(x)) cv_fp_mixed <- apply(fp_mixed@basis[, 1:16384], 2, function(x) sd(x)) dummy_fp <- fp_bacteria@basis[1, 1:16384] dummy_fp[dummy_fp > 0.00000001] <- NA nbin <- 128 Y <- c() for (i in 1:nbin) Y <- c(Y, rep(i, 128)) X = rep(1:nbin, nbin) df_cv_bacteria <- data.frame(dev = cv_fp_bacteria, X = rep(1:nbin, nbin), Y = Y) df_cv_mixed <- data.frame(dev = cv_fp_mixed, X = rep(1:nbin, nbin), Y = Y) df_dummy <- data.frame(dev = dummy_fp, X = rep(1:nbin, nbin), Y = Y) colnames(df_cv_mixed)[2:3] <- c("FL1-H", "FL3-H") colnames(df_cv_bacteria)[2:3] <- c("FL1-H", "FL3-H") colnames(df_dummy)[2:3] <- c("FL1-H", "FL3-H") df_dummy <- df_dummy[is.na(df_dummy$dev), ] # Filter out low SD values df_cv_bacteria <- df_cv_bacteria %>% dplyr::filter(dev > 5) df_cv_mixed <- df_cv_mixed %>% filter(dev > 5) v_bact <- ggplot2::ggplot(df_cv_bacteria, ggplot2::aes(`FL1-H`, `FL3-H`, z = dev))+ ggplot2::geom_point(data = df_dummy, colour="gray",size = 1, shape = 22)+ ggplot2::geom_tile(ggplot2::aes(fill=dev))+ ggplot2::scale_fill_distiller(palette="RdBu", na.value="white", trans = "log", labels = seq(15, 60, 15), breaks = seq(15, 60, 15)) + # ggplot2::stat_contour(ggplot2::aes(fill=..level..), geom="polygon", binwidth=0.1)+ ggplot2::theme_bw()+ # ggplot2::geom_contour(color = "white", alpha = 1)+ ylim(25,100)+ xlim(40,110)+ theme(axis.title=element_text(size=16), strip.text.x=element_text(size=16), legend.title=element_text(size=15),legend.text=element_text(size=14), axis.text = element_text(size=14),title=element_text(size=20), strip.background=element_rect(fill=adjustcolor("lightgray",0.2)) #,panel.grid.major = element_blank(), panel.grid.minor = element_blank() ) print(v_bact) v_mixed <- ggplot2::ggplot(df_cv_mixed, ggplot2::aes(`FL1-H`, `FL3-H`, z = dev))+ ggplot2::geom_tile(ggplot2::aes(fill=dev)) + # ggplot2::geom_point(size = 1, ggplot2::aes(fill=cor), shape =22, # color = "transparent")+ ggplot2::scale_fill_distiller(palette="RdBu", na.value="white", trans = "log", labels = seq(15, 60, 15), breaks = seq(15, 60, 15)) + # ggplot2::stat_contour(ggplot2::aes(fill=..level..), geom="polygon", binwidth=0.1)+ ggplot2::theme_bw()+ # ggplot2::geom_contour(color = "white", alpha = 1)+ ylim(0,100)+ xlim(40,110)+ theme(axis.title=element_text(size=16), strip.text.x=element_text(size=16), legend.title=element_text(size=15),legend.text=element_text(size=14), axis.text = element_text(size=14),title=element_text(size=20), strip.background=element_rect(fill=adjustcolor("lightgray",0.2)) #,panel.grid.major = element_blank(), panel.grid.minor = element_blank() ) print(v_mixed) ### Extract labels of samples belonging to different "robust" community types ### For natural community contaminations lab_mixed_c0 <- results_mixed$cluster_label == 1 & results_mixed$Time < 10 lab_mixed_c1 <- results_mixed$cluster_label == 2 lab_mixed_c2 <- results_mixed$cluster_label == 3 lab_mixed_c3 <- results_mixed$cluster_label == 4 lab_mixed_c4 <- results_mixed$cluster_label == 5 ### Calculate contrasts between control and contaminations for all 5 contaminations fp_mixed_c1 <- fp_contrasts(fp_mixed, comp2 = lab_mixed_c0, comp1 = lab_mixed_c1) fp_mixed_c2 <- fp_contrasts(fp_mixed, comp2 = lab_mixed_c0, comp1 = lab_mixed_c2) fp_mixed_c3 <- fp_contrasts(fp_mixed, comp2 = lab_mixed_c0, comp1 = lab_mixed_c3) fp_mixed_c4 <- fp_contrasts(fp_mixed, comp2 = lab_mixed_c0, comp1 = lab_mixed_c4) ### Merge all contrasts fp_merged <- data.frame(rbind(fp_mixed_c1, fp_mixed_c2, fp_mixed_c3, fp_mixed_c4), Contamination = c(rep("Evian", nrow(fp_mixed_c1)), rep("Pond", nrow(fp_mixed_c2)), rep("River-1", nrow(fp_mixed_c3)), rep("River-2", nrow(fp_mixed_c4)))) ### Visualize different contrasts v_c_all <- ggplot(fp_merged, aes(`FL1.H`, `FL3.H`, z = Density))+ geom_tile(aes(fill=Density)) + geom_point(colour="#333333", alpha=0.3, size =1)+ scale_fill_distiller(expression(Delta~"Density"), palette="RdYlBu", na.value="white", limits = c(-0.65, 0.65)) + stat_contour(aes(fill=..level..), geom="polygon", binwidth=0.1)+ theme_bw()+ facet_grid(~Contamination)+ geom_contour(color = "white", alpha = 1)+ labs(x="Green fluorescence intensity (a.u.)", y="Red fluorescence intensity (a.u.)")+ theme(axis.title=element_text(size=16), strip.text.x=element_text(size=16), legend.title=element_text(size=15),legend.text=element_text(size=14), axis.text = element_text(size=14),title=element_text(size=20), strip.background=element_rect(fill=adjustcolor("lightgray",0.2)) #,panel.grid.major = element_blank(), panel.grid.minor = element_blank() ) pdf("Fig6a.pdf", height = 5, width = 10) print(v_c_all) dev.off() ### Visualize different contrasts # idx <- duplicated(interaction(fp_merged$FL1.H, fp_merged$FL3.H)) | duplicated(interaction(fp_merged$FL1.H, fp_merged$FL3.H), fromLast = TRUE) # fp_merged$Contamination <- as.character(fp_merged$Contamination) # fp_merged$Contamination[idx] <- "Shared" v_c_cat <- fp_merged %>% ggplot(aes(`FL1.H`, `FL3.H`, z = Density))+ geom_tile(aes(fill=Contamination), alpha=0.7) + geom_point(colour="#333333", alpha=0.3, size = 1)+ # scale_fill_distiller(palette="RdBu", na.value="white") + scale_fill_manual(values = c("#33A02C","#E31A1C","#FF7F00","#6A3D9A", "Grey"))+ # stat_contour(aes(fill=..level..), geom="polygon", binwidth=0.1)+ theme_bw()+ # geom_contour(color = "white", alpha = 1)+ labs(x="Green fluorescence intensity (a.u.)", y="Red fluorescence intensity (a.u.)")+ theme(axis.title=element_text(size=16), strip.text.x=element_text(size=16), legend.title=element_text(size=15),legend.text=element_text(size=14), axis.text = element_text(size=14),title=element_text(size=20), strip.background=element_rect(fill=adjustcolor("lightgray",0.2)) #,panel.grid.major = element_blank(), panel.grid.minor = element_blank() ) pdf("Fig6b.pdf",height = 5, width = 7) print(v_c_cat) dev.off() <file_sep>This is the data analysis conducted for the manuscript: ******************* **"Detection of microbial disturbances in a drinking water microbial community through continuous acquisition and advanced analysis of flow cytometry data"** by <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> and <NAME>, *Water Research*, accepted manuscript. ******************* Data can be downloaded from Flowrepository under [ID FR-FCM-ZY5P](https://flowrepository.org/experiments/1209). *******************
bb3f3893f8ac787ffaa6ff42574045e364fc1974
[ "Markdown", "R" ]
2
R
bpollner/WaterResearch_Props2018
3db7878a53b52624b55aae2b4e98fc8484a7b7f5
baa7ced24b89ee72485fc5b9b310f86ec2c7a415
refs/heads/master
<file_sep># EDGECASTLE ASP.Net Identity (Graph) # An ASP.NET Identity provider backed by the Neo4J Graph Database.<file_sep>using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin; using Microsoft.Owin.Security; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Text; using System.Threading.Tasks; namespace Edgecastle.AspNet.Identity.Neo4j { /// <summary> /// Manages sign in operations /// </summary> public class ApplicationSignInManager : SignInManager<ApplicationUser, string> { /// <summary> /// Creates a new <see cref="ApplicationSignInManager"/> /// </summary> /// <param name="options">The identity-factory options</param> /// <param name="context">The OWIN context</param> /// <returns>A new <see cref="ApplicationSignInManager"/></returns> public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context) { return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication); } /// <summary> /// Initializes a new instance of the <see cref="ApplicationSignInManager"/> class. /// </summary> /// <param name="userManager">The user manager</param> /// <param name="authenticationManager">The authentication manager</param> public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager) : base(userManager, authenticationManager) { } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Edgecastle.AspNet.Identity.Neo4j { /// <summary> /// Groups together attributes /// </summary> public class Role { /// <summary> /// The name of the role /// </summary> public string Name { get; set; } } } <file_sep>using Microsoft.AspNet.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Text; using System.Threading.Tasks; namespace Edgecastle.AspNet.Identity.Neo4j { /// <summary> /// An ASP.NET identity (user) /// </summary> public class ApplicationUser : User, IUser<string> { /// <summary> /// Initializes a new instance of the <see cref="ApplicationUser"/> class /// </summary> public ApplicationUser() { } public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return userIdentity; } /// <summary> /// The user's password hash /// </summary> public string PasswordHash { get; set; } /// <summary> /// Cleans and sets up a new <see cref="ApplicationUser"/> object for persistence to the graph database /// </summary> public void SanitizeNewUser() { this.UserName = this.UserName.ToLowerInvariant(); this.Email = this.Email.ToLowerInvariant(); this.Id = Guid.NewGuid().ToString(); this.Joined = DateTimeOffset.UtcNow; this.LastLogin = this.Joined; } } } <file_sep>using Microsoft.AspNet.Identity; using Neo4jClient; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Security.Claims; using System.Text; using System.Threading.Tasks; namespace Edgecastle.AspNet.Identity.Neo4j { /// <summary> /// A user service using a graph database as a backing store /// </summary> public class UserStore : IUserStore<ApplicationUser>, IUserRoleStore<ApplicationUser>, IUserClaimStore<ApplicationUser>, IUserTwoFactorStore<ApplicationUser, string>, IUserLoginStore<ApplicationUser>, IUserPasswordStore<ApplicationUser>, IUserEmailStore<ApplicationUser>, IUserLockoutStore<ApplicationUser, string>, IUserPhoneNumberStore<ApplicationUser> { private GraphClient DB = null; /// <summary> /// Initializes a new instance of the <see cref="UserStore"/> class. /// </summary> public UserStore() { this.DB = Neo4jProvider.GetClient(); } /// <summary> /// Returns a user by email address /// </summary> /// <param name="email">The email address to search for</param> /// <returns>The user, if found, or null, if not found.</returns> public async Task<ApplicationUser> GetUserByEmailAddress(string email) { if(string.IsNullOrWhiteSpace(email)) { throw new ArgumentNullException("email"); } var user = (await DB.Cypher .Match("(existingUser:User { Email: {email} })") .WithParam("email", email.ToLowerInvariant()) .Return(existingUser => existingUser.As<ApplicationUser>()) .ResultsAsync).SingleOrDefault(); return user; } /// <summary> /// Ascertains whether the user already exists (based on the email address) /// </summary> /// <param name="email">The email address to search for.</param> /// <returns>True, if already exists, otherwise false.</returns> public async Task<bool> UserAlreadyExists(string email) { return (await GetUserByEmailAddress(email)) != null; } /// <summary> /// Creates and persists a user to the backing store. /// </summary> /// <param name="user">The user to save</param> /// <returns>Nothing. Asynchronous void.</returns> public async Task CreateAsync(ApplicationUser user) { if (user == null) { throw new ArgumentNullException("user"); } // Cleanses and sets up properties for new users ready to be persisted to the DB user.SanitizeNewUser(); // Create User await DB.Cypher .Create("(:User {user})") .WithParam("user", user) .ExecuteWithoutResultsAsync(); } /// <summary> /// Deletes a user /// </summary> /// <param name="user">The user to delete</param> /// <returns>Nothing. Asynchronous void.</returns> public Task DeleteAsync(ApplicationUser user) { throw new NotImplementedException(); } /// <summary> /// Finds a user by their unique identifier /// </summary> /// <param name="userId">The identifier to search for</param> /// <returns>The <see cref="ApplicationUser"/> if found, otherwise null.</returns> public async Task<ApplicationUser> FindByIdAsync(string userId) { if (string.IsNullOrWhiteSpace(userId)) { throw new ArgumentNullException("userId"); } var query = DB.Cypher .Match("(identity:User { Id: {userId} })") .WithParam("userId", userId) .Return(identity => identity.As<ApplicationUser>()); return (await query.ResultsAsync).SingleOrDefault(); } /// <summary> /// Finds a user by the username /// </summary> /// <param name="userName">The username to search for</param> /// <returns>The <see cref="ApplicationUser"/> if found, otherwise null.</returns> public async Task<ApplicationUser> FindByNameAsync(string userName) { if (string.IsNullOrWhiteSpace(userName)) { throw new ArgumentNullException("userName"); } var query = DB.Cypher .Match("(identity:User { UserName: {userName} })") .WithParam("userName", userName.ToLowerInvariant()) .Return(identity => identity.As<ApplicationUser>()); return (await query.ResultsAsync).SingleOrDefault(); } /// <summary> /// Updates the user with the new properties /// </summary> /// <param name="user">The <see cref="ApplicationUser"/> to update</param> /// <returns>Nothing. Asynchronous void.</returns> public async Task UpdateAsync(ApplicationUser user) { if (user == null) { throw new ArgumentNullException("user"); } user.LastLogin = DateTimeOffset.UtcNow; await DB.Cypher .Match("(user:User { Id: {userId} })") .WithParam("userId", user.Id) .Set("user = {user}") .WithParam("user", user) .ExecuteWithoutResultsAsync(); } /// <summary> /// Disposes all native and managed resources used by this class. /// </summary> public void Dispose() { this.Dispose(true); } /// <summary> /// Adds a role to a user account /// </summary> /// <param name="user">The user account to add the role to</param> /// <param name="roleName">The role to add</param> /// <returns>Nothing. Asynchronous void.</returns> public async Task AddToRoleAsync(ApplicationUser user, string roleName) { await DB.Cypher .Match("(user:User { Id: {userId} })-[rel:IN_ROLE]->(role:Role { Name: {roleName}})") .WithParams(new { userId = user.Id, roleName = roleName }) .CreateUnique("(user)-[:IN_ROLE]->(role:Role { Name: {roleName} })") .WithParam("roleName", roleName) .ExecuteWithoutResultsAsync(); } /// <summary> /// Gets the roles for the user /// </summary> /// <param name="user">The user to get the roles for</param> /// <returns>A list of the roles the user is in.</returns> public async Task<IList<string>> GetRolesAsync(ApplicationUser user) { if (user == null) { throw new ArgumentNullException("user"); } string matchString = String.Format("(user:{0} {{ Id: {{userId}} }})-[:IN_ROLE]-(role:{1})", Configuration.Global.UserLabel, Configuration.Global.RoleLabel); var results = await DB.Cypher .Match(matchString) .WithParam("userId", user.Id) .Return(role => role.As<Role>()) .ResultsAsync; return results.Select(role => role.Name).ToList(); } /// <summary> /// Checks if the user is in the given role /// </summary> /// <param name="user">The user to check</param> /// <param name="roleName">The role</param> /// <returns>True, if in the role, otherwise false.</returns> public Task<bool> IsInRoleAsync(ApplicationUser user, string roleName) { throw new NotImplementedException(); } /// <summary> /// Removes the user from the role. /// </summary> /// <param name="user">The user to remove from the role.</param> /// <param name="roleName">The role</param> /// <returns>Nothing. Asynchronous void.</returns> public Task RemoveFromRoleAsync(ApplicationUser user, string roleName) { throw new NotImplementedException(); } /// <summary> /// Adds a claim to the user /// </summary> /// <param name="user">The user</param> /// <param name="claim">The claim</param> /// <returns>Nothing. Asynchronous void.</returns> public Task AddClaimAsync(ApplicationUser user, System.Security.Claims.Claim claim) { throw new NotImplementedException(); } /// <summary> /// Gets the claims for the given user /// </summary> /// <param name="user">The user to get the claims for</param> /// <returns>The list of claims</returns> public Task<IList<Claim>> GetClaimsAsync(ApplicationUser user) { List<Claim> claims = new List<Claim>(); claims.Add(new Claim(ClaimTypes.Email, user.Email)); return Task.FromResult<IList<Claim>>(claims); } /// <summary> /// Removes the claim from the user /// </summary> /// <param name="user">The user from which to remove the claim</param> /// <param name="claim">The claim to remove</param> /// <returns>Nothing. Asynchronous void.</returns> public Task RemoveClaimAsync(ApplicationUser user, System.Security.Claims.Claim claim) { throw new NotImplementedException(); } /// <summary> /// Whether the user has enabled two-factor authentication (2FA) /// </summary> /// <param name="user">The user to query</param> /// <returns>True, if 2FA is enabled, otherwise false.</returns> public Task<bool> GetTwoFactorEnabledAsync(ApplicationUser user) { return Task.FromResult<bool>(user.IsTwoFactorAuthEnabled); } /// <summary> /// Sets two factor authentication (2FA) for the user /// </summary> /// <param name="user">The user to set 2FA for</param> /// <param name="enabled">Whether to enable or disable 2FA</param> /// <returns>Nothing. Asynchronous void.</returns> public async Task SetTwoFactorEnabledAsync(ApplicationUser user, bool enabled) { user.IsTwoFactorAuthEnabled = enabled; await this.UpdateAsync(user); } /// <summary> /// Adds an external login to a local user account /// </summary> /// <param name="user">The local user account</param> /// <param name="login">The external login</param> /// <returns>Nothing. Asynchronous void.</returns> public async Task AddLoginAsync(ApplicationUser user, UserLoginInfo login) { await DB.Cypher .Match("(user:User { Id: {userId} })") .WithParam("userId", user.Id) .CreateUnique("(user)-[:EXTERNAL_LOGIN]->(login:ExternalLogin {loginInfo})") .WithParam("loginInfo", login) .ExecuteWithoutResultsAsync(); } /// <summary> /// Finds a user by external login. /// </summary> /// <param name="login">The external login details</param> /// <returns>The local user account, if found, otherwise null.</returns> public async Task<ApplicationUser> FindAsync(UserLoginInfo login) { if (login == null) { throw new ArgumentNullException("login"); } string matchString = String.Format("(user:{0})-[]-(externalLogin:{1} {{ ProviderKey: {{loginProviderKey}} }})", Configuration.Global.UserLabel, Configuration.Global.ExternalLoginLabel); var query = DB.Cypher .Match(matchString) .WithParam("loginProviderKey", login.ProviderKey) .Return(user => user.As<ApplicationUser>()); var result = (await query.ResultsAsync).SingleOrDefault(); return result; } /// <summary> /// Gets external logins for the local user account /// </summary> /// <param name="user">The user to find external logins for.</param> /// <returns>A list of external logins for the given user.</returns> public async Task<IList<UserLoginInfo>> GetLoginsAsync(ApplicationUser user) { if (user == null) { throw new ArgumentNullException("user"); } string matchString = String.Format("(user:{0} {{ Id: {{userId}} }})-[:EXTERNAL_LOGIN]-(externalLogin:{1})", Configuration.Global.UserLabel, Configuration.Global.ExternalLoginLabel); var results = (await DB.Cypher .Match(matchString) .WithParam("userId", user.Id) .Return(externalLogin => externalLogin.As<UserLoginInfoPrivate>()) .ResultsAsync) .Select(userLoginInfo => new UserLoginInfo(userLoginInfo.LoginProvider, userLoginInfo.ProviderKey)) .ToList(); return results; } /// <summary> /// Removes an external login for the given local user account. /// </summary> /// <param name="user">The local user account</param> /// <param name="login">The external login to remove</param> /// <returns>Nothing. Asynchronous void.</returns> public Task RemoveLoginAsync(ApplicationUser user, UserLoginInfo login) { throw new NotImplementedException(); } /// <summary> /// Gets the password hash for the given user. /// </summary> /// <param name="user">The local user account</param> /// <returns>The password hash.</returns> public Task<string> GetPasswordHashAsync(ApplicationUser user) { return Task.FromResult<string>(user.PasswordHash); } /// <summary> /// Whether the local user account has a password or not. /// </summary> /// <param name="user">The local user account</param> /// <returns>True, if the account has a password, otherwise false.</returns> public Task<bool> HasPasswordAsync(ApplicationUser user) { return Task.FromResult<bool>(user.PasswordHash != null); } /// <summary> /// Sets the password on the local user account. /// </summary> /// <param name="user">The user to set the password for</param> /// <param name="passwordHash">The password (hash) to set.</param> /// <returns>Nothing. Asynchronous void.</returns> public async Task SetPasswordHashAsync(ApplicationUser user, string passwordHash) { user.PasswordHash = passwordHash; await this.UpdateAsync(user); } /// <summary> /// Finds a user by their email address. /// </summary> /// <param name="email">The email address to look up</param> /// <returns>The user account, if found, otherwise null.</returns> public async Task<ApplicationUser> FindByEmailAsync(string email) { return await GetUserByEmailAddress(email); } /// <summary> /// Gets the email address for the given user. /// </summary> /// <param name="user">The local user account</param> /// <returns>The email address for the given user.</returns> public Task<string> GetEmailAsync(ApplicationUser user) { return Task.FromResult<string>(user.Email); } /// <summary> /// Gets whether the email address for the given user has been verified. /// </summary> /// <param name="user"></param> /// <returns></returns> public Task<bool> GetEmailConfirmedAsync(ApplicationUser user) { return Task.FromResult<bool>(user.IsEmailConfirmed); } /// <summary> /// /// </summary> /// <param name="user"></param> /// <param name="email"></param> /// <returns></returns> public async Task SetEmailAsync(ApplicationUser user, string email) { user.Email = email; await this.UpdateAsync(user); } /// <summary> /// /// </summary> /// <param name="user"></param> /// <param name="confirmed"></param> /// <returns></returns> public async Task SetEmailConfirmedAsync(ApplicationUser user, bool confirmed) { user.IsEmailConfirmed = confirmed; await this.UpdateAsync(user); } /// <summary> /// /// </summary> /// <param name="user"></param> /// <returns></returns> public Task<int> GetAccessFailedCountAsync(ApplicationUser user) { return Task.FromResult<int>(user.FailedLogins); } /// <summary> /// /// </summary> /// <param name="user"></param> /// <returns></returns> public Task<bool> GetLockoutEnabledAsync(ApplicationUser user) { return Task.FromResult<bool>(user.IsLockoutEnabled); } /// <summary> /// /// </summary> /// <param name="user"></param> /// <returns></returns> public Task<DateTimeOffset> GetLockoutEndDateAsync(ApplicationUser user) { return Task.FromResult<DateTimeOffset>(user.LockoutEndDate); } /// <summary> /// /// </summary> /// <param name="user"></param> /// <returns></returns> public async Task<int> IncrementAccessFailedCountAsync(ApplicationUser user) { user.FailedLogins += 1; await this.UpdateAsync(user); return user.FailedLogins; } /// <summary> /// /// </summary> /// <param name="user"></param> /// <returns></returns> public async Task ResetAccessFailedCountAsync(ApplicationUser user) { user.FailedLogins = 0; await this.UpdateAsync(user); } /// <summary> /// /// </summary> /// <param name="user"></param> /// <param name="enabled"></param> /// <returns></returns> public async Task SetLockoutEnabledAsync(ApplicationUser user, bool enabled) { user.IsLockoutEnabled = enabled; await this.UpdateAsync(user); } /// <summary> /// /// </summary> /// <param name="user"></param> /// <param name="lockoutEnd"></param> /// <returns></returns> public async Task SetLockoutEndDateAsync(ApplicationUser user, DateTimeOffset lockoutEnd) { user.LockoutEndDate = lockoutEnd; await this.UpdateAsync(user); } /// <summary> /// /// </summary> /// <param name="user"></param> /// <returns></returns> public Task<string> GetPhoneNumberAsync(ApplicationUser user) { return Task.FromResult<string>(Convert.ToString(user.PhoneNumber)); } /// <summary> /// /// </summary> /// <param name="user"></param> /// <returns></returns> public Task<bool> GetPhoneNumberConfirmedAsync(ApplicationUser user) { return Task.FromResult<bool>(user.IsPhoneNumberConfirmed); } /// <summary> /// /// </summary> /// <param name="user"></param> /// <param name="phoneNumber"></param> /// <returns></returns> public async Task SetPhoneNumberAsync(ApplicationUser user, string phoneNumber) { user.PhoneNumber = phoneNumber; await this.UpdateAsync(user); } /// <summary> /// /// </summary> /// <param name="user"></param> /// <param name="confirmed"></param> /// <returns></returns> public async Task SetPhoneNumberConfirmedAsync(ApplicationUser user, bool confirmed) { user.IsPhoneNumberConfirmed = confirmed; await this.UpdateAsync(user); } /// <summary> /// Disposes of resources /// </summary> /// <param name="includeManagedResources">Whether to dispose of managed resources as well as native resources</param> protected virtual void Dispose(bool includeManagedResources) { } // Necessary because UserLoginInfo is sealed but doesn't have a default ctor. // Summary: // Represents a linked login for a user (i.e. a facebook/google account) private class UserLoginInfoPrivate { // Summary: // Provider for the linked login, i.e. Facebook, Google, etc. public string LoginProvider { get; set; } // // Summary: // User specific key for the login provider public string ProviderKey { get; set; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Edgecastle.AspNet.Identity.Neo4j { /// <summary> /// Error thrown when user already exists /// </summary> [Serializable] public class UserAlreadyExistsException : Exception { } } <file_sep>using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Edgecastle.AspNet.Identity.Neo4j { /// <summary> /// Allows configuration of the labels used for different objects in the graph DB /// </summary> public class Configuration { private static Configuration _singleton = null; private NameValueCollection Settings = null; /// <summary> /// Initializes a new instance of the <see cref="Configuration"/> class. /// </summary> /// <param name="settings">The settings used to define the labels</param> public Configuration(NameValueCollection settings) { this.Settings = settings ?? ConfigurationManager.AppSettings; } /// <summary> /// Initializes a new instance of the <see cref="Configuration"/> class. /// </summary> public Configuration() : this(null) { } /// <summary> /// The connection string to use to connect to the graph databases /// </summary> public string ConnectionString { get { return Settings["Neo4jConnectionString"] ?? "http://neo4j:neo4j@localhost:7474/db/data"; } } /// <summary> /// The label applied to User objects (nodes) in the graph database /// </summary> public string UserLabel { get { return Settings["UserLabel"] ?? "User"; } } /// <summary> /// The label applied to External Login objects (nodes) in the graph database /// </summary> public string ExternalLoginLabel { get { return Settings["ExternalLoginLabel"] ?? "ExternalLogin"; } } /// <summary> /// The label applied to Role objects (nodes) in the graph database /// </summary> public string RoleLabel { get { return Settings["RoleLabel"] ?? "Role"; } } /// <summary> /// Global singleton for accessing common graph configuration settings /// </summary> public static Configuration Global { get { if (_singleton == null) { _singleton = new Configuration(); } return _singleton; } } } } <file_sep>using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin; using Neo4jClient; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Edgecastle.AspNet.Identity.Neo4j { /// <summary> /// Manager for users backed by a graph database store /// </summary> public class ApplicationUserManager : UserManager<ApplicationUser> { private readonly GraphClient DB; /// <summary> /// Initializes a new instance of the <see cref="ApplicationUserManager"/> class. /// </summary> /// <param name="store"></param> public ApplicationUserManager(IUserStore<ApplicationUser> store) : base(store) { this.DB = Neo4jProvider.GetClient(); } /// <summary> /// /// </summary> /// <param name="options"></param> /// <param name="context"></param> /// <returns></returns> public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) { ApplicationUserManager manager = new ApplicationUserManager(new UserStore()); // Username rules manager.UserValidator = new UserValidator<ApplicationUser>(manager) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true }; // Password rules manager.PasswordValidator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = true, RequireDigit = true, RequireLowercase = true, RequireUppercase = true }; // Configure lockouts manager.UserLockoutEnabledByDefault = true; manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5); manager.MaxFailedAccessAttemptsBeforeLockout = 5; // Two-factor authentication manager.RegisterTwoFactorAuthProviders(); var dataProtectionProvider = options.DataProtectionProvider; if (dataProtectionProvider != null) { manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("AspNetIdentityGraph")); } return manager; } /// <summary> /// Configures two-factor authentication (2FA) providers /// </summary> protected virtual void RegisterTwoFactorAuthProviders() { // Add two factor authentication providers here, or derive from this class and override } /// <summary> /// /// </summary> /// <param name="user"></param> /// <param name="password"></param> /// <returns></returns> public override async Task<IdentityResult> CreateAsync(ApplicationUser user, string password) { IdentityResult createResult = null; user.PasswordHash = base.PasswordHasher.HashPassword(password); // Cleanses and sets up properties on user object ready for commit to the DB user.SanitizeNewUser(); var matchString = String.Format("(existingUser:{0} {{ Username: {{user}}.UserName }})", Configuration.Global.UserLabel); var matchedUsers = (await DB.Cypher .Match(matchString) .WithParam("user", user) .Return(existingUser => existingUser.Count()) .ResultsAsync) .Single(); if(matchedUsers != 0) { // User already exists // TODO: Globalize createResult = new IdentityResult("User already exists."); } else { var createString = String.Format("(newUser:{0} {{newUser}})", Configuration.Global.UserLabel); await DB.Cypher .Create(createString) .WithParam("newUser", user) .ExecuteWithoutResultsAsync(); createResult = IdentityResult.Success; } return createResult; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Edgecastle.AspNet.Identity.Neo4j { /// <summary> /// Represents a user in the system. /// </summary> public class User { /// <summary> /// Initializes a new instance of the <see cref="User"/> class. /// </summary> public User() { // Safe by default IsLockoutEnabled = true; } /// <summary> /// The globally unique identifier for this user (Guid as string) /// </summary> public string Id { get; set; } /// <summary> /// The user's username /// </summary> public string UserName { get; set; } // Account milestones /// <summary> /// Date the user joined the service /// </summary> public DateTimeOffset Joined { get; set; } /// <summary> /// Date the user last logged in /// </summary> public DateTimeOffset LastLogin { get; set; } // Contact / verification details /// <summary> /// The user's phone number /// </summary> public string PhoneNumber { get; set; } /// <summary> /// Whether the phone number has been verified /// </summary> public bool IsPhoneNumberConfirmed { get; set; } /// <summary> /// The user's email address /// </summary> public string Email { get; set; } /// <summary> /// Whether the email address has been verified /// </summary> public bool IsEmailConfirmed { get; set; } // Account Lockout /// <summary> /// Whether this account can be locked out /// </summary> public bool IsLockoutEnabled { get; set; } /// <summary> /// Number of failed logins /// </summary> public int FailedLogins { get; set; } /// <summary> /// Date the lockout expires /// </summary> public DateTimeOffset LockoutEndDate { get; set; } // Two-factor auth /// <summary> /// Whether this user has enabled two-factor authentication (2FA) /// </summary> public bool IsTwoFactorAuthEnabled { get; set; } } }
d3deb07b54f5f4a7da556ef1657258bc9ccab8e6
[ "Markdown", "C#" ]
9
Markdown
edgecastle/AspNetIdentityGraph
1d37fdf4c184bbb0902e8bfedaa2ec569aba2085
ac537f18f8f89a3069ad7244c514a532194e2ab3
refs/heads/master
<repo_name>danielfedatto/typewriter<file_sep>/typewriter/stories/index.js import './stylesheets/typewriter.scss' import './plain-text' import './rich-text' import './contextual-toolbar' import './video' import './embed' import './image' import './inserter' import './showcase' <file_sep>/typewriter/src/plugins/paragraph.js import React from 'react' import { Placeholder } from 'slate-react' export default (options = {}) => { const { placeholder, placeholderClassName = 'placeholder', } = options const dispatchCustomEvent = (eventName, detail) => { const event = new CustomEvent(eventName, { detail: detail }) global.dispatchEvent(event) } const PARAGRAPH_RENDER_RULE = { match: node => node.type == 'paragraph', render: (props) => { return ( <p {...props.attributes} style={{ position: 'relative' }} onMouseEnter={ () => dispatchCustomEvent(`paragraph:mouseenter`, { node: props.node }) } onMouseOver={ () => dispatchCustomEvent(`paragraph:mouseover`, { node: props.node }) } > {props.children} {placeholder ? <Placeholder className={placeholderClassName} node={props.node} parent={props.state.document} state={props.state} > {placeholder} </Placeholder> : null} </p> ) } } const schema = { rules: [ PARAGRAPH_RENDER_RULE, ] } return { schema, } } <file_sep>/test/dummy/app/helpers/spawner_helper.rb module SpawnerHelper def component_for(name, attributes = {}, html = { class: 'component' }) data = stringify_active_models(attributes) .merge(component: name, authenticity_token: form_authenticity_token) tag.div({data: data}.merge(html)) do yield if block_given? end end def typewriter_for(name, attributes = {}, html = { class: 'component' }) attributes = attributes.merge({ presign_from: typewriter_nanofile.presign_path, upload_to: typewriter.image_uploads_path }) component_for(name, attributes, html) end private def stringify_active_models(attributes) attributes.map do |key, value| value = value.try(:as_json) || value [key, value] end.to_h end end <file_sep>/app/assets/config/typewriter_manifest.js //= link_directory ../javascripts/typewriter .js //= link_directory ../stylesheets/typewriter .css <file_sep>/test/dummy/config/routes.rb Rails.application.routes.draw do resources :articles mount Typewriter::Engine => '/typewriter' end <file_sep>/typewriter/src/components/video.js import React, { Component } from 'react' import createEmbedUrl from '../helpers/create-embed-url' export default class Video extends Component { currentUrl = () => { return this.props.node.data.get('video') } isSelected = () => { const { node, state } = this.props const isSelected = state.selection.hasEdgeIn(node) return isSelected } onClick = (event) => { event.stopPropagation() } render() { const colorSystem = '#4F47FF' return ( <div {...this.props.attributes} className="video-input" style={{ outline: this.isSelected() ? `4px solid ${colorSystem}` : 'none', }} > <div className="mask" /> <iframe type="text/html" className="embed" src={this.currentUrl()} frameBorder="0" /> </div> ) } } <file_sep>/typewriter/src/components/embed.js import React, { Component } from 'react' import renderHTML from 'react-render-html' export default class Embed extends Component { componentWillMount() { this.embedComponent = renderHTML(this.cleanContent()) } isSelected = () => { const { node, state } = this.props const isSelected = state.selection.hasEdgeIn(node) return isSelected } onClick = (event) => { event.stopPropagation() } cleanContent = () => { const content = this.props.node.data.get('content') const extractedScript = /<script[^>]+>((?:\s|.)+)<\/script>/gi.exec(content) if (!extractedScript) return content const cleanContent = content.replace(extractedScript[0], '') setTimeout(() => { eval(extractedScript[1]) }, 10) return cleanContent } render() { const colorSystem = '#4F47FF' return ( <div {...this.props.attributes} className="embed-input" style={{ outline: this.isSelected() ? `4px solid ${colorSystem}` : 'none', }} > <div className="mask" /> <div className="embed"> {this.embedComponent} </div> </div> ) } } <file_sep>/typewriter/src/plugins/video.js import React from 'react' import Video from '../components/video' export default options => { const schema = { nodes: { video: Video, }, } return { schema, } } <file_sep>/typewriter/src/plugins/phrase.js import React from 'react' import { Placeholder } from 'slate-react' export default (options = {}) => { const { renderAs, placeholder, placeholderClassName = 'placeholder', } = options const PHRASE_RENDER_RULE = { match: node => node.type === 'phrase', render: (props) => { const attrs = Object.assign({}, {...props.attributes}, {style: { position: 'relative' }}) const children = <span> {props.children} {placeholder ? <Placeholder className={placeholderClassName} node={props.node} parent={props.state.document} state={props.state} > {placeholder} </Placeholder> : null} </span> return renderAs(attrs, children) } } const schema = { rules: [ PHRASE_RENDER_RULE, ] } return { schema, } } <file_sep>/typewriter/src/plugins/code-markdown.js import React from 'react' import MarkInlineShortcut from '../helpers/mark-inline-shortcut' export default options => { const CODE_RENDER_RULE = { match: node => node.type == 'code', render: props => <code>{props.children}</code>, } const schema = { rules: [ CODE_RENDER_RULE, ] } const { onKeyDown } = MarkInlineShortcut({ type: 'code', regex: /`([^`]+)`/g, }) return { schema, onKeyDown, } } <file_sep>/typewriter/src/plugins/italic-markdown.js import MarkInlineShortcut from '../helpers/mark-inline-shortcut' export default options => { const { onKeyDown } = MarkInlineShortcut({ type: 'italic', regex: /_([^_]+)_/g, }) return { onKeyDown } } <file_sep>/typewriter/src/components/contextual-toolbar/link-input-edit.js import React, { Component } from 'react' import { findDOMNode } from 'slate-react' import Portal from 'react-portal' import keycode from 'keycode' import HoveringElement from './hovering-element' import hrefAutoWrap from '../../helpers/href-auto-wrap' import performBounceAnimation, { resetBounceAnimation } from '../../helpers/perform-bounce-animation' export default class LinkInputEdit extends Component { state = { shouldBeVisible: false, value: '', rect: null, } closeTimeoutId = null delayToClose = 1500 componentDidUpdate(prevProps, prevState) { if (prevProps.isSelectionMenuOpen !== this.props.isSelectionMenuOpen && this.props.isSelectionMenuOpen) { this.close() return } const isVisibleUpdated = prevProps.isVisible !== this.props.isVisible const hoveringLinkUpdated = prevProps.hoveringLink !== this.props.hoveringLink if (hoveringLinkUpdated || isVisibleUpdated) { this.updateVisibility() } } updateVisibility = () => { const rect = this.props.hoveringLink && findDOMNode(this.props.hoveringLink).getBoundingClientRect() this.setState({ shouldBeVisible: this.shouldBeVisible(), rect: rect, }) } shouldBeVisible = () => { return this.props.hoveringLink && this.props.isVisible } onOpen = () => { performBounceAnimation(this.portalNode, this.state.rect) this.setState({ value: this.props.hoveringLink.data.get('href') }) this.scheduleClose() } scheduleClose = () => { this.cancelScheduledClose() const id = setTimeout(this.close, this.delayToClose) this.closeTimeoutId = id } cancelScheduledClose = () => { clearTimeout(this.closeTimeoutId) } handleKeyUp = (event) => { if (keycode(event) === 'enter') { this.addLink() this.close() } } addLink = () => { const { editorState } = this.props const href = hrefAutoWrap(this.input.value) const next = editorState.change() .setNodeByKey(this.props.hoveringLink.key, { data: { href } }) .collapseToEndOf(this.props.hoveringLink) .focus() this.setState({ value: '' }) this.props.onChange(next) } onChange = (event) => { this.setState({ value: event.target.value }) } close = () => { resetBounceAnimation(this.portalNode) this.props.onBlur() } onMouseEnter = () => { this.cancelScheduledClose() } onMouseOut = () => { this.scheduleClose() } handleCleanUp = (event) => { const { hoveringLink } = this.props const { editorState } = this.props const next = editorState .change() .moveToRangeOf(hoveringLink) .unwrapInline('link') this.props.onChange(next) this.close() } onLoad = (portal) => { this.portalNode = portal.firstChild } render() { const { shouldBeVisible, value, rect, } = this.state const { editorState, onBlur, } = this.props return ( <HoveringElement editorState={editorState} onOpen={this.onOpen} onLoad={this.onLoad} shouldBeVisible={shouldBeVisible} rect={rect} className="link-input" > <input type="text" onKeyUp={this.handleKeyUp} ref={i => this.input = i} onBlur={onBlur} onChange={this.onChange} value={value} autoComplete="False" className="input" onMouseEnter={this.onMouseEnter} onMouseOut={this.onMouseOut} /> <button onMouseDown={this.handleCleanUp} className="remove" onMouseEnter={this.onMouseEnter} onMouseOut={this.onMouseOut} /> </HoveringElement> ) } } <file_sep>/typewriter/src/plugins/bold-mark.js import React from 'react' import MarkHotkey from '../helpers/mark-hotkey' export default options => { const BOLD_RENDER_RULE = { match: node => node.type == 'bold', render: props => <strong>{props.children}</strong>, } const schema = { rules: [ BOLD_RENDER_RULE, ] } const {onKeyDown} = MarkHotkey({ key: 'b', type: 'bold' }) return { schema, onKeyDown, } } <file_sep>/typewriter/src/components/contextual-toolbar/menu.js import React, { Component } from 'react' import Portal from 'react-portal' import MarkButton from './mark-button' import BlockButton from './block-button' import LinkButton from './link-button' import HoveringElement from './hovering-element' import performBounceAnimation, { resetBounceAnimation } from '../../helpers/perform-bounce-animation' export default class Menu extends Component { state = { portalNode: null, shouldBeVisible: false, rect: null } componentDidUpdate(prevProps) { this.prevSelection = prevProps.editorState.selection if (this.prevSelection !== this.props.editorState.selection) { this.updateVisibility() } } updateVisibility = () => { this.setState({ shouldBeVisible: this.shouldBeVisible(), rect: this.getSelectionRect(), }) } getSelectionRect = () => { if (window.getSelection().anchorNode) { return window.getSelection().getRangeAt(0).getBoundingClientRect() } } shouldBeVisible = () => { const { editorState } = this.props const currentSelection = editorState.selection // if menu is not ready yet if (!this.state.portalNode) return false // selection is empty if (editorState.isBlurred) return false // selection is empty if (currentSelection.isCollapsed) return false // browser loses track of selection // - pressing cmd+z while selecting text const selectionRect = this.getSelectionRect() if (selectionRect.top === 0 && selectionRect.left === 0) return false return true } onOpen = () => { this.props.onOpen && this.props.onOpen() performBounceAnimation(this.state.portalNode, this.getSelectionRect()) } onClose = () => { resetBounceAnimation(this.state.portalNode) this.props.onClose && this.props.onClose() } onLoad = (portal) => { this.setState({ portalNode: portal.firstChild }) } render() { const { shouldBeVisible, isVisible, rect, } = this.state const { editorState, onChange, marks, blocks, inlines, } = this.props return ( <HoveringElement editorState={editorState} onLoad={this.onLoad} onOpen={this.onOpen} onClose={this.onClose} shouldBeVisible={shouldBeVisible} rect={rect} className="highlight-toolbar" > {marks.map(type => <MarkButton key={type} type={type} state={editorState} onChange={onChange} /> )} {blocks.map(type => <BlockButton key={type} type={type} state={editorState} onChange={onChange} /> )} {inlines.includes('link') && <LinkButton openLinkInput={this.props.openLinkInput} /> } </HoveringElement> ) } } <file_sep>/Dockerfile FROM ruby:2.4.1 RUN apt-get update -qq && apt-get install -y -qq build-essential RUN apt-get install -y apt-transport-https # for postgres RUN apt-get install -y -qq libpq-dev # for JavaScript runtime RUN curl -sL https://deb.nodesource.com/setup_8.x | bash - RUN apt-get update && apt-get install -y nodejs # for JavaScript dependencies RUN echo "yarn" && curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - RUN echo "." && echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list RUN echo "get" && apt-get update && apt-get install -y yarn # for UTF-8 terminal RUN apt-get install -y -qq locales RUN locale-gen C.UTF-8 && /usr/sbin/update-locale LANG=C.UTF-8 RUN apt-get remove -y locales # editor for terminal RUN apt-get install -y -qq nano ENV EDITOR nano ENV LANG C.UTF-8 # Install Heroku CLI RUN wget -qO- https://cli-assets.heroku.com/install-ubuntu.sh | sh # Yarn cache ENV YARN_CACHE_FOLDER /yarn_modules/cache # Paths ENV APP_HOME /engine ENV GEM_HOME /gems RUN mkdir $APP_HOME RUN mkdir $GEM_HOME WORKDIR $APP_HOME # Cache gems locally ENV BUNDLE_PATH $GEM_HOME ENV GEM_PATH $GEM_HOME ENV GEM_CACHE $GEM_HOME/cache ENV PATH $PATH:$GEM_HOME/bin RUN gem install bundler --no-ri --no-rdoc <file_sep>/docker-compose.yml version: '2' services: postgres: image: postgres:9.5.6 engine: build: . command: bin/server ports: - 8080:3000 # puma - 3065:3065 # webpacker - 1048:1048 # Byebug # volumes: # - .:/engine # - ./gems:/gems # - ./yarn_modules:/yarn_modules depends_on: - postgres environment: - PORT=3000 <file_sep>/README.md # Typewriter Adaptable content editor for CMS creators. ## Usage How to use my plugin. ## Installation Add this lines to your application's Gemfile: ```ruby gem 'typewriter', github: 'flama/typewriter' gem 'nanofile', github: 'flama/nanofile' ``` And then execute: ```bash $ bundle ``` Add an initializer with image upload configurations: `config/initializers/typewriter.rb` ```ruby Typewriter.config_images( access_key_id: ENV['AWS_KEY_ID'], secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'], region: ENV['S3_REGION'], bucket: ENV['S3_BUCKET'], breakpoints: { small: 640, medium: 1024, large: 1440, huge: 1920 }, sizes: { small: 512 * 2, medium: 730 * 2, large: 780 * 2, huge: 1040 * 2, } ) ``` And install the migrations: ```bash $ rails typewriter:install:migrations db:migrate ``` ## License The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT). <file_sep>/typewriter/src/plugins/highlight-mark.js import React from 'react' import MarkHotkey from '../helpers/mark-hotkey' export default options => { const HIGHLIGH_RENDER_RULE = { match: node => node.type == 'highlight', render: props => <em>{props.children}</em>, } const schema = { rules: [ HIGHLIGH_RENDER_RULE, ] } const {onKeyDown} = MarkHotkey({ key: 'e', type: 'highlight' }) return { schema, onKeyDown, } } <file_sep>/typewriter/src/components/inserter/button.js import React, { Component } from 'react' import Tooltip from '../tooltip' export default (props) => { const { tool, name, onMouseEnter, } = props const button = <label className={`${name} tool`} htmlFor={`${name}-input`} onMouseEnter={onMouseEnter} /> const { tooltip } = tool.props if (tooltip) { return <Tooltip tip={tooltip}> {button} </Tooltip> } else { return button } } <file_sep>/typewriter/src/helpers/create-embed-url.js import getVideoId from 'get-video-id' export default (url) => { const video = getVideoId(url) if (typeof video === 'undefined') return false switch (video.service) { case 'youtube': return `https://youtube.com/embed/${video.id}` case 'vimeo': return `https://player.vimeo.com/video/${video.id}` default: return false } } <file_sep>/typewriter/src/plugins/strike-through-mark.js import React from 'react' import MarkHotkey from '../helpers/mark-hotkey' export default options => { const STRIKE_THROUGH_RENDER_RULE = { match: node => node.type == 'strikethrough', render: props => <del>{props.children}</del>, } const schema = { rules: [ STRIKE_THROUGH_RENDER_RULE, ] } const {onKeyDown} = MarkHotkey({ key: 'd', type: 'strikethrough' }) return { schema, onKeyDown, } } <file_sep>/app/models/typewriter/image_upload.rb module Typewriter class ImageUpload < ApplicationRecord has_image :image, sizes: Typewriter.image_sizes end end <file_sep>/lib/typewriter/engine.rb module Typewriter class Engine < ::Rails::Engine isolate_namespace Typewriter end end <file_sep>/typewriter/src/components/inserter/index.js import React, { Component } from 'react' import { findDOMNode } from 'slate-react' import Button from './button' export default class Inserter extends Component { state = { position: 0, isOpen: false, currentTool: false, } inserterLifespan = 2000 nodeVariantsBy = {} inputs = {} triggers = [ 'blockquote', 'ul', 'ol', 'li', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'paragraph', ] componentWillMount() { this.triggers.forEach((trigger) => { global.addEventListener(`${trigger}:mouseenter`, this.updateNode, false) global.addEventListener(`${trigger}:mouseover`, this.show, false) }) } componentWillUnmount() { clearTimeout(this.state.inserterTimeoutId) this.triggers.forEach((trigger) => { global.removeEventListener(`${trigger}:mouseenter`, this.updateNode, false) global.removeEventListener(`${trigger}:mouseover`, this.show, false) }) } updateNode = (event) => { const { node } = event.detail this.setState((prevState) => { let nextState = {node} if (node !== prevState.node && !prevState.isOpen) { this.currentNode = findDOMNode(node) } // don't update position while open if (!prevState.isOpen) { nextState = {...nextState, position: this.currentNode.offsetTop } } // re-enable animations next time it will be visible if (prevState.isVisible) { this.disableAnimation = false } return nextState }) } hide = () => { this.setState({ isVisible: false }) } isCurrentBlockEmpty = () => { const { editorState } = this.props return editorState.startBlock && editorState.startBlock.type === 'paragraph' && editorState.startBlock.text === '' } show = () => { // if (this.isCurrentBlockEmpty()) return clearTimeout(this.state.inserterTimeoutId) this.setState({ isVisible: true, inserterTimeoutId: setTimeout(this.hide, this.inserterLifespan) }) } toggle = () => { if (this.state.isOpen) { this.close() } else { this.open() } } open = () => { if (this.currentNode) { this.currentNode.classList.add('-with-menu-open') } this.setState({ isOpen: true }) } close = () => { this.setState( { isOpen: false }, this.currentNode && this.currentNode.classList.remove('-with-menu-open') ) this.clearPlaceholder() } closeWithoutAnimation = () => { this.disableAnimation = true this.close() } isOpenVariant = () => { return this.state.isOpen ? '-open' : '' } isVisibleVariant = () => { return this.isVisible() ? '-visible' : '' } placeholderVariant = () => { const { currentTool } = this.state if (currentTool) { const toolName = this.nameFrom(currentTool) return this.nodeVariantsBy[toolName] } return '' } isVisible = () => { const { isVisible, isHovering, } = this.state return isVisible || isHovering } handleMouseEnter = () => { this.setState({ isHovering: true }) } handleMouseLeave = () => { this.setState({ isHovering: false }) } focusPlaceholderInput = () => { const { currentTool } = this.state if (this.getInputBy(currentTool)) { this.getInputBy(currentTool).focus() } } getInputBy = (tool) => { return this.inputs[tool.type.name] } showPlaceholderFor = (tool) => { return (event) => { this.clearPlaceholder() if (this.currentNode) { const toolName = this.nameFrom(tool) this.currentNode.classList.add(this.nodeVariantsBy[toolName]) } this.setState({ currentTool: tool }, this.focusPlaceholderInput) } } clearPlaceholder = () => { this.tools.forEach(tool => { if (this.currentNode) { const toolName = this.nameFrom(tool) this.currentNode.classList.remove(this.nodeVariantsBy[toolName]) } }) this.setState({ currentTool: false }) } onMount = (tool, input) => { this.inputs[tool.type.name] = input } extractNodeVariantFrom = (tool) => { const toolName = this.nameFrom(tool) const nodeVariant = tool.props.nodeVariant || `-with-${toolName}` this.nodeVariantsBy[toolName] = nodeVariant } nameFrom = (tool) => { return tool.props.buttonClass || tool.type.name.toLowerCase() } render() { const { editorState, onChange, } = this.props const { node, } = this.state this.nodeVariantsBy = {} this.tools = React.Children.map(this.props.children, (child) => { this.extractNodeVariantFrom(child) return React.cloneElement(child, { node, onChange, editorState, close: this.close, onMount: input => this.onMount(child, input), }) }) || [] return ( <div className={`inserter-menu ${this.isOpenVariant()} ${this.isVisibleVariant()}`} style={{ top: `${this.state.position}px` }} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} > <div className="toggle" onClick={this.toggle} style={this.disableAnimation ? { transition: 'none', opacity: 0 } : {}} /> <div className="content"> <div className="menu"> { this.tools.map(tool => { return <Button tool={tool} name={this.nameFrom(tool)} key={this.nameFrom(tool)} onMouseEnter={this.showPlaceholderFor(tool)} /> }) } </div> <div className={`placeholder ${this.placeholderVariant()}`}> {this.tools} </div> </div> </div> ) } } <file_sep>/typewriter/src/helpers/href-auto-wrap.js export default (href) => { const hrefHasHttp = ~href.search(/^https?:\/\//i) return hrefHasHttp ? href : `http://${href}` } <file_sep>/typewriter/stories/embed.js import React from 'react' import { storiesOf } from '@storybook/react' import { action } from '@storybook/addon-actions' import { RichText, Embed, EmbedsToolbar, } from '../src' const multiple = JSON.stringify({ document: { nodes: [{ kind: 'block', type: 'heading-two', nodes: [{ kind: 'text', leaves: [{ text: 'A heading' }] }] }, { kind: 'block', type: 'paragraph', nodes: [{ kind: 'text', leaves: [{ text: 'Nam te purto deserunt, sed suavitate democritum cotidieque ut. Has case eius maiorum cu. Has id liber adolescens, ex per omnes causae aeterno, tation eirmod pro in. An nobis scripta epicurei nam, eu purto corrumpit eum, ex probatus tacimates invenire ius. Ad molestie assentior reprimique per, legendos expetendis efficiantur ad sed. Id omnium percipit petentium nec.' }] }] }, { kind: 'block', type: 'heading-three', nodes: [{ kind: 'text', leaves: [{ text: 'A subheading' }] }] }, { kind: 'block', type: 'paragraph', nodes: [{ kind: 'text', leaves: [{ text: 'Nam te purto deserunt, sed suavitate democritum cotidieque ut. Has case eius maiorum cu. Has id liber adolescens, ex per omnes causae aeterno, tation eirmod pro in. An nobis scripta epicurei nam, eu purto corrumpit eum, ex probatus tacimates invenire ius. Ad molestie assentior reprimique per, legendos expetendis efficiantur ad sed. Id omnium percipit petentium nec.' }] }] }] } }) storiesOf('Embed', module) .add('with tooltip', () => <RichText content={multiple}> <EmbedsToolbar> <Embed tooltip='Embutir código' placeholder='Cole aqui o código a ser embutido' /> </EmbedsToolbar> </RichText> ) <file_sep>/typewriter/src/plugins/underline-mark.js import React from 'react' import MarkHotkey from '../helpers/mark-hotkey' export default options => { const UNDERLINE_RENDER_RULE = { match: node => node.type == 'underline', render: props => <u>{props.children}</u>, } const schema = { rules: [ UNDERLINE_RENDER_RULE, ] } const {onKeyDown} = MarkHotkey({ key: 'u', type: 'underline' }) return { schema, onKeyDown, } } <file_sep>/config/initializers/active_record.rb ActiveRecord::Base.send(:include, Typewriter::Editable) <file_sep>/test/typewriter_test.rb require 'test_helper' class Typewriter::Test < ActiveSupport::TestCase test "truth" do assert_kind_of Module, Typewriter end end <file_sep>/typewriter/src/plugins/link.js import React from 'react' import Link from '../components/link' export default options => { const schema = { nodes: { link: props => <Link {...props} />, } } return { schema, } } <file_sep>/typewriter/stories/plain-text.js import React from 'react' import { storiesOf } from '@storybook/react' import { action } from '@storybook/addon-actions' import { PlainText } from '../src' const h1 = (attrs, text) => <h1 className="title" {...attrs}> {text} </h1> const plain = (text) => JSON.stringify({ document: { nodes: [ { kind: 'block', type: 'phrase', nodes: [ { kind: 'text', leaves: [{ text: text }] } ] } ] } }) storiesOf('PlainText', module) .add('empty', () => <PlainText renderAs={h1} onChange={action('title changed')} /> ) .add('with placeholder', () => <PlainText placeholder="Clique aqui para dar um título" renderAs={h1} onChange={action('title changed')} /> ) .add('with content', () => <PlainText content={plain("Um título de exemplo")} placeholder="Clique aqui para dar um título" renderAs={h1} onChange={action('title changed')} /> ) <file_sep>/test/dummy/app/helpers/application_helper.rb module ApplicationHelper def ensure_default(title) return title if title.present? 'Untitled' end end <file_sep>/typewriter/src/components/embeds-toolbar.js import React, { Component } from 'react' import Button from './inserter/button' export default class EmbedsToolbar extends Component { state = { currentTool: null, } nodeVariantsBy = {} nameFrom = (tool) => { return tool.props.buttonClass || tool.type.name.toLowerCase() } placeholderVariant = () => { const { currentTool } = this.state if (currentTool) { const toolName = this.nameFrom(currentTool) return this.nodeVariantsBy[toolName] } return '' } showPlaceholderFor = (tool) => { return (event) => { this.clearPlaceholder() if (this.currentNode) { const toolName = this.nameFrom(tool) this.currentNode.classList.add(this.nodeVariantsBy[toolName]) } this.setState({ currentTool: tool }, this.focusPlaceholderInput) } } clearPlaceholder = () => { this.tools.forEach(tool => { if (this.currentNode) { const toolName = this.nameFrom(tool) this.currentNode.classList.remove(this.nodeVariantsBy[toolName]) } }) this.setState({ currentTool: false }) } extractNodeVariantFrom = (tool) => { const toolName = this.nameFrom(tool) const nodeVariant = tool.props.nodeVariant || `-with-${toolName}` this.nodeVariantsBy[toolName] = nodeVariant } close = () => { this.clearPlaceholder() } render() { const { editorState, onChange, } = this.props this.tools = React.Children.map(this.props.children, (child) => { this.extractNodeVariantFrom(child) return React.cloneElement(child, { onChange, editorState, close: this.close, }) }) || [] return ( <div className="embeds-toolbar"> <div className="content"> <div className="menu"> { this.tools.map(tool => { return <Button tool={tool} name={this.nameFrom(tool)} key={this.nameFrom(tool)} onMouseEnter={this.showPlaceholderFor(tool)} /> }) } </div> <div className={`placeholder ${this.placeholderVariant()}`}> {this.tools} </div> </div> </div> ) } } <file_sep>/typewriter/stories/inserter.js import React from 'react' import { storiesOf } from '@storybook/react' import { action } from '@storybook/addon-actions' import { RichText, Inserter, Video, Embed, Image } from '../src' const multiple = JSON.stringify({ document: { nodes: [{ kind: 'block', type: 'heading-two', nodes: [{ kind: 'text', leaves: [{ text: 'A heading' }] }] }, { kind: 'block', type: 'paragraph', nodes: [{ kind: 'text', leaves: [{ text: 'Nam te purto deserunt, sed suavitate democritum cotidieque ut. Has case eius maiorum cu. Has id liber adolescens, ex per omnes causae aeterno, tation eirmod pro in. An nobis scripta epicurei nam, eu purto corrumpit eum, ex probatus tacimates invenire ius. Ad molestie assentior reprimique per, legendos expetendis efficiantur ad sed. Id omnium percipit petentium nec.' }] }] }, { kind: 'block', type: 'heading-three', nodes: [{ kind: 'text', leaves: [{ text: 'A subheading' }] }] }, { kind: 'block', type: 'paragraph', nodes: [{ kind: 'text', leaves: [{ text: 'Nam te purto deserunt, sed suavitate democritum cotidieque ut. Has case eius maiorum cu. Has id liber adolescens, ex per omnes causae aeterno, tation eirmod pro in. An nobis scripta epicurei nam, eu purto corrumpit eum, ex probatus tacimates invenire ius. Ad molestie assentior reprimique per, legendos expetendis efficiantur ad sed. Id omnium percipit petentium nec.' }] }] }] } }) storiesOf('Inserter', module) .add('empty', () => <RichText content=''> <Inserter /> </RichText> ) .add('complete', () => <RichText content={multiple}> <Inserter> <Video tooltip='Adicionar Vídeo' placeholder='Cole aqui o link do seu vídeo no Youtube e clique em Enter' /> <Embed tooltip='Embutir código' placeholder='Cole aqui o código a ser embutido' /> <Image tooltip='Adicionar Imagem' presignPath='/' fetchPath='/' promotePath='/uploads/promote' captions={{ subtitle: 'Clique para inserir uma legenda', author: 'Clique para incluir créditos para a imagem', }} > Arraste e solte ou <span className="linklike">selecione seus arquivos</span> </Image> </Inserter> </RichText> ) .add('with empty body', () => <RichText content={null}> <Inserter> <Video tooltip='Adicionar Vídeo' placeholder='Cole aqui o link do seu vídeo no Youtube e clique em Enter' /> <Embed tooltip='Embutir código' placeholder='Cole aqui o código a ser embutido' /> </Inserter> </RichText> ) <file_sep>/test/dummy/config/initializers/typewriter.rb Typewriter.config_images( access_key_id:ENV['AWS_KEY_ID'], secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'], region: "sa-east-1", bucket: "nanofile-temp-uploads", breakpoints: { small: 640, medium: 1024, large: 1440, huge: 1920 }, sizes: { small: 512 * 2, medium: 730 * 2, large: 780 * 2, } ) <file_sep>/typewriter/src/plugins/markdown-block.js import React from 'react' import keycode from 'keycode' const wrapWithElement = (Element, options) => { const dispatchCustomEvent = (eventName, detail) => { const event = new CustomEvent(eventName, { detail: detail }) global.dispatchEvent(event) } return props => ( <Element onMouseEnter={ () => dispatchCustomEvent(`${Element}:mouseenter`, { node: props.node }) } onMouseOver={ () => dispatchCustomEvent(`${Element}:mouseover`, { node: props.node }) } {...props.attributes} > {props.children} </Element> ) } export default (options = {}) => { const schema = { nodes: { 'block-quote': wrapWithElement('blockquote', options), 'bulleted-list': wrapWithElement('ul', {...options, className: 'article-list'}), 'numbered-list': wrapWithElement('ol', {...options, className: 'article-list -numbered'}), 'list-item': wrapWithElement('li', {className: 'item'}), 'heading-one': wrapWithElement('h1', options), 'heading-two': wrapWithElement('h2', options), 'heading-three': wrapWithElement('h3', options), 'heading-four': wrapWithElement('h4', options), 'heading-five': wrapWithElement('h5', options), 'heading-six': wrapWithElement('h6', options), } } const TYPES = { '*': 'bulleted-list', '-': 'bulleted-list', '+': 'bulleted-list', '1.': 'numbered-list', '1-': 'numbered-list', '>': 'block-quote', '#': 'heading-one', '##': 'heading-two', '###': 'heading-three', '####': 'heading-four', '#####': 'heading-five', '######': 'heading-six', } const onKeyDown = (event, data, state) => { switch(keycode(event.which)) { case 'space': return onSpace(event, state) case 'backspace': return onBackspace(event, state) case 'enter': return onEnter(event, state) } } const isList = (type) => { return type === 'bulleted-list' || type === 'numbered-list' || type === 'list-item' } const onSpace = (event, change) => { const { state } = change if (state.isExpanded) return const { startBlock, startOffset } = state const match = startBlock.text.slice(0, startOffset).replace(/\s*/g, '') const type = TYPES[match] if (!type) return if (isList(type) && isList(startBlock.type)) return event.preventDefault() if (!isList(type)) { change.setBlock(type) } else { change.setBlock('list-item') change.wrapBlock(type) } change .extendToStartOf(startBlock) .delete() return true } const onBackspace = (event, change) => { const { state } = change if (state.isExpanded) return if (state.startOffset !== 0) return const { startBlock } = state if (startBlock.type === 'paragraph') return event.preventDefault() let next = change.setBlock('paragraph') if (isList(startBlock.type)) { change.unwrapBlock(startBlock.type) change.unwrapBlock('bulleted-list') change.unwrapBlock('numbered-list') } return true } const onEnter = (event, change) => { const { state } = change if (state.isExpanded) return const { startBlock, startOffset, endOffset } = state if (startOffset === 0 && startBlock.text.length === 0) { return onBackspace(event, change) } if (!Object.values(TYPES).includes(startBlock.type)) return event.preventDefault() change.splitBlock() if (startBlock.type === 'list-item') { change.setBlock('list-item') } else { change.setBlock('paragraph') } return true } return { schema, onKeyDown, } } <file_sep>/typewriter/src/components/link.js import React, { Component } from 'react' import keycode from 'keycode' import hrefAutoWrap from '../helpers/href-auto-wrap' export default class Link extends Component { onMouseEnter = (event) => { this.stillHovering = true setTimeout(() => { if (this.stillHovering) { global.dispatchEvent(new CustomEvent('link:mouseenter', { detail: { node: this.props.node } })) } }, 500) } onMouseLeave = (event) => { this.stillHovering = false } render() { return ( <a {...this.props.attributes} href={this.props.node.data.get('href')} onMouseEnter={this.onMouseEnter} onMouseLeave={this.onMouseLeave} > {this.props.children} </a> ) } } <file_sep>/typewriter/src/components/contextual-toolbar/link-input.js import React, { Component } from 'react' import keycode from 'keycode' import Portal from 'react-portal' import HoveringElement from './hovering-element' import hrefAutoWrap from '../../helpers/href-auto-wrap' export default class LinkInput extends Component { state = { value: '', rect: null, shouldBeVisible: false, } componentDidUpdate(prevProps, prevState) { if (this.state.shouldBeVisible && prevProps.isVisible !== this.props.isVisible) { this.updateVisibility() } this.prevSelection = prevProps.editorState.selection if (this.prevSelection !== this.props.editorState.selection) { this.updateVisibility() } } updateVisibility = () => { this.setState({ shouldBeVisible: this.shouldBeVisible(), rect: this.getSelectionRect() }) } getSelectionRect = () => { if (window.getSelection().anchorNode) { return window.getSelection().getRangeAt(0).getBoundingClientRect() } } shouldBeVisible = () => { return this.props.isVisible } onOpen = () => { setTimeout(() => this.input.focus(), 0) } handleKeyUp = (event) => { if (keycode(event) === 'enter') { this.addLink() } if (keycode(event) === 'enter' || keycode(event) === 'esc') { this.cleanUp() this.props.onBlur() } } cleanUp = () => { this.setState({ value: '' }) } addLink = () => { const { editorState } = this.props const href = hrefAutoWrap(this.input.value) const next = editorState .change() .unwrapInline('link') .wrapInline({ type: 'link', data: { href }, }) .collapseToEnd() .focus() this.props.onChange(next) } onChange = (event) => { this.setState({ value: event.target.value }) } render() { const { shouldBeVisible, value, rect, } = this.state const { editorState } = this.props return ( <HoveringElement editorState={editorState} onOpen={this.onOpen} shouldBeVisible={shouldBeVisible} rect={rect} className="link-input" > <input type="text" value={value} className="input" autoComplete="False" onChange={this.onChange} onBlur={this.props.onBlur} onKeyUp={this.handleKeyUp} ref={i => this.input = i} /> </HoveringElement> ) } } <file_sep>/test/dummy/app/javascript/packs/application.js import spawn from '../helpers/Spawner' import ArticleEditor from '../components/article-editor' spawn({ ArticleEditor }) <file_sep>/typewriter/src/helpers/perform-bounce-animation.js export default (node, boundingBox) => { const numOfTicks = 25 const distance = 10 let currentTick = 0 let positionY = 0 const setNodeStyle = ({ positionY, positionZ }) => { node.style.transform = `translate3d(0, ${positionY}px, ${positionZ}px)` } const nodeHasPositionY = (positionY) => { return ~node.style.transform.search(`^translate3d.0px, -${positionY}`) } const animateUpCallback = () => { if (currentTick >= numOfTicks) return currentTick += 1 positionY += -distance / numOfTicks const positionZ = -positionY / distance setNodeStyle({ positionY, positionZ }) setTimeout(animateUpCallback, 1) } const animateDownCallback = () => { if (currentTick >= numOfTicks) return currentTick += 1 positionY += distance / numOfTicks const positionZ = positionY / distance setNodeStyle({ positionY, positionZ }) setTimeout(animateDownCallback, 1) } const isNearTopOfScreen = () => { return boundingBox.top < 50 } if (isNearTopOfScreen()) { const finalPosition = boundingBox.height + node.offsetHeight - distance // If already showing, don't animate if (nodeHasPositionY(finalPosition)) return positionY = finalPosition animateDownCallback() } else { const finalPosition = distance / 2 // If already showing, don't animate if (nodeHasPositionY(finalPosition)) return positionY = finalPosition animateUpCallback() } } export function resetBounceAnimation(node) { node.style.transform = '' } <file_sep>/typewriter/src/plugins/image.js import React from 'react' import Image from '../components/image' export default (options = {}) => { const { attributes, } = options const schema = { nodes: { 'image': (props => <Image {...attributes} {...props} />), } } return { schema, } } <file_sep>/app/controllers/typewriter/image_uploads_controller.rb class Typewriter::ImageUploadsController < ApplicationController skip_before_action :verify_authenticity_token def create render json: Typewriter::ImageUpload.create!(image_params).to_json end def show upload = Typewriter::ImageUpload.find(params[:id]) render json: { src: upload.image_src, srcset: upload.image_srcset } end private def image_params params.permit(:image) end end <file_sep>/test/dummy/app/javascript/helpers/Spawner.js import React from 'react' import ReactDOM from 'react-dom' import merge from 'lodash/merge' import mapValues from 'lodash/mapValues' // To spawn an <Example /> react component: // <div data-component="Example"></div> // To spawn an Example behavior: // <div data-behavior="Example"></div> const tryAsJson = (thing) => { try { let result = JSON.parse(thing) // Handle non-exception-throwing cases: // Neither JSON.parse(false) or JSON.parse(1234) throw errors, hence the type-checking, // but... JSON.parse(null) returns null, and typeof null === "object", // so we must check for that, too. Thankfully, null is falsey, so this suffices: if (result && typeof result === 'object') { return result } } catch (e) { } return thing } export default function (componentList = {}, behaviorsList = {}) { document.addEventListener('DOMContentLoaded', () => { const components = document.querySelectorAll('[data-component]') components.forEach(component => { const ComponentClass = componentList[component.dataset.component] if (typeof ComponentClass !== 'undefined') { let attributes = mapValues(component.dataset, (value) => tryAsJson(value)) let element = React.createElement( ComponentClass, merge(attributes, { children: component.innerHTML.trim() })) ReactDOM.render(element, component) } else { console.error(`${component.dataset.component} is undefined`) } }) const behaviors = document.querySelectorAll('[data-behavior]') behaviors.forEach(behavior => { try { const BehaviorClass = behaviorsList[behavior.dataset.behavior] new BehaviorClass(behavior, window, document) } catch (e) { console.error(`${behavior.dataset.behavior} is undefined`) } }) }) } <file_sep>/typewriter/src/components/tooltip.js import React from 'react' import RcTooltip from 'rc-tooltip' export default (props) => { return ( <RcTooltip trigger={['hover']} mouseEnterDelay={.3} mouseLeaveDelay={0} destroyTooltipOnHide={true} placement="top" overlay={ props.tip || '' } transitionName="" > { props.children } </RcTooltip> ) } <file_sep>/typewriter.gemspec $:.push File.expand_path('../lib', __FILE__) # Maintain your gem's version: require 'typewriter/version' # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = 'typewriter' s.version = Typewriter::VERSION s.authors = ['<NAME>'] s.email = ['<EMAIL>'] s.homepage = 'https://flama.is' s.summary = 'Adaptable content editor for CMS creators.' s.description = 'Simple yet powerful content editor for people who build their own CMS.' s.license = 'MIT' s.files = Dir['{app,config,db,lib}/**/*', 'MIT-LICENSE', 'Rakefile', 'README.md'] s.add_dependency 'rails', '~> 5.2.0' s.add_development_dependency 'sqlite3' s.add_development_dependency 'byebug', '~> 9.1' s.add_development_dependency 'webpacker', '3.0.1' s.add_development_dependency 'sass-rails', '~> 5.0', '>= 5.0.6' end <file_sep>/typewriter/src/index.js import PlainText from './components/plain-text' import RichText from './components/rich-text' import ContextualToolbar from './components/contextual-toolbar/' import Inserter from './components/inserter/' import Video from './components/inserter/video' import Embed from './components/inserter/embed' import Image from './components/inserter/image' import EmbedsToolbar from './components/embeds-toolbar' export default { PlainText, RichText, ContextualToolbar, Inserter, Video, Embed, Image, EmbedsToolbar, } export { PlainText, RichText, ContextualToolbar, Inserter, Video, Embed, Image, EmbedsToolbar, } <file_sep>/typewriter/src/components/contextual-toolbar/index.js import React, { Component } from 'react' import Menu from './menu' import LinkInput from './link-input' import LinkInputEdit from './link-input-edit' export default class ContextualToolbar extends Component { state = { isSelectionMenuOpen: false, shouldLinkInputBeVisible: false, shouldLinkInputEditBeVisible: false, } componentWillMount() { global.addEventListener('link:mouseenter', this.handleLinkMouseEnter, false) } componentWillUnmount() { global.removeEventListener('link:mouseenter', this.handleLinkMouseEnter, false) } onSelectionMenuOpen = () => { this.setState({isSelectionMenuOpen: true}) } onSelectionMenuClose = () => { this.setState({isSelectionMenuOpen: false}) } handleOpenLinkInput = (event) => { this.setState({ shouldLinkInputBeVisible: true }) } handleCloseLinkInput = (event) => { this.setState({ shouldLinkInputBeVisible: false }) } handleCloseLinkInputEdit = (event) => { this.setState({ hoveringLink: null, shouldLinkInputEditBeVisible: false }) } handleLinkMouseEnter = (event) => { if (this.state.isSelectionMenuOpen) return this.setState({ hoveringLink: event.detail.node, shouldLinkInputEditBeVisible: true }) } render() { const { marks, blocks, editorState, onChange, } = this.props const { shouldLinkInputBeVisible, shouldLinkInputEditBeVisible, isSelectionMenuOpen, hoveringLink, } = this.state return (<div> <Menu {...this.props} onOpen={this.onSelectionMenuOpen} onClose={this.onSelectionMenuClose} openLinkInput={this.handleOpenLinkInput} /> <LinkInput editorState={editorState} onChange={onChange} isVisible={shouldLinkInputBeVisible} onBlur={this.handleCloseLinkInput} /> <LinkInputEdit editorState={editorState} onChange={onChange} onBlur={this.handleCloseLinkInputEdit} isVisible={shouldLinkInputEditBeVisible} hoveringLink={hoveringLink} isSelectionMenuOpen={isSelectionMenuOpen} /> </div>) } } ContextualToolbar.defaultProps = { marks: [], blocks: [], inlines: [], } <file_sep>/typewriter/src/components/inserter/image.js import React, { Component } from 'react' export default class Image extends Component { componentDidMount() { this.props.onMount && this.props.onMount(this.input) } handleChange = (event) => { event.preventDefault() const file = event.target.files[0] this.props.close() this.appendImage(file) } appendImage = (file) => { const { editorState, node } = this.props const next = editorState.change() if (node) { next.collapseToStartOf(node) } next.insertBlock({ type: 'image', data: { file }, isVoid: true, }) .collapseToEnd() .focus() this.props.onChange(next) } render() { const { children } = this.props return ( <label className="image droparea" htmlFor="image-upload-editor"> {children} <input id="image-upload-editor" type="file" onChange={this.handleChange} style={{ height: 0, position: 'absolute', overflow: 'hidden' }} accept="image/*" ref={i => this.input = i} /> </label> ) } } <file_sep>/config/routes.rb Typewriter::Engine.routes.draw do resources :image_uploads mount Nanofile::Engine => '/nanofile', as: :typewriter_nanofile end <file_sep>/typewriter/src/helpers/mark-inline-shortcut.js export default (options = {}) => { const { regex, type } = options return { onKeyDown(event, data, change) { const { startBlock } = change.state const chars = startBlock.text const match = regex.exec(chars) if(!match) return const start = match.index const end = start + match[1].length const markdownToken = match[0].slice(0, match[0].indexOf(match[1])) event.preventDefault() return change .moveOffsetsTo(start, start + markdownToken.length) .delete() .moveOffsetsTo(end, end + markdownToken.length) .delete() .moveOffsetsTo(start, end) .toggleMark(type) .moveOffsetsTo(end, end) } } } <file_sep>/typewriter/src/helpers/mark-hotkey.js import keycode from 'keycode' export default options => { // Change the options to take a `key`. const { type, key, isAltKey = false } = options return { onKeyDown(event, data, change) { // Change the comparison to use the key name. if (!event.metaKey || keycode(event.which) != key || event.altKey != isAltKey) return event.preventDefault() return change.toggleMark(type) } } } <file_sep>/test/dummy/app/javascript/components/article-editor/index.js import React, { Component } from 'react' import { PlainText, RichText, ContextualToolbar, Inserter, Video, Embed, Image, } from 'typewriter' import './style.scss' export default class ArticleEditor extends Component { state = this.props.article renderTitleAs = (attrs, text) => <h1 className="title" {...attrs}>{text}</h1> onTitleChange = (title) => { this.setState({ title }) } onBodyChange = (body) => { this.setState({ body }) } render() { const { title, body, } = this.state const { presignFrom, uploadTo, } = this.props return ( <div className="article-editor"> <PlainText content={title} placeholder="Título do artigo" renderAs={this.renderTitleAs} onChange={this.onTitleChange} /> <RichText content={body} placeholder="Escreva seu artigo aqui" onChange={this.onBodyChange} presignFrom={presignFrom} uploadTo={uploadTo} captions={{ comment: 'Comment', photographer: 'Photographer' }} > <ContextualToolbar marks={[ 'bold', 'italic', ]} inlines={[ 'link' ]} blocks={[ 'heading-two', 'heading-three', 'bulleted-list', 'numbered-list', ]} /> <Inserter> <Video tooltip='Adicionar Vídeo' placeholder='Cole aqui o link do seu vídeo no Youtube e clique em Enter' /> <Embed tooltip='Embutir código' placeholder='Cole aqui o código a ser embutido' /> <Image tooltip='Adicionar Imagem' captions={{ subtitle: 'Clique para inserir uma legenda', author: 'Clique para incluir créditos para a imagem', }} > Arraste e solte ou <span className="linklike">selecione seus arquivos</span> </Image> </Inserter> </RichText> <input type="hidden" name="article[title]" value={title || ''} /> <input type="hidden" name="article[body]" value={body || ''} /> </div> ) } } <file_sep>/app/models/concerns/typewriter/editable.rb module Typewriter::Editable extend ActiveSupport::Concern class Block include ActionView::Helpers::TagHelper include ActionView::Helpers::TextHelper include ActionView::Context def self.parser_for(block) block_type_class = BLOCK_TYPES[block['type']] throw "Unknown Block Type `#{block['type']}`" unless block_type_class block_type_class.new(block) end def initialize(block) @block = block end def text children(parsed_as: :text) end def html throw :unknow_block_type end private def children(parsed_as: :html) child_nodes.map(&parsed_as).join end def child_nodes if @block['isVoid'] [] else @child_nodes ||= @block['nodes'].map do |node| if node['kind'] == 'block' Block.parser_for(node) elsif node['kind'] == 'inline' Inline.parser_for(node) else TextNode.new(node) end end end end end class Inline < Block def self.parser_for(inline) inline_type_class = INLINE_TYPES[inline['type']] throw "Unknown Inline Type `#{inline['type']}`" unless inline_type_class inline_type_class.new(inline) end end class Link < Inline def html tag.a href: @block['data']['href'], target: '_blank' do raw(children) end end end INLINE_TYPES = { 'link' => Link } class BlockQuote < Block def html tag.blockquote(raw(children)) end end class BulletedList < Block def html tag.ul(raw(children)) end end class NumberedList < Block def html tag.ol(raw(children)) end end class ListItem < Block def html tag.li(raw(children)) end end class HeadingOne < Block def html tag.h1(raw(children)) end end class HeadingTwo < Block def html tag.h2(raw(children)) end end class HeadingThree < Block def html tag.h3(raw(children)) end end class HeadingFour < Block def html tag.h4(raw(children)) end end class HeadingFive < Block def html tag.h5(raw(children)) end end class HeadingSix < Block def html tag.h6(raw(children)) end end class Paragraph < Block def html tag.p(raw(children)) end end class Phrase < Block def html raw(children) end end class Video < Block def html return '' unless @block['data']['video'].present? # remove related videos at the end video_url = @block['data']['video'] + '?rel=0&amp;showinfo=0' tag.div class: 'video' do tag.iframe src: video_url, frameborder: '0', webkitallowfullscreen: true, mozallowfullscreen: true, allowfullscreen: true end end end class Embed < Block def html return '' unless @block['data']['content'].present? tag.div class: 'embed' do raw(@block['data']['content']) end end end class Image < Block def html return '' unless @block['data']['id'].present? id = @block['data']['id'] upload = Typewriter::ImageUpload.find(id) src = upload.image_src srcset = upload.image_srcset caption_list = @block['data'].select do |key, value| ['id', 'file'].exclude?(key) end.to_h tag.figure class: 'article-image' do tag.div class: 'container' do concat image(src, srcset) concat captions(caption_list) end end end private def image(src, srcset) tag.div class: 'image' do tag.img src: src, srcset: srcset end end def captions(list) tag.figcaption class: 'info' do raw(list.map do |label, caption| raw tag.div(caption, class: label) end.join) end end end BLOCK_TYPES = { 'block-quote' => BlockQuote, 'bulleted-list' => BulletedList, 'numbered-list' => NumberedList, 'list-item' => ListItem, 'heading-one' => HeadingOne, 'heading-two' => HeadingTwo, 'heading-three' => HeadingThree, 'heading-four' => HeadingFour, 'heading-five' => HeadingFive, 'heading-six' => HeadingSix, 'paragraph' => Paragraph, 'video' => Video, 'embed' => Embed, 'image' => Image, 'phrase' => Phrase, } class TextNode def initialize(node) @node = node end def text return @node['text'] if flat? leaves.map(&:text).join end def html return @node['text'] if flat? leaves.map(&:html).join end private def flat? [email protected]?('leaves') end def leaves return [] if flat? @leaves ||= @node['leaves'].map{ |leaf| Leaf.new(leaf) } end end class Leaf include ActionView::Helpers::TagHelper MARKS = { 'bold' => 'strong', 'italic' => 'i', 'strikethrough' => 'del', 'highlight' => 'em', 'code' => 'code', } def initialize(leaf) @leaf = leaf end def text @leaf['text'] end def html return text unless marks.any? add_marks(text, marks) end private def marks return [] if flat? @leaf['marks'] end def flat? [email protected]?('marks') end def add_marks(text, marks) a_mark, *remaining_marks = marks tag_name = MARKS[a_mark['type']] if remaining_marks.empty? content_tag(tag_name, text) else content_tag(tag_name, raw(add_marks(text, remaining_marks))) end end end class Blocks def initialize(content) @content = content end def as_html blocks .map(&:html) .join("\n") .html_safe end def as_words blocks .map(&:text) .join .split(' ') end def blocks nodes.map do |block| Block.parser_for(block) end end def nodes return [] unless @content.present? JSON.parse(@content)['document']['nodes'] end end class EditableAttribute delegate :empty?, :present?, :blank?, to: :to_s def initialize(attr_name, raw_value) @attr_name, @raw_value = attr_name, raw_value end def as_json(options = {}) @raw_value end def to_s to_html end def to_html Blocks.new(@raw_value).as_html end def to_words Blocks.new(@raw_value).as_words end def raw @raw_value end end class_methods do def has_editable(*attributes) attributes.each do |attribute| # @article.body # => <html> # @article.body.raw # {json} define_method(attribute) do EditableAttribute.new(attribute, read_attribute(attribute)) end end end end end <file_sep>/test/dummy/app/models/article.rb class Article < ApplicationRecord has_editable :title, :body # TODO: Implement breakpoints for image # has_editable :title, body: { # image: { small: 500, medium: 800 } # } end <file_sep>/typewriter/src/components/image.js import React, { Component } from 'react' import ImageCaption from './image-caption' export default class Image extends Component { state = { src: false, srcset: null, } getData = (_) => this.props.node.data.get(_) componentWillMount() { if (!this.isValid()) { return this.implode() } if (this.shouldFetchImage()) { this.fetchAndRenderImage() } else { this.uploadAndPreviewImage() } } implode = () => { const { node, state, editor } = this.props const change = state.change() .removeNodeByKey(node.key) editor.onChange(change) } shouldFetchImage = () => { return !!this.getData('id') } fetchAndRenderImage = () => { let { uploadTo } = this.props const id = this.getData('id') if (/\/$/.test(uploadTo)) { uploadTo = fetchPath.slice(0, -1) } fetch(`${uploadTo}/${id}`) .then(r => r.json()) .then(response => { const { src, srcset } = response this.setState({src, srcset}) }) } uploadAndPreviewImage = () => { const file = this.getData('file') this.preview(file) this.upload(file) } isValid = () => { return this.hasValidFile() || this.getData('id') } hasValidFile = () => { const file = this.getData('file') return file && !this.isEmpty(file) } isEmpty = (object) => { return object.constructor === Object && Object.keys(object).length === 0 } upload = (file) => { const { presignFrom, uploadTo } = this.props if (!presignFrom) return fetch(presignFrom, { credentials: 'same-origin', headers: { Accept: 'application/json', } }) .then(r => r.json()) .then((presign) => { let formData = new FormData() Object.keys(presign.fields).forEach(key => { formData.append(key, presign.fields[key]) }) formData.append('file', file) const fileName = presign.fields.key.replace(/cache\//, '') return fetch(presign.url, { method: 'post', body: formData }) .then(r => presign.fields.key.replace(/cache\//, '')) .catch((error) => { console.error('aws upload', error) }) }) .then((fileName) => fetch(uploadTo, { method: 'post', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ image: JSON.stringify({ "id": fileName, "storage": "cache", "metadata": {} }) }) })) .then(r => r.json()) .then(imageUpload => this.setImageUpload(imageUpload.id)) .catch((error) => { console.error('rails upload', error) }) } setImageUpload = (id) => { const { node, state, editor } = this.props this.isUploading = false const change = state.change() .setNodeByKey(node.key, { data: { id, file: {} } }) editor.onChange(change) } isSelected = () => { const { node, state } = this.props return state.selection.hasEdgeIn(node) } preview = (file) => { this.isUploading = true let reader = new FileReader() reader.onloadend = () => { this.setState({ src: reader.result }) } reader.readAsDataURL(file) } updateNodeData = (values) => { const { node, state, editor } = this.props const nextData = node.data.merge(values) const change = state.change() .setNodeByKey(node.key, { data: nextData }) editor.onChange(change) } onCaptionChange = (caption, event) => { const { value } = event.target this.updateNodeData({[caption]: value}) } selectedVariant = () => { return this.isSelected() ? '-selected' : '' } render() { if (!this.state.src) return null return ( <figure {...this.props.attributes} className={`article-image ${this.selectedVariant()}`}> <div className="container"> <div className="image" style={{opacity: this.isUploading ? 0.6 : 1}}> <img src={this.state.src} srcSet={this.state.srcset} /> </div> <figcaption className="info"> { Object.keys(this.props.captions).map(caption => ( <ImageCaption key={caption} className={caption} isSelected={this.isSelected()} value={this.getData(caption)} onChange={e => this.onCaptionChange(caption, e)} placeholder={this.props.captions[caption]} /> )) } </figcaption> </div> </figure> ) } } <file_sep>/typewriter/src/plugins/bold-markdown.js import MarkInlineShortcut from '../helpers/mark-inline-shortcut' export default options => { const { onKeyDown } = MarkInlineShortcut({ type: 'bold', regex: /\*{2}([^\*]+)\*{2}/g, }) return { onKeyDown } } <file_sep>/lib/typewriter.rb require "typewriter/engine" module Typewriter class << self attr_reader :image_sizes end def self.config_images(config = {}) @image_sizes = config.delete(:sizes) || {} Nanofile.config(config) end end <file_sep>/typewriter/src/components/rich-text.js import React, { Component } from 'react' import { Editor } from 'slate-react' import { State } from 'slate' import { tryAsJson } from '../helpers/utils' import Paragraph from '../plugins/paragraph' import BoldMark from '../plugins/bold-mark' import BoldMarkdown from '../plugins/bold-markdown' import ItalicMark from '../plugins/italic-mark' import ItalicMarkdown from '../plugins/italic-markdown' import StrikeThroughMark from '../plugins/strike-through-mark' import StrikeThroughMarkdown from '../plugins/strike-through-markdown' import UnderlineMark from '../plugins/underline-mark' import HighlightMark from '../plugins/highlight-mark' import MarkdownBlockPlugin from '../plugins/markdown-block' import CodeMarkdown from '../plugins/code-markdown' import Link from '../plugins/link' import Video from '../plugins/video' import Embed from '../plugins/embed' import Image from '../plugins/image' export default class RichText extends Component { emptyState = { document: { nodes: [ { kind: 'block', type: 'paragraph', nodes: [] } ] } } state = { editorState: State.fromJSON(tryAsJson(this.props.content) || this.emptyState), } plugins = [ Paragraph({ placeholder: this.props.placeholder }), BoldMark(), BoldMarkdown(), ItalicMark(), ItalicMarkdown(), StrikeThroughMark(), StrikeThroughMarkdown(), UnderlineMark(), HighlightMark(), MarkdownBlockPlugin({}), CodeMarkdown(), Link(), Video(), Embed(), Image({ attributes: { presignFrom: this.props.presignFrom, uploadTo: this.props.uploadTo, captions: this.props.captions, } }), ] onChange = ({ state }) => { this.props.onChange(JSON.stringify(state.toJSON())) this.setState({ editorState: state }) } render() { const { editorState, } = this.state // Pass default props to children const children = React.Children.map(this.props.children, (child) => { return React.cloneElement(child, { editorState, onChange: this.onChange, }) }) return ( <div className="richtext-editor"> {children} <Editor state={editorState} onChange={this.onChange} plugins={this.plugins} autoFocus={true} /> </div> ) } } RichText.defaultProps = { onChange: (_ => _), presignFrom: null, uploadTo: null, captions: {}, }
558fb94ad2eefe6517e815eef01ffc7645fda970
[ "Ruby", "YAML", "JavaScript", "Markdown", "Dockerfile" ]
58
JavaScript
danielfedatto/typewriter
75ffbdc3cf576202cc457c883fca52b4a88418d0
191ac25438f887b01c83f25dcd2c17cadb2d9992
refs/heads/main
<file_sep> ================================================================== Migrating a DIY TGW to Aviatrix Managed TGW Deployment ================================================================== If you built an AWS Transit Gateway (TGW) deployment by yourself (the DIY way) and would like to migrate to an Aviatrix managed TGW deployment, this document is for you. The objectives here are: - Minimum downtime during migration. - No change to existing VPC infrastructure. - Minimum change to on-prem network. .. Note:: This document assumes you have already `launched an Aviatrix Controller <http://docs.aviatrix.com/StartUpGuides/aviatrix-cloud-controller-startup-guide.html>`_. .. Before the migration process starts, plan out what security domains you need to create and which security domains should connect other domains. If you are not sure and need to transition, proceed with no worries. The security domains can be added and modified at any time. The Solution ^^^^^^^^^^^^^^^^ There are multiple ways to migrate. For example, you can simply detach a spoke VPC from the DIY TGW and attach it to Aviatrix-managed TGW and then build hybrid connection if necessary. In this implementation, the migrated spoke VPCs can communicate with the not yet migrated VPCs during migration process, and in addition the migrated spoke VPCs can communicate with on-prem network, thus reducing the downtime, as shown in the migration architecture below. |migration_architecture| The key idea is to build an IPsec tunnel between TGW VPN and Aviatrix Transit Gateway, so that migrated VPC can communicate with not yet migrated VPCs and also to on-prem. 1. `Launch a new AWS Transit Gateway <https://docs.aviatrix.com/HowTos/tgw_plan.html#creating-an-aws-tgw>`_. 2. If you have plans for custom security domains, `create new security domains <https://docs.aviatrix.com/HowTos/tgw_plan.html#creating-a-new-security-domain>`_. Then, `build your domain connection policies <https://docs.aviatrix.com/HowTos/tgw_plan.html#building-your-domain-connection-policies>`_. If you do not intend to build custom security domains, skip this section. 3. `Launch an Aviatrix Transit GW and enable HA in the Transit Hub VPC <https://docs.aviatrix.com/HowTos/tgw_plan.html#setting-up-an-aviatrix-transit-gw>`_. As a best practice, create a new Transit Hub VPC to deploy the Aviatrix Transit GW. .. Note:: Make sure you enable `ActiveMesh Mode <https://docs.aviatrix.com/HowTos/gateway.html?#activemesh-mode>`_. This document is written for Aviatrix Transit GW with ActiveMesh mode enabled. .. Then, create a TGW VPN Attachment using the steps below. Creating TGW VPN Attachment ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1. Log in to the AWS console and select **VPC Service**. 2. Click Transit Gateway Attachments > Create Transit Gateway Attachment. 3. Select Attachment type VPN, as shown below. |tgw_vpn_config| 4. After the attachment is created, go to Site-to-Site VPN Connections and click **Download Configuration**. Make sure you select Vendor **Generic** and download the configuration text file. Creating VPN on Aviatrix Transit Gateway ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This step is to create the other end of the VPN tunnel that terminates on the Aviatrix Transit GW. 1. Log in to the Aviatrix Controller. 2. Navigate to Multi-Cloud Transit > Setup > External Connection tab. 3. Select **External Device** and fill in the parameters from the downloaded configuration text file as shown below, where the right side shows the screen capture of the AWS VPN configuration text file. |migrate_tgw_config_vpn| Starting to Migrate VPCs ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ In this step, you detach VPCs from DIY TGW and attach them to an Aviatrix-managed TGW. :: - Before or after you detach a VPC, you may need to clean up the VPC route tables entries so that they do not have conflict routes entries when later attaching it to Aviatrix managed TGW. Repeat this step to migrate all VPCs. Building the Hybrid Connectivity ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Once all VPCs have migrated to Aviatrix-managed TGW deployment, the migrated VPCs communicate with on-prem via Aviatrix Transit GW to DIY TGW and then to on-prem. At this point, you can move DIY TGW Direct Connect to Aviatrix Transit GW or to Aviatrix managed TGW directly. Deleting DIY TGW ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ After all VPCs and hybrid connectivity if any are all removed, you can safely delete DIY TGW. .. |tgw_vpn_config| image:: diy_tgw_migrate_to_aviatrix_tgw_media/tgw_vpn_config.png :scale: 30% .. |migration_architecture| image:: diy_tgw_migrate_to_aviatrix_tgw_media/migration_architecture.png :scale: 30% .. |migrate_tgw_config_vpn| image:: diy_tgw_migrate_to_aviatrix_tgw_media/migrate_tgw_config_vpn.png :scale: 30% .. disqus:: <file_sep>#!/bin/bash find . -name "*.rst" -type f -print0 | while read -r -d '' filename; do tmpfile=$(mktemp) grep -v -e '^\.\. meta::' -e ':description:' -e ':keywords:' "$filename" > "$tmpfile" cat "$tmpfile" > "$filename" rm "$tmpfile" done <file_sep> ============================================================ Aviatrix CloudN FAQ ============================================================ What is the Aviatrix CloudN? --------------------------------------- Aviatrix CloudN manages and automates secure connectivity of on-prem Cisco IOS Routers to the cloud. The IPsec connection terminates with AWS Transit Gateway (TGW), Aviatrix Transit Gateway, or Azure Virtual WAN. Starting in Release 6.2, CloudN also manages Aviatrix CloudN appliance for high performance encryption connection (up to 25Gbps) from on-prem to the cloud. This document focuses on CloudN for Cisco IOS devices. For configuration information on CloudN appliance, refer to `Managed CloudN Workflow <https://docs.aviatrix.com/HowTos/CloudN_workflow.html>`_. CloudN can be used to fulfill the following tasks. 1. Manage multiple Cisco IOS Routers from the Aviatrix Controller. This includes uploading and viewing the IOS configuration, making configuration changes and monitoring the health and stats of these routers. #. Automate secure connection of Cisco IOS routers to the Aviatrix Transit Gateway or AWS TGW with IPsec VPN over the Internet, thus allowing them to be part of the Transit Network where they gain connectivity to Spoke VPCs. What are the CloudN deployment architectures? ------------------------------------------------------------------- There are three ways to deploy CloudN. CloudN Deployment 1 ^^^^^^^^^^^^^^^^^^^^^^^^^ CloudN can be deployed to connect with Aviatrix Transit Network as shown below. |cloud_wan_1| CloudN Deployment 2 ^^^^^^^^^^^^^^^^^^^^^^^^^ Alternatively, you can deploy CloudN as an attachment to TGW where the Aviatrix Transit Gateway functions as edge to the TGW. |cloud_wan_2| CloudN Deployment 3 ^^^^^^^^^^^^^^^^^^^^^^^^^ In this deployment IPsec tunnels are built directly to TGW VPN. |cloud_wan_3| CloudN Deployment on Azure ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ CloudN can terminate branch router IPsec connection with Aviatrix Transit Gateway deployed in Azure, as shown in the diagram below. |cloud_wan_azure| CloudN Deployment on Azure Virtual WAN ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ CloudN is integrated with Azure Virtual WAN, as shown in the diagram below. For configuration example, refer to `CloudN on Azure vWAN Configuration Example <https://docs.aviatrix.com/HowTos/cloud_wan_workflow_azure_vwan.html>`_. |cloudwan_azure_vwan| What are the benefits of CloudN? ----------------------------------------- - **No Friction** Leverage what you have already invested in the on-prem edge router for connecting to the cloud. - **Shortest Latency** Leverage AWS Global Accelerator or Azure backbone to connect your on-prem routers to the nearest cloud provider edge and route through the their backbone with the optimal path. - **Automation** Avoid human errors and the complexity of VPN configuration when building VPN connections to the cloud. - **Centrally Managed** Use the single pane of glass to both provision and monitor router health and stats. How does CloudN work in AWS? --------------------------------- CloudN leverages AWS Global Accelerator and the AWS backbone for the shortest latency path to the cloud. |global_accelerator| For example, if the application is in us-west-2 and you have a branch office in Singapore country. If you built an IPsec tunnel to the gateway in us-west-2 without deploying CloudN, the traffic initiated from Singapore typically traverse through many ISP carriers and eventually to AWS us-west-2. On the other hand, with CloudN, traffic from Singapore gets to the first ISP, hops onto the AWS edge in the area and moves through the uncongested AWS backbone to us-west-2. Both latency and jitter should be minimal. Can I use CloudN just to manage the Cisco routers? ------------------------------------------------------ Yes. You can use CloudN for making changes to the routers from a central place, even if you are not ready to connect the on-prem routers to the cloud. What are the use cases for CloudN? ----------------------------------------------------- CloudN can be used to connect branch routers to the cloud directly. It can also be used to manage routers you deploy in the branch or partner network where you have full access. Can CloudN manage other vendor devices? ------------------------------------------------------------ No. Currently CloudN only manages Cisco IOS routers. How many routers can CloudN manage? -------------------------------------------------------- If the on-prem router terminates with Aviatrix Transit Gateway, there is no limitation on how many routers can be connected. What are the requirements to deploy CloudN? ------------------------------------------------------------------ General requirement is to have each managed Cisco router needs Internet access and a public IP address. Please make sure the following items are properly configured in Cisco IOS router. 1. Please make sure Cisco router’s login username is set to privilege 15. Cisco IOS CLI examples: :: username admin privilege 15 password 0 password username administrator privilege 15 secret 5 $1$WbTk$uk7Au2PkCardkaM3BCcIS. username superuser privilege 15 2. Please make sure line vty is set to "privilege level 15" and ssh is included for “transport input." Cisco IOS CLI example: :: line vty 1 4 privilege level 15 login local transport input ssh 3. Please enable ip ssh in Cisco IOS, either password authentication, private key authentication, or both. See `this article <https://www.cisco.com/c/en/us/support/docs/security-vpn/secure-shell-ssh/4145-ssh.html>`_. 4. Please enable scp server in Cisco IOS. Cisco IOS CLI example: :: ip scp server enable What routing protocols are supported on CloudN? ------------------------------------------------------------------ CloudN supports BGP and static routing. Can CloudN support branch to branch communications? ------------------------------------------------------------------------- When BGP is enabled on the branch router, CloudN can route traffic between branches. How do I configure CloudN? --------------------------------------- Follow the `CloudN workflow to get started. <https://docs.aviatrix.com/HowTos/cloud_wan_workflow.html>`_. How should I secure my IOS router? -------------------------------------------------- When a router is attached, an ACL rule to permit TCP port 22 access from the Aviatrix Controller. What Cisco routers are supported? ------------------------------------------------ Cisco routers that run IOS Classic and IOS XE are supported. For example, ISR G2, ASR and ISR G3. .. |cloud_wan_1| image:: cloud_wan_faq_media/cloud_wan_1.png :scale: 30% .. |cloud_wan_2| image:: cloud_wan_faq_media/cloud_wan_2.png :scale: 30% .. |cloud_wan_3| image:: cloud_wan_faq_media/cloud_wan_3.png :scale: 30% .. |cloud_wan_azure| image:: cloud_wan_faq_media/cloud_wan_azure.png :scale: 30% .. |cloudwan_azure_vwan| image:: cloud_wan_faq_media/cloudwan_azure_vwan.png :scale: 30% .. |global_accelerator| image:: cloud_wan_faq_media/global_accelerator.png :scale: 30% .. |domain_policy_diagram| image:: tgw_overview_media/domain_policy_diagram.png :scale: 30% .. |tgw_view| image:: tgw_overview_media/tgw_view.png :scale: 30% .. |tgw_transit_vpc_compare| image:: tgw_overview_media/tgw_transit_vpc_compare.png :scale: 30% .. |tgw_transit_orchestrator_compare| image:: tgw_overview_media/tgw_transit_orchestrator_compare.png :scale: 30% .. disqus:: <file_sep> ====================================================================== Azure Controller Security for SAML Based Authentication VPN Deployment ====================================================================== The best security practice for the Aviatrix Controller is to prevent the Controller from being widely accessible from the internet. Access on TCP port 443 should be limited to: - The range of management IPs coming from the enterprise or the data center. - Ingress and egress access for basic communications and keep-alive signals from each gateway. The exception to this best practice is when the Aviatrix Controller is used for Security Assertion Markup Language (SAML) based authentication user VPN access. In this case, the VPN user first contacts the Aviatrix Controller, which then redirects user browser traffic to an Identity Provider (IdP) system, Okta for example. The initial VPN authentication traffic runs on Aviatrix Controller TCP port 443 for VPN users located off-site, so Controller TCP port 443 needs to be open to all which may cause security concerns. You must configure Aviatrix SAML authentication for your user VPN access. The SAML authentication should be configured through the Azure Application Gateway (AppGW) so the URLs generated for use in the IdP and domain information in the ovpn file point to the domain of the AppGW. The URLs generated use the AppGW domain instead of Controller domain. VPN users should not access the Controller directly; they should access the Controller through the AppGW where access rules are enforced. In order prevent the Controller from being widely accessible and allow SAML authentication user VPN access, please follow the instructions in this section to secure your Controller when Security Assertion Markup Language (SAML) based authentication is being used. Azure Application Gateways and the Aviatrix Controller ====================================================== The Azure Application Gateway is a generic, workload agnostic reverse proxy and load balancer that includes a web application firewall (WAF). - The service consists of Azure-managed VMs running Nginx in a VNET. Unless restricted, these VMs have access to the public internet, the VNet address space, and anything else a VM in that VNet can talk to. - In addition to VMs, backends can be IP addresses. - The Application Gateway is also an Ingress Controller option for the Azure Kubernetes Service. From an Application Gateway perspective, the Aviatrix Controller is just another workload. The configurations in this section can be applied to any other HTTP or HTTPS workload. For example, you can use the Azure Application Gateway to: - Protect an application running in an on-prem data center. - Protect a hosted PaaS web application injected into the VM. - Add HTTPS support to an older application that can only run HTTP. - Restrict or redirect URL patterns within an application. Prerequisites ============= You need to understand how to configure OpenVPN SAML authentication. For more information, see `OpenVPN with SAML Authentication <https://docs.aviatrix.com/HowTos/VPN_SAML.html>`_. Securing the Aviatrix Controller for SAML Based Authentication Behind an Azure Application Gateway ================================================================================================== To secure your Controller when Security Assertion Markup Language (SAML) based authentication is being used: 1. Create valid SSL certificates for the Aviatrix Controller and Azure Application Gateway virtual machine. Use any valid SSL certificate generation application. 2. On the Azure portal, create a subnet for the Azure Application Gateway. Create the subnet in your Aviatrix Controller’s VNet for the Azure Application Gateway. The Azure Application Gateway requires its own subnet. 3. Apply the certificates to the Controller. A. On the Aviatrix Controller, go to the Controller Settings > Security > Advanced > Controller Certificate Import Methods. The preferred method is to select **Import Certificate with Key**, but you can also select **Generate CSR and Import Certificate**. B. Import the certificate files. C. After you click **OK**, the Aviatrix Controller browser refreshes using the new certificate. Verify the correct certificates are in use with your favorite SSL validation site. For more information, see `Controller Certificate Management <https://docs.aviatrix.com/HowTos/import_cert_with_key.html>`_. 4. On the Aviatrix Controller, go to Settings > Controller > Access Security > Security. Enable the Controller Primary Access Account on the Controller Security Group Management card to only allow access to the Controller Public IP from Aviatrix Gateways. In the Azure Portal, the Network Security Group (NSG) assigned to the Controller is usually <controllername>-nsg. 5. On the Azure portal, create a new Azure Application Gateway: * Specify the Basic details. * Configure Frontends and create a Public IP. * Create 2 backend pools. Create one pool to allow VPN user requests on the flask endpoint and the other pool to block access to any other endpoints on the Aviatrix Controller. - Specify the NIC of the Controller virtual machine as the target. - Chose HTTP Settings: <controller-settings>. - **<controller>** - Select the Controller instance as target. - **<dont-allow>** - This backend pool is used to block endpoints on the Controller except for ‘flask’. - Create a path-based rule in listener rules. - Choose Backend target as <dont-allow>, so that the App GW returns “502 Bad Gateway” response to any paths other than ‘/flask*’. - Create a path-based rule for the path “/flask*“, with the backend target set to <controller>. * Add a Routing Rule. Create a rule Name and enter the required values on the Listener tab. * Enter the required values on the Backend targets tab. The Backend Target is the backend pool created earlier. * Click **Add new** and configure the HTTP Settings. * Set the Request timeout value to 3600. Otherwise, timeouts on legitimate requests may occur. * Set the Override with new hostname setting to **No**. 6. On the Azure portal, modify the associated Azure Network Security Group to allow the Azure Application Gateway subnet. 7. On the Azure portal, enable monitoring of the Application Gateway. Add a diagnostic setting and configure the desired logging settings. 8. On the Azure portal, disable rules for the Application Gateway to prevent errors with onboarding accounts. * Enable advanced rule configuration. * Disable rules 200004, 931130, and 942430. 9. On the Azure portal, enable URL Rewrite to avoid Cross-Origin Resource Sharing (CORS) errors. * Create a Rewrite set. * Name the Rewrite set and assign it to the Aviatrix Controller routing rule. * Rename the rule to something descriptive. * On the Azure portal, enable URL Rewrite to avoid Cross-Origin Resource Sharing (CORS) errors. 10. On the Azure portal, put the Aviatrix Controller behind the Application which includes a web application firewall (WAF). The WAF will block requests with special entity names. Do not create entity name with special strings because the API will be blocked with a 403 error. 11. Create SAML endpoint. For more information see `OpenVPN with SAML Authentication <https://docs.aviatrix.com/HowTos/VPN_SAML.html>`_. After the Azure AppGW is configured and the Aviatrix Controller is placed behind the AppGW, you are ready to test your SAML based authentication for user VPN access. .. Note:: For the HTTP Settings, when using the "Use well known CA certificate" option you may see a message about the root certificate of the server certificate used by the backend not matching the trusted root certificate added to the application gateway. To resolve this issue, use the fullchain certificate when importing the server certificate into the Controller. .. .. Note:: While authenticating the VPN user with an IdP and when sending the SAML response to the Controller, you may see an error message about an invalid SAML response and the subject or username 'NoneType'. To resolve this issue, disable "override hostname" in the application gateway's HTTP settings. .. Example ------------------------- The following example demonstrates securing the Aviatrix Controller for SAML based authentication behind an Azure application gateway with the Okta IdP. The objective is to limit access to Aviatrix Controller port 443 to authorized IPs and at the same time allow a VPN client to contact the Controller for SAML authentication. In the following example, the Aviatrix Controller is placed and Azure application gateway with WAF enabled. All the steps used to create the Azure application gateway are not included, the example focuses on the special steps to implement the configuration. 1. Create domain names for Controller and App GW. For example: - Controller: azure-ctlr.customertest.com. - App GW: azure-ctlr-appgw.customertest.com. 2. Create certificates for Controller and App GW. For example: - Let’s encrypt to create certificates. - Validate using DNS validation. 3. Import certificates into Controller. For example: - Import certs at Controller > Settings > Advanced > Security > “Controller Imported Certificate Status”. - Use ‘fullchain’ cert for server cert as well as Controller seems to not send the full chain and App GW fails to validate the backend Controller certs. 4. Create the Application Gateway (App GW). Then access the Controller through App GW for the configuration. 5. When configuring SAML authentication and setting up App in Okta IdP: - set the Default Backend target in App GW rules to ‘controller’, - set the WAF’s Firewall mode to ‘Detection.’ - create HTTP Settings: - Name: controller-settings - Backend port: 443 - Use well known CA cert: Yes - Cookie-based policy, Connection draining: Disable - Request time-out: 3600 - Override with new host name: No. Otherwise, the Backend Health status is bad. - Custom probe: Create a custom probe. 6. Create a custom health probe because the default probe checks that the Hostname matches what is seen in the certificate. - Name: <test-https-probe> - Set protocol as “HTTPS” - Set Host to the Controller Domain name - Pick host name from backend HTTP settings: No - Pick port from backend HTTP settings: Yes - Path: / - interval, timeout, unhealthy threshold: Can leave these as defaults. - Chose HTTP Settings: controller-settings 7. Create 2 Backend pools. - Choose Backend target as ‘dont-allow‘, so that the App GW returns “502 Bad Gateway” response to any paths other than ‘/flask*’. - Create a path-based rule for the path “/flask*“, with the backend target set to <controller>. 8. Create a path-based rule in listener rules. - Choose Backend target as ‘dont-allow’, so that the App GW returns “502 Bad Gateway” response to any paths other than ‘/flask*’. - Create a path-based rule for the path “/flask*“, with Backend target set to <controller>. 9. Set up SAML authentication by accessing the Controller through the App GW domain name. - In the Okta application: - set the SSO, Destination, Recipient URLs to https://azure-ctlr.customertest.com/flask/saml/sso/aviatrix_saml_controller. - set Audience restriction and Default relay state to https://azure-ctlr-appgw.customertest.com/. 10. Verify the SAML configuration by verifying VPN client authentication is successful. - In the App GW ‘rules’ section, set the Backend target to ‘dont-allow’ to not allow access endpoints that VPN users shouldn’t be able to access. - In WAF section, set the Firewall mode to ‘Prevention’. 11. Verify that when accessing through App GW, the VPN user is not able to access paths other than ‘/flask*’. .. disqus:: <file_sep> .. _AWS billing: https://console.aws.amazon.com/billing/home?#/account ====================================================================== Multi-Cloud: Connecting Azure to AWS and GCP ====================================================================== Overview -------------- Companies are relying more and more on multiple cloud (multi-cloud) providers. However, setting up the connectivity between those providers is difficult. And, maintaining and monitoring the tunnels is time-consuming and cumbersome to troubleshoot. Aviatrix simplifies this by providing simple, point-and-click tunnel creation between cloud providers. Additionally, Aviatrix gives you a single, centralized location from which to troubleshoot and monitor your connections. |imageAvtxDashboard0| Getting Started ------------------------ The Aviatrix Controller automates, monitors, and reacts to events in each cloud environment on your behalf. In order to do this, we'll need to configure a few things in each cloud to support this. We'll walk through these steps in the following sections. Once complete, you can connect to one or both cloud providers. Start by logging into the `Azure Portal <https://portal.azure.com>`__. Installing Aviatrix Controller from the Azure Marketplace ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The first step is to install the Aviatrix Controller from the Azure Marketplace. Select the **Aviatrix Cloud Gateway to AWS and GCP** from the Marketplace. Configure the new VM to meet your preferences and requirements. Be sure to allow inbound connections on port 443. Once ready, launch the new VM and continue to the next step. Preparing your Azure Account ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ While the VM is being deployed in the selected region, configure the following items: Registering Aviatrix with Active Directory ####################################### 1. Go to the Azure Active Directory (available from the left navigation panel or More Services). 2. Click **Properties** (available under Manage on the left inner navigation bar). .. important:: Copy and save the **Directory ID** for later use. It will be referred to again as the Application Endpoint. 3. Click **App registrations** (available under Manage on the left inner navigation bar). 4. Click **+ New application registration** along the top. |imageAzureAppRegBtn| 5. Populate the fields as follows: +--------------------+--------------------------------------------------+ | Field | Value | +====================+==================================================+ | Name | Aviatrix Controller | +--------------------+--------------------------------------------------+ | Application type | Web app / API | +--------------------+--------------------------------------------------+ | Sign-on URL | http://aviatrix | +--------------------+--------------------------------------------------+ 6. Click **Create**. |imageAzureAppRegForm| Adding a Key ########### 1. Find and select the application you just registered in the list displayed. |imageAzureAppRegAppID| .. important:: Copy and save the **Application ID** for later. It will be referred to again later in this document as the **Application Client ID**. 2. Click **Keys** in the Settings pane on the right. |imageAzureAppRegKeysBtn| 3. Enter a new row: +--------------------+--------------------------------------------------+ | Field | Value | +====================+==================================================+ | Key description | Aviatrix | +--------------------+--------------------------------------------------+ | Expires | Never expires | +--------------------+--------------------------------------------------+ 4. Click **Save**. |imageAzureAppRegKeySave| 5. Copy the displayed key value and save it for later. |imageAzureAppRegKeySaveComplete| .. important:: Save this value. It will be referred to again later in this document as the **Application Client Secret**. 6. Exit the Keys window. Adding Required Permissions ########################## 1. Select the **Aviatrix Controller** application registration again (you may already be on it). 2. Click **Required permissions** just above Keys. |imageAzureAppRegPermBtn| 3. Click **+ Add** button. 4. Click **Select an API** (on the right). 5. Find and select **Windows Azure Service Management API**. |imageAzureAppRegPermSelectAPI| 6. Click **Select**. 7. In the Enable Access panel, mark the **Access Azure Service Management as organization users (preview)** checkbox. |imageAzureAppRegPermEnableAccess| 8. Click **Select**. 9. Click **Done**. 10. Exit the Required Permissions panel. Granting Permissions to Aviatrix Controller ######################################## 1. Go to the Subscriptions service (available from the left navigation panel or from More Services). 2. Click on the subscription where Aviatrix Controller is installed. .. important:: Copy and save the **Subscription ID** for later. 3. Click **Access Control (IAM)**. |imageAzureSubscriptionIAM| 4. Click **+ Add**. 5. Populate the fields as follows: +--------------------+--------------------------------------------------+ | Field | Value | +====================+==================================================+ | Role | Contributor | +--------------------+--------------------------------------------------+ | Assign access to | Azure AD user, group, or application | +--------------------+--------------------------------------------------+ | Select | Aviatrix Controller | +--------------------+--------------------------------------------------+ |imageAzureSubscriptionIAMAddPerm| 6. Click **Save**. 7. Exit the Access control (IAM) panel. Configuring Aviatrix ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Your Aviatrix Controller should be up and running by now. Go back to the Microsoft Azure portal and find the newly created instance. Open it and copy the **Public IP address**. Open a browser and navigate to https://<public ip address>/ . .. tip:: You may receive a warning about the certificate not matching. You can safely ignore this and continue to the page. When you arrive at the login prompt, log in with the Username "admin." The password is the private IP address of the Azure instance. .. tip:: Find the Private IP address on the instance page by selecting **Networking**. |imageAviatrixFirstLogin| After logging in, you will be prompted to provide your email address. This is used for alert notifications as well as for password recovery. Enter your email address and click **OK**. Set the admin password to something you will remember and click **Save**. If you require a proxy for this instance to get to the internet, enter that now. Otherwise, click **Skip**. Finally, the software will be upgraded. Click **Run** button and the latest version of the Controller will be downloaded and installed. This will take a few minutes. Once complete, the login prompt will appear. |imageAviatrixFirstLoginRunUpdate| Log in with the username "admin" and the new password. Azure ---------- After logging in, click **Azure ARM** to connect Aviatrix to your Azure account. |imageAviatrixOnboardAzureSelect| Creating the Account ^^^^^^^^^^^^^^^^^^^^ Fill out the fields as follows: +-------------------------------+--------------------------------------------+ | Field | Expected Value | +===============================+============================================+ | Account Name | The login/username for users who will have | | | admin access to Azure resources. | | | For example, `AzureOpsTeam`. | +-------------------------------+--------------------------------------------+ | E-mail | The e-mail address for this team. | +-------------------------------+--------------------------------------------+ | Password | Password for login to the controller | +-------------------------------+--------------------------------------------+ | Confirm Password | | +-------------------------------+--------------------------------------------+ | ARM Subscription ID | The **Subscription ID** you saved in a | | | previous step. | +-------------------------------+--------------------------------------------+ | Application Endpoint | The **Application Endpoint** (i.e., the | | | **Directory ID**) retrieved earlier. | +-------------------------------+--------------------------------------------+ | Application Client ID | The **Client ID** (i.e., the **Application | | | ID**) saved earlier. | +-------------------------------+--------------------------------------------+ | Application Client Secret | The **Client Secret** (i.e., the key value)| | | displayed earlier. | +-------------------------------+--------------------------------------------+ Once complete, click **Create** button at the bottom of the form. |imageAviatrixOnboardAzureCreate| Accepting License Agreement ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Before you can automate launching an Aviatrix Gateway, you must first subscribe to the Aviatrix Companion Gateway in the `Azure Marketplace <https://portal.azure.com/#blade/Microsoft_Azure_Marketplace/GalleryFeaturedMenuItemBlade/selectedMenuItemId/home/resetMenuId/>`__. 1. Search for "aviatrix companion gateway." 2. Select the result. |imageAzureCompanionGWSearchResult| 3. Click on the link at the very bottom titled "Want to deploy programmatically? Get started ➔". |imageAzureCompanionGWDeployLink| 4. Click **Enable** status button. |imageAzureCompanionGWEnableAccess| 5. Click **Save**. Creating a Gateway ^^^^^^^^^^^^^^^^^^ The Controller can now automate creating a Gateway within Azure. Switch back to the browser tab or window with the Aviatrix Controller. Click **Gateway** in the left navigation bar: |imageAviatrixNavGateway| Next, click **+ New Gateway**. Populate the Gateway Name and select the appropriate Region, VNet, and Public Subnet. The Gateway Size can be left at the smallest size. It can be scaled up (and out) later if needed. |imageAviatrixGWCreate| Click **OK** to create the Gateway automatically. This will take a few minutes as it creates the instance in the selected region and sets up the appropriate route table entries, etc. Once complete, click **X Close**. Now you have a Gateway in Azure that can connect to either AWS, GCP, or both. AWS ---------------- Creating the Account ^^^^^^^^^^^^^^^^^^^ 1. Go to the Onboarding section on your Controller. |imageAviatrixOnboardNav| 2. Click **AWS**. Fill out the fields as follows: +-------------------------------+--------------------------------------------+ | Field | Expected Value | +===============================+============================================+ | Account Name | The login/username for users who will have | | | admin access to AWS resources. | | | For example, AWSOpsTeam. | +-------------------------------+--------------------------------------------+ | E-mail | The e-mail address for this team. | +-------------------------------+--------------------------------------------+ | Password | <PASSWORD> | +-------------------------------+--------------------------------------------+ | Confirm Password | | +-------------------------------+--------------------------------------------+ | AWS Account Number | You can find your account number | | | on the AWS billing page | +-------------------------------+--------------------------------------------+ | IAM role-based | Leave this unchecked for now. For | | | production use, you'll want to use IAM | | | roles with specific permissions. | +-------------------------------+--------------------------------------------+ | AWS Access Key ID | An admin user's AWS access key ID | +-------------------------------+--------------------------------------------+ | AWS Secret Key | An admin user's AWS secret key | +-------------------------------+--------------------------------------------+ Once complete, click **Create** at the bottom of the form. |imageAviatrixOnboardAWSCreate| Deploying a Gateway in AWS ^^^^^^^^^^^^^^^^^^^^^^^^^^ Head back over to the Gateways section in the Aviatrix Controller and click **+ New Gateway**. 1. Select **AWS** for Cloud Type. 2. Enter a Gateway name. 3. Select the appropriate values for Region, VPC ID, and Public Subnet. 4. Set the default Gateway Size at **t3.large**. 5. Mark the **Allocate New EIP** checkbox so a new Elastic IP will be allocated on creation. 6. Click **OK** when ready. .. tip:: Create a new VPC for testing. |imageAviatrixGWCreateAWS| Peering the Gateways ^^^^^^^^^^^^^^^^^^^^^ 1. Click on the **Peering** navigation link on the Controller. 2. Click **+ New Peering**. |imageAviatrixGWCreateAWSPeerAddBtn| 3. Select the AWS Gateway and the Azure Gateway. |imageAviatrixGWCreateAWSPeerAddNew| 4. Click **OK**. |imageAviatrixGWCreateAWSPeerUp| Complete ^^^^^^^^^^^^ Your Azure VNet instances can now talk to your AWS instances over a secure tunnel. You will soon receive an email notification that the tunnel is up. You'll receive additional notifications if the tunnel goes down. GCP -------------- Preparing your Google Cloud Account ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The Aviatrix Controller requires a few settings to be enabled in order for it to be able to interact with your Google Cloud account. 1. From the `Google Cloud Console Dashboard <https://console.cloud.google.com/home/dashboard>`__, copy and save the **Project ID**. |imageGCPProjectID| 2. Enable GCloud Messaging Service. The Controller relies on Google Cloud Pub/Sub APIs to communicate with the Gateways in GCP. Enable these APIs by going to the `APIs & services Dashboard <https://console.cloud.google.com/apis/dashboard>`__ for the selected project. Select **Enable APIs and Services** at the top of the page. |imageGCPEnableAPIsBtn| Select **Google Cloud Pub/Sub API** from the list. Then, click **Enable**. |imageGCPEnablePubSubBtn| 3. Create a Credentials File. Navigate back to the `APIs & services Dashboard <https://console.cloud.google.com/apis/dashboard>`__ and select **Credentials** (or click `here <https://console.cloud.google.com/apis/credentials>`__). |imageGCPCredentialsPage| Click the **Create credentials** dropdown menu and select **Service account key**. |imageGCPCredentialsCreateStep1| Select **Compute Engine default service account** for the Service account and select **JSON** for Key type. |imageGCPCredentialsCreateStep2| Then, click **Create**. A file will be downloaded to your computer. Find it and store it in a safe location. Then, click **Close**. |imageGCPCredentialsSaved| You are now ready to connect the Aviatrix Controller to your Google Cloud Platform account. Create Account ^^^^^^^^^^^^^^^^ 1. Go to the Onboarding section on the Aviatrix Controller. |imageAviatrixOnboardNav| 2. Click **GCloud**. Fill out the fields as follows: +-------------------------------+--------------------------------------------+ | Field | Expected Value | +===============================+============================================+ | Account Name | The login/username for users who will have | | | admin access to Google Cloud resources. | | | For example, "GCPOpsTeam." | +-------------------------------+--------------------------------------------+ | E-mail | The e-mail address for this team. | +-------------------------------+--------------------------------------------+ | Password | <PASSWORD> | +-------------------------------+--------------------------------------------+ | Confirm Password | | +-------------------------------+--------------------------------------------+ | GCloud Project ID | The **Project ID** saved earlier | +-------------------------------+--------------------------------------------+ | GCloud Project Credentials | Select the credentials file created in an | | | earlier step. | +-------------------------------+--------------------------------------------+ Once complete, click **Create** at the bottom of the form. |imageAviatrixOnboardGCPCreate| Deploying a Gateway in GCP ^^^^^^^^^^^^^^^^^^^^^^^^^^ Head back over to the Gateways section in the Aviatrix Controller and click on **+ New Gateway** button. 1. Select **GCloud** for the Cloud Type. 2. Enter a Gateway name. 3. Select a VPC ID and Public Subnet. 4. Keep the default Gateway Size of "f1-micro." 5. Click **OK** when ready. |imageAviatrixGWCreateGCP| Peering the Gateways ^^^^^^^^^^^^^^^^^^^^^ 1. Click on the **Peering** navigation link on the Controller. 2. Click **+ New Peering**. |imageAviatrixGWCreateAWSPeerAddBtn| 3. Select the AWS Gateway and the Azure Gateway. |imageAviatrixGWCreateGCPPeerAddNew| 4. Click **OK**. |imageAviatrixGWCreateGCPPeerUp| Complete ^^^^^^^^ Your Azure VNet instances can now talk to your GCP instances over a secure tunnel. You will soon receive an email notification that the tunnel is up. You'll receive additional notifications if the tunnel goes down. Summary ----------------- If you peered your Azure account with both AWS and GCP, then you should see something like this on your Aviatrix Controller Dashboard: |imageAviatrixDashboardFinal| Now that you have the accounts established, you can easily add connectivity to other VPCs in either AWS or GCP. And, of course, you can also connect AWS to GCP. .. |imageAvtxDashboard0| image:: GettingStartedAzureToAWSAndGCP_media/aviatrix/screenshot_aviatrix_dashboard_sample.png .. |imageAzureAppRegBtn| image:: GettingStartedAzureToAWSAndGCP_media/azure/button_add_app_registration.png .. |imageAzureAppRegForm| image:: GettingStartedAzureToAWSAndGCP_media/azure/form_app_registration_create.png .. |imageAzureSubscriptionIAM| image:: GettingStartedAzureToAWSAndGCP_media/azure/access_control_btn.png .. |imageAzureSubscriptionIAMAddPerm| image:: GettingStartedAzureToAWSAndGCP_media/azure/access_control_add_perm.png .. |imageAzureAppRegKeysBtn| image:: GettingStartedAzureToAWSAndGCP_media/azure/app_registration_keys_btn.png .. |imageAzureAppRegKeySave| image:: GettingStartedAzureToAWSAndGCP_media/azure/app_registration_save.png .. |imageAzureAppRegKeySaveComplete| image:: GettingStartedAzureToAWSAndGCP_media/azure/app_registration_key_value.png .. |imageAzureAppRegPermBtn| image:: GettingStartedAzureToAWSAndGCP_media/azure/app_reg_permissions_btn.png .. |imageAzureAppRegPermSelectAPI| image:: GettingStartedAzureToAWSAndGCP_media/azure/app_reg_permissions_select_api_2.png .. |imageAzureAppRegPermEnableAccess| image:: GettingStartedAzureToAWSAndGCP_media/azure/app_reg_permissions_enable_access.png .. |imageAzureAppRegAppID| image:: GettingStartedAzureToAWSAndGCP_media/azure/app_registration_select_app_id.png .. |imageAviatrixFirstLogin| image:: GettingStartedAzureToAWSAndGCP_media/aviatrix/configure_first_login.png .. |imageAviatrixFirstLoginRunUpdate| image:: GettingStartedAzureToAWSAndGCP_media/aviatrix/configure_run_update.png .. |imageAviatrixOnboardAzureSelect| image:: GettingStartedAzureToAWSAndGCP_media/aviatrix/onboard_azure_btn.png .. |imageAviatrixOnboardAzureCreate| image:: GettingStartedAzureToAWSAndGCP_media/aviatrix/onboard_azure_account_create.png .. |imageAviatrixNavGateway| image:: GettingStartedAzureToAWSAndGCP_media/aviatrix/gateway_nav.png .. |imageAviatrixGWCreate| image:: GettingStartedAzureToAWSAndGCP_media/aviatrix/gateway_create.png .. |imageAzureCompanionGWSearchResult| image:: GettingStartedAzureToAWSAndGCP_media/azure/companion_subscribe/search_results.png .. |imageAzureCompanionGWDeployLink| image:: GettingStartedAzureToAWSAndGCP_media/azure/companion_subscribe/deploy_programmatically_link.png .. |imageAzureCompanionGWEnableAccess| image:: GettingStartedAzureToAWSAndGCP_media/azure/companion_subscribe/select_enable.png .. |imageAviatrixOnboardAWSCreate| image:: GettingStartedAzureToAWSAndGCP_media/aviatrix/onboard_aws_account.png .. |imageAviatrixOnboardNav| image:: GettingStartedAzureToAWSAndGCP_media/aviatrix/onboard_nav.png .. |imageAviatrixGWCreateAWS| image:: GettingStartedAzureToAWSAndGCP_media/aviatrix/gateway_create_aws_us_east.png .. |imageAviatrixGWCreateAWSPeerAddBtn| image:: GettingStartedAzureToAWSAndGCP_media/aviatrix/peering_new_btn.png .. |imageAviatrixGWCreateAWSPeerAddNew| image:: GettingStartedAzureToAWSAndGCP_media/aviatrix/peering_add_new.png .. |imageAviatrixGWCreateAWSPeerUp| image:: GettingStartedAzureToAWSAndGCP_media/aviatrix/peering_up.png .. |imageGCPProjectID| image:: GettingStartedAzureToAWSAndGCP_media/gcp/gcp_project_id.png .. |imageGCPEnableAPIsBtn| image:: GettingStartedAzureToAWSAndGCP_media/gcp/gcp_enable_apis_btn.png .. |imageGCPEnablePubSubBtn| image:: GettingStartedAzureToAWSAndGCP_media/gcp/gcp_enable_pub_sub_btn.png .. |imageGCPCredentialsPage| image:: GettingStartedAzureToAWSAndGCP_media/gcp/gcp_credentials_create_btn.png .. |imageGCPCredentialsCreateStep1| image:: GettingStartedAzureToAWSAndGCP_media/gcp/gcp_credentials_btn_expanded.png .. |imageGCPCredentialsCreateStep2| image:: GettingStartedAzureToAWSAndGCP_media/gcp/gcp_credentials_create.png .. |imageGCPCredentialsSaved| image:: GettingStartedAzureToAWSAndGCP_media/gcp/gcp_credentials_saved.png .. |imageAviatrixGWCreateGCP| image:: GettingStartedAzureToAWSAndGCP_media/aviatrix/gateway_create_gcp.png .. |imageAviatrixOnboardGCPCreate| image:: GettingStartedAzureToAWSAndGCP_media/aviatrix/onboard_gcp_account.png .. |imageAviatrixGWCreateGCPPeerAddNew| image:: GettingStartedAzureToAWSAndGCP_media/aviatrix/peering_add_new_gcp.png .. |imageAviatrixGWCreateGCPPeerUp| image:: GettingStartedAzureToAWSAndGCP_media/aviatrix/peering_up_gcp.png .. |imageAviatrixDashboardFinal| image:: GettingStartedAzureToAWSAndGCP_media/aviatrix/dashboard_with_aws_gcp_peering.png .. disqus:: <file_sep> ========================================================= Example Configuration for FortiGate VM in GCP ========================================================= You can follow this example to set up the FortiGate Next Generation Firewall instance for GCP, to validate that packets are indeed sent to the FortiGate Next Generation Firewall for VPC to VPC and from VPC to internet traffic inspection. You must first complete steps 1-6 `here <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_gcp.html>`_. Step 7a on that page (launching a FortiGate Next Generation Firewall instance) links to this example. After the FireNet launch is complete, the Aviatrix Controller displays the FortiGate Next Generation Firewall instance with its public IP address for the management/egress interface. You can click the IP address link to access the FortiGate UI. Below are the settings and values used in this example to launch the firewall instance from the Aviatrix Controller (Firewall Network > Setup > Step 7a). You can adjust these depending on your requirements. ========================================== ========== **Example setting** **Example value** ========================================== ========== VPC ID Gateway Name Firewall Instance Name Firewall Image Fortinet FortiGate Next-Generation Firewall Firewall Image Version 7.05 Firewall Instance Size Standard_D3_v2 Egress Interface VPC ID Egress Interface Subnet Select the desired subnet Zone Attach Check ========================================== ========== Below are the steps for initial setup. Logging on to the FortiGate Next Generation Firewall ------------------------------------------------------- 1. After completing the FireNet setup and `deploying the FortiGate firewall instance in GCP <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_gcp.html>`_, navigate to Firewall Network > List > Firewall in the Aviatrix Controller. #. Select the firewall in the list. #. In the Actions menu, select Download key. This downloads the PEM file to your machine. Make note of the name and location of the PEM file (matches your firewall instance name). #. Click on the link as shown. |gcp_FortiGate_launch_instance| .. note:: Use a different browser (e.g. Firefox/Chrome) if the FortiGate UI link does not open in your default browser. FortiGate Next Generation Firewall Initial Setup --------------------------------------------------------- Use the default username and password to log in. You may have to SSH into the firewall instance and change the default password using CLI. Since this is the initial setup of this FortiGate UI, you may be prompted to specify your hostname; change your password; upgrade your firmware; and complete your dashboard setup. After completing those steps, go to Network > Interfaces in the FortiGate UI and review the interface configuration. This interface configuration was completed by the Aviatrix Controller during the firewall launch. |review_fggcp_interfaces| Configuring the LAN Interface ----------------------------- Before configuring the static routes you must configure the port 2 (LAN) interface as follows. The port 1 (WAN) interface does not need to be configured; it is the default management port and is configured during the deployment. 1. In the FortiGate UI, navigate to Interfaces > port2. Configure the interface as follows: - Alias: LAN - Administrative Access > IPv4: FortiGate requires administrative access to reply to health probes from a network load balancer (load balancers are created automatically in GCP when you set up your Transit FireNet connection). Select the HTTP, HTTPS, SSH and PING checkboxes. When you select HTTPS this opens TCP port 443 to check the health of the firewall. 2. Click **OK**. #. SSH into the firewall instance using the following command: ssh -I <firewallname>.pem #. Run these commands to disable the source check. This enables the firewall to forward packets received on that interface. config system interface edit "port2" set src-check disable end (Optional) Firewall Vendor Integration ---------------------------------------- Integrating a FortiGate firewall with the Aviatrix Controller enables the Controller to make automatic RFC 1918 and non-RFC 1918 route updates to the FortiGate routing tables. You may also manually enable the integration with your CSP management tools. FortiGate integration is supported in AWS, Azure, and GCP clouds. In this procedure you generate a Firewall API Token from FortiGate. This token is required to integrate the FortiGate firewall with the Aviatrix Controller. 1. In the FortiGate GUI, navigate to System > Administrators > Create New > REST API Admin. #. Provide a username and profile for this user. |fort_admin_profile| 3. Click OK to create the user with this profile. An API key is generated. #. Copy the key string that displays. It is only displayed once. #. Go to Aviatrix Controller > Firewall Network > Vendor Integration > Firewall. #. Enter the vendor firewall information in the Controller. - Transit VPC ID: select the VPC ID for the CSP - Firewall Instance ID: automatically populated - Firewall Name: the name you gave your FortiGate firewall - Firewall Vendor Type: Fortinet FortiGate - Firewall API token: paste the API token string from step 1 here - Firewall Management IP Address: IP address of your firewall - Firewall Route Table (Optional): #. Click **Save**. #. You can click **Show** or **Sync** to view the integration or sync with the firewall. |vendor_integration_fortgcp| The Aviatrix Controller is now enabled to make automatic route updates to the FortiGate routing tables. .. note:: If the necessary routes are not created via vendor integration, you must manually configure routes to the health probe IP ranges on each interface that receives traffic. This prevents the reverse path forwarding check from blocking the health probes. The 0.0.0.0/0 route on the external interface covers the ranges that the external network load balancer uses. Configuring a DNAT Policy for Health Check ------------------------------------------ A DNAT policy is required on the firewall to translate the destination of the health check packets to the firewall interface IP address. Before you begin, you need the TCP and UDP load balancer front end IP addresses from your GCP portal, along with the firewall instance nic0 internal IP address. 1. In the firewall UI, navigate to Policy & Objects > Virtual IPs and click Create New > Virtual IP. #. In the New Virtual IP dialog, configure the following: - Name: ilb-vip (or an equivalent name of your choosing) - Interface: port2 - Type: Static NAT - External IP address/range (TCP load balancer front end IP address) - Map to IPv4 address/range (firewall instance port2 IP address) 3. Click **OK**. #. Repeat steps 1-3 for creating a UDP virtual IP. In this case the External IP address/range is the UDP load balancer front end IP address. Configuring a Security Policy for Health Check ---------------------------------------------- You now need to create a security policy granting health check access to the virtual IPs you just created. 1. Create two new GCP health check source IP address ranges: a. In the firewall UI, navigate to Policy & Objects > Addresses and click **Create New > Address**. b. Enter a name for the address. c. In the IP/Netmask field, enter 172.16.58.3/22. d. Select the port2 interface. e. Click **OK**. f. You may need to create another IP address for 192.168.3.11/16. 2. In the firewall UI, navigate to Policy & Objects > Firewall Policy and click **Create New**. #. In the Edit Policy dialog, configure the following for the TCP load balancer health check: - Name: a name of your choosing - Incoming Interface: port2 - Outgoing Interface: port2 - Source: select the 172.16.58.3/22 and 192.168.3.11/16 IP addresses you created in the previous step. - Destination: ilb-vip (or equivalent, as per what you configured in the previous section) - Schedule: always - Service: All - NAT: disabled 4. Click **OK**. #. Repeat steps 1-4 (or 2-4?) to create the UDP load balancer health check? #. Make sure these are added to the static routes (manually or via Vendor Integration). Configuring Basic Policy to allow VPC to VPC Traffic ------------------------------------------------------ You can configure a basic traffic security policy that allows traffic to pass through the firewall. 1. In the FortiGate UI, navigate to Policy & Objects > Firewall Policy and click **Create New** to configure the policy as per the following screenshot. #. In the New Policy dialog, configure the following for the basic traffic security policy: - Name: configure any name - Incoming Interface: port2 - Outgoing Interface: port2 - Source: all - Destination: all - Schedule: always - Service: All - Action: Accept - NAT: disabled |gcp_fortigate_policy_vpc_to_vpc| 3. Click **OK**. After validating that your traffic is being routed through your firewall instances, you can customize the security policy to your requirements. [Optional] Configuring Basic Policy to Allow Traffic from VPC to Internet ------------------------------------------------------------------------------ You can configure a basic traffic security policy that allows internet traffic to pass through the firewall. Given that Aviatrix gateways will only forward traffic to the LAN port of the Firewall, you set your policy condition to match any packet that is going into the LAN interface and out of the WAN interface. .. important:: Enable `Egress inspection <https://docs.aviatrix.com/HowTos/firewall_network_faq.html#how-do-i-enable-egress-inspection-on-firenet>`_ feature on FireNet. 1. In the Aviatrix Controller, navigate to Firewall Network > List > Firenet. #. Select the GCP transit gateway and click **Details**. #. On the next screen, under Egress Through Firewall, click **Enable**. |gcp_fortigate_egress_internet| #. In the FortiGate UI navigate to Policy & Objects > Firewall Policy and click **Create New**. #. In the New Policy dialog, configure the following: - Name: configure any name - Incoming Interface: port2 (LAN) - Outgoing Interface: port1 (WAN) - Source: Click on the + sign and add all - Destination: Click on the + sign and add all - Schedule: always - Service: ALL - Action: ACCEPT - NAT: Enable .. important:: NAT function needs to be enabled on this VPC to Internet policy. |gcp_fortigate_NAT| After validating that your traffic is being routed through your firewall instances, you can customize the security policy to your requirements. Validating your Configuration ----------------------------- Now your Security Gateway instance is configured and ready to receive packets. The next step is to validate your configurations and polices using FlightPath and Diagnostic Tools (ping, traceroute etc.). Viewing the Traffic Log ----------------------- You can view if traffic is forwarded to the firewall instance by logging in to the Fortigate Next Generation Firewall console. Navigate to Dashboard > FortiView Sessions or FortiView Destinations. Traffic can also be viewed from Log & Report. .. note:: To view Forward Traffic logs under Logs & Report, navigate to Policy & Objects > Firewall Policy. Select a policy and click **Edit**. Under Logging Options, select **All Sessions** for Log Allowed Traffic. Testing Traffic Flow ********************** You can configure a packet capture in the FortiGate UI to test traffic flow. |fortgcp_packetcapture| In this example, the spoke10 instance (172.22.130.4) pings the spoke20 instance (172.22.140.4). |fortgcp_packetcapture2| You can also use CoPilot AppIQ to check traffic flow and troubleshoot any issues. For more information on CoPilot AppIQ click `here <https://docs.aviatrix.com/HowTos/copilot_reference_guide.html?highlight=AppIQ>`_. .. |gcp_FortiGate_launch_instance| image:: config_FortiGate_media/gcp_FortiGate_launch_instance.png :scale: 35% .. |fg_first_login_1| image:: config_FortiGate_media/fg_first_login_1.png :scale: 30% .. |fg_first_login_2| image:: config_FortiGate_media/fg_first_login_2.png :scale: 30% .. |fg_first_login_3| image:: config_FortiGate_media/fg_first_login_3.png :scale: 30% .. |review_fggcp_interfaces| image:: config_FortiGate_media/review_fggcp_interfaces.png :scale: 30% .. |fort_admin_profile| image:: config_FortiGate_media/fort_admin_profile.png :scale: 25% .. |vendor_integration_fortgcp| image:: config_FortiGate_media/vendor_integration_fortgcp.png :scale: 30% .. |gcp_fortigate_policy_vpc_to_vpc| image:: config_FortiGate_media/gcp_fortigate_policy_vpc_to_vpc.png :scale: 30% .. |health-check| image:: config_FortiGate_media/health-check.png :scale: 30% .. |health-probe-logs| image:: config_FortiGate_media/health-probe-logs.png :scale: 30% .. |fortgcp_packetcapture| image:: config_FortiGate_media/fortgcp_packetcapture.png :scale: 30% .. |fortgcp_packetcapture2| image:: config_FortiGate_media/fortgcp_packetcapture2.png :scale: 30% .. |gcp_fortigate_egress_internet| image:: config_FortiGate_media/gcp_fortigate_egress_internet.png :scale: 30% .. |gcp_fortigate_NAT| image:: config_FortiGate_media/gcp_fortigate_NAT.png :scale: 30% .. disqus:: <file_sep> ================================================================= Bootstrap Configuration Example for FortiGate Firewall in AWS ================================================================= Using the bootstrap option significantly simplifies Fortinet FortiGate initial configuration setup. In this document, we provide a bootstrap example to set up an "Allow All" and Egress NAT policy for the FortiGate to validate that traffic is indeed sent to the FortiGate for VPC-to-VPC traffic inspection. For a manual setup, follow `manual setup example <https://docs.aviatrix.com/HowTos/config_FortiGateVM.html>`_. FortiGate also supports the User Data method as an alternative bootstrap mechanism. This mechanism is same for both AWS and Azure. To use the User Data method, see `Bootstrap with User Data on FortiGatew in Azure <https://docs.aviatrix.com/HowTos/fortigate_bootstrap_example_azure.html#method-1-configure-fortigate-firewall-via-user-data>`_. Creating an IAM Role and Policy -------------------------------------- 1. Log in to the AWS console and create an IAM role with the name: for example, "bootstrap-FortiGate-S3-role". 2. Attach an IAM policy with the name: for example, "bootstrap-FortiGate-S3-policy". The policy has the following statements. :: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:ListBucket" ], "Resource": [ "arn:aws:s3:::*" ] }, { "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": [ "arn:aws:s3:::*" ] } ] } Creating bootstrap Bucket Structure --------------------------------------------- In AWS S3, at the top level create a bucket for bootstrap with a **unique** name, for example "bootstrap-fortigate-bucket", with the following structure: :: bootstrap-fortigate-bucket/ init.conf license.lic Upload Config Giles ------------------------------- 1. The example init.conf file contains the "Allow All" setup. To download the file, click :download:`init.conf <fortigate_bootstrap_example_media/init.conf>`. 2. For the example license.lic file, click :download:`license.lic <fortigate_bootstrap_example_media/license.lic>`. For Metered AMI, this file is not required. .. Note:: You must specify the password in the example init.conf file. For initial Fortigate login information, go to `Credentials for FortiGate Initial Login <https://aviatrix.zendesk.com/hc/en-us/articles/4417531104781>`_. You must be registered to access the Aviatrix Customer Support website. If you are not already registered, you can sign-up at https://support.aviatrix.com. 3. Upload these two files to your config folder in the bootstrap-fortigate-bucket. Launching the Fortigate Instance ---------------------------------------------- Follow the Aviatrix Firewall Network (FireNet) workflow to `this step <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#launching-and-associating-firewall-instance>`_. Fill in the required fields. Click **Advanced**. Fill in the following parameters. ================================ ====================== **Advanced Field** **Example Value** ================================ ====================== IAM Role bootstrap-FortiGate-S3-role Bootstrap Bucket Name fortigate-bootstrap-bucket (must be a unique name in S3) ================================ ====================== Launch the instance. Wait for 15 minutes for it to boot up and initialize. Log in to the HTTPS interface of the public IP with username "admin" and the password specified in the example init.conf file. You should change the username and password after the initial login. Configuring Static Routes -------------------------------------- Follow `the instructions here <https://docs.aviatrix.com/HowTos/config_FortiGateVM.html#create-static-routes-for-routing-of-traffic-vpc-to-vpc>`_ to configure the static routes. Ready to Go -------------------- Now your firewall instance is ready to receive packets. The next step is to specify which Security Domain needs packet inspection by defining a connection policy that connects to the firewall domain. This is done by `this step <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#specify-security-domain-for-firewall-inspection>`_ in the Firewall Network workflow. For example, deploy Spoke-1 VPC in Security_Domain_1 and Spoke-2 VPC in Security_Domain_2. Build a connection policy between the two domains. Build a connection between Security_Domain_2 to Firewall Domain. Launch one instance in Spoke-1 VPC and Spoke-2 VPC. From one instance, ping the other instance. The ping should go through. .. |bootstrap_bucket| image:: bootstrap_example_media/bootstrap_bucket.png :scale: 30% .. disqus:: <file_sep> =============================================================== Aviatrix Controller Security for SAML auth based VPN Deployment =============================================================== Best practices call for the Aviatrix Controller to be not widely accessible from the internet. Access on TCP port 443 should be limited to - the management range of IPs coming from the Enterprise or the Datacenter, and - access to/from each of the deployed gateways for general communication/keep-alives. However, the exception to that rule is when `Aviatrix SAML authentication <http://docs.aviatrix.com/HowTos/VPN_SAML.html>`_ is used for user VPN access. In this case, the VPN user first contacts the Controller which then redirects user browser traffic to an IDP. This initial traffic runs on TCP port 443 and as vpn users are located in off site locations, the Controller TCP port 443 needs to open to all which may cause security concerns. In order to accommodate for both functions in a secure manner, please follow the instructions below to secure your controller when SAML authentication is being used. Pre-requisites ====================== - We assume you already know how to deploy the Aviatrix solution. If you need help, check out this `reference design <https://s3-us-west-2.amazonaws.com/aviatrix-download/Cloud-Controller/Cloud+Networking+Reference+Design.pdf>`__. - You have deployed Aviatrix SAML authentication for your user VPN access. Configuration Workflow when SAML is configured =============================================== 1. Go to your AWS console and under EC2->Load Balancer, click on "Create Load Balancer": Type: Application Load Balancer Name: << Insert LB name >> Scheme: internet-facing IP address Type: ipv4 #. Add Listener HTTPS port 443 Listeners: Protocol: HTTPS(443) #. In the Availability Zones section, select the VPC and AZ where your Aviatrix Controller currently resides. #. Availability zones: Select all sub regions #. Click next. #. For certificate upload from ACM, use your self/CA signed certificates. If you already have a Route53 domain name, an ACM certificate can be requested for your domain and can be easily validated through email. You will need to add a record in your DNS with CNAME pointing the load balancer to match the certificate used for the load balancer. Note: for self signed certificate select Security Policy: ELBSecurityPolicy-2015-05 #. Click next. #. Configure security groups to make it accessible to the world. Type: ALL TCP Protocol: TCP Port Range: 0-65535 Source: 0.0.0.0/0 #. Click next. #. On the Configure routing page, create a new target group for HTTPS:443 : Target group: New target group Name: << Insert Target group name >> Protocol: HTTPS Port: 443 Target type: instance #. Health checks: Protocol: HTTPS Path: / #. Click next #. On the Register target page, select the Aviatrix Controller instance and click "add to register" #. Click on next to go to the review page #. Review and then click on "Create" #. Select the new loadbalancer, on the lower tabs select Listeners #. Select the current listener on port 443 and click on "View/Edit Rules" #. Add new rule: If: Path-is: /flask/* Then: Forward: << Select the recently created Target Group >> On the Controller #. Configure SAML by accessing the controller through the loadbalancer's certificate domain name. This will generate everything (URLs for the IDP and VPN user certificates) with respect to the DNS name. If you had configured SAML already, you will need to update the Assertion consumer URLs at the IDP to the domain name of the signed certificate. After you download the VPN user certificate, ensure that the domain name in the #AviatrixController section is set correctly(If not, update it) .. note:: The Controller's security group for 443 must allow from Loadbalancer's internal IP address which can be usually VPC CIDR and also the Gateways public IP To block general access: 1. After the SAML configuration is complete, you can block general access to your controller. Create a dummy target group pointing to an invalid port path rule / will be pointing to an dummy target group path rule /flask will be pointing to valid target group at HTTPS 443 to controller. By doing this only the SAML application is being forwarded by the ELB and is open to the world This ensures that the rest of the controller configuration is open to the admin alone. .. add in the disqus tag .. disqus:: <file_sep> ================================= Use Azure IAM Custom Role ================================= When Aviatrix Controller uses Azure API to manage networking and gateway resources, an application must be first created in Azure AD with an identity of Service Principal. This service principal requires an Azure IAM role assignment together with a set of permissions required by the Aviatrix Controller to provide service. By default, we use the Azure built-in "Contributor" role. The Contributor role has access to all resources of the subscription. If you wish to limit the Controller access permissions, you can do so by creating a custom role with a set of permissions required by the Controller as shown below. This document describes how to accomplish this task through the Azure portal. Aviatrix Required Custom Role Permissions --------------------------------------------------------- :: { "properties": { "roleName": "Aviatrix Controller Custom Role", "description": "Custom role for Aviatrix Controller", "assignableScopes": [], "permissions": [ { "actions": [ "Microsoft.MarketplaceOrdering/offerTypes/publishers/offers/plans/agreements/*", "Microsoft.Compute/*/read", "Microsoft.Compute/availabilitySets/*", "Microsoft.Compute/virtualMachines/*", "Microsoft.Compute/disks/*", "Microsoft.Network/*/read", "Microsoft.Network/publicIPAddresses/*", "Microsoft.Network/networkInterfaces/*", "Microsoft.Network/networkSecurityGroups/*", "Microsoft.Network/loadBalancers/*", "Microsoft.Network/routeTables/*", "Microsoft.Network/virtualNetworks/*", "Microsoft.Storage/storageAccounts/*", "Microsoft.Resources/*/read", "Microsoft.Resourcehealth/healthevent/*", "Microsoft.Resources/deployments/*", "Microsoft.Resources/tags/*", "Microsoft.Resources/marketplace/purchase/*", "Microsoft.Resources/subscriptions/resourceGroups/*" ], "notActions": [], "dataActions":[], "notDataActions":[] } ] } } * For Azure China, please remove "Microsoft.MarketplaceOrdering/offerTypes/publishers/offers/plans/agreements/*" and "Microsoft.Resources/marketplace/purchase/*" from "actions". Creating a Custom Role ---------------------------------------------------- 1. Log in to the Azure portal. Go to Subscriptions. Select the subscription whose network already managed by Aviatrix Controller. 2. Click **Access control (IAM)**. 3. Click **Roles**, as shown below. |iam_role| 4. Click **+Add Role** and select **Add custom role**. 5. Select **Start from scratch** and click **Next**, as shown below. |start_from_scratch| 6. Click **JSON**, and then click **Edit**. |click_json| 7. Remove the existing JSON template and copy and paste the above Aviatrix required permissions JSON into the Editor box, as shown below. Click **Save**. |aviatrix_custom_role| 8. Click **Permissions**. You should see the permissions have been populated, as shown below. |show_permission| 9. Click **Assignable scopes** and then **Add assignable scopes**. Select the subscription. 10. Click **JSON**. You should say the subscription has been added to the assignable Scopes, as shown below. |subscription_scope| 11. Click **Review + create**, and then click **Create**. Replacing the Contributor Role --------------------------------------- This step is optional. It is only applicable if you have already assigned the "Contributor" role to the Aviatrix Controller service principal. If not, skip this step and proceed to the next step. 1. Now that you have created a custom role called Aviatrix Controller Custom Role, go ahead replace the Contributor role, as shown below. |remove_contributor| 2. Click **+Add**, select **Add role assignment**. Fill in the fields as shown below. |replace_role| Multiple Custom Roles Approach ------------------------------------------------------ The Aviatrix role permissions can be split into multiple custom roles each with a subset of permissions. Subscription permission must be at the subscription scope. The additional permission may have the scope of one or more Resource Groups. Below is an example where the "Aviatrix Custom Role for subscription" has the scope of subscription and the remaining permissions has the scope of Resource Group. Subscription Scope IAM Custom Role ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :: { "properties": { "roleName": "Aviatrix Custom Role for subscription", "description": "Aviatrix Custom role for gateway subscription permission", "assignableScopes": [], "permissions": [ { "actions": [ "Microsoft.MarketplaceOrdering/offerTypes/publishers/offers/plans/agreements/*" ], "notActions": [], "dataActions":[], "notDataActions":[] } ] } } Resource Group Scope IAM Custom role ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Note when creating a custom role for a resource group on Azure portal, start at Subscription > Resource groups, select one resource group, and click **Access Control (IAM)**. Then, follow the role creation process with the permission described in the file below to create the role. When configuring Assignable scopes, select one or more resource groups (it is multi-selectable) for this role. After the role is created, assign the role to the Service principal of the Aviatrix Controller application. .. note:: It takes a few minutes for the display to appear for the custom role just created. Once it can be displayed, you can find it by going to Subscription > Resource groups > select one resource group assigned to the role, then click **Access Control (IAM)**, then click **Roles**. Then search for the role you just created. :: { "properties": { "roleName": "Aviatrix Custom Role for services", "description": "Aviatrix Custom role for the network and gateway services", "assignableScopes": [], "permissions": [ { "actions": [ "Microsoft.Compute/*/read", "Microsoft.Compute/availabilitySets/*", "Microsoft.Compute/virtualMachines/*", "Microsoft.Network/*/read", "Microsoft.Network/publicIPAddresses/*", "Microsoft.Network/networkInterfaces/*", "Microsoft.Network/networkSecurityGroups/*", "Microsoft.Network/loadBalancers/*", "Microsoft.Network/routeTables/*", "Microsoft.Network/virtualNetworks/*", "Microsoft.Storage/storageAccounts/*", "Microsoft.Resources/*/read", "Microsoft.Resourcehealth/healthevent/*", "Microsoft.Resources/deployments/*", "Microsoft.Resources/tags/*", "Microsoft.Resources/marketplace/purchase/*", "Microsoft.Resources/subscriptions/resourceGroups/*" ], "notActions": [], "dataActions":[], "notDataActions":[] } ] } } .. tip :: If you wish to use Contributor role for the above part of the permission, ignore the JSON file listed above. Simply navigate to the Azure portal > Resource groups > select the resource group. Click **Access Control (IAM)** > **+Add** > **Add Role assignment**. Then, select **Contributor** as the Role and assign the Contributor role to the Aviatrix Controller service principal. Additional References -------------------------- To learn more on Azure custom role and how to configure it, see `Azure Custom Roles. <https://docs.microsoft.com/en-us/azure/role-based-access-control/custom-roles>`_ To view the complete Azure role permissions, refer to `Azure resource provider operations. <https://docs.microsoft.com/en-us/azure/role-based-access-control/resource-provider-operations>`_. .. |aviatrix_custom_role| image:: azure_custom_role_media/aviatrix_custom_role.png :scale: 30% .. |iam_role| image:: azure_custom_role_media/iam_role.png :scale: 30% .. |remove_contributor| image:: azure_custom_role_media/remove_contributor.png :scale: 30% .. |start_from_scratch| image:: azure_custom_role_media/start_from_scratch.png :scale: 30% .. |click_json| image:: azure_custom_role_media/click_json.png :scale: 30% .. |replace_role| image:: azure_custom_role_media/replace_role.png :scale: 30% .. |subscription_scope| image:: azure_custom_role_media/subscription_scope.png :scale: 30% .. |show_permission| image:: azure_custom_role_media/show_permission.png :scale: 30% .. disqus:: <file_sep> ================================= Access Account ================================= The Aviatrix Controller is a multi-cloud and multi-accounts platform. The Controller uses your cloud provider API credentials to make API calls, for example, to launch an Aviatrix gateway instance, on behalf of your cloud accounts. One cloud credential is represented as an Aviatrix access account on the Controller. The Controller supports multiple Aviatrix accounts. One Aviatrix account may represent multiple cloud credentials, one from each cloud. For example, an Aviatrix account name DevOps can have an IAM role for AWS, Azure ARM credentials, and GCP credentials. Starting from release 3.2, an access account for AWS only consists of the 12-digit account ID. * For Azure, the account information consists of `Azure ARM credentials. <http://docs.aviatrix.com/HowTos/Aviatrix_Account_Azure.html>`_ * For GCP (Google Cloud), the account information consists of `GCP credentials. <http://docs.aviatrix.com/HowTos/CreateGCloudAccount.html>`_ * For AWS China, please refer `Account with Access Key <http://docs.aviatrix.com/HowTos/accesskey.html>`_. The Aviatrix account structure is shown in the diagram below, where admin is the default user for the primary access account. |account_structure| To add more admin users, refer to `this doc. <http://docs.aviatrix.com/HowTos/AdminUsers_DuoAuth.html>`_ Setting up a Primary Access Account for AWS Cloud ------------------------------------------------------------------------- For AWS, a `primary access account <http://docs.aviatrix.com/HowTos/onboarding_faq.html#what-is-the-aviatrix-primary-access-account>`_ is created during the onboarding process. Using this account credential, the Controller can launch gateways and build connectivity on VPCs that belong to this AWS account. Setting Up Additional Access Accounts for AWS Cloud ------------------------------------------------------------------- After you go through the onboarding process and create the primary access account, you can create additional or secondary Aviatrix access accounts on the Controller. This allows you to launch gateways and build connectivity across different AWS accounts. The configuration steps are shown below: |access_account_35| The above diagram is described in the following steps. 1. Go to Aviatrix -> Accounts -> Access Accounts #. Click **+New Account** to create this new secondary account. #. Enter a unique account name: for example, BU-Group-3. #. Mark the **AWS** checkbox. #. Mark the **IAM role-based** checkbox (enabled by default). #. Enter the secondary account's `AWS 12-digit account number <https://docs.aws.amazon.com/IAM/latest/UserGuide/console_account-alias.html>`_. #. Click **Launch CloudFormation Script** to go to the AWS Console and run the CloudFormation script to setup IAM roles and policies and establish a trust relationship with the primary account. When finished, return to this page and proceed to the next step. #. Click **OK**. #. The new secondary account is created. #. Now you can create connectivity between two VPCs in different AWS accounts. Setting Up Additional Access Accounts Using Terraform -------------------------------------------------------------- If you use Terraform to create more access accounts, you need to run the CloudFormation script on each secondary account first, then use Terraform account resource to create the account. :: Follow the above section, but only execute step 7 to run the CloudFormation script that creates IAM roles, policies and build trust relationship to the primary account (the Controller account). The CloudFormation is necessary to create IAM roles and policies and to establish a trust relationship with the primary account (the account where the Controller is launched.) .. |secondary_account| image:: adminusers_media/secondary_account.png :scale: 30% .. |account_structure| image:: adminusers_media/account_structure.png :scale: 30% .. |access_account_35| image:: adminusers_media/access_account_35.png :scale: 30% .. |account_name_alias| image:: adminusers_media/account_name_alias.png :scale: 30% .. disqus:: <file_sep> ========================================================================================= Aviatrix Global Transit Network with AWS S3 end point ========================================================================================= This technical note provides a step-by-step configuration on the Aviatrix controller that will address the following requirements: 1. Deploy Aviatrix Global Transit Network - https://docs.aviatrix.com/HowTos/transitvpc_workflow.html 2. Deploy AWS Endpoint for Amazon S3 in a Shared Service VPC - https://docs.aws.amazon.com/vpc/latest/userguide/vpc-endpoints-s3.html 3. On-Prem privately connects to AWS S3 service/AWS S3 Bucket via Shared Service Spoke VPC end point in a specific region 4. Spoke VPCs privately connect to AWS S3 service/AWS S3 Bucket via Shared Service Spoke VPC end point in a specific region Topology: 1. Aviatrix Global Transit Network for AWS - Spoke VPCs * 3 - Transit VPC * 1 - AWS VGW :: Example: Spoke VPC 1: 192.168.1.0/24 Spoke VPC 2: 192.168.2.0/24 Shared Service Spoke VPC: 192.168.99.0/24 [region us-east-1] Transit VPC: 192.168.100.0/24 2. On-Prem CIDR :: Example: On-Prem: 10.3.0.0/16 3. End point for Amazon S3/Bucket service in region us-east-1 |S3_ENDPOINT_TRANSIT_SOLUTION| Scenario: 1. Traffic from On-Prem to AWS S3 service/AWS S3 Bucket via Shared Service Spoke VPC end point in region us-east-1 - Traffic which is sent from On-Prem to AWS S3 service/AWS S3 Bucket goes through Aviatrix Transit Gateway and Aviatrix Spoke Gateway along with IPSec VPN tunnel and AWS end point service. In addition, regarding to AWS requirement, traffic to AWS VPC S3 end point needs to be source NATed on Aviatrix Spoke Gateway in the Shared Service VPC. 2. Traffic from Spoke VPCs to AWS S3 service/AWS S3 Bucket via Shared Service Spoke VPC end point in region us-east-1 - Traffic which is sent from Spoke VPCs in cloud to AWS S3 service/AWS S3 Bucket goes through Aviatrix Transit Gateway and Aviatrix Spoke Gateway along with IPSec VPN tunnel and AWS end point service. In addition, regarding to AWS requirement, traffic to AWS VPC S3 end point needs to be source NAT on Aviatrix Spoke Gateway in the Shared Service VPC. Notes: 1. AWS S3 service/S3 bucket has different public CIDR range regarding to region. Here is the link for AWS service CIDR: https://ip-ranges.amazonaws.com/ip-ranges.json Additionally, those S3 service CIDR can be found on end point routing entry on AWS routing table. |AWS_S3_ENDPOINT| 2. Since AWS S3 end point changes 'the source IPv4 addresses from instances in your affected subnets as received by Amazon S3 change from public IPv4 addresses to the private IPv4 addresses from your VPC', we need to perform source NAT function on Aviatrix Spoke Gateway in the Shared Service VPC for the traffic from On-Prem or other Spoke VPCs to reach AWS S3 service/S3 buckets via AWS end point properly. https://docs.aws.amazon.com/vpc/latest/userguide/vpc-endpoints-s3.html 3. Users from on-prem or other Spoke VPCs can access only S3 buckets which are in the same region as the Shared Service Spoke VPC locates. In other words, AWS S3 Service/S3 buckets and the Shared Service Spoke VPC need to be deployed in the same region. 4. Users are able to customize VPC endpoint policy to restricting access to a specific bucket. Follow the steps below to set up for the scenario. Step 1. Prerequisite ------------------------- 1.1. Upgrade the Aviatrix Controller to at least version UserConnect-4.7.591 - https://docs.aviatrix.com/HowTos/inline_upgrade.html 1.2. Prepare a region where both S3 buckets and Shared Service VPC locate (for example: us-east-1). Notes: this solution only can access the S3 Service/S3 Bucket in the same region where the Shared Service Spoke VPC locate. Step 2. Build Aviatrix Global Transit Network FOR AWS ------------------------- - deploy the topology by following the online document https://docs.aviatrix.com/HowTos/transitvpc_workflow.html Step 3. Deploy AWS S3 end point in Shared Service VPC ------------------------- - https://docs.aws.amazon.com/vpc/latest/userguide/vpc-endpoints-s3.html - ensure the AWS subnet/routing table where Aviatrix Shared Service Spoke gateway locates is selected when AWS S3 end point is created Step 4. Perform Customize Spoke Advertised VPC CIDRs feature on the Aviatrix Spoke gateway in the Shared Service VPC ------------------------- - https://docs.aviatrix.com/HowTos/gateway.html#customize-advertised-spoke-vpc-cidrs This action will advertise the customized routes to On-Prem via BGP session and other Aviatrix Spoke Gateways if the function Connected Transit is enabled. :: Example: AWS S3 service CIDR in region us-east-1: 172.16.58.3/17 and 172.16.58.3/15 To configure: 4.1. Go to the Gateway page, click on the Aviatrix Spoke Gateway first in Shared Service VPC. Click Edit. 4.2. Continue on to the Edit page, scroll to Customize Spoke Advertised VPC CIDRs. 4.3. Enter the value of the On-Prem routable CIDR - for example: 172.16.58.3/17,172.16.58.3/15,192.168.99.0/24 - notes: 192.168.99.0/24 in this example is the Shared Service VPC CIDR 4.4. Click the button "Save" |SHARED_SERVICE_SPOKE_CUSTOMIZE_SPOKE_ADVERTISED_VPC_CIDRS| Step 5. Configure Aviatrix Customized SNAT function on Aviatrix Spoke Gateway in Shared Service VPC ------------------------- - https://docs.aviatrix.com/HowTos/gateway.html#customized-snat This action changes the packet’s source IP address from On-Prem or other Spoke VPCs in the Cloud to the private IP of Aviatrix Spoke Gateway in Shared Service VPC. :: Example: Spoke Gateway: traffic to the IP range of AWS S3 Service in region us-east-1 (for example: 172.16.58.3/17 and 172.16.58.3/15) translates to IP 192.168.99.18 To configure: 5.1. Go to the Gateway page, click on the Aviatrix Spoke Gateway first in Shared Service VPC. Click Edit. 5.2. Continue on to the Edit page, scroll to SNAT. Select Customized SNAT. 5.3. Select Customized SNAT 5.4. Click Add New 5.5. Enter fields for Src CIDR, protocol, Interface (select Interface eth0) and SNAT IP as below example. 5.6. Click Save 5.7. Repeat the above steps for more entries. 5.8. Click Enable SNAT to commit. |SNAT_SHARED_SERVICE_SPOKE_PRIMARY| 5.9. Go to Gateway page, click on the Aviatrix Spoke HA Gateway. Click Edit. 5.10. Repeat the above steps to configure Customized SNAT for Aviatrix Spoke HA Gateway with its own private IP. Step 6. Perform Connected Transit feature to build a full mesh network where Spoke VPCs communicate with each other via Transit GW ------------------------- - https://docs.aviatrix.com/HowTos/site2cloud.html#connected-transit To configure: 6.1 Go to the Transit Network -> Advanced Config -> Edit Transit 6.2 Click the toggle button on "Connected Transit" Step 7. Verify S3 traffic flow ------------------------- 7.1. Traffic from On-Prem -> Transit -> Shared Service Spoke -> AWS S3 service/S3 bucket - Issue AWS S3 CLI from On-Prem |ONPREM_AWS_S3_CLI| - Execute packet capture on the tunnel interface of Aviatrix Shared Service Spoke |ONPREM_SHARED_SPOKE_TUN| - Execute packet capture on the eth0 interface of Aviatrix Shared Service Spoke and check whether On-Prem IP has been sourced NATed to the private IP of the eth0 interface of Aviatrix Shared Service Spoke |ONPREM_SHARED_SPOKE_ETH0| 7.2. Traffic from Spoke -> Transit -> Shared Service Spoke -> AWS S3 service/S3 bucket - Issue AWS S3 CLI from Spoke VPC |SPOKE_AWS_S3_CLI| - Execute packet capture on the tunnel interface of Aviatrix Shared Service Spoke |SPOKE_SHARED_SPOKE_TUN| - Execute packet capture on the eth0 interface of Aviatrix Shared Service Spoke and check whether Spoke VPC's IP has been sourced NATed to the private IP of the eth0 interface of Aviatrix Shared Service Spoke |SPOKE_SHARED_SPOKE_ETH0| .. |S3_ENDPOINT_TRANSIT_SOLUTION| image:: transit_s3_end_point/S3_ENDPOINT_TRANSIT_SOLUTION.png :scale: 60% .. |AWS_S3_ENDPOINT| image:: transit_s3_end_point/AWS_S3_ENDPOINT.png :scale: 30% .. |SNAT_SHARED_SERVICE_SPOKE_PRIMARY| image:: transit_s3_end_point/SNAT_SHARED_SERVICE_SPOKE_PRIMARY.png :scale: 30% .. |SHARED_SERVICE_SPOKE_CUSTOMIZE_SPOKE_ADVERTISED_VPC_CIDRS| image:: transit_s3_end_point/SHARED_SERVICE_SPOKE_CUSTOMIZE_SPOKE_ADVERTISED_VPC_CIDRS.png :scale: 30% .. |ONPREM_AWS_S3_CLI| image:: transit_s3_end_point/ONPREM_AWS_S3_CLI.png :scale: 30% .. |ONPREM_SHARED_SPOKE_TUN| image:: transit_s3_end_point/ONPREM_SHARED_SPOKE_TUN.png :scale: 30% .. |ONPREM_SHARED_SPOKE_ETH0| image:: transit_s3_end_point/ONPREM_SHARED_SPOKE_ETH0.png :scale: 30% .. |SPOKE_AWS_S3_CLI| image:: transit_s3_end_point/SPOKE_AWS_S3_CLI.png :scale: 30% .. |SPOKE_SHARED_SPOKE_TUN| image:: transit_s3_end_point/SPOKE_SHARED_SPOKE_TUN.png :scale: 30% .. |SPOKE_SHARED_SPOKE_ETH0| image:: transit_s3_end_point/SPOKE_SHARED_SPOKE_ETH0.png :scale: 30% .. disqus:: <file_sep> ================================================ Aviatrix IAM Policy Requirements ================================================ Introduction ============ This documentation explains why AWS IAM permissions are needed by Aviatrix, and specifies which ones. .. note:: * The Aviatrix IAM Policy **aviatrix-app-policy** has reached the max-character-limitation. * Wildcard/all (*) is the default resource for all Aviatrix IAM permissions except for #13, “`IAM Policy Scanning Requirement <https://docs.aviatrix.com/HowTos/aviatrix_iam_policy_requirements.html#iam-policy-scanning-requirement>`_”. This resource needs to be customized per your resource requirements to be secure. We advise you to work with your Aviatrix account team to restrict what resources need to be in scope for your IAM policy. 1. SQS Requirement -------------------------------- SQS permission is required as the Aviatrix Controller uses an SQS messages queue to communicate with the gateways. This permission applies to all use cases where there is an Aviatrix Gateway. :: { "Action": [ "sqs:Get*", "sqs:List*", "sqs:AddPermission", "sqs:ChangeMessageVisibility", "sqs:CreateQueue", "sqs:DeleteMessage", "sqs:DeleteQueue", "sqs:PurgeQueue", "sqs:ReceiveMessage", "sqs:RemovePermission", "sqs:SendMessage", "sqs:SetQueueAttributes", "sqs:TagQueue" ], "Resource":"*", "Effect": "Allow" } | 2. Aviatrix Gateway Deployment Requirement ------------------------------------------------------------- This applies to all use cases where an Aviatrix Gateway needs to be launched. Aviatrix gateway deployment requires permissions from the following categories: + Security iroup + Key pair + Network interface + EIP + IAM - Security Group: Aviatrix creates a Security Group to associate Aviatrix gateways and provide security at the protocol and port access level. - IAM: Aviatrix will check if the user's IAM role has the correct configuration or not. If not, Aviatrix will fix the issue during gateway creation. - For the permission, "ec2:ModifyInstanceCreditSpecification": If your gateway type/size is under AWS T2-series category (t2.medium, t2.large, etc.) Aviatrix software will try to enable the AWS feature, T2-Unlimited for you. This is an optional feature which is not required and won’t impact your gateway operations. You can still manually enable this feature manually later from AWS console. :: { "Action": [ "ec2:Describe*", "ec2:Get*", "ec2:Search*", "ec2:RunInstances", "ec2:TerminateInstances", "ec2:ModifyInstanceAttribute", "ec2:ResetInstanceAttribute", "ec2:MonitorInstances", "ec2:ReportInstanceStatus", "ec2:UnmonitorInstances", "ec2:CreateTags", "ec2:DeleteTags", "ec2:CreateKeyPair", "ec2:DeleteKeyPair", "ec2:AttachNetworkInterface", "ec2:CreateNetworkInterface", "ec2:DeleteNetworkInterface", "ec2:DetachNetworkInterface", "ec2:ModifyNetworkInterfaceAttribute", "ec2:ResetNetworkInterfaceAttribute", "ec2:AllocateAddress", "ec2:AssociateAddress", "ec2:DisassociateAddress", "ec2:ReleaseAddress", "ec2:AssignPrivateIpAddresses", "ec2:UnassignPrivateIpAddresses", "ec2:DeleteSecurityGroup", "ec2:RevokeSecurityGroupEgress", "ec2:RevokeSecurityGroupIngress", "ec2:AuthorizeSecurityGroup*", "ec2:CreateSecurityGroup", "ec2:ModifyInstanceCreditSpecification", "iam:List*", "iam:Get*", "iam:PassRole", "iam:AddRoleToInstanceProfile", "iam:CreateInstanceProfile", "iam:DeleteInstanceProfile", "iam:RemoveRoleFromInstanceProfile" ], "Resource": "*", "Effect": "Allow" } | 3. Aviatrix Transit Network & TGW-Orchestrator requirement ------------------------------------------------------------------------------- The Aviatrix Transit Network feature requires the following additional permissions to create an AWS Customer Gateway before creating an AWS VPN connection to connect an Aviatrix Transit Gateway to an AWS VGW. :: { "Action": [ "ec2:CreateCustomerGateway", "ec2:DeleteCustomerGateway", "ec2:CreateVpnConnection", "ec2:DeleteVpnConnection", "ec2:CreateVpcPeeringConnection", "ec2:AcceptVpcPeeringConnection", "ec2:DeleteVpcPeeringConnection", "ec2:EnableVgwRoutePropagation", "ec2:DisableVgwRoutePropagation" ], "Resource": "*", "Effect": "Allow" }, { "Action": [ "ec2:AssociateTransitGatewayRouteTable", "ec2:AcceptTransitGatewayVpcAttachment", "ec2:CreateTransitGateway", "ec2:CreateTransitGatewayRoute", "ec2:CreateTransitGatewayRouteTable", "ec2:CreateTransitGatewayVpcAttachment", "ec2:DeleteTransitGateway", "ec2:DeleteTransitGatewayRoute", "ec2:DeleteTransitGatewayRouteTable", "ec2:DeleteTransitGatewayVpcAttachment", "ec2:DisableTransitGatewayRouteTablePropagation", "ec2:DisassociateTransitGatewayRouteTable", "ec2:EnableTransitGatewayRouteTablePropagation", "ec2:ExportTransitGatewayRoutes", "ec2:ModifyTransitGatewayVpcAttachment", "ec2:RejectTransitGatewayVpcAttachment", "ec2:ReplaceTransitGatewayRoute", "ec2:EnableRoutePropagation", "ec2:*TransitGatewayPeeringAttachment" ], "Resource": "*", "Effect": "Allow" }, { "Action": [ "ram:CreateResourceShare", "ram:DeleteResourceShare", "ram:UpdateResourceShare", "ram:AssociateResourceShare", "ram:DisassociateResourceShare", "ram:TagResource", "ram:UntagResource", "ram:AcceptResourceShareInvitation", "ram:EnableSharingWithAwsOrganization" ], "Resource": "*", "Effect": "Allow" }, { "Action": [ "directconnect:CreateDirectConnectGateway", "directconnect:CreateDirectConnectGatewayAssociation", "directconnect:CreateDirectConnectGatewayAssociationProposal", "directconnect:DeleteDirectConnectGateway", "directconnect:DeleteDirectConnectGatewayAssociation", "directconnect:DeleteDirectConnectGatewayAssociationProposal", "directconnect:AcceptDirectGatewayAssociationProposal" ], "Resource": "*", "Effect": "Allow" } | 4. Peering Requirement --------------------------------- Aviatrix features such as Transit Network, Encrypted Peering, Transitive Peering, etc. require the following permissions. :: { "Action": [ "ec2:CreateRoute", "ec2:DeleteRoute", "ec2:ReplaceRoute" ], "Resource": "*", "Effect": "Allow" } | 5. Gateway Resizing requirement ------------------------------------------- An Aviatrix gateway needs to be in the STOP state before the instance type/size is modified. :: { "Action": [ "ec2:StartInstances", "ec2:StopInstances" ], "Resource": "*", "Effect": "Allow" } | 6. VPN Gateway & Load Balancer Requirement ------------------------------------------------------------ * Aviatrix VPN feature requires the following (and gateway creation) permissions if the user chooses to create an NLB/ELB along with the VPN gateway creation. * For "iam:CreateServiceLinkedRole": A service-linked role is a unique type of IAM role that is linked directly to an AWS service. Service-linked roles are predefined by the service and include all the permissions that the service requires to call other AWS services on your behalf. Hence, the service linked role is required to confirm that you allow Elastic Load Balancing to make calls to other services. See the following AWS documentations for more information. + `AWS Doc 1 <https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/elb-service-linked-roles.html#service-linked-role-permissions>`__ + `AWS Doc 2 <https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/elb-service-linked-roles.html#create-service-linked-role>`__ + `AWS Doc 3 <https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/elb-api-permissions.html#required-permissions-v2>`__ * These permissions also apply to Private Mode and GWLB-based FireNet. :: { "Action": [ "elasticloadbalancing:Describe*", "elasticloadbalancing:ApplySecurityGroupsToLoadBalancer", "elasticloadbalancing:AttachLoadBalancerToSubnets", "elasticloadbalancing:ConfigureHealthCheck", "elasticloadbalancing:CreateLoadBalancer*", "elasticloadbalancing:DeleteLoadBalancer*", "elasticloadbalancing:DeregisterInstancesFromLoadBalancer", "elasticloadbalancing:ModifyLoadBalancerAttributes", "elasticloadbalancing:SetLoadBalancerPoliciesForBackendServer", "elasticloadbalancing:RegisterInstancesWithLoadBalancer", "elasticloadbalancing:CreateTargetGroup", "elasticloadbalancing:DescribeTargetGroups", "elasticloadbalancing:DeleteTargetGroup", "elasticloadbalancing:CreateListener", "elasticloadbalancing:DescribeListeners", "elasticloadbalancing:DeleteListener", "elasticloadbalancing:RegisterTargets", "elasticloadbalancing:DeregisterTargets", "iam:CreateServiceLinkedRole" ], "Resource": "*", "Effect": "Allow" } | 7. VPN with AWS-Global-Accelerator ----------------------------------------------- In order to enable a VPN with the AWS-Global-Accelerator feature, the following permissions are needed. :: { "Action": [ "globalaccelerator:*" "globalaccelerator:CreateAccelerator", "globalaccelerator:CreateEndpointGroup", "globalaccelerator:CreateListener", "globalaccelerator:DeleteAccelerator", "globalaccelerator:DeleteEndpointGroup", "globalaccelerator:DeleteListener", "globalaccelerator:DescribeAccelerator", "globalaccelerator:DescribeAcceleratorAttributes", "globalaccelerator:DescribeEndpointGroup", "globalaccelerator:DescribeListener", "globalaccelerator:GetWaiter", "globalaccelerator:ListAccelerators", "globalaccelerator:ListEndpointGroups", "globalaccelerator:ListListeners", "globalaccelerator:UpdateAccelerator", "globalaccelerator:UpdateAcceleratorAttributes", "globalaccelerator:UpdateEndpointGroup", "globalaccelerator:UpdateListener" ], "Resource": "*", "Effect": "Allow" } | 8. GuardDuty Requirement ------------------------------------- In order to enable GuardDuty, the following permissions are needed. :: { "Action": [ "guardduty:Get*", "guardduty:List*", "guardduty:CreateDetector", "guardduty:DeleteDetector", "guardduty:UpdateDetector", "ec2:CreateNetworkAclEntry", "ec2:ReplaceNetworkAclEntry", "ec2:DeleteNetworkAclEntry" ], "Resource": "*", "Effect": "Allow" } | 9. Aviatrix Gateway Single AZ HA Requirement ------------------------------------------------------------- In order to enable the Aviatrix Gateway Single AZ HA feature, the following permission is needed. :: { "Action": [ "ec2:RebootInstances" ], "Resource": "*", "Effect": "Allow" } | 10. Controller Backup & Restore Requirement ----------------------------------------------------------------- In order to enable the Controller Backup & Restore feature, the following permissions are needed. :: { "Action": [ "s3:List*", "s3:Get*", "s3:PutObject", "s3:DeleteObject" ], "Resource": "*", "Effect": "Allow" } | 11. EBS Volume Encryption Requirement -------------------------------------------------------- In order to enable the EBS Volume Encryption feature, the following permissions are needed. :: { "Action": [ "ec2:DescribeInstances", "ec2:StopInstances", "ec2:StartInstances", "ec2:DescribeVolumes", "ec2:CreateVolume", "ec2:DeleteVolume", "ec2:AttachVolume", "ec2:DetachVolume", "ec2:DescribeSnapshots", "ec2:CopySnapshot", "ec2:CreateSnapshot", "ec2:DeleteSnapshot" ], "Resource": "*", "Effect": "Allow" } | 12. AWS Peering Requirement -------------------------------------------- In order to create an AWS Peering, the following permissions are needed. :: { "Action": [ "ec2:CreateVpcPeeringConnection", "ec2:AcceptVpcPeeringConnection", "ec2:DeleteVpcPeeringConnection" ], "Resource": "*", "Effect": "Allow" } | 13. IAM Policy Scanning Requirement ------------------------------------------------------ In order to enable the IAM Policy Scanning feature, the following permissions are needed. :: { "Action": [ "iam:List*", "iam:Get*", "iam:DeletePolicyVersion", "iam:CreatePolicyVersion" ], "Resource": "arn:aws:iam::*:policy/aviatrix-*", "Effect": "Allow" } | 14. UDP Load-Balancer Requirement ------------------------------------------------------- In order to enable the UDP Load-Balancer feature, the following permissions are needed. :: { "Action": [ "route53:ChangeResourceRecordSets" ], "Resource": "*", "Effect": "Allow" } | 15. Private Mode and GWLB-Based FireNet Requirement ---------------------------------------------------------------------------- In order to enable Private Mode usage and GWLB-based FireNet, the following permissions are needed: :: { "Action": [ "elasticloadbalancing:DescribeTargetHealth", "ec2:CreateVpcEndpointServiceConfiguration", "ec2:DeleteVpcEndpointServiceConfigurations", "ec2:CreateVpcEndpoint", "ec2:DeleteVpcEndpoints", "ec2:ModifyVpcEndpointServicePermissions", "ec2:DescribeVpcEndpointServicePermissions", "ec2:DescribeVpcEndpoints" ], "Resource": "*", "Effect": "Allow" } | .. disqus:: <file_sep> ################################### Security Patches ################################### The following security patches are recently released by Aviatrix. ================================================================= ==================== ======================================================= **Patch Name** **Version** **Description** ================================================================= ==================== ======================================================= Increase File Descriptor limit 5.4 or earlier This patch will fix the VPN connection issue. Before this patch openVPN do not have permission to open more than 1024 connections socket and it hangs if more than 1024 sockets are open. This patch is only applicable to Gateways, and not required after UserConnect-4.3. Enable support for FIPS 140-2 6.0 or earlier Enable support for FIPS 140-2 Module. Click `here <https://docs.aviatrix.com/HowTos/fips140-2.html>`_ for more details. This patch is only applicable to Aviatrix Gateways. Remove old UI 6.0 or earlier This patch will remove the unnecessary web server components from old UI pages which could be accessible without requiring a credentials. Patch applied to Avitrix Controller only. X-XSS-Protection and X-Content-Type-Options Headers 5.2+ X-XSS-Protection and X-Content-Type-Options Headers did not configure properly without the patch. Applicable to Aviatrix Gateway and Controller both. SAML XML signature wrapping vulnerability 6.0 or earlier The SAML implementation in the Aviatrix controller was vulnerable to XML Signature Wrapping without the patch. Without the patch, an attacker with any signed SAML assertion from the Identity Provider can establish a connection even if that SAML assertion has expired or is from a user who is not authorized to access Aviatrix. Applicable to Aviatrix Controller only. ================================================================= ==================== ======================================================= .. important:: Increase File Descriptor limit patch will disconnect all VPN Users. To apply a patch: 1) Backup your Aviatrix Controller. For more information, see `Controller Backup and Restore <https://docs.aviatrix.com/HowTos/controller_backup.html>`_. 2) Apply the security or software patch on the controller. From the Aviatrix Controller, navigate to Settings > Maintenance > SecurityPatches or SoftwarePatches and click on **UpdateAvailablePatches**. You should see the new patch in the display. 3) Apply the patch by clicking on the icon on the right and selecting **Apply Patch** from the popup menu. 4) Validate the update by clicking on the icon on the right and selecting **Patch Status** and scrolling down to bottom of page. 5) Backup your Aviatrix Controller again to save the new configuration. .. disqus:: <file_sep> ================================= Account Audit ================================= The Aviatrix Controller periodically checks the accounts it manages to make sure they are intact: 1. The Controller instance's IAM role aviatrix-role-ec2 is attached to the instance. #. The Controller instance's IAM role aviatrix-role-app exists. #. An access account IAM role aviatrix-role-ec2 exists. #. An access account IAM role aviatrix-role-app exists. #. An access account IAM role aviatrix-role-ec2 has associated policies. #. An access account IAM role aviatrix-role-app has associated policies. #. An access account has trust relationship to the primary account (the Controller's AWS account). #. An access account has an expired, deleted, or invalid credential. If any of the above condition fails, the Controller sends out alert email and logs the event. In addition, the controller will also send alert email on behalf of any of the above condition failures reported by a gateway upon the first detection and subsequently every 24 hours until the problem is rectified. Note the event requires immediate attention; otherwise, it can lead to catastrophic operation outage. Go through the above conditions to repair the configuration. If you need help, please open a support ticket at the `Aviatrix Support Portal <https://support.aviatrix.com>`_. .. Note:: - Account auditing does not work with the new enhancement "customized IAM role name" in 6.4. In the current design, the account auditing feature looks for the Aviatrix standard IAM role names, which are aviatrix-role-app and aviatrix-role-ec2 and the Aviatrix standard policy name, which is aviatrix-app-policy. - The account auditing feature also does not work if the IAM app role has more than one policy attached because only the first policy is used. .. .. |secondary_account| image:: adminusers_media/secondary_account.png :scale: 50% .. |account_structure| image:: adminusers_media/account_structure.png :scale: 50% .. |access_account_35| image:: adminusers_media/access_account_35.png :scale: 50% .. disqus:: <file_sep> =============================================================================== Bootstrap Configuration Example for Check Point Security Gateway in AWS/Azure =============================================================================== This document applies to both AWS and Azure. Using the bootstrap option significantly simplifies Check Point Security Gateway initial configuration setup. In this document, we provide a basic bootstrap example for Check Point. Bootstrap Configuration can be a vendor specific script or configuration. For a manual setup, follow `manual setup example. <https://docs.aviatrix.com/HowTos/config_CheckPointAzure.html>`_ Configure Check Point Security Gateway using Custom Data --------------------------------------------------------- Follow the Aviatrix Firewall Network (FireNet) workflow to `this step <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#launching-and-associating-firewall-instance>`_ to launch the firewall instance. To Configure Check Point Security Gateway using Custom Data, go to the Aviatrix Controller > Firewall Network > Setup > Launch & Associate Firewall Instance. Fill in the required fields. Click Advanced. Fill in the following parameters. You must specify a custom username and password, and generate a hash string for the password. ================================ ====================== **Advanced Field** **Example Value** ================================ ====================== User Data Bootstrap Configuration ================================ ====================== Sample Check Point Bootstrap Configuration to configure firewall "Allow-all" policy, health check policy and RFC 1918 static routes is shown below: :: #!/bin/bash clish -c "set user <user> password-hash <100+ character hash string>" -s clish -c 'set interface eth1 state on' -s clish -c 'set hostname checkpoint' -s blink_config -s 'upload_info=false&download_info=false&install_security_gw=true&install_ppak=true&install_security_managment=false&ipstat_v6=off&ftw_sic_key=<password>' |cp_bootstrap_example| Launch the instance. Wait for 15 minutes for it to boot up and initialize. Log into the HTTPS interface of the public IP with the username and password specified in the Bootstrap Configuration file. Ready to Go ---------------- Now your firewall instance is ready to receive packets. Next step is to validate your configurations in the Check Point Security Gateway, and configure polices for Ingress and Egress inspection. By default, all traffic is allowed in Check Point that can be verified by launching one instance in PROD Spoke VPC/VNet and DEV Spoke VPC/VNet. Start ping packets from a instance in DEV Spoke VPC/VNet to the private IP of another instance in PROD Spoke VPC/VNet. The ICMP traffic should go through the Check Point and be inspected in Security Gateway. Additional References -------------------------- Check Point Reference `Custom Data <https://supportcenter.checkpoint.com/supportcenter/portal?eventSubmit_doGoviewsolutiondetails=&solutionid=sk105242&partition=General&product=vSEC>`_ .. |cp_bootstrap_example| image:: bootstrap_example_media/cp-bootstrap-example.png :scale: 40% .. disqus:: <file_sep> =========================================================================================== Site2Cloud (S2C) Custom Network Mapped Solutions Workflow =========================================================================================== This document describes a solution to solving network connectivity issues where there are overlapping network CIDRs. The solution uses the Custom Mapped under the `Mapped` option of Aviatrix `Site2Cloud <https://docs.aviatrix.com/HowTos/site2cloud.html>`_ feature when building IPSEC tunnels. Custom Mapped Site2Cloud provides the advantage of not having to configure individual SNAT/DNAT rules, also it gives flexibility to build address translations of all scenarios. (e.g. Many-to-Many, Many-to-One etc.) This document covers examples with Aviatrix Transit Gateway only and below topology will be used for all scenarios. |cmap_topology| .. note:: Same virtual CIDR for multiple customer sites cannot be used. .. important:: This document applies to both Aviatrix Transit and AWS Transit Gateway (TGW). "Forward Traffic to Transit Gateway" needs to be enabled under S2C connection in Aviatrix Transit Gateway case. Terminology Definitions -------------------------- The primary reason for terminology definitions is that in connecting overlapping networks with IPSec tunnels, the address translation requirements are often not symmetric. For example, Remote Initiated Traffic may all require to be source NATed to a single or small range of addresses, while Local Initiated Traffic may require to have a 1-1 DNAT and SNAT. By separating different traffic directions, address translations can be done specifically for the direction, thus providing the ultimate flexibility. Remote Initiated Traffic ~~~~~~~~~~~~~~~~~~~~~~~~~~~ From the point of view of an Aviatrix gateway where site2cloud (with IPSec tunnel) connection is established, traffic initiating from the remote end of the IPSec tunnel is called Remote Initiated Traffic. Local Initiated Traffic ~~~~~~~~~~~~~~~~~~~~~~~~~ From the point of view of an Aviatrix gateway where site2cloud (with IPSec tunnel) connection is established, traffic initiating from the Aviatrix gateway side of the IPSec tunnel is called Local Initiated Traffic. This traffic may originally come from an Aviatrix Transit Gateway to the Aviatrix Spoke gateway where IPSec tunnels are established. Problem Statement ------------------------------------------------------------------------- In this use case, a customer needs to connect certain on-prem hosts to certain EC2 instances in a VPC over an IPSEC tunnel over the Internet, but the on-prem network range overlaps with the customer's VPC CIDR range, and the requirement from the customer is that traffic can be initiated from either side. :: VPC CIDR = 10.10.0.0/16, instance-1 in Client-1 has an IP address 10.10.43.145 CIDR = 10.10.0.0/16, instance-1 in Client-2 has an IP address 10.10.35.41 On-Prem CIDR = 10.10.0.0/16, host-1 in On-Prem has an IP address 10.10.0.212. Aviatrix offers multiple solutions to this requirement. The solutions uses in this document to solve this scenario is called "custom mapped" feature in Site2Cloud that removes the need to configure individual SNAT/DNAT rules and gives flexibility to map Real CIDRs to small Virtual CIDRs range. .. note:: The maximum number of CIDRs for Site2Cloud network maps is 32. This solution uses a site2cloud route-based IPSEC tunnel using Virtual Tunnel Interface (VTI) between VPC and On-Prem Router. The packet flow is demonstrated as below: 1. Client-1 instance-1 sends a packet to host-1 with a virtual destination IP address, for example 172.16.31.10. From Client-1 instance-1's point of view, the destination instance is a virtual address - 172.16.31.10. #. When the packet arrives at the Aviatrix Spoke gateway, the gateway does DNAT on the packet to translate the virtual destination IP address to 10.10.0.212 which is the host-1 physical IP address. #. The Spoke gateway then translates the packet source IP address (10.10.43.145) to a virtual source IP address, say it is 172.16.17.32. #. The packet then arrives at On-Prem Cisco IOS Router with destination IP address 10.10.0.212 and source IP address 172.16.17.32. From host-1's point of view, instance-1's address is a virtual IP address - 172.16.17.32. #. When host-1 sends a packet to instance-1, the destination is the virtual IP address 172.16.17.32. #. When the packet arrives at the Spoke gateway over the IPSEC tunnel, the Spoke gateway translates its destination IP address from virtual address 172.16.17.32 to 10.10.43.145. #. The Spoke gateway then translates the source IP address of the packet from 10.10.0.212 to virtual address 172.16.31.10. Scenarios: -------------- Use Case 1: Customer's Multi-Sites CIDRs overlaps with on-prem CIDRs ------------------------------------------------------------------------- Traffic Initiated from either sides. Traffic initiated from customer's side ######################################## Traffic initiated from Client's side means it is a remote initiated traffic from Aviatrix Gateway perspective as shown below. Furthermore, requirement is to map customer's Real CIDR into the smaller Virtual CIDRs of 16 IP addresses range. SNAT is only required to translate 10.10.0.0/16 to small range of ip address 172.16.17.32/28, 192.168.127.12/28 respectively. ================================================== ======================================================================= **Client 1 S2C CIDR** **Remote Initiated** ================================================== ======================================================================= Source (Real) 10.10.0.0/16 Source (Virtual) 172.16.17.32/28 Destination (Real) 10.10.0.212/32 Destination (Virual) 172.16.31.10/32 ================================================== ======================================================================= Traffic initiated from on-prem's side ######################################## Traffic initiated from the on-prem's side means it is a local initiated traffic from Aviatrix Gateway perspective as shown below. ================================================== ======================================================================= **Client 1 S2C CIDR** **Remote Initiated** ================================================== ======================================================================= Source (Real) 10.10.0.0/16 Source (Virtual) 172.16.17.32/32 Destination (Real) 10.10.43.144/28 Destination (Virual) 172.16.17.32/28 ================================================== ======================================================================= Use Case 2: Customer's Multi-Sites CIDRs overlaps each other and on-prem CIDRs is non-overlapping -------------------------------------------------------------------------------------------------- SNAT is only required to translate 10.10.0.0/16 to small range of ip address 172.16.17.32/28, 192.168.127.12/28 respectively, and DNAT will not be required. Traffic initiated from customer's side ######################################## Traffic initiated from Client's side means it is a remote initiated traffic from Aviatrix Gateway perspective as shown below. Furthermore, requirement is to map customer's Real CIDR into the smaller Virtual CIDRs of 16 IP addresses range. ================================================== ======================================================================= **Client 1 S2C CIDR** **Remote Initiated** ================================================== ======================================================================= Source (Real) 10.10.0.0/16 Source (Virtual) 172.16.17.32/28 Destination (Real) 172.16.17.32/32 Destination (Virual) 172.16.17.32/32 ================================================== ======================================================================= Traffic initiated from on-prem's side ######################################## Traffic initiated from the on-prem's side means it is a local initiated traffic from Aviatrix Gateway perspective as shown below. ================================================== ======================================================================= **Client 1 S2C CIDR** **Remote Initiated** ================================================== ======================================================================= Source (Real) 10.10.0.0/16,192.168.127.12/32 Source (Virtual) 172.16.17.32/32,192.168.127.12/32 Destination (Real) 10.10.43.144/28 Destination (Virual) 172.16.17.32/28 ================================================== ======================================================================= The Configuration Steps ========================== Step 1: Launch Transit Gateway ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Log in to the Controller console, go to Multi-Cloud Network. Follow step 1 to launch a gateway in the VPC. Transit Aviatrix Gateway can be deployed using the `Transit Gateway Workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-a-transit-gateway>`_ 1. Navigate to **MULTI-CLOUD TRANSIT -> Setup -> #1 Launch an Aviatrix Transit Gateway** #. Choose instance size **C5x.large** #. Enable **ActiveMesh Mode (Mandatory)** #. Enable InsaneMode for higher throughputs (optional) #. Enable Transit VPC GW HA by navigating to **MULTI-CLOUD TRANSIT -> Setup -> #2 (Optional) Enable HA to an Aviatrix Transit Gateway** .. note:: Instance size of c5.xlarge will be required for Insane Mode Encryption for higher throughput. Step 2: Deploy Spoke Gateways ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Now that we have Aviatrix Transit Gateway, we can deploy Aviatrix Spoke Gateways in the spoke VPCs using `Aviatrix Spoke Gateway Workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-a-spoke-gateway>`_. 1. Navigate to **MULTI-CLOUD TRANSIT -> Setup -> #4 Launch an Aviatrix Spoke Gateway** #. Deploy a Spoke Gateway (GW) in the spoke VPCs using defaults while choose correct Account and VPC info #. Choose the Public Subnet #. Enable Spoke Gateway HA by navigating to Transit network -> Setup -> #5 (Optional) Enable/Disable HA at Spoke GW .. note:: Instance size of c5.xlarge will be required for Insane Mode Encryption for higher throughput. Step 3: Attach Spoke Gateways to Transit Network ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Transit and spoke gateways are deployed, next step is to connect them. Navigate to **MULTI-CLOUD TRANSIT -> Setup -> #6a Attach Spoke Gateway to Transit Network** Step 4: Connect Transit Gateway to On-Prem ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Aviatrix Transit Gateway can be connected to On-Prem Cisco IOS from Multi-Cloud Transit using `Connect Transit Gateway to External Device workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#external-device>`_ Step 5: Create a Site2Cloud tunnel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Before creating a S2C tunnel, it is important to understand few terms here: Go to Controller Console -> Site2Cloud. Click "+Add New". Fill the form and click OK. Select "Mapped" for the Connection Type field. |s2c_connection| 5.1 VPC-1 gateway-1 side ######################### For the VPC gateway side, the Local Subnet field should be the subnet of VPC-1 (e.g. 10.24.0.0/20), and the Remote Subnet field should be the subnet of OnPrem Router (e.g. 10.24.0.0/20), as shown below. ================================================== ======================================================================= **Field** **Value** ================================================== ======================================================================= VPC ID/VNet Name Choose VPC ID Connection Type Mapped Connection Name Arbitrary (e.g. S2C-VPC-OnPrem) Remote Gateway Type Generic Tunnel Type Route-based Algorithms Uncheck this box Encryption over ExpressRoute/DirectConnect Uncheck this box Enable HA Check this box if HA is required Primary Cloud Gateway Select the Aviatrix Gateway created above Remote Gateway IP Address Public IP of IOS Router WAN port (52.40.45.197 in this example) Pre-shared Key Optional (auto-generated if not entered) Remote Subnet (Real) 10.24.0.0/20 (On-Prem Network CIDR) Remote Subnet (Virtual) Any/20 (On-Prem Network Virtual CIDR) Local Subnet (Real) 10.24.0.0/20 (VPC-Cloud Network CIDR) Local Subnet (Virtual) Any/20 (VPC-Cloud Network Virtual CIDR) ================================================== ======================================================================= .. |cmap_topology| image:: custom_mapped_solution_media/cmap_topology.png :scale: 35% .. |scenario1_overlapping_cidr| image:: custom_mapped_solution_media/scenario1_overlapping_cidr.png :scale: 35% .. |scenario1_remote_initiated| image:: custom_mapped_solution_media/scenario1_remote_initiated.png :scale: 35% .. |scenario1_local_initiated| image:: custom_mapped_solution_media/scenario1_local_initiated.png :scale: 35% .. |scenario2_remote_initiated| image:: custom_mapped_solution_media/scenario2_remote_initiated.png :scale: 35% .. |scenario2_local_initiated| image:: custom_mapped_solution_media/scenario2_local_initiated.png :scale: 35% .. |s2c_connection| image:: connect_overlap_cidrs_media/s2c_connection.png :scale: 35% .. disqus:: <file_sep>sphinxcontrib-disqus ## use v1.6 of Sphinx to make disqus work correctly ##sphinx==1.6 ## pin docutils to 0.17 to work around https://github.com/sphinx-doc/sphinx/issues/9727 docutils<0.18 urllib3<2.0 <file_sep>I will move all images to this directory eventually <file_sep> ===================================================================== Aviatrix Gateway to Meraki vMX100 ===================================================================== Overview --------------------- This document describes how to create an IPsec tunnel between an Aviatrix Gateway and a Meraki vMX100 using Aviatrix Site2Cloud. The network setup is as follows: **VPC/VNet1 (with Aviatrix Gateway)** *VPC/VNet1 CIDR: 10.0.0.0/16* *VPC/VNet1 Subnet (public for AWS, GCP, or OCI): 10.0.0.0/24* **VPC/VNet2 (with Meraki vMX100)** *VPC/VNet2 CIDR: 10.10.0.0/16* *VPC/VNet2 Subnet (public for AWS, GCP, or OCI): 10.10.0.0/24* Adding a Site2Cloud Tunnel in Aviatrix Controller ----------------------------------------------------------------- 1. Log in to your Aviatrix Controller. 2. Select Site2Cloud on the left navigation bar. 3. Click **+ Add New** near the top of the Site2Cloud tab. 4. Under Add a New Connection, enter the following: +-------------------------------+------------------------------------------+ | Field | Expected Value | +===============================+==========================================+ | VPC ID / VNet Name | Select the VPC/VNet where this tunnel will | | | terminate in the cloud. | +-------------------------------+------------------------------------------+ | Connection Type | Unmapped unless there is an | | | overlapping CIDR block. | +-------------------------------+------------------------------------------+ | Connection Name | Name this connection. This connection | | | represents the connectivity to the | | | edge device. | +-------------------------------+------------------------------------------+ | Remote Gateway Type | Generic | +-------------------------------+------------------------------------------+ | Tunnel Type | UDP | +-------------------------------+------------------------------------------+ | Algorithms | Unmark this checkbox | +-------------------------------+------------------------------------------+ | Encryption over ExpressRoute/ | Unmark this checkbox | | Direct Connect | | +-------------------------------+------------------------------------------+ | Enable HA | Unmark this checkbox | +-------------------------------+------------------------------------------+ | Primary Cloud Gateway | Select the Gateway where the tunnel will | | | terminate in this VPC/VNet. | +-------------------------------+------------------------------------------+ | Remote Gateway IP Address | Public IP of the Meraki vMX100. | +-------------------------------+------------------------------------------+ | Pre-shared Key | Optional. Enter the pre-shared key for | | | this connection. If nothing is entered | | | one will be generated for you. | +-------------------------------+------------------------------------------+ | Remote Subnet | Enter the VPC/VNet2 CIDR representing the | | | network behind the Meraki vMX100 that | | | this tunnel supports. | +-------------------------------+------------------------------------------+ | Local Subnet | The VPC/VNet1 Subnet block that should be | | | advertised on Meraki vMX100 for the | | | cloud network (will default to the VPC/VNet | | | CIDR block). | +-------------------------------+------------------------------------------+ 5. Click **OK**. 6. Click on this newly created Site2Cloud connection and select Vendor **Aviatrix** to Download Configuration so that you can copy and paste the pre-shared key into the Meraki configuration later. Configuring Site-to-site VPN in Meraki vMX100 ----------------------------------------------------------- 1. Log in to your Meraki dashboard. 2. In the Security appliance menu, select **Site-to-site VPN** under the Configure section. |meraki_vmx01| 3. Configure your Meraki vMX100 and add a peer according to the screenshot below. |meraki_vmx02| 4. Click on **Custom** in the IPsec Policies to create a custom policy that matches the Aviatrix Site2Cloud configuration that was previously downloaded. |meraki_vmx03| 5. Click **Update** to save the Custom policy. 6. Remember to click **Save Changes**. 7. Go to AWS and update the VPC/VNet2 (Meraki vMX100 instance) route table to make sure traffic destined to VPC/VNet1 (Aviatrix Gateway) is pointed to the vMX100 eni. |meraki_vmx04| 8. At the AWS console, please allow UDP port 500 and 4500 from the public IP of the Aviatrix Gateway in the vMX100's security group. For testing purposes, you may want to allow ICMP traffic from its local network 10.10.0.0/16 as well. |meraki_vmx05| 7. In the Security appliance menu, click **VPN Status** under the Monitor section. |meraki_vmx06| 8. Send traffic from the Meraki vMX100 VPC/VNet2 internal network to Aviatrix Gateway VPC/VNet1. Verify that the VPN Status is green under the Non-Meraki peer tab. |meraki_vmx07| 9. Log in to the Aviatrix Controller and browse to the Site2Cloud page to confirm that the connection is UP. |meraki_vmx08| .. |meraki_vmx01| image:: site2cloud_meraki_vmx100_media/meraki_vmx01.png .. |meraki_vmx02| image:: site2cloud_meraki_vmx100_media/meraki_vmx02.png .. |meraki_vmx03| image:: site2cloud_meraki_vmx100_media/meraki_vmx03.png .. |meraki_vmx04| image:: site2cloud_meraki_vmx100_media/meraki_vmx04.png .. |meraki_vmx05| image:: site2cloud_meraki_vmx100_media/meraki_vmx05.png .. |meraki_vmx06| image:: site2cloud_meraki_vmx100_media/meraki_vmx06.png .. |meraki_vmx07| image:: site2cloud_meraki_vmx100_media/meraki_vmx07.png .. |meraki_vmx08| image:: site2cloud_meraki_vmx100_media/meraki_vmx08.png .. disqus:: <file_sep> ============================ Onboarding and Account FAQs ============================ Where do I start? ------------------------- The first time you log in to Aviatrix Controller, complete the onboarding process. The onboarding process involves entering the information about your cloud provider account(s) that the Controller requires for launching gateways and building connectivity in the VPCs/VNets/VCNs of your account(s). The account information required can vary depending on the cloud provider. To complete the onboarding process, click on **Onboarding** from the Aviatrix Controller left sidebar, click on the icon of the cloud provider in which your Controller is to launch gateways, and then follow the steps to enter your cloud provider account information. What is an Aviatrix Customer ID? ------------------------------------ If you have a BYOL license, metered license, or use a community image, you need to have a customer ID provided by Aviatrix to be able to use the product. Please open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_ if you do not have a customer ID. What is an Aviatrix Access Account on the Controller? ------------------------------------------------------------- An Aviatrix access account (or account for short) represents the following information: - The cloud provider account (for example, AWS) credential that the Controller uses to launch Aviatrix Gateway in that cloud account. What is the Controller ID? ----------------------------------- Controller ID is a 32-digit Universal Unique Identifier (UUID). This ID is unique per customer and used for tracking purposes. This 32-digit UUID is available under Settings > Controller > License. What are the different types of licenses available? --------------------------------------------------------------- There are three different types of licenses option available in Aviatrix Controller. #. Bring Your Own License (BYOL) License - This license supports public cloud AWS, Azure, GCP and OCI. Please open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_ to get BYOL license. #. Metered or Platinum Metered License - This is only applicable to AWS public cloud. #. Utility - The utility machine image (AMI/VM Image) is available in AWS and Azure both and supports maximum 100 tunnels and limited number of VPN users. To check your license type, navigate to the Aviatrix Controller's console > Settings > Controller > License. Why do I need an AWS account credential? -------------------------------------------------------- To build connectivity between two VPCs in AWS, the Aviatrix Controller launches Aviatrix Gateway instances in the respective VPCs, instructs the gateways to build an IPsec tunnel and modifies AWS route tables in each VPC. To accomplish this task, the Controller needs your AWS credentials to issue AWS APIs, for example, to launch the Gateway instances and modify route tables, on your behalf. An AWS credential consists of: - `The 12-digit AWS account number <https://docs.aws.amazon.com/IAM/latest/UserGuide/console_account-alias.html>`_ - `IAM roles and IAM policies <http://docs.aviatrix.com/HowTos/HowTo_IAM_role.html>`_ If you need to connect two VPCs that are owned by one AWS account, you just need one AWS credential, that is, one Aviatrix access account. If you need to connect two VPCs that are owned by two different AWS accounts, you then need two AWS credentials, and therefore two access accounts. The access account is also used to access the Controller web console. Therefore, it is associated with an email address and login password in case you want to log in to only manage that one account. What is the Aviatrix Primary Access Account? ---------------------------------------------------------- There is only one primary access account on the Controller. The primary access account's AWS account credential is the one that the Controller is launched on and it is already set up during the Controller instance launch time with a CloudFormation template. To set up the primary access account during onboarding time, you just need to enter the 12-digit AWS account that Controller is launched on. (For release 3.1 and earlier you also need to enter the Controller access credentials: email and password). Once you set up the primary access account, you can launch Aviatrix Gateways in the VPCs that belong to this account. Why should I use an IAM role instead of access key and secret key? ------------------------------------------------------------------------------------- With the support of AWS IAM role, there is no need to enter an AWS access key and secret key when creating an access account on an Aviatrix Controller. Instead, two IAM roles are created. The Aviatrix Controller uses the dynamically obtained security credentials to request access to AWS resources. A role-based IAM cloud account helps to reduce the risk of AWS credentials being compromised. Can an Aviatrix Access Account be multi-cloud? ---------------------------------------------------------------- No. An Aviatrix Cloud Account corresponds to one cloud account of one cloud type. You can create multiple Cloud Accounts to support multi cloud and multi account deployment environment. How Do We Apply Azure Role-Based Access Control (RBAC) to an Aviatrix Azure Account? ------------------------------------------------------------------------------------------------------------- The Aviatrix Controller is viewed as an application running on Azure. Since this application needs to create or program Azure resources, such as launching a gateway, modifying route entries in a route table, etc., the application requires a role with certain permissions. By default, this role is a pre-defined Azure built-in role called "Contributor." If you wish not to use the Contributor role and instead creating a custom role with Aviatrix-provided permission, you can do so via Azure portal or with via PowerShell. Below is guide on how to accomplish that via PowerShell. **Note:** For security purposes, Aviatrix recommends you use a custom role rather than the default role Aviatrix created. When you use a custom role name it is important to make sure the AssumeRole policy and Trust policy are correct. The AssumeRole policy is attached to the Azure Virtual Machine role and the Trust policy is accessed on the APP role Trust Relationship tab. For replacing the Contributor role via Azure portal, refer to `Azure IAM Custom Role <https://docs.aviatrix.com/HowTos/azure_custom_role.html>`_. Step 1. Add a Custom Role through Powershell ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The custom role must have permission that meets the requirement for Aviatrix Controller to function. The permission is represented by the json file below. Remember to replace the subscription "11111111-1111-1111-1111-111111111111" with your own valid subscription ID. :: avx_rbac_role.json: { "Name": "Aviatrix Controller Custom Role", "IsCustom": true, "Description": "Custom role for Aviatrix Controller", "Actions": [ "Microsoft.MarketplaceOrdering/offerTypes/publishers/offers/plans/agreements/*", "Microsoft.Compute/*/read", "Microsoft.Compute/availabilitySets/*", "Microsoft.Compute/virtualMachines/*", "Microsoft.Network/*/read", "Microsoft.Network/publicIPAddresses/*", "Microsoft.Network/networkInterfaces/*", "Microsoft.Network/networkSecurityGroups/*", "Microsoft.Network/loadBalancers/*", "Microsoft.Network/routeTables/*", "Microsoft.Network/virtualNetworks/*", "Microsoft.Storage/storageAccounts/*", "Microsoft.Resources/*/read", "Microsoft.Resourcehealth/healthevent/*", "Microsoft.Resources/deployments/*", "Microsoft.Resources/tags/*", "Microsoft.Resources/marketplace/purchase/action", "Microsoft.Resources/subscriptions/resourceGroups/*" ], "NotActions": [], "AssignableScopes": [ "/subscriptions/11111111-1111-1111-1111-111111111111" ] } In Powershell, perform the following: 1. Edit avx_rbac_role.json, copy and paste above Aviatrix RBAC role. Save the file. 2. New-AzRoleDefinition -InputFile avx_rbac_role.json Step 2. Add a Role Assignment in the Azure Portal ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In Azure portal > Subscriptions > Access Control (IAM) > Add > Add role assignment. At Role assignment, fill the fields as shown below. ======================== ======================= Role Aviatrix Controller Custom Role (this is the role created from above) Assign access to User, group, or service principal Select My-new-controller (this is the registered application name for the Controller) ======================== ======================= Once the above step is complete, you have assigned the My-new-controller (as a service principal) the custom role called "Aviatrix Controller Custom Role." For more information on how to PowerShell to create custom role on Azure, refer to `this link. <https://docs.microsoft.com/en-us/azure/role-based-access-control/custom-roles-powershell>`_. How do I set up OCI account credentials? ------------------------------------------------------ Follow the instructions on `Oracle Cloud Infrastructure Documentation. <https://docs.cloud.oracle.com/en-us/iaas/Content/API/Concepts/apisigningkey.htm>`_. How do I upgrade software? --------------------------- Click Settings > Upgrade, select latest. This upgrades to the latest release of the Controller software. When a new release becomes available, an alert message appears on the Dashboard. An email will also be sent to the admin of the Controller. Are there reference design examples? ------------------------------------------------ Check out docs.aviatrix.com. What is the support model? ------------------------------------- For support, please open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_. We also offer premium customers 24/7 support. To request a feature, click **Make a wish** at the bottom of each page. In my environment, Aviatrix will be within a PCI CDE environment. Do you have a SOC2 or PCI AOC you would be able to share? ------------------------------------------------------------------------------------------------------------------------------------------------------------- Aviatrix does not need to be PCI compliant or provide a PCI AOC. Companies that sell some types of **equipment or software** used in cardholder data processing, transmission, and storage environments, but have no access to, or do not impact, those environments, are also not required to be PCI compliant and therefore do not have AOCs. A few examples include routers, firewalls, application servers, database servers, telecommunications equipment, server operating systems, **application firewalls**, etc. What is Certificate Domain? -------------------------------- Entering Certificate Domain is required for Aviatrix China Solution. The domain is the one that you registered in China and applied for ICP license. For more information, see `What is a China ICP License <https://docs.aviatrix.com/HowTos/aviatrix_china_overview.html?highlight=What%20is%20a%20China%20ICP%20License#what-is-a-china-icp-license>`_. .. important:: Aviatrix recommends that you use the default Certificate Domain and that you do not change the default Certificate Domain. Changing the default Certificate Domain may cause network outages. If you must change the default Certificate Domain, please open a support ticket with `Aviatrix Support <https://support.aviatrix.com>`_ and get assistance before changing the default Certificate Domain. How do I set up an Account Name Alias? --------------------------------------------------- For configuration details, refer to `Setup Account Name Alias <https://docs.aviatrix.com/HowTos/aviatrix_account.html#setup-account-name-alias>`_. .. |image1| image:: FAQ_media/image1.png .. disqus:: <file_sep>========================================================= Transit Connection to pfSense over the internet. ========================================================= 1. From the Controller go to Transit Network -> Setup -> Launch a Transit VPC GW. |image1| 2. Connect the transit VPC GW to the pfSense. Go to Transit Network -> Setup -> Connect to VGW/External Device. select External Device and input the following parameters. a. BGP Local AS number: ASN of the transit VPC GW b. BGP Remote AS number: ASN of the pfSense c. Remote Gateway IP Address: pfSense WAN Public IP. |image2| 3. Download the configuration by going to Site2Cloud -> Click on the Connection. select generic and Download Configuration and configure on pfSense accordingly. |image3| The following is a sample configuration based on the site2cloud configuration above. |image4| 4. Create an IPsec tunnel in pfSense --------------------------------- 4.a Login to your pfSense dashboard. 4.b In the `VPN` menu, select `IPsec`. 4.c Click `+ Add P1` 4.d Populate the fields according to your preferences. The important fields are (with :orange:`extra emphasis` on a few key fields): *General Information* +-------------------------------+------------------------------------------+ | Field | Expected Value | +===============================+==========================================+ | Key exchange version | IKEv1 | +-------------------------------+------------------------------------------+ | Remote Gateway | Enter the public IP address of the | | | Aviatrix Transit gateway here. | +-------------------------------+------------------------------------------+ *Phase 1 Proposal* +-------------------------------+------------------------------------------+ | Field | Expected Value | +===============================+==========================================+ | Authentication Method | Mutual PSK | +-------------------------------+------------------------------------------+ | My identifier | WAN port Public IP | +-------------------------------+------------------------------------------+ | :orange:`Peer identifier` | :orange:`IP address. Enter the private` | | | :orange:`IP address of the remote` | | | :orange:`Aviatrix Gateway` | +-------------------------------+------------------------------------------+ | Pre-Shared Key | Enter the PSK from the Site2Cloud | | | configuration downloaded at step 3. | +-------------------------------+------------------------------------------+ *Phase 1 Proposal (Algorithms)* +-------------------------------+------------------------------------------+ | Field | Expected Value | +===============================+==========================================+ | Encryption Algorithm | AES - 256 bits | +-------------------------------+------------------------------------------+ | Hash Algorithm | SHA1 | +-------------------------------+------------------------------------------+ | DH Group | 2 (1024 bit) | +-------------------------------+------------------------------------------+ *Advanced Options* +-------------------------------+------------------------------------------+ | Field | Expected Value | +===============================+==========================================+ | Disable rekey | :orange:`Unchecked` | +-------------------------------+------------------------------------------+ |image5| |image6| 4.e Click `Save` 4.d Add a Phase 2 entry and click on save. |image7| |image8| 4.f Click on Firewall -> Virtual IPs -> add. |image9| 4.g Click on status -> IPsec Status is shown as Established. |image10| 5. BGP Configuration on pfSense: --------------------------------- 5.a Click on System -> Package Manager Check whether *FRR* package which is used for BGP configuration is avialable in installed packages or else install it by clicking on available packages and search for *FRR* |image11| 5.b Click on Services -> FRR BGP. |image12| |image13| Click on Status -> FRR -> BGP to see the BGP routes. 6. After configuration pfSense the tunnel should change the status from down to up. |image14| 7. Go to Transit Network -> Advanced Config on the Controller and Click on Diagnostics and select the GW name from the dropdown list and select Show Ip bgp Command from the predefined Show list to verify the BGP Routes. .. |image1| image:: ./Transit_ExternalDevice_pfsense/1.png :width: 7.00000 in :height: 5.00000 in .. |image2| image:: ./Transit_ExternalDevice_pfsense/2.png :width: 7.00000 in :height: 5.00000 in .. |image3| image:: ./Transit_ExternalDevice_pfsense/3.png :width: 7.00000 in :height: 5.00000 in .. |image4| image:: ./Transit_ExternalDevice_pfsense/4.png :width: 7.00000 in :height: 5.00000 in .. |image5| image:: ./Transit_ExternalDevice_pfsense/5.png :width: 5.55625in :height: 3.26548in .. |image6| image:: ./Transit_ExternalDevice_pfsense/6.png :width: 5.55625in :height: 3.26548in .. |image7| image:: ./Transit_ExternalDevice_pfsense/7.png :width: 5.55625in :height: 3.26548in .. |image8| image:: ./Transit_ExternalDevice_pfsense/8.png :width: 5.55625in :height: 3.26548in .. |image9| image:: ./Transit_ExternalDevice_pfsense/9.png :width: 5.55625in :height: 3.26548in .. |image10| image:: ./Transit_ExternalDevice_pfsense/10.png :width: 100% .. |image11| image:: ./Transit_ExternalDevice_pfsense/11.png :width: 5.55625in :height: 3.26548in .. |image12| image:: ./Transit_ExternalDevice_pfsense/12.png :width: 7.00000 in :height: 5.00000 in .. |image13| image:: ./Transit_ExternalDevice_pfsense/13.png :width: 7.00000 in :height: 5.00000 in .. |image14| image:: ./Transit_ExternalDevice_pfsense/14.png :width: 100% <file_sep> ============================================== Route Traffic to an Egress Security Appliance ============================================== Overview -------- Using a central security appliance for egress is one approach for managing outbound internet traffic filtering. There are two methods to consider when building this architecture: #. `Use existing Transit Network <#security-arch-method-1>`__ to route internet-bound traffic from the spoke(s) through the transit VPC to a security appliance #. `Directly connect <#security-arch-method-2>`__ each VPC to the security appliance .. note:: The security appliance can be provisioned in any VPC. In this article, we are assuming it is provisioned in a VPC called **Security**. .. tip:: Aviatrix recommends inline egress traffic filtering. Read more about that `here <https://www.aviatrix.com/solutions/egress-security.php>`__. This method filters traffic right at the source and as a result avoids any unnecessary egress charges. In addition, this allows you to filter traffic based on the VPC requirements. In this article, we will walk through the steps to set up either method. .. _security_arch_method_1: Method 1: Route traffic through Transit VPC ------------------------------------------- In this design approach, internet-bound traffic from instances in the spoke(s) will return through the transit VPC to the security appliance. |transit_security_architecture_method_1| This method has the advantage of using existing tunnels to create a less complex and cleaner architecture. However, it comes with a few downsides: #. The primary disadvantage is the additional burden put on the transit gateways to carry all internet-bound traffic in addition to the spoke-data center traffic. This can be amplified if you are doing filtering of traffic since the traffic has to go through the transit and into a firewall before it is dropped. #. The second disadvantage to be aware of is the additional egress charges. You will be paying for traffic leaving the spoke VPC when it might be filtered. Deployment Guide ################ #. Using the AVX Controller, build out a `transit network <transitvpc_workflow.html>`__ with at least one spoke #. Create a **Security** VPC and provision and configure your security appliance #. From the AWS console in the region where your transit **Virtual Private Gateway** resides: #. Create a **Customer Gateway** for the security appliance #. Create a new **VPN Connection** attached to the transit Virtual Private Gateway and using the Customer Gateway and appropriate routing options. #. Save the connection and **Download Configuration** for your appliance #. Finish configuring the IPsec tunnel using the security appliance console .. tip:: Be sure to advertise 0.0.0.0/0 from your security appliance to the VGW. This route will be propagated to the spoke(s) automatically Once the tunnel is UP, you should see the 0.0.0.0/0 route in the private subnet route tables in the spoke(s). .. _security_arch_method_2: Method 2: Route traffic directly to security appliance ------------------------------------------------------ In this design approach, internet-bound traffic from instances in the spoke(s) or even non-spoke VPCs is routed directly from the VPC to the security appliance. This alleviates some of the egress charges. However, with this design you are still egressing out of the VPC to the Security VPC and then to the internet. The primary disadvantage of this approach is the additional tunnels required to route the traffic from the VPC to security VPC. |transit_security_architecture_method_2| .. note:: This architecture works even if there is no transit VPC. Deployment Guide ################ #. Create a **Security** VPC and provision and configure your security appliance #. Using the AVX Controller, create a `Site2Cloud Connection <site2cloud.html>`__ that connects to your security appliance. Be sure to advertise the remote CIDR of 0.0.0.0/0 Once the tunnel is UP, you should see the 0.0.0.0/0 route in the private subnet route tables in the spoke(s). Traffic will route to the AVX gateway and then across the tunnel to the security appliance. .. |transit_security_architecture_method_1| image:: transit_plus_security_vpc_media/transit-security-vpc.png .. |transit_security_architecture_method_2| image:: transit_plus_security_vpc_media/transit-security-vpc-direct.png <file_sep> ========================================================= Aviatrix Transit Network Segmentation Workflow ========================================================= For questions, refer to `Aviatrix Transit Segmentation FAQ. <https://docs.aviatrix.com/HowTos/transit_segmentation_faq.html>`_ .. note:: In releases prior to 6.7, the term "security domain" was used. This has been renamed to "network domain". 1. Enable the Aviatrix Transit Gateway for segmentation. ========================================== ========== **Setting** **Value** ========================================== ========== Aviatrix Transit Gateway Name An `Aviatrix Transit Gateway deployed in the Multi-Cloud Transit Network workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-a-transit-gateway>`_ ========================================== ========== 2. Create a Multi-Cloud Network domain. You can make changes to your network segmentation at any time, simply come back to this page. ========================================== ========== **Setting** **Value** ========================================== ========== Network Domain Name Specify a unique domain name. For example, Dev_Domain ========================================== ========== 3. Add/modify connection policies. This step specifies the connection relationship of one domain to others. Two connected domains imply that Spokes in each domain can communicate with each other despite the fact that they are in different domains. Highlight a domain on the left panel and click Add, the domain will appear to the right. ----------------------------------------------------------------------------------------------------------------------- This section is to build the network segmentation by associating a Spoke. 1. Associate Aviatrix Spoke/Edge to the domain. ========================================== ========== **Setting** **Value** ========================================== ========== Aviatrix Transit Gateway Name The name of the Aviatrix Transit Gateway Network Domain Name The name of the Network Domain Attachment Name The name of a Spoke or edge connection to associate to the domain ========================================== ========== 2. Disassociate Aviatrix Spoke/Edge to domain. ========================================== ========== **Setting** **Value** ========================================== ========== Aviatrix Transit Gateway Name The name of the Aviatrix Transit Gateway Network Domain Name The name of the Network Domain Attachment Name The name of a Spoke or edge connection to disassociate from the domain ========================================== ========== ------------------------------------------ This section consists of the delete functions. 1. Delete Multi-Cloud Network domain. ========================================== ========== **Setting** **Value** ========================================== ========== Network Domain Name The name of the Network Domain ========================================== ========== 2. Disable Aviatrix Transit Gateway for segmentation. ========================================== ========== **Setting** **Value** ========================================== ========== Aviatrix Transit Gateway Name An `Aviatrix Transit Gateway deployed in the Multi-Cloud Transit Network workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-a-transit-gateway>`_ ========================================== ========== .. |tgw_peer| image:: tgw_plan_media/tgw_peer.png :scale: 30% .. disqus:: <file_sep> ====================================================================================== Using Aviatrix to Build a Site to Site IPsec VPN Connection ====================================================================================== Aviatrix gateways can be used to connect one site to another. This solution requires one Aviatrix gateway in each location that needs to be connected. These on-premise gateways can be deployed as virtual machines on VMware, KVM or Hyper-V. | Environment Requirements --------------------------------------------------------- An Aviatrix Site to Site IPSEC tunnel is accomplished by one gateway initiating the session with the other gateway. For this to work at least one of the Aviatrix virtual appliances needs to accessible via a public IP address. This can be accomplished by setting up at the public IP address on the edge router in the on-premise network and configuring NAT from that public IP address to the Aviatrix VM with a 1-1 IP address NAT. The only ports that need to be forwarded from the edge router to the VM are UDP ports 500 and 4500. |image1| On the other site, the second gateway does not need a public IP assigned to the Aviatrix gateway. This second gateway will reach outbound to the first Aviatrix GW (GW1) The last requirement is to configure static routes in the internal routers (default gateway of the Aviatrix VM) in both the sites. This static route should send traffic destined to the other site to the Aviatrix GW as the next hop. |image2| |image3| | Steps to Configure IPSec connectivity --------------------------------------------------------- + **Step 1: Install Aviatrix gateway in each site.** Download and install the Aviatrix Gateways VMs by following the instructions in this `document <http://docs.aviatrix.com/StartUpGuides/CloudN-Startup-Guide.html>`__ + **Step 2: Configure Site2Cloud in Gateway 1** .. Note:: In the Aviatrix terminology, Site2Cloud is the name of the feature that enables connections from one site (or datacenter) to other sites (including cloud environments). .. **a.** Log into the Web UI of the first Gateway (GW1). **b.** Click on Site2Cloud in the navigation pane. **c.** Click on Add New Connection button. |image4| **d.** Fill out the details in the Site2Cloud form as shown below. i. Remote Gateway IP as the public IP of the other Site ii. The Remote Subnet is the CIDR (or comma separated CIDRs) of the other site iii. Local Subnet is the CIDRs in the local site. |image5| **e.** Click OK. You will see the connection listed in the Site2Cloud UI. **f.** Click on the connection from the list. You will see “Edit Site2Site” options appear under the list. |image6| **g.** Select Aviatrix in the Vendor dropdown. **h.** Click on Download Configuration button. This will download a text file (.txt) to your local machine. **i.** Log in to Gateway 2’s web UI on the other site (GW2). **j.** Go to the Site2Cloud page **k.** Click on Add New Connection **l.** Locate the Import button at the bottom of the screen. **m.** Select the text file you downloaded from the other Gateway. This will auto populate the details in the form. **n.** Click “OK” **o.** This will start the IPsec negotiations between both gateways. You should see the connection status change to “Up” within a few minutes. |image7| Please reach out to <EMAIL> if you have any questions. .. |image1| image:: site_to_site_vpn_media/img_01.png :scale: 30% .. |image2| image:: site_to_site_vpn_media/img_02.png :scale: 30% .. |image3| image:: site_to_site_vpn_media/img_03.png :scale: 30% .. |image4| image:: site_to_site_vpn_media/img_04.png :scale: 30% .. |image5| image:: site_to_site_vpn_media/img_05.png :scale: 30% .. |image6| image:: site_to_site_vpn_media/img_06.png :scale: 30% .. |image7| image:: site_to_site_vpn_media/img_07.png :scale: 30% .. disqus:: <file_sep>============================================= AWS ============================================= The Aviatrix cloud network solution consists of two components, controller and gateway, both are AWS instances. Gateways are launched from the controller browser console by using your account IAM roles and AWS APIs. This guide helps you to launch the Controller instance in AWS. The Controller image is also available in Azure Marketplace and GCloud. Create an AWS EC2 Account ========================= You need to have an AWS EC2 account to use the solution. Note that the Controller supports multiple accounts with each one associated with a different AWS IAM role or account, but there needs to be at least one to start with. This AWS account can be a root account, IAM role, IAM administrator account or IAM user account with access privileges required by the Aviatrix solution. We strongly recommend you to use IAM role for security reasons. Subscribe to Aviatrix on AWS Marketplace ========================================= You must subscribe to one of the Aviatrix AMIs on AWS marketplace prior to launch the Controller. Once you subscribe, return to this page and continue to the next section. Search "aviatrix" on AWS marketplace and accept the terms and conditions to use the software. After subscription, follow the instructions in the next sections to launch the Controller. If you choose the BYOL image, you need a customer ID (license ID) to use Aviatrix solution. Please open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_ to obtain one. DNS Server Connectivity Check ============================== If the VPC where the Controller is deployed in has a custom DNS server (via DHCP option), make sure the Controller instance can reach this DNS server. .. Warning:: Any resources created by the Controller, such as Aviatrix gateways, route entries, ELB, SQS queues, etc, must be deleted from the Controller console. If you delete them directly on AWS console, the Controller's view of resources will be incorrect which will lead to features not working properly. .. Launch Aviatrix Controller ============================================= Controller must be launched on a public subnet of a VPC. Launch from CloudFormation script ---------------------------------- If you select the Aviatrix BYOL AMI, the recommended way to launch the Controller is by our CloudFormation script. Follow the instruction `for Aviatrix QuickStart Cloudformation Script <https://docs.aviatrix.com/StartUpGuides/aviatrix-cloud-controller-startup-guide.html#step-2-launch-the-controller-with-cloudformation>`__ to launch a controller instance in a selected region. Launch Utility AMIs manually ---------------------------- For utility AMIs, you need to `launch the utility AMIs controller manually described in this document. <http://docs.aviatrix.com/StartUpGuides/aws_manual_startup_guide.html>`_ Access the Controller ======================= After the Controller instance is in running state in AWS, you can access the Controller via a browser by `https://Controller_public_EIP`, where Controller_public_EIP is the Elastic IP address of the Controller. The initial password is the private IP address of the instance. Follow the steps to go through an initial setup phase to download the latest software. After the latest software is downloaded, re-login again to go through the onboarding process. Onboarding =========== The purpose of onboarding is to help you setup an account on Aviatrix Controller that corresponds to an IAM role with policies so that the Controller can launch gateways and build networks using AWS APIs. If you launched the Controller via CloudFormation script, the required IAM roles and policies are already setup, follow `this instruction <http://docs.aviatrix.com/HowTos/HowTo_IAM_role.html#aviatrix-controller-launched-from-cloudformation>`_ to complete account creation. Note you can create a single Aviatrix account that corresponds to AWS, Azure and GCloud account credentials. This is a multi cloud platform. To create a Global Transit Network, click Transit VPC on the main navigation bar to start. Setup for Operations ===================== If this Controller is for your production, we strongly recommend you to enable Controller `Backup/Restore feature. <http://docs.aviatrix.com/HowTos/controller_backup.html>`_ This allows you to backup configurations on the Controller to an S3 bucket so that you can recover the configurations in a disaster situation. Controller HA ============== To enable Controller HA in AWS, follow `the instructions here. <http://docs.aviatrix.com/HowTos/controller_ha.html>`_ Controller Monitoring ====================== If Controller HA is not enabled, we recommend you to use AWS CloudWatch to configure alarms and actions to reboot the controller when it fails Status Check. Key Use cases =================== - `Inter region and inter cloud peering <http://docs.aviatrix.com/HowTos/peering.html>`_ - `Global Transit Network <http://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ - `Client VPN or OpenVPN® <http://docs.aviatrix.com/HowTos/uservpn.html>`_ For support, please open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_. Enjoy! OpenVPN is a registered trademark of OpenVPN Inc. .. |image0| image:: AviatrixCloudControllerStartupGuide_media/image001.png :width: 2.90683in :height: 0.35000in .. |image1| image:: AviatrixCloudControllerStartupGuide_media/image002.png :width: 4.80625in :height: 3.21803in .. |image2| image:: AviatrixCloudControllerStartupGuide_media/image003.png :width: 5.33067in :height: 2.04513in .. |image3| image:: AviatrixCloudControllerStartupGuide_media/image004.png :width: 4.92712in :height: 2.20352in .. |image4| image:: AviatrixCloudControllerStartupGuide_media/image005.png :width: 5.53494in :height: 3.11814in .. |image5| image:: AviatrixCloudControllerStartupGuide_media/image006.png :width: 5.21042in :height: 2.60298in .. |image6| image:: AviatrixCloudControllerStartupGuide_media/image007.png :width: 4.61664in :height: 4.22847in .. add in the disqus tag .. disqus:: <file_sep> ========================================================= Setup API Access to Palo Alto Networks VM-Series ========================================================= Follow the following steps to enable Palo Alto Networks API programming. Enabling Ping ~~~~~~~~~~~~~~~~~~ Make sure the Palo Alto Networks management interface has ping enabled and the instance's security group has ICMP policy open to the Aviatrix Controller's public IP address. At the Palo Alto VM-Series console, 1. Click **Device**. 2. Click **Interfaces**. 3. Click **Management**. 4. Make sure the setup is as following screenshot. |pan_ping| Creating API Administrator Role Profile ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ a. Create a new role profile and name it Aviatrix-API-Role: Go to Device > Admin Roles > **+Add**. #. Click **XML/API**. #. Click **Report**, **Configuration**, **Operation Requests** and **Commit**. #. Click **Commit**. |pan_role_profile| Adding an Administrator for API ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ At the VM-Series Console, go to Device > Administrators > **+Add**, to add an administrator for Role-Based access as shown below. Use the profile created in previous step. Remember to click **Commit**. |pan_admin| Configuring on the Aviatrix Controller ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Managing VM-Series Directly ---------------------------------- Login to the Aviatrix Controller, go to Firewall Network > Vendor Integration > Firewall. Configure the following parameters and click **Save**. ========================================== ========== **Setting** **Value** ========================================== ========== FireNet VPC/VNet ID The FireNet VPC/VNet ID for the Firewall Network deployment. Firewall instance ID The firewall virtual machine (EC2/GCE) instance ID. Aviatrix Controller monitors the health of this instance and determines fail over when it becomes unreachable. Firewall Name (Optional) A name to remember. Firewall Vendor Type Select PAN Firewall Login User Name firewall login name for API calls from the Controller. For example, admin-api, as shown in the screen shot. Firewall Login Password firewall login password for API calls. Firewall Management IP Address The public IP address of the firewall management interface for API calls from the Aviatrix Controller Firewall Virtual Router name (Optional) Specify the firewall virtual Router name you wish the Controller to program. If left unspecified, the Controller programs the firewall's default router. ========================================== ========== .. Note:: - The controller only supports one virtual router. If Firewall Virtual Router name is not specified, the controller takes the first virtual router in the list. Managing VM-Series by Panorama ------------------------------------ If Panorama is used to manage the VM-Series, any dynamic route updates initiated by Aviatrix Controller are sent to Panorama. Before you integrate Panorama with the Aviatrix Controller, you need to first launch and configure Panorama. The steps are as follows: Launching Panorama ^^^^^^^^^^^^^^^^^^^^^^ Launch Panorama from the AWS portal and SSH in to set the UI password, which is the same as the PAN firewall. Change the Panorama management interface security group to allow port 3978. This is the port used by Panorama and the firewall to exchange information. Install a license in Panorama. Without the correct license, it won't work. Upgrading Panorama ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Panorama MUST be on the same or higher software version as its managed firewalls. Currently (May, 2020) a newly launched firewall instance is on version 9.0.6 or 9.1.2. If the Panorama instance version is on 8.1.x, upgrade it to version 9.0.6 or higher version by following the instructions below. Go to Panorama > Dynamic Updates, click **Check Now**, select the latest version in Applications and Threats, download and install. Go to Panorama > Software, select the desired version, download and install. After installation, Panorama will reboot. This will take a few minutes. Creating Templates and Template Stack ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Template and template stack are used to configure Network properties, such as interfaces, zones, and route tables. This is the one that we need to monitor and update through API. 1. **Create Template** You should create a template for each firewall group: One for the FireNet primary Gateway and one for FireNet backup Gateway. #. **Configure Template** Add interfaces (ethernet1/1, ethernet1/2), zones (LAN, WAN), and Virtual Routers (route tables). Do not name the route table as "default" since this may conflict with the firewall's default route table. Please refer to the step 7 and 10 of https://docs.aviatrix.com/HowTos/config_paloaltoVM.html #. **Create Template Stack** A Template stack is a bundle to bound templates with managed devices. When creating, select template(s) and devices. Create one template stack for the primary FireNet Gateway, another for backup FireNet Gateway. Remember the template stack name. Commit and push. Creating Device Group ^^^^^^^^^^^^^^^^^^^^^^^^ A Device Group is used to manage all the firewall policies. 1. **Add Device Group** Go to Panorama > Device Groups, click **Add** to create a new device group for both FireNet GWs. Add managed VMs to the device group. Remember the device group name, for example "west2-firenet-primary". You may create two device groups as well if you want to separately edit for each FireNet GW. The following 3 # steps, please refer to the step 8 and 9 of https://docs.aviatrix.com/HowTos/config_paloaltoVM.html. #. **Add Example Policy** (Optional if internet traffic is needed) Add "Outbound" policy to the just created device group. #. **Add Egress Policy** (Optional) If you plan to deploy Egress inspection, add source-nat and security outbound rule policies #. **Commit The Change** Commit and push. After the above steps, once VM-Series instances are added to Panorama, all configuration should be done through the Panorama console. Creating Admin role and User ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This is the same as for individually managed VM-Series. Create an admin role with XML API permission and create an admin user with the admin role. After you have set up and configured your Panorama, go to the Aviatrix Controller > Firewall Network > Vendor Integration > Firewall Manager (Panorama) and configure the following. ========================================== ========== **Setting** **Value** ========================================== ========== FireNet VPC/VNet ID The FireNet VPC/VNet ID for the Firewall Network deployment. FireNet Gateway The FireNet Gateway name. Vendor Type Select Palo Alto Panorama. Management IP Address The public IP address of the Panorama instance. Login User Name Panorama login name for API calls from the Controller. For example, admin-api, as shown in the screen shot. Login Password Panorama login password for API calls. Template Name Panorama template for each FireNet Gateway. (If FireNet Gateway HA is configured, there should be two templates) Template Stack Name Panorama template stack for each FireNet Gateway.((If FireNet Gateway HA is configured, there should be two template stacks) Router name (Optional) Specify the firewall virtual Router name you wish the Controller to program. If left unspecified, the Controller programs the Panorama template's first router. ========================================== ========== .. Note:: - The Panorama needs to be configured separately for the primary and backup FireNet Gateways. - Panorama can be configured even when there is no VM-Series associated with a FireNet Gateway. However in such case, the egress subnet is not decided, therefore the egress route cannot be added. Once the first VM-Series instance is launched and is in sync with Panorama, the egress route will be automatically added. - If any VM-Series for a FireNet Gateway is already managed by the Controller, you need to remove that configuration before configuring Panorama. See the migration instructions in the next section. - After Panorama is setup, any additional VM-Series associated with same gateway will be controlled by Panorama and no further configuration on the VM-Series is needed. - When Panorama is configured, the associated will show the vendor as "Palo Alto Panorama." Clicking **Show** will use the same access account and password to access firewall and retrieve route information. To enable this, you need to configure admin role and user (same name and password as configured for Panorama itself) in the template in Panorama. - The controller only supports one virtual router. If Router name is not specified, the controller takes the first virtual router in the list. Migrating from Individually VM to Panorama ################################################################# Assuming you have existing individually managed VM-Series by the Aviatrix Controller and have prepared your Panorama, follow the instructions below to migrate individually VM to Panorama. Removing the Firewall Integration as PAN ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ If any firewall for a FireNet Gateway is already integrated with the Controller with PAN as the Vendor type, you need to remove that configuration. To do so, go to Controller > Firewall Network > Vendor Integration > Firewall, select the Transit VPC/VNet ID, Firewall Instance ID. For the Firewall Vendor Type, select **Generic**. This effectively removes the Controller integration. Removing Firewall Configuration (if this is a new VM, skip this step) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ From your firewall console, remove the interfaces, zone, virtual router, policies, api admin role and api administrator. Adding Firewall to Panorama ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Refer to `How to Add a Locally Managed Firewall to Panorama Management <https://knowledgebase.paloaltonetworks.com/KCSArticleDetail?id=kA10g000000CloRCAS>`_. 1. Add the firewall to the Panorama-managed devices list. Log into Panorama, select Panorama > Managed Devices and click **Add**. Enter the serial number of the firewall and click **OK**. Commit. For the Commit Type, select Panorama and click **Commit** again. 2. Set up a connection from the firewall to Panorama. Log in to the firewall, select Device > Setup, and edit the Panorama Settings. In the Panorama Servers fields, enter the IP addresses of the Panorama management server. Click **OK** and **Commit**. 3. Make any necessary configuration changes and commit your changes to the VMs. Click **Commit** and for the Commit Type select **Device Group**. Select **Merge with Device Candidate Config**, mark the **Include Device and Network Templates** checkbox, and click **Commit**. 4. Go back to Panorama > Managed Devices > Summary and mark the checkbox for the device which should show "Connected." Port 3978 also needs to be allowed on the firewall side. After 4.7, newly launched firewalls through the AVX Controller will handle this, but for existing firewalls, the user need to do it manually. Adding the Device into the Desired Template Stack and Device Group ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Go to Panorama > Template, select the desired template stack, and check the firewall from the device list. Go to Panorama > Device Group, select the desired group and check the firewall from the device list. Commit and push. Integrating Panorama with the Aviatrix Controller ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Go to the Aviatrix Controller > Firewall Network >Vendor Integration > Firewall Manager (Panorama), fill out all the required information and save. After this step, the Panorama and PAN firewalls are attached to the Controller. API calls ~~~~~~~~~~~~~~~~ The integrated functions by the Controller are the following: - The Controller monitors the health of Palo Alto Network software by using the VM-series API and performs switch over based on the API return status. - The Controller dynamically programs Palo Alto Network route tables for any new propagated new routes discovered both from new Spoke VPC/VNets and new on-premise routes. Examples of Palo Alto Networks API used: 1. get key: :: https://172.16.17.32/api/?password=<PASSWORD>&type=keygen&user=apiadmin 2. get route tables: :: https://172.16.17.32/api/?type=config&xpath=/config/devices/entry[@name='localhost.localdomain']/network/virtual-router/entry[@name='default']&key=<KEY>=&action=get 3. show interfaces: :: https://172.16.17.32/api/?key=<KEY>=&type=op&cmd=<show><interface>ethernet1/2</interface></show> 4. add route: :: https://192.168.3.11/api/?type=config&xpath=/config/devices/entry[@<EMAIL>']/network/virtual-router/entry[@name='default']/routing-table/ip/static-route/entry[@name='test2']&key=<KEY>=&action=set&element=<nexthop><ip-address>10.201.1.1</ip-address></nexthop><bfd><profile>None</profile></bfd><path-monitor><enable>no</enable><failure-condition>any</failure-condition><hold-time>2</hold-time></path-monitor><metric>10</metric><destination>10.40.0.0/24</destination><route-table><unicast/></route-table> 5. delete route: :: https://192.168.3.11/api/?type=config&xpath=/config/devices/entry[@<EMAIL>='<EMAIL>']/network/virtual-router/entry[@name='default']/routing-table/ip/static-route/entry[@name='test2']&key=<KEY>=&action=delete 6. commit :: https://192.168.3.11/api/?type=commit&key=<KEY>nST0=&cmd=<commit></commit> .. |main_companion_gw| image:: transit_dmz_workflow_media/main_companion_gw.png :scale: 30% .. |pan_admin| image:: transit_dmz_vendors_media/pan_admin.png :scale: 30% .. |download_pem_file| image:: transit_dmz_vendors_media/download_pem_file.png :scale: 30% .. |pan_role_profile| image:: transit_dmz_vendors_media/pan_role_profile.png :scale: 30% .. |pan_ping| image:: transit_dmz_vendors_media/pan_ping.png :scale: 30% .. disqus:: <file_sep> ================================================================================ |imageLogo| Datadog Integration ================================================================================ Summary ------- The Datadog integration sends system metrics from Aviatrix Gateways and the Controller to your Datadog instance. Once enabled, all existing and new Gateways will send system metrics via an installed `Datadog agent <https://github.com/DataDog/dd-agent>`__ to the configured Datadog instance. Prerequisites ------------- In order to complete the steps in this guide, you'll need: - A Datadog account and API Key .. tip:: Sign up for a Datadog account `here <https://www.datadoghq.com>`__. Once you have an account, you can create a new `API Key` from the `Integrations~APIs <https://app.datadoghq.com/account/settings#api>`__ menu. Enable/Disable Integration -------------------------- Login to the Aviatrix Controller. Go to the `Settings` in the navigation bar and click on `Logging`. At the bottom of the page, find `Datadog Agent`: |imageAgentIsDisabled| Change the status to `Enabled` and enter your Datadog `API Key` and finally click `Enable`. |imageEnableAgent| What Data Is Collected ---------------------- Once enabled, the Controller will install and configure the `Datadog agent <https://github.com/DataDog/dd-agent>`__ on each of your Gateways and on the Controller automatically. Host Name --------- Metrics from Aviatrix Gateways will have a host name in this format :: aviatrix-gw-<Gateway Name> The Aviatrix Controller will appear as:: aviatrix-ucc-<Controller Public IP Address> .. |imageLogo| image:: Datadog_media/dd_logo.png :scale: 50% .. |imageAgentIsDisabled| image:: Datadog_media/dd_disabled_agent.png .. |imageEnableAgent| image:: Datadog_media/dd_enable_agent.png .. disqus:: <file_sep> ================================================================== Multi-cloud Transit Gateway Peering over Public Network Workflow ================================================================== Aviatrix Transit Gateway peering over public network expands Aviatrix Transit Gateway peering across multi-cloud where the connection between cloud service providers is over the internet. The Aviatrix Controller builds multipe tunnels between the peered transit gateways using Insane Mode High-Performance Encryption (HPE), enabling high performance data throughput and data security. For more information about multi-cloud transit gateway encrypted peering, see the following documents: - `Aviatrix Transit Gateway Encrypted Peering <https://docs.aviatrix.com/HowTos/transit_gateway_peering.html>`_ - `Transit Network Design Patterns <https://docs.aviatrix.com/HowTos/transitvpc_designs.html>`_ - `Multi-cloud Transit Network Workflow Instructions (AWS/Azure/GCP/OCI) <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ Topology ======== |transit_gateway_peering_over_internet_topology| Prerequisite ============ 1. Upgrade Aviatrix Controller to version 6.7. Refer to `Upgrading the Aviatrix Cloud Network Platform <https://docs.aviatrix.com/HowTos/inline_upgrade.html>`_. 2. Create and launch the Aviatrix Transit Gateways with HA and Insane Mode enabled in the clouds where you want to establish peered transit connection and attach the Spoke Gateways to the Transit Gateways. Refer to `Multi-cloud Transit Network Workflow Instructions (AWS/Azure/GCP/OCI) <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_. .. note:: - Aviatrix Transit Gateway peering over public network solution requires high-performance encryption. Aviatrix Transit Gateways must have Insane Mode Encryption enabled when the Transit Gateway is created for peered connection over the internet. - This solution requires ActiveMesh 2.0. To migrate to AcitveMesh 2.0, refer to `How to migrate to ActiveMesh 2.0 <https://docs.aviatrix.com/HowTos/activemesh_faq.html#how-to-migrate-to-activemesh-2-0>`_ . Establishing Transit Gateway Peering over Public Internet --------------------------------------------------------- To establish transit gateway peering across cloud service providers over the internet: 1. In the Aviatrix Controller, go to **MULTI-CLOUD TRANSIT** > **Transit Peering**. 2. In Transit Peering, click **+ADD NEW**. 3. In Add a New Peering: a. For **Transit Gateway 1**, select a transit gateway in one cloud service provider. b. For **Transit Gateway 2**, select a transit gateway in another cloud service provider. c. Under Advanced options, check **Insane mode Encryption over internet**. .. note:: If this option is not checked, then a single tunnel is created. d. For **Number of Public Tunnels per Transit Gateway**, enter the number of tunnels to create. By default, the gateways create four HPE tunnels. The supported range is 2 to 20 HPE tunnels for each transit gateway. e. Click **OK**. 4. Confirm the transit peering status is Up. This may take a few minutes. |transit_gateway_peering_status| .. |transit_gateway_peering_over_internet_topology| image:: transit_gateway_peering_over_public_network_workflow_media/transit_gateway_peering_over_internet_topology.png :width: 500 .. |transit_gateway_peering_status| image:: transit_gateway_peering_over_public_network_workflow_media/transit_gateway_peering_status.png :scale: 30% .. disqus:: <file_sep> ========================================================= AWS Getting Started Guide ========================================================= |aws_getting_started_diagram| The Aviatrix Controller is a management and control plane or a single pane of glass that enables you to manage and support a single or multi-cloud network architecture. You can deploy an Aviatrix Controller through any of the four major CSP (Cloud Service Provider) marketplaces: * AWS (Amazon Web Services) * Microsoft Azure * GCP (Google Cloud Platform) * OCI (Oracle Cloud Infrastructure) Aviatrix recommends Controller deployment on AWS or Azure, as these CSPs enable you to set up HA (High Availability) for resiliency. This document shows you how to set up and launch an Aviatrix Controller through the AWS Marketplace. .. tip:: The Aviatrix Controller enables you to design and manage your single or multi-cloud network architecture. `Aviatrix CoPilot <https://docs.aviatrix.com/HowTos/copilot_overview.html>`_ provides a global view of your multi-cloud network. CoPilot includes features like FlowIQ to analyze global network traffic and ThreatIQ to monitor for potential malicious activity. You can deploy and configure CoPilot after launching the Controller. .. note:: If you are familiar with Terraform, it is possible to deploy a Controller by using Terraform modules. Please see the Aviatrix Terraform Modules on `GitHub <https://github.com/AviatrixSystems/terraform-modules>`_. .. important:: As a general cloud security best practice, do not use the root user credentials of your AWS account to launch the Aviatrix Controller or any other AWS resources in your AWS account. Prerequisites ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Before launching a Controller from your AWS account, complete the following prerequisites: Setting up a Dedicated VPC -------------------------------------------------------------------- To organize and segment resources more easily, set up a dedicated VPC for your Controller. You can use an existing VPC or create a new one, depending on your organization’s resources and needs. Choosing to Use an Existing VPC vs. Creating a New VPC ******************************************************** +--------------+------------------------------------+----------------------------------+ | | Using an Existing VPC | Creating a New VPC | +==============+====================================+==================================+ | Cost | Equal |Equal unless your organization’s | | | |policy is to create a dedicated | | | |AWS account for each new VPC | +--------------+------------------------------------+----------------------------------+ |Network |Equal | Equal | |performance | | | +--------------+------------------------------------+----------------------------------+ |Simplicity | Maintaining a VPC with resources |Improved fault isolation in Day 2 | |and | many different requirements may be |operations, as it is less likely | |resiliency | more difficult |that changing components in the | | | |same location will harm the | | | |control plane's connectivity | +--------------+------------------------------------+----------------------------------+ If you choose to use an existing VPC, make sure it uses the settings specified below in the “Creating a New VPC” section. .. note:: Note that if you use a shared VPC, different accounts are not allowed to see each other’s instances. This is by design by AWS. In this case, put in a feature request with AWS to allow users inside RAM permissions to allow all accounts in each shared subnet to see all the instances in the subnet. Otherwise, certain Aviatrix features will not work properly in your account. Creating a New VPC *********************** 1. Log into your AWS account, preferably an Infrastructure OU – Networking or Shared Services account. 2. If you have decided to launch a new VPC, go to VPC > Create VPC. Make sure this new VPC has the following settings: Region – Before configuring any settings, click on the dropdown menu in the top right and select the region in which to locate this VPC. *In the example below, the current region is Oregon.* |choose_vpc_region| +----------------------------+-----------------------------------------------------------------------------------------------+ | Setting | Value | +============================+===============================================================================================+ | Resources to create | Select the **VPC and more** radio button. | +----------------------------+-----------------------------------------------------------------------------------------------+ | Name tag | Enter a clear and recognizable name (such as | | | "aviatrix-mgt" or "aviatrix-management"). | +----------------------------+-----------------------------------------------------------------------------------------------+ | IPv4 CIDR block | Enter the IPv4 CDIR block for the Controller | | | VPC. The minimum is /26; the maximum is /16. A | | | best practice is to use RFC1918 ranges. | +----------------------------+-----------------------------------------------------------------------------------------------+ | IPv6 CDIR block | No IPv6 CIDR block | +----------------------------+-----------------------------------------------------------------------------------------------+ | Tenancy | Default | +----------------------------+-----------------------------------------------------------------------------------------------+ | Number of Availability | Select **1** if you choose **not** to | | Zones (AZs) | configure | | | `HA <https://docs.aviatrix.com/HowTos/controller_ha.html>`_. | | | One Availability Zone offers a simpler deployment but no | | | resiliency. | | | | | | Select **2** if you require Controller resiliency through HA. | +----------------------------+-----------------------------------------------------------------------------------------------+ | Number of public subnets | Select **1** if you choose not to configure HA. | | Services - Migration | | | | Select **2** if you choose to configure HA (make sure you have | | | also selected two Availability Zones). | +----------------------------+-----------------------------------------------------------------------------------------------+ | Number of private subnets | 0 | +----------------------------+-----------------------------------------------------------------------------------------------+ | NAT gateways ($) | None | +----------------------------+-----------------------------------------------------------------------------------------------+ | VPC endpoints | None | +----------------------------+-----------------------------------------------------------------------------------------------+ | DNS options | Leave these settings at their defaults (both checkboxes | | | marked). | +----------------------------+-----------------------------------------------------------------------------------------------+ 3. Click **Create VPC**. See the screenshot below to confirm your settings. This example VPC uses two Availability Zones and two public subnets to enable HA. |create_vpc_settings| Saving the Management CIDR Range ------------------------------------------------------------------------ Find and save the **CIDR range** for the device of the main Controller user. Note that this IP address is different than the IP for the VPC itself, which you configured when you launched the VPC. .. note:: To find a device’s IP address and determine this CIDR range, search for “what is my IP” on the browser’s search engine. You can also check **icanhazip.com** or **ifconfig.io**. .. tip:: Optional steps (not required for deployment): * Create an `S3 bucket <https://docs.aws.amazon.com/AmazonS3/latest/userguide/creating-bucket.html>`_ for storage. An S3 bucket is not required to launch a Controller, but is required for `HA (High Availability) <https://docs.aviatrix.com/HowTos/controller_ha.html>`_ and `Backup and Restore Configuration <https://docs.aviatrix.com/HowTos/controller_backup.html>`_. .. note:: The S3 bucket you use or create for Controller HA and Backups does not need to have public access enabled and should be configured to restrict general public access. * Create an `Application Load Balancer <https://docs.aws.amazon.com/elasticloadbalancing/latest/application/introduction.html>`_ with a `Web Application Firewall (WAF) <https://aws.amazon.com/waf/#:~:text=AWS%20WAF%20is%20a%20web,security%2C%20or%20consume%20excessive%20resources.>`_ for additional security. This configuration requires a second subnet in a different Availability Zone. See `Configuring an AWS Load Balancer with SSL in front of Aviatrix Controller <https://docs.aviatrix.com/HowTos/controller_ssl_using_elb.html>`_ for more information about this configuration. Prerequisite Checklist ----------------------------------------------------------------- Make sure you have completed these prerequisites before launching your Controller: - Launched a dedicated VPC with settings listed above - Saved the CIDR range for the main user of the Controller - Reviewed the optional steps `above <https://docs.aviatrix.com/StartUpGuides/aws_getting_started_guide.html#setting-up-a-dedicated-vpc>`_ (creating an S3 bucket and an Application Load Balancer) and completed them if needed for your configuration Launching the Controller ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ After completing the Prerequisite Checklist above, you can set up and launch your Aviatrix Controller. Subscribing to the Metered Aviatrix AMI (Amazon Machine Image) ------------------------------------------------------------------------------------ An Amazon Machine Image (AMI) contains the information required to launch an instance. Your Aviatrix Controller will be listed as an instance, or EC2 (Elastic Cloud Compute), on your AWS account. .. note:: For current pricing information for each AMI, please see each AMI subscription’s page in the AWS Marketplace. To launch your Controller, subscribe to the correct Aviatrix AMI from the AWS Marketplace. 1. Log into the AWS Marketplace. Enter “Aviatrix” in the search bar under Search AWS Marketplace products. Several options appear: |aws_marketplace_options| +----------------------------+-------------------------------------------------+ | License | Description | +============================+=================================================+ | Aviatrix CoPilot | License for Aviatrix CoPilot only, a separate | | | product that provides a global view of your | | | multi-cloud network. This subscription offers | | | a 64-bit (x86) architecture. | | | | | | .. note:: | | | | | | See the Aviatrix CoPilot (ARM) license below | | | for a different CoPilot option. | +----------------------------+-------------------------------------------------+ | Aviatrix Secure Networking | This license offers the Aviatrix Controller and | | Platform BYOL (Bring Your | CoPilot image only. It requires a separate | | Own License) | licensing agreement directly with Aviatrix. | +----------------------------+-------------------------------------------------+ | Aviatrix CoPilot (ARM) | License for Aviatrix CoPilot only, a separate | | | product that provides a global view of your | | | multi-cloud network. This subscription offers a | | | a 64-bit ARM architecture. | +----------------------------+-------------------------------------------------+ | Aviatrix Secure Networking | An all-in-one license that allows unlimited | | Platform - Enterprise | deployment. Charged at an hourly rate unless | | Subscription | there is a private offer to adjust pricing with | | | Aviatrix separately. | +----------------------------+-------------------------------------------------+ | Aviatrix Professional | This license offers an automated and streamlined| | Services - Custom | process with the help of the Aviatrix | | | Professional Services Architect (PSA) team. | | | Contact the `Professional Services team | | | <<EMAIL>>`_ for more information. | +----------------------------+-------------------------------------------------+ | **Aviatrix Secure | With this licensing option, the AWS Marketplace | | Networking Platform Metered| receives usage data from your Controller and | | 2208-Universal 24x7 | charges based on consumption of Aviatrix | | Support** | functionality as described within the offer. | | | | | | Make sure to subscribe to the correct metered | | | offer, which has "2208" in the name. | +----------------------------+-------------------------------------------------+ | Aviatrix Professional | Select this option to have the Advanced Services| | Services - Migration | team manage your migration from an AWS Transit | | | Gateway to an Aviatrix secure cloud network | | | infrastructure. Contact the `Professional | | | Services team <<EMAIL>>`_ for more | | | information. | +----------------------------+-------------------------------------------------+ 2. Select the **Aviatrix Secure Networking Platform Metered 2208-Universal 24x7 Support** option. On the subscription’s page, click **Continue to Subscribe**. Subscribing means that you can begin deploying the software in later steps using the CloudFormation template. 3. On the next page, click **Subscribe** again to confirm. Then, click **Set up Your Account**. 4. Under Aviatrix Metered Controller Subscription, enter your email address in the Email field and click **Verify Email**. 5. Open the email you receive from <EMAIL>, copy the six-digit verification code, and enter it in the Verification Code field. Then, click **Submit Form**. 6. You receive a new email from <EMAIL> with the subject line "License key for Aviatrix Metered Controller and Copilot." This email contains your Controller customer ID, Copilot customer ID, and offer subscription ID. Save these values in a secure place to use later for onboarding. Activating the Metered AMI through the BYOL (Bring Your Own License) Offer ------------------------------------------------------------------------------------------------------ After subscribing to the Aviatrix Secure Networking Platform Metered 2208-Universal 24x7 Support subscription, click on the link in the email you received to open the Aviatrix Secure Network Platform (BYOL) offer. On the offer's page, click **Continue to Subscribe**. .. note:: The BYOL or Bring Your Own License offer is required to activate the metered license you subscribed to above. You will only be billed for the metered subscription. Next, use a CloudFormation template to launch your Controller. Launching the Controller with CloudFormation ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A CloudFormation template provides a layer of abstraction that makes the configuration process simpler and easier by automating many of the minor steps. Use the default CloudFormation template to launch your Controller. 1. In your AWS account, go to AWS Marketplace Subscriptions > select the Aviatrix Secure Networking Platform - BYOL subscription. Scroll down to the Agreement section, click the Actions dropdown menu, and select **Launch CloudFormation stack**. 2. On the Configure this software page, click on the **Fulfillment** option dropdown menu and select **CloudFormation Template**. * Under Software version, select the most recent version. * Under Region, click on the dropdown menu in the top right corner and select the region in which you want to deploy the Controller. |location_for_cloudformation| .. warning:: Make sure to choose the correct region before launching the Controller instance (see the “Setting up a Dedicated VPC” prerequisite above). After launching a Controller instance, you can only change that instance’s region by stopping that Controller and re-deploying a new one. 3. Use the options on the CloudFormation template to set up your Controller. * **Step 1: Create Stack** – Leave the settings on this page at their defaults. Click **Next**. * **Step 2: Specify stack details** – +----------------------------+-------------------------------------------------+ | Setting | Value | +============================+=================================================+ | Stack name | Enter a clear and recognizable name, such as | | | "AviatrixController." | +----------------------------+-------------------------------------------------+ | Which VPC should the | Select the dedicated VPC you created for the | | Aviatrix Controller be | Aviatrix Controller. Please see the Prerequisite| | deployed in? | section. | +----------------------------+-------------------------------------------------+ | Which public subnet in the | Select a public subnet in the VPC. Make sure | | VPC? | this subnet is public (it has "public" in the | | | name). | +----------------------------+-------------------------------------------------+ | IPv4 address(es) to include| Enter the IP address for the main user or | | | operator of the Aviatrix Controller. You can | | | enter a CIDR block, but you must add **/32** to | | | limit the Controller's access. | +----------------------------+-------------------------------------------------+ | Select Controller size | Leave the size at the default, t3.large. | +----------------------------+-------------------------------------------------+ | IAM role creation | * If this is the first time you have attempted | | | to launch the Controller, leave this setting | | | at **New**. | | | * If this is the second or later attempt, click | | | on the dropdown menu and select | | | **aviatrix-role-ec2**. | +----------------------------+-------------------------------------------------+ .. note:: The Aviatrix Controller must be launched on a **public** subnet. * If this your first time launching an Aviatrix Controller, select the default setting **New** for IAM Role Creation. * If an Aviatrix IAM role has been created before, select **aviatrix-role-ec2** for IAM Role Creation. * Wildcard/all (*) is the default resource for all `Aviatrix IAM permissions <https://docs.aviatrix.com/HowTos/aviatrix_iam_policy_requirements.html>`_ except for #13, “IAM Policy Scanning Requirement”. This resource needs to be customized per your resource requirements to be secure. We advise you to work with your Aviatrix account team to restrict what resources need to be in scope for your IAM policy. * **Step 3: Configure stack options** – Leave the settings on this page at their defaults and click **Next**. * **Step 4: Review *Stack_Name*** – Review the settings to make sure they are correct. Mark the **I acknowledge that AWS CloudFormation might create IAM resources with custom names** checkbox at the bottom of the page and click **Create stack**. After configuring the stack options, at the bottom of the **Review *Stack_Name*** page, click **Create**. Saving the Public and Private IP Address --------------------------------------------------------------------------------------- When the stack creation completes, its status changes to CREATE_COMPLETE. 1. Select the new Controller instance on the Aviatrix Controller instance’s Stacks page. 2. Select the **Outputs** tab. 3. Save the values for the Account ID, Elastic IP (EIP) address, and Private IP addresses listed on the Outputs tab. You will need to use these later to onboard the primary access account for AWS in your Controller. |cloudformation_outputs_tab| .. note:: You might have to refresh your browser window and/or AWS account to see your Stack displayed with an updated status. .. note:: If you experience a rollback error and cannot successfully launch the stack, please see the Troubleshooting section at the end of this document. Setting up the New Instance in AWS ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1. In the rare situation in which you deployed CoPilot before deploying this Controller, add Aviatrix CoPilot’s IP address to the Controller’s security group. 2. Verify that your own device’s public IP address is listed as one of the Controller’s `security group rules <https://docs.aws.amazon.com/quicksight/latest/user/vpc-security-groups.html>`_. This step ensures that you can open the deployed Controller successfully. .. note:: To find your device’s IP address, you can search for “what is my IP” on your browser’s search engine. You can also check **icanhazip.com** or **ifconfig.io**. Add IP Addresses to the Controller’s Security Group Rules ----------------------------------------------------------------------------------- 1. Navigate to your AWS account > EC2 > your Controller’s instance > Security tab. 2. Scroll down and select the name of the **Security group** on the left side of the page. 3. On the security group’s page, click **Edit inbound security rules** on the right. 4. On the **Edit inbound rules** page, click **Add New** and enter the following information: +----------------------------+-------------------------------------------------+ | Setting | Value | +============================+=================================================+ | Type | HTTPS | +----------------------------+-------------------------------------------------+ | Port range | Leave at 0 | +----------------------------+-------------------------------------------------+ | Source | Custom | +----------------------------+-------------------------------------------------+ | Address | Enter the CoPilot’s IP address followed by the | | | CIDR block (/32 in the example screenshot). | +----------------------------+-------------------------------------------------+ | Description (optional) | Aviatrix CoPilot Public IP address | +----------------------------+-------------------------------------------------+ 5. Click **Save rules**. 6. Repeat the previous steps to add your own device’s Public IP address to the security group rules: +----------------------------+-------------------------------------------------+ | Setting | Value | +============================+=================================================+ | Type | HTTPS | +----------------------------+-------------------------------------------------+ | Port range | Leave at 0 | +----------------------------+-------------------------------------------------+ | Source | Custom | +----------------------------+-------------------------------------------------+ | Address | Enter your device’s public IP address followed | | | by the CIDR block: for example, | | | 44.257.233.220/32. | +----------------------------+-------------------------------------------------+ | Description (optional) | To better remember which IP address this is | | | later, you can enter the name of your device | | | here and “public IP address.” | +----------------------------+-------------------------------------------------+ .. note:: If your IP address changes based on device or location, make sure to add those IP addresses to the Security group rules. Make sure this list contains only verified, secure IP addresses listed to limit access to your Controller. .. note:: Later, when you launch gateways from your Controller, each gateway creates a new Security group. You will need to add your device’s IP address to each new gateway’s Security group. 7. Return to your instance’s page. If you have not already done so, save the **Public IPv4** and **Private IPv4** for your Controller. |save_ip_addresses| Onboarding your AWS account in your Aviatrix Controller ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ After launching your Controller instance in AWS, you can log in and initialize your account. Log In and Initialize ------------------------------------------------------------------- 1. To log into your Controller, navigate to your AWS account > EC2 > your Controller instance. Select the **open address |open_icon| icon** next to your Controller’s Public IP address near the top of the page. .. note:: If you cannot open this Public IP address, make sure your device’s IP address is listed in the Controller instance’s inbound security rules. 2. If a “Your connection is not private” warning appears, click **Advanced > Proceed to *your_Controller’s_Public_IP_Address***. 3. The Controller login page opens. Enter: * **Username** – admin * **Password** – Your Controller’s private IP address. This address is listed in the top right of the Controller instance’s page in AWS. 4. Enter your email address. This email will be used for alerts as well as password recovery if needed. 5. When prompted, change your password. Make sure this password is secure. If the (Optional) Proxy Configuration message appears, click **Skip**. 6. Click **Run**. The Controller upgrades itself to the latest software version. Wait for a few minutes for the process to finish. .. tip:: The Controller upgrade takes about 3-5 minutes. When the upgrade is complete, you can log in. Use the username “admin” and your new password to log in. Onboard your Access Account ----------------------------------------------------------------------------- After logging in and initializing, onboard your AWS account in your Controller. 1. In your Controller, navigate to Onboarding in the left sidebar. Click on the AWS icon. |click_aws_icon| 2. Enter your AWS account’s Account ID. To find this Account ID, open your AWS account and click on the dropdown menu in the top right corner. Select Account. Your Account ID is listed at the top of the page under Account Settings. 3. Mark the **Use IAM Roles** checkbox. .. note:: If you leave this checkbox unmarked, use ARN values to set up user roles. ARN values are only required if you are onboarding an account that is separate from the one from which you deployed the Controller. 4. Click **Create**. 5. Your AWS account is now onboarded. To verify your email address, open Settings > Controller. Enter the verification code sent to your email address. You can now use advanced settings to configure your `IAM roles <https://docs.aviatrix.com/HowTos/iam_policies.html>`_, launch `gateways <https://docs.aviatrix.com/HowTos/gateway.html>`_, and build a single- or multi-cloud network architecture. .. tip:: To launch Aviatrix CoPilot, please see the `CoPilot Deployment Guide <https://docs.aviatrix.com/HowTos/copilot_getting_started.html>`_. Note that CoPilot requires a separate license from the AWS Marketplace. .. note:: You need to deploy a separate Controller to use AWS China. Please see `this document <https://docs.aviatrix.com/HowTos/aviatrix_china_overview.html?highlight=china>`_. Troubleshooting if the Stack Creation Fails ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ If your stack creation fails to launch your Controller instance in AWS, check the following settings: * Subscribing to the AMI first – Make sure you subscribed to the Metered Controller license from the AWS Marketplace **before** launching the CloudFormation template. * IAM roles – If this attempt was the first time you tried to launch your Controller, make sure the value is set to **New**. In later attempts, click on the dropdown menu and select **aviatrix-role-2**. * CIDR block – When you enter the primary user’s IP address, make sure the address includes **/32** to ensure that only this user can access the Controller (for now). You can add more users later by: * Creating new user accounts in the Controller. See `this document <https://docs.aviatrix.com/HowTos/rbac_faq.html>`_ for more information about new users and permissions. * Through `OpenVPN <https://docs.aviatrix.com/HowTos/uservpn.html>`_ using Single Sign On (SSO). .. |aws_getting_started_diagram| image:: aws_getting_started_guide_media/aws_getting_started_diagram.png :scale: 40% .. |choose_vpc_region| image:: aws_getting_started_guide_media/choose_vpc_region.png :scale: 60% .. |create_vpc_settings| image:: aws_getting_started_guide_media/create_vpc_settings.png :scale: 50% .. |aws_marketplace_options| image:: aws_getting_started_guide_media/aws_marketplace_options.png :scale: 40% .. |location_for_cloudformation| image:: aws_getting_started_guide_media/location_for_cloudformation.png :scale: 60% .. |cloudformation_outputs_tab| image:: aws_getting_started_guide_media/cloudformation_outputs_tab.png :scale: 60% .. |save_ip_addresses| image:: aws_getting_started_guide_media/save_ip_addresses.png :scale: 60% .. |open_icon| image:: aws_getting_started_guide_media/open_icon.png :scale: 60% .. |click_aws_icon| image:: aws_getting_started_guide_media/click_aws_icon.png :scale: 30% .. disqus:: <file_sep> =========================== Frequently Asked Questions =========================== The Aviatrix product consists of a Controller and Gateways. When the product is deployed in the public cloud marketplace, what you launch is the Controller instance. From the Controller console, you launch gateways by using cloud provider APIs. When the product is deployed as a virtual appliance in a virtualized data center environment, the Controller and Gateway are bundled into one virtual image, such as OVF (Open Virtualization Format) and VHD (Virtual Hard Disk). The following FAQ discusses only the cloud deployment scenario. Aviatrix Secure Cloud Network Platform ======================================= What can the Aviatrix platform do for me? ----------------------------------------------------- Aviatrix cloud-native networking solution provides an end-to-end secure network solution for AWS, Azure, Google GCloud, and Oracle Cloud (OCI). The solution includes `AWS Global Transit Network <http://docs.aviatrix.com/HowTos/transitvpc_faq.html>`_, an enterprise `OpenVPN® <http://docs.aviatrix.com/HowTos/openvpn_faq.html>`_ access to VPC/VNet, `encrypted routing <http://docs.aviatrix.com/HowTos/peering.html>`_ for VPC/VNet to VPC/VNet traffic, `Stateful Firewall and Egress FQDN <http://docs.aviatrix.com/HowTos/FQDN_Whitelists_Ref_Design.html>`_ and `monitoring and logging <http://docs.aviatrix.com/HowTos/AviatrixLogging.html>`_ of link status and latency. The solution enables you to build a secure private network spanning one or more public clouds where a user can access any instance/VM with a private IP address directly. No more bastion stations and jump hosts: the solution gives the user the seamless experience that they enjoy when using the on-prem network. For an Aviatrix overview, check out `this document <http://docs.aviatrix.com/StartUpGuides/aviatrix_overview.html>`_. In addition, the product interoperates with any third-party IPsec capable devices, including AWS VGW and Aviatrix's own on-prem virtual appliance CloudN. Architecturally, Aviatrix solution is a centrally managed, loosely coupled, and globally deployed platform built for the cloud from the ground up. How do I launch the product? -------------------------------------------- The product consists of two components: the Controller and one or more Gateways. The Gateway is launched from the Controller. The Controller provides a central console for all provisioning, monitoring and upgrades of the services. The Controller is available in the AWS and Azure marketplace. It is also available as a GCloud community image. For marketplace launch, search for “Aviatrix” in marketplace. * Follow `Getting Started on AWS <http://docs.aviatrix.com/StartUpGuides/aviatrix-cloud-controller-startup-guide.html>`_ instructions to launch the Controller on AWS. * Follow `Getting Started on Azure <http://docs.aviatrix.com/StartUpGuides/azure-aviatrix-cloud-controller-startup-guide.html>`_ instructions to launch the Controller on Azure. * Follow `Getting Started on Google <http://docs.aviatrix.com/StartUpGuides/google-aviatrix-cloud-controller-startup-guide.html>`_ instructions to launch the Controller on Google. What are the deployment requirements for the Aviatrix product? -------------------------------------------------------------------------------- Aviatrix Controller and Gateways are deployed on subnets (public subnets in AWS, GCP, and OCI) with public IP addresses for Internet access, as shown below. |deployment| How do I access the Controller? --------------------------------------- If your Controller is launched as a machine image (AMI/VM Image/Custom Image) from marketplace, you access the Controller instance via a web browser. https://public\_IP\_address\_of\_the\_controller\_instance Log in with the username “admin.” The first-time password is the private IP address of the Controller instance. You are required to change the password at your first login. If you are using an Aviatrix Hosted Service (AHS), following the instructions sent to you to access. How do I secure the Controller access? -------------------------------------------------- There are several ways to secure your Controller access, as discussed below. 1. Enabling Controller Security Group Management ############################################### Only TCP port 443 needs to be opened for inbound traffic to the Controller. If you wish to reduce the scope of source addresses by specifying a custom IP address, you must include all gateway public IP addresses, in addition to your own public IP address. This is because gateways launched from the Controller use its public IP address to communicate back to the Controller. You can use the Controller Security Management feature to automatically manage the Controller instance's inbound rules from gateways. Go to Settings > Controller > Access Security > Controller Security Group Management, select the `primary access account <http://docs.aviatrix.com/HowTos/aviatrix_account.html#setup-primary-access-account-for-aws-cloud>`_, and click **Enable**. .. note:: After this feature is enabled, you can now edit the security rules that are outside gateways public IP addresses to limit the source address range. AWS: ^^^^^^^ AWS Network ACLs are not stateful, so they are not recommended for controlling access to/from Aviatrix Controllers and Gateways. When this feature is enabled, the Controller will immediately create 4 security groups. Since each security group can support 50 security rules, the Controller can support up to 200 gateways. AZURE: ^^^^^^^^ When this feature is enabled, the Controller utilizes the associated network security group which can support up to 1,000 security rules. .. note:: If you deploy Aviatrix SAML clients for user VPN access, you can follow `this document <http://docs.aviatrix.com/HowTos/controller_security_for_SAML.html>`_ to add security to the Controller. 2. Using a Signed Certificate ########################## The Aviatrix Controller is shipped with a self-signed certificate. Therefore, there is a "Note Secure" warning sign shown on your browser console. You can change that by importing your own signed certificate. To do so, go to Settings > Controller > Certificate. On the Controller Certificate Management page, select Generate CSR and Import Certificate. Here you generate a CSR (certificate sign request), and then import the CA and the signed Controller certificate. You can also use an `ALB in front of the Controller <./controller_ssl_using_elb.html>`__. 3. Removing Less Secure TLS Version(s) #################################### You can disable access from a browser that runs TLSv1 and TLSv1.1 and only supports TLSv1.2. To do so, go to Settings > Advanced > Security > TLS Versions Support. Uncheck TLSv1 and TLSv1.1. 4. Enabling LDAP or DUO Second Factor to Log in ################################################ In addition to username and password login credentials to the Controller, you can also enable LDAP or DUO authentication. To enable LDAP authentication, go to Settings > Controller > LDAP Login and fill the form. To enable DUO authentication, go to Settings > Controller > Duo Login and follow `the instructions <http://docs.aviatrix.com/HowTos/AdminUsers_DuoAuth.html#configuration-workflow-for-duo-authentication>`_ to set up DUO. 5. Creating Read-Only Accounts ############################# You can create read_only accounts for your operations team. They can view and list pages but not making changes. Follow the `answer <http://docs.aviatrix.com/HowTos/FAQ.html#can-there-be-read-only-account-for-operation-team>`_ to have it set up. 6. Remove Admin Account Login ############################### The "admin" account login can be disabled to use an account user instead. To disable the admin login to the Controller, go to Settings > Controller > Login Customization. Click **Disable**. Please note that you need a local user with admin privileges to be created before you can disable the "admin" account. 7. Encrypting the Controller EBS Volume ################################## Follow the `instructions here <https://github.com/AviatrixSystems/EBS-encryption>`_ to encrypt the Controller EBS Volume after the Controller is launched. 8. Encrypting the Gateway EBS Volume ################################# Aviatrix Gateway EBS volume can be encrypted after it is launched following `the same instructions <https://docs.aviatrix.com/HowTos/encrypt_ebs_volume.html?highlight=volume>`_. In addition, we provide an `open source script <https://github.com/AviatrixSystems/EBS-encryption>`_ to automate the process. 9. Enabling Controller SAML Login ################################ You can enable `SAML authentication for Controller login. <https://docs.aviatrix.com/HowTos/Controller_Login_SAML_Config.html>`_ 10. Securing Controller when using SAML for VPN User Authentication ###################################################################### This scenario is explained in detail `here <https://docs.aviatrix.com/HowTos/controller_security_for_SAML.html>`_ 11. Enabling Login Banner ####################### This function is explained in detail `here <https://docs.aviatrix.com/HowTos/controller_config.html#login-banner>`_. What events does the Aviatrix Controller monitor? -------------------------------------------------------------------------- 1. **VPN tunnel status** Alert when it goes down and alert when it comes back up. #. **Gateway health status** Alert when gateway goes to down state. Alert when it comes back up. #. **Overlap network CIDR range** Alert when BGP routes overlap. #. **Route limit** Alert when BGP route limits reach a threshold. #. **TGW Auditor** Monitors the configuration changes. Alert when there is an inconsistency between AWS console and Aviatrix Controller for resources related to TGW operation. #. **IAM role and policy** Alert when account IAM policy is not up to date or being deleted. #. **Guard Duty integration** Alert and block malicious IP addresses. #. **Black hole route** Alert when VPC/VNet route table has inactive routes. #. **Subnet** Alert when there are unwanted instances launched on specific subnets (public subnets in AWS, GCP, and OCI). #. **CPU/Memory/Disk** Alert when gateway memory usage crosses 80% or disk space reaches 90% of its capacity. How do I ensure my Transit Network is secure when an Aviatrix Gateway is deployed on an AWS public subnet? -------------------------------------------------------------------------------------------------------------------------------------- The Customer Concerns ###################### Some organizations have concerns about having public subnets in a VPC in AWS. The concern is that if there were a public subnet in a VPC, users may find ways to launch an instance on the public subnet and associate the instance with a public IP address, thus enabling the instance to access the Internet without going through a proper egress firewall (in the cloud or on-prem). The Reality ############## However, when deploying a `AWS Global Transit Network solution <https://aws.amazon.com/answers/networking/aws-global-transit-network/>`_, a vendor gateway must be deployed on a public subnet in the Transit VPC. This is true for all vendor appliances on the AWS marketplace. This is because the vendor gateway in the Transit VPC establishes IPsec tunnels with Spoke VPC over public IP address, whether or not the Spoke VPC deploys a vendor gateway or VGW. Another reason is the vendor gateway requires SSH access to configure its VPN tunnels. Note that this connectivity between Transit VPC and Spoke VPC, although using public IP addresses as IPsec tunnel endpoints, does not imply that traffic between Transit VPC and Spoke VPC go through the Internet. AWS recognizes that it owns these public IP addresses and therefore always tries to route the traffic through its own backbone network without ever going out to Internet. The Aviatrix Solution ###################### An Aviatrix gateway instance has strict security groups. It only opens to the Controller on TCP port 443 and port 22 (for the Controller to reach the Gateway for diagnostics purposes.) In addition, Aviatrix provides multiple features to ensure your Transit Network is secure, as described below. #. If you use AWS Transit Gateway (TGW) to build a transit network, the Aviatrix Gateway is only launched in the transit VPC. All spoke VPCs have no Aviatrix Gateway. #. Enable `Gateway Subnet Monitoring <http://docs.aviatrix.com/HowTos/gateway.html#monitor-gateway-subnet>`_. When this feature is enabled, the Controller will monitor the selected public subnets periodically. When it detects any instances being launched on these subnets, the Controller will alert the admin and stop the instances. #. Enable `VPC Egress Firewall`. If you need to optimize application performance, you should consider allowing instances to access Internet directly, rather than backhauling to on-prem. When this feature is enabled, any traffic initiated from instances on the private subnet must go through the inline and in VPC egress whitelists before going out to the Internet. #. Enable `Remote User VPN`. If you need to optimize developer experience (less latency, higher bandwidth), you should consider allowing users to access instances in the VPC directly with SSL VPN. When this feature is enabled, all user traffic is tracked and logged for audit and tracking purposes. #. Secure the Controller. Follow the guidelines `here <http://docs.aviatrix.com/HowTos/FAQ.html#how-do-i-secure-the-controller-access>`_ to secure the Controller access. #. Log everything. Enable `Logging` to send all events from gateways, Controllers and user activities to your favorite log service platform for audit and compliance. Is Aviatrix Cloud Gateway a SaaS offer? ------------------------------------------ No. The Aviatrix Controller and gateways are software products that are deployed in your own network perimeter. Onboarding =============== Where do I start? --------------------------- The first time you log in, complete the steps of the Onboarding process. If you have a BYOL license or use a community image, you need to have a customer ID provided by Aviatrix to be able to use the product. Please open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_ if you do not have a customer ID. What is an Aviatrix Access Account? ---------------------------------------------- An Aviatrix Access Account is specific and unique on the Controller. It contains cloud credentials, for example, your AWS IAM Access Key ID and Secret Key. The Controller uses these credentials to launch Aviatrix gateways by using cloud APIs. An Aviatrix Cloud Account can correspond to multiple cloud accounts. For example, it can contain credentials for an AWS IAM account, Azure account, and GCloud account. How do I upgrade the software? ------------------------------------------ Click Settings > Upgrade. This upgrades to the latest release of the Controller software. When a new release becomes available, an alert message appears on Dashboard. An email will also be sent to the admin of the Controller. Is there a reference design example? --------------------------------------- Check out docs.aviatrix.com. What is the support model? --------------------------------------- For support, please open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_ or reach out to your respective Account Executive. We also offer `Platinum <https://aviatrix.com/support/>`__ customers with 24x7 support. Logging and Monitoring ====================== How do I forward syslog events to my Logstash server? ---------------------------------------------------------------------- Click on Settings > Logging > LogStash logging and input the required parameters to enable forwarding of Controller syslog events and all gateways syslog and auth log to a Logstash server. SUMO Logic, Splunk, DataDog and rSyslog are also supported. What are the monitoring capabilities? ----------------------------------------------- Encrypted tunnel (peering and site2cloud) status is monitored. When a tunnel status changes, an alert email is sent to the Controller admin. Active VPN users are displayed on the Dashboard. Click on any username and the user VPN connectivity history is displayed. You can also disconnect a user from the dashboard. Can alert emails be sent to a different email address? ----------------------------------------------------------------- Yes, you can choose an alternative email address to send alert messages. This is useful if the Controller admin is different from the operation team. Administration ============== Can there be multiple admins? --------------------------------------- Yes. Username “admin” is the default admin user. But you can create multiple users with admin privileges. Follow `the instructions <http://docs.aviatrix.com/HowTos/AdminUsers_DuoAuth.html>`_ to learn more about setting up multiple admin users. Is there 2FA support to log in to the console? ---------------------------------------------------------- Yes. In addition to password login, DUO authentication and LDAP are supported. Starting from Release 4.2, SAML authentication is supported to login to the Controller console. Can there be read-only account for operation team? ----------------------------------------------------------------- Yes. Navigate to Accounts > Account Users > Add a New User, at Account Name field and select "read_only" from the dropdown menu. This user account will have views to all pages but cannot make changes to any configurations. Is Aviatrix FIPS 140-2 compliant? ------------------------------------------- Yes. Aviatrix has achieved FIPS 140-2 compliant status with certificate number `#3273 <https://csrc.nist.gov/projects/cryptographic-module-validation-program/certificate/3273>`_ as listed at NIST site. What are the FIPS 140-2 compliant algorithms? ------------------------------------------------ FIPS 140-2 approved crypto functions can be found in `this link. <https://csrc.nist.gov/csrc/media/publications/fips/140/2/final/documents/fips1402annexa.pdf>`_. According to this document, the following algorithms that are supported on Aviatrix are FIPS 140-2 compliant. ======================= ========== **IPsec algorithms** **Value** ======================= ========== Phase 1 Authentication SHA-1, SHA-512, SHA-384, SHA-256 Phase 1 DH Groups 2, 1, 5, 14, 15, 16, 17, 18 Phase 1 Encryption AES-256-CBC, AES-192-CBC, AES-128-CBC, 3DES Phase 2 Authentication HMAC-SHA-1, HMAC-SHA-512, HMAC-SHA-384, HMAC-SHA-256 Phase 2 DH Groups 2, 1, 5, 14, 15, 16, 17, 18 Phase 2 Encryption AES-256-CBC, AES-192-CBC, AES-128-CBC, AES-128-GCM-64, AES-128-GCM-96, AES-128-GCM-128, 3DES ======================= ========== SSL VPN encryption algorithm set on the server is AES-256-CBC. For OpenVPN clients running a version 2.3 or lower the negotiated algorithm would be AES-256-CBC. For OpenVPN clients running 2.4 or higher, the negotiated algorithm would be AES-256-GCM due to NCP (Negotiable Crypto Parameters) SSL VPN authentication algorithm is SHA512. What is the difference between IKEv1 and IKEv2? ---------------------------------------------------------------- Internet Key Exchange (IKE) protocol is the control plane to IPsec data encryption. Its responsibility is in setting up security association that allow two parties to send data securely. There is no difference in data encryption algorithms and data encryption strength itself between IKEv1 and IKEv2. The primary difference between IKEv1 and IKEv2 is that it takes fewer messages to establish the security association in IKEv2. There are a couple of other differences regarding IKEv2, which has a better support for mobile devices which does not apply to site to site and site to cloud VPN where Aviatrix is being used. How to encrypt Aviatrix Controller and gateway EBS volume? ----------------------------------------------------------------------------- You can follow the `instructions here <https://www.alienvault.com/documentation/usm-appliance/kb/2017/02/encrypting-root-volumes-for-aws-deployments.html>`_ to encrypt the Controller. For automation, you can reference our `python script on the Github repository. <https://github.com/AviatrixSystems/EBS-encryption>`_ Starting Release 4.2, Aviatrix gateway EBS volume can be encrypted from the Controller. How do I launch the Controller by Terraform? ------------------------------------------------------- Terraform for Controller launch is supported as a community project on Github on `this Aviatrix repo. <https://github.com/AviatrixSystems/terraform-modules>`_ How do I migrate a Controller from a Metered license to BYOL license? ------------------------------------------------------------------------------------- Follow the instructions described in `this document. <https://docs.aviatrix.com/HowTos/Migration_From_Marketplace.html>`_ What is the best practice to ensure high availability of the Controller? --------------------------------------------------------------------------------------- The best practice is to enable `backup and restore function <https://docs.aviatrix.com/HowTos/controller_backup.html>`_. In the event of Controller being terminated or become non-functional, you can restore the system by following the instructions `here. <https://docs.aviatrix.com/HowTos/Migration_From_Marketplace.html>`_ Since Aviatrix Controller is not in the data plane, temporary loss of the Controller does not affect the existing tunnels or packet forwarding. For AWS deployment, you can also enable `Controller HA <https://docs.aviatrix.com/HowTos/controller_ha.html>`_ for auto recovery when the current Controller becomes unhealthy. Do you have the CloudFormation source code for launching the Controller? ------------------------------------------------------------------------------------------- Yes, the source repository for Controller launch can be found on Github at `here. <https://github.com/AviatrixSystems/aws-controller-launch-cloudformation-templates>`_ How are security updates handled and delivered by Aviatrix? ---------------------------------------------------------------------------- These are the steps: 1. **Field Notice** All Aviatrix customers are notified when a security update is available. #. **Security Patch** Aviatrix Controller provides a inline software patch to fix vulnerability with the instructions from the Field Notice. The updates do not require reboot of the Controller or gateways most of the time. How can an account recover when a Controller software upgrade fails? ------------------------------------------------------------------------------------------ Here is the best practice procedure to follow: 1. Before a software upgrade, go to Settings > Maintenance > Backup & Restore > Backup Now. This will save a copy of the deployment configuration to your S3 bucket. #. Do a dry run before upgrading. Go to Settings > Maintenance > Upgrade > Upgrade to the Latest > Dry Run. If the Dry Run is successful, proceed to the next step. If the Dry Run fails, do not proceed to the upgrade until you determine the root cause of the issue. #. Upgrade. Go to Settings > Maintenance > Upgrade > Upgrade to the Latest > Upgrade. Wait for the process to finish. #. If Controller upgrade is successful and some gateways fail, you can 'force upgrade' the failed gateway again. Go to Troubleshoot > Gateway > Force Upgrade. Select the gateway and click **Upgrade**. #. If Gateway force upgrade fails, proceed to replace the gateway. Go to Troubleshoot > Gateway > Gateway Replace. Select the failed gateway and click **Replace**. What IP addresses does the Controller need to reach out to? ---------------------------------------------------------------------------- Please see `Required Access for External Sites <https://aviatrix.zendesk.com/hc/en-us/articles/4417312119437-Aviatrix-Products-Access-to-external-FQDN-required>`_. .. note:: You must be registered to access the Aviatrix Customer Support website. If you are not already registered, you can sign-up at https://support.aviatrix.com. What IP addresses does an Aviatrix Gateway need to reach out to? ----------------------------------------------------------------------------------- Please see `Required Access for External Sites <https://aviatrix.zendesk.com/hc/en-us/articles/4417312119437-Aviatrix-Products-Access-to-external-FQDN-required>`_. .. note:: You must be registered to access the Aviatrix Customer Support website. If you are not already registered, you can sign-up at https://support.aviatrix. Centralized Logging Within AWS Government Cloud ----------------------------------------------------------------- When attempting to perform centralized logging for AWS Government Cloud, due to restrictions with communication inside of Government Cloud, it is not possible to have your Aviatrix Controller hosted in AWS Public Cloud and receive logs from gateways in AWS Gov Cloud. In order for the Aviatrix Controller to be able to accept logs from gateways inside of the Government Cloud, the Aviatrix Controller must be hosted within AWS Government Cloud as well. How does an Aviatrix Gateway support high availability in Azure? --------------------------------------------------------------------------------- Aviatrix support Azure Availability Set for HA gateway provides 99.95% of up time. Azure has started to introduce Availability Zone in some regions. Aviatrix will start to support this option in the future. .. |image1| image:: FAQ_media/image1.png .. |deployment| image:: FAQ_media/deployment.png :scale: 30% .. disqus:: <file_sep> ========================================================= Transit FireNet Workflow for GCP ========================================================= You use Aviatrix Transit FireNet to deploy firewall functions for the Aviatrix Multi-Cloud transit architecture. With the Transit FireNet feature, the Firewall Network (FireNet) function is integrated into the Aviatrix Transit gateway. To learn about Transit FireNet, see `Transit FireNet FAQ. <https://docs.aviatrix.com/HowTos/transit_firenet_faq.html>`_ To deploy firewall networks in other CSPs: - `AWS Transit Gateway (TGW) <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html>`_ - `AWS Transit FireNet multi-cloud transit <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html>`_ - `Azure Transit FireNet workflow <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_azure.html>`_ In this example, a Transit VPC with Aviatrix Gateways is deployed, and two Spoke Gateways (DEV and PROD) are attached. A firewall of supported vendors (Check Point, Palo Alto Networks, Fortinet FortiGate, etc.) will be deployed within the Transit VPC. See the diagram below for more details. Once the infrastructure is in place you create a policy to inspect the east-west and north-south traffic. |avx_tr_firenet_topology| Create VPCs ************** VPCs can be created manually on GCP or directly from the Aviatrix Controller. See `Create a VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ for guidelines on how to use the Aviatrix Controller to create VPCs. 1. Log in to the Aviatrix Controller with a username and password. #. Navigate to Useful Tools > Create A VPC. #. Select GCloud as the Cloud Type. #. Add one VPC for Transit FireNet Gateway and enable the Transit FireNet Function as shown below. #. Add three more VPCs as shown in the topology (i.e., Egress VPC, LAN VPC and Management VPC). #. Create two more VPCs for Spoke Gateways. |create_vpc| Deploy the Transit Aviatrix Gateway ************************************ Transit Aviatrix Gateway can be deployed using the `Transit Gateway Workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-a-transit-gateway>`_. Procedure ~~~~~~~~~~~ 1. Navigate to Multi-Cloud Transit > Setup > Transit > #1 Launch an Aviatrix Transit Gateway. #. Select the Cloud Type **Gcloud**. #. Enter a Gateway Name. #. Select the GCP Access Account Name. #. Select the VPC ID of the Transit FireNet VPC. #. Select the Public Subnet. #. Select the zone. #. Select the gateway size **n1-standard-1**. #. (optional) Enable Insane Mode Encryption for higher throughputs. #. Check the **Enable Transit FireNet Function** checkbox. #. Enable Transit Gateway HA by navigating to Multi-Cloud > Setup > #2 (Optional) Enable HA to an Aviatrix Transit Gateway. The example below shows the configuration of the Transit FireNet Gateway: |tr_firenet_gw| Deploy Spoke Gateways ********************** Now that we have set up an Aviatrix Transit Gateway, we can deploy Aviatrix Spoke Gateways in the spoke VPCs using the `Aviatrix Spoke Gateway Workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-a-spoke-gateway>`_. 1. Navigate to Multi-Cloud Transit > Setup > Spoke > #1 Launch an Aviatrix Spoke Gateway. #. Deploy a Spoke Gateway (GW) in each of the Spoke VPCs using the defaults, selecting the appropriate account and VPC information. #. Choose the Public Subnet. #. Enable Spoke Gateway HA by navigating to Multi-Cloud Transit > Setup > #5 (Optional) Enable/Disable HA at Spoke GW. |launch_spk_gw| Attach Spoke Gateways to Transit Network ***************************************** The Transit and Spoke gateways are now deployed. To connect them: 1. Navigate to Multi-Cloud Transit > Setup > Attach/Detach > #1 Attach Spoke Gateway to Transit Network. #. Select one Spoke at a time and attach it to the Transit Gateway. |attach_spk_trgw| .. note:: Although the Transit Gateway is now attached to the Spoke Gateways, it will not route traffic between Spoke Gateways. Enable Connected Transit ************************* By default, spoke VPCs are in isolated mode where the Transit will not route traffic between them. To allow the Spoke VPCs to communicate with each other, you must enable Connected Transit by navigating to Multi-Cloud Transit > Advanced Config. Select the Transit Gateway and toggle Connected Transit to **Enabled**. |connected_transit| Load balancers are created in GCP after this step is performed. Configure Transit Firewall Network ************************************ Transit and Spoke Gateways have now been deployed. You must now deploy and enable the Firewall for traffic inspection. To enable the firewall function and configure the FireNet policy: 1. Navigate to Firewall Network > Setup > #3a Enable Transit FireNet on Aviatrix Transit Gateway. #. Choose the Aviatrix Transit Gateway and click **Enable**. .. Note:: In a GCP deployment, the Transit FireNet function is enabled when launching the gateway. You can skip this step. 3. Navigate to Firewall Network > Policy > Manage FireNet Policy. #. Add Spokes to the Inspected box for traffic inspection. .. note:: By default, FireNet inspects ingress (Internet to VPC) and east-west traffic (VPC to VPC) only. |tr_firenet_policy| Launch and Associate Firewall Instance ************************************** This approach is recommended if this is the first Firewall instance being attached to the gateway. This step launches a Firewall instance and associates it with one of the FireNet gateways. .. important:: The Firewall instance and the associated Aviatrix FireNet gateway above must be in the same AZ (Availability Zone). Also, the Management Interface Subnet and Egress (untrust dataplane) Interface Subnet should not be in the same subnet. Launch and Attach ~~~~~~~~~~~~~~~~~~ In the Aviatrix Controller, navigate to Firewall Network > Setup > Firewall > Step 2a. Provide all the required input as shown in a table. Click **Launch**. .. important:: The vendor firewall may take 5-10 minutes to become available. ========================================== ========== **Setting** **Value** ========================================== ========== VPC ID The Security VPC created in Step 1. Gateway Name The primary FireNet gateway. Firewall Instance Name The name that will be displayed on GCP Console. Firewall Image The AWS AMI that you subscribed to in Step 2. Firewall Image Version Firewall instance current supported software versions. Firewall Instance Size Firewall instance type. Management Interface VPC ID Select the Firewall Management VPC Management Interface Subnet Select the subnet for Firewall Management Egress Interface VPC ID Select the Firewall Egress VPC. Egress Interface Subnet Select the subnet for Firewall Egress. Attach (Optional) By selecting this option, the firewall instance is inserted in the data path to receive the packet. If this is the second firewall instance for the same gateway and you have an operational FireNet deployment, you should not select this option as the firewall is not configured yet. You can attach the firewall instance later at the Firewall Network > Advanced page. Advanced (Optional) Click this selection to allow Palo Alto firewall bootstrap files to be specified. Bootstrap Bucket Name In advanced mode, specify a bootstrap bucket name where the initial configuration and policy file is stored. ========================================== ========== Check Point Specifications ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Check Point support for Google Cloud will be available in a future release. Palo Alto VM-Series Specifications ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Palo instance has three interfaces as described below. ======================================================== =============================== ================================ **Palo Alto VM instance interfaces** **Description** **Inbound Security Group Rule** ======================================================== =============================== ================================ nic0 Egress or Untrusted interface Allow ALL nic1 Management interface Allow SSH, HTTPS, ICMP, TCP 3978 nic2 LAN or Trusted interface Allow ALL (Do not change) ======================================================== =============================== ================================ Note that firewall instance nic2 is on the same subnet as the FireNet gateway nic1 interface. .. important:: For Panorama managed firewalls, you need to prepare Panorama first and then launch a firewall. See `Setup Panorama <https://docs.aviatrix.com/HowTos/paloalto_API_setup.html#managing-vm-series-by-panorama>`_. When a VM-Series instance is launched and connected with Panorama, you need to apply a one time "commit and push" from the Panorama console to sync Panorama and the firewall instance. .. Tip:: If VM-Series are individually managed and integrated with the Controller, you can still use Bootstrap to save initial configuration time. Export the first firewall's configuration to bootstrap.xml, create an IAM role and Bootstrap bucket structure as indicated above, then launch additional firewalls with IAM role and the S3 bucket name. Follow `Palo Alto Network (VM Series) GCP Example <https://docs.aviatrix.com/HowTos/config_paloaltoGCP.html>`_ to launch VM Series firewall in GCP and for more details. Fortinet Fortigate Specifications ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For details on how to configure Transit FireNet for GCP click `here <https://docs.aviatrix.com/HowTos/config_FortigateGCP.html>`_. Associate an Existing Firewall Instance ****************************************** This is the alternative step to Step 2a. If you already launched the firewall (Check Point, Palo Alto Network or Fortinet) instance from AWS Console, you can still associate it with the FireNet gateway. In the Aviatrix Controller navigate to Firewall Network > Setup > Firewall > Step 2b and associate a firewall with a FireNet Gateway. Vendor Firewall Integration ***************************** Vendor integration programs RFC 1918 and non-RFC 1918 routes in the firewall. 1. In the Aviatrix Controller, navigate to Firewall Network > Vendor Integration > Firewall. Select the firewall Vendor Type and fill in the details of your Firewall instance. #. Click **Save**. #. You can click **Show** or **Sync** to show the integration details or sync the configuration with the firewall. Example Setup for "Allow All" Policy ************************************* After a firewall instance is launched, wait 5-15 minutes for it to become available. Time varies for each firewall vendor. In addition, please follow the example configuration guides as indicated below to build a simple policy on the firewall instance, to validate that traffic is indeed being routed to firewall instance. Palo Alto Network (PAN) ~~~~~~~~~~~~~~~~~~~~~~~~~~ For basic configuration, please see `example Palo Alto Network configuration guide <https://docs.aviatrix.com/HowTos/config_paloaltoVM.html>`_. For implementation details on using Bootstrap to launch and initiate VM-Series, see `Bootstrap Configuration Example <https://docs.aviatrix.com/HowTos/bootstrap_example.html>`_. Verification ************* There are multiple ways to verify if Transit FireNet is configured properly: 1. Aviatrix Flightpath - Control-plane Test #. SSH, SCP or Telnet Test between Spoke VPCs (East-West) - Data-plane Test .. note:: ICMP is blocked on Google Cloud Load balancer. FlightPath Test for FireNet Control-Plane Verification ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FlightPath is a powerful troubleshooting Aviatrix tool which allows users to validate the control plane and gives end to end visibility of packet flow. 1. In the Aviatrix Controller, navigate to Troubleshoot > FlightPath. #. Provide the Source and Destination Region and VPC information. #. Select SSH and Private subnet, and run the test. .. note:: A VM instance will be required in GCP, and SSH/Telnet port should be allowed in firewall the rules for Spoke VPCs. SSH/Telnet Test for FireNet Data Plane Verification ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Once the control plane is established and no problem is found in the security and routing polices, data plane validation needs to be verified to make sure traffic is flowing and not blocked. There are multiple ways to check the data plane. One way is to SSH to Spoke instance (e.g. DEV1-VM) and telnet the other Spoke instance (e.g PROD1-VM) to make sure there is no traffic loss in the path. .. |subscribe_firewall| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/subscribe_firewall.png :scale: 35% .. |en_tr_firenet| image:: transit_firenet_workflow_media/transit_firenet_GCP_workflow_media/en_tr_firenet.png :scale: 35% .. |tr_firenet_policy| image:: transit_firenet_workflow_media/transit_firenet_GCP_workflow_media/tr_firenet_policy.png :scale: 35% .. |avx_tr_firenet_topology| image:: transit_firenet_workflow_media/transit_firenet_GCP_workflow_media/avx_tr_firenet_topology.png :scale: 35% .. |create_vpc| image:: transit_firenet_workflow_media/transit_firenet_GCP_workflow_media/create_vpc.png :scale: 35% .. |tr_firenet_gw| image:: transit_firenet_workflow_media/transit_firenet_GCP_workflow_media/tr_firenet_gw.png :scale: 35% .. |launch_spk_gw| image:: transit_firenet_workflow_media/transit_firenet_GCP_workflow_media/launch_spk_gw.png :scale: 35% .. |attach_spk_trgw| image:: transit_firenet_workflow_media/transit_firenet_GCP_workflow_media/attach_spk_trgw.png :scale: 35% .. |connected_transit| image:: transit_firenet_workflow_media/transit_firenet_GCP_workflow_media/connected_transit.png :scale: 35% .. disqus:: <file_sep>=============================================== Launch Aviatrix Controller Manually =============================================== Aviatrix Controller should be launched by CloudFormation script following the `AWS Getting Started Guide <http://docs.aviatrix.com/StartUpGuides/aws_getting_started_guide.html>`_. The method below has been deprecated. It is kept here for record only. Before you launch the controller with IAM role, you must first create 2 IAM roles and its associated policies. Follow `this link <http://docs.aviatrix.com/HowTos/HowTo_IAM_role.html>`__ to have them setup. Then go to https://aws.amazon.com/marketplace, search for “Aviatrix” and select the image type you wish to launch. :: You need a customer ID from Aviatrix for launching gateways. Send email to <EMAIL> or open a support ticket at Aviatrix Support Portal (https://support.aviatrix.com) to request a customer ID. Customer ID is not needed if you select utility images such as “5 Connections” and “10 Connections”. At the AWS marketplace console, select “\ **Manual Launch**\ ” that takes you to EC2 console to launch with IAM role. Once you select Manual Launch, click at a region where you wish to launch the controller. |image1| Once you are at AWS EC2 console, follow the steps below: 1. Select the instance size “t3.large” of 8GB of memory, which is the minimum instance required. 2. Select the VPC where the controller will be launched. 3. Subnet. Make sure the subnet you select is a public subnet with IGW as its default gateway, otherwise the controller will not be accessible as it won't have a public IP address. 4. Enable IAM role by selecting “aviatrix-role-ec2” you created earlier, as shown below |image2| 5. Edit security groups to allow inbound TCP port 443 open to anywhere, as shown below: |image3| 6. Use an Elastic IP address for the controller. 7. After launching the instance, note down the instance’s Private IP address and Public IP. 8. Use a browser to log in to the console. Use a web browser, go to https://controller_Public_IP to access the controller console, as shown below. |image4| At the Sign In page, log in with username 'admin'. The default password is the instance’s Private IP address. You can retrieve the Private IP address from the AWS console instance panel, as shown below. |image5| |image6| 9. Once you are logged in, change your password for future accesses via the console. 10. Go through the initial installation of software. 11. After the installation is complete, log in again to the controller by typing at the browser: https://controller_public_EIP 12. Troubleshooting tips: a. If you experience 'Login timeout error', check your instance outbound security policy to make sure it opens on port 443. b. If you cannot find your instance’s public IP address, you may have launched the instance from a private subnet. The controller instance must be launched from a public IP address. c. The controller needs to have its inbound port 443 open to AWS address ranges as Aviatrix gateways need to communicate to the controller on this port. Please open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_. Enjoy! .. |image0| image:: AviatrixCloudControllerStartupGuide_media/image001.png :width: 2.90683in :height: 0.35000in .. |image1| image:: AviatrixCloudControllerStartupGuide_media/image002.png :width: 4.80625in :height: 3.21803in .. |image2| image:: AviatrixCloudControllerStartupGuide_media/image003.png :width: 5.33067in :height: 2.04513in .. |image3| image:: AviatrixCloudControllerStartupGuide_media/image004.png :width: 4.92712in :height: 2.20352in .. |image4| image:: AviatrixCloudControllerStartupGuide_media/image005.png :width: 5.53494in :height: 3.11814in .. |image5| image:: AviatrixCloudControllerStartupGuide_media/image006.png :width: 5.21042in :height: 2.60298in .. |image6| image:: AviatrixCloudControllerStartupGuide_media/image007.png :width: 4.61664in :height: 4.22847in .. add in the disqus tag .. disqus:: <file_sep> ################################### Software Patches ################################### The following software patches are recently released by Aviatrix. ================================================================= ==================== =============================================================== **Patch Name** **Version** **Description** ================================================================= ==================== =============================================================== Update with latest instance types support for cloud regions 5.4 or earlier Update the latest instance types support for cloud regions This patch is only applicable to Aviatrix Controller. Update controller version info in the DB 5.4 or earlier Update the controller version info in the DB This patch is only applicable to Aviatrix Controller. Apply xml file patch for Splunk year 2020 bug 5.4 or earlier This patch is required due to changes in Splunk. Click `here <https://docs.splunk.com/Documentation/Splunk/8.0.1/ReleaseNotes/FixDatetimexml2020>`_ for more details. Patch applied to Avitrix Controller and Gateway both. Mitigation for Datadog Agent installation issue on opensource OS 5.2 or earlier DataDog will not be installed properly without the patch on Controller due to known DataDog issue with "hash sum mismatch" in APT repositories. Applicable to Aviatrix Gateway and Controller both. ================================================================= ==================== =============================================================== To apply a patch: 1) Backup your Aviatrix Controller. For more information, see `Controller Backup and Restore <https://docs.aviatrix.com/HowTos/controller_backup.html>`_. 2) Apply the security or software patch on the controller. From the Aviatrix Controller, navigate to Settings > Maintenance > SecurityPatches or SoftwarePatches and click on **UpdateAvailablePatches**. You should see the new patch in the display. 3) Apply the patch by clicking on the icon on the right and selecting **Apply Patch** from the popup menu. 4) Validate the update by clicking on the icon on the right and selecting **Patch Status** and scrolling down to bottom of page. 5) Backup your Aviatrix Controller again to save the new configuration. .. disqus:: ======= ################################### Software Patches ################################### For detailed information about specific software patches, please see `Controller and Gateway Release Notes <https://read.docs.aviatrix.com/HowTos/Controller_and_Software_Release_Notes.html>`_. ================================================================= ==================== =============================================================== **Patch Name** **Version** **Description** ================================================================= ==================== =============================================================== Update with latest instance types support for cloud regions 5.4 or earlier Update the latest instance types support for cloud regions This patch is only applicable to Aviatrix Controller. Update controller version info in the DB 5.4 or earlier Update the controller version info in the DB This patch is only applicable to Aviatrix Controller. Apply xml file patch for Splunk year 2020 bug 5.4 or earlier This patch is required due to changes in Splunk. Click `here <https://docs.splunk.com/Documentation/Splunk/8.0.1/ReleaseNotes/FixDatetimexml2020>`_ for more details. Patch applied to Avitrix Controller and Gateway both. Mitigation for Datadog Agent installation issue on opensource OS 5.2 or earlier DataDog will not be installed properly without the patch on Controller due to known DataDog issue with "hash sum mismatch" in APT repositories. Applicable to Aviatrix Gateway and Controller both. ================================================================= ==================== =============================================================== To apply a patch: 1) Backup your Aviatrix Controller. For more information, see `Controller Backup and Restore <https://docs.aviatrix.com/HowTos/controller_backup.html>`_. 2) Apply the security or software patch on the controller. From the Aviatrix Controller, navigate to Settings > Maintenance > SecurityPatches or SoftwarePatches and click on **UpdateAvailablePatches**. You should see the new patch in the display. 3) Apply the patch by clicking on the icon on the right and selecting **Apply Patch** from the popup menu. 4) Validate the update by clicking on the icon on the right and selecting **Patch Status** and scrolling down to bottom of page. 5) Backup your Aviatrix Controller again to save the new configuration. .. disqus:: <file_sep> ========================================================================================= Aviatrix Active Mesh with customized SNAT and DNAT on spoke gateway ========================================================================================= The Problem ------------------ Organizations usually plan out cloud network address ranges for building non-overlapping connectivity to on-prem, but there are times where a cloud network CIDR conflicts with an on-prem network address range. Moreover, there might be a constraint that neither source NAT nor destination NAT can be performed in the on-prem network but still requires connectivity to on-prem. Therefore, how to fulfill source NAT and destination NAT in the cloud becomes a key solution. Aviatrix Solution ------------------ This technical note illustrates an example solution of performing source NAT and destination NAT feature on Aviatrix spoke gateway to a specific use case where a customer needs a connectivity between certain on-prem hosts and certain cloud instances, but the on-prem network range overlaps with the cloud network CIDR as shown in the diagram below. Additionally, traffic can be initiated from either side. Topology - Aviatrix Global Transit HA Network with Active Mesh: |TRANSIT_ACTIVEMESH_SPOKE_OVERLAP_CIDR_TOPOLOGY| :: In this example, the on-prem network address range is 10.3.0.0/16 and all other spoke VPCs connect to on-prem via Aviatrix Global Transit HA Network with Active Mesh, however there is one spoke VPC with an identical CIDR of 10.3.0.0/16. .. Note:: This tech note supports: 1. specific on-prem hosts and cloud instances which means no identical IP on each side including IPs of Aviatrix Spoke primary/HA gateway 2. bi-direction traffic 3. both on-prem and cloud network allow only RFC 1918 CIDR .. Furthermore, this technical note provides a step-by-step configuration on the Aviatrix controller that will address the following requirements: 1. Deploy `Aviatrix Global Transit HA Network with Active Mesh <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`__ 2. Deploy virtual CIDR within RFC 1918 range to solve the overlapping CIDR between on-prem network and cloud network - `Customize Advertised Spoke VPC CIDRs <https://docs.aviatrix.com/HowTos/gateway.html#customize-advertised-spoke-vpc-cidrs>`__ - `Destination NAT with Mark and Exclude Route Table <https://docs.aviatrix.com/HowTos/gateway.html#destination-nat>`__ - `Customized SNAT with Mark and Exclude Route Table <https://docs.aviatrix.com/HowTos/gateway.html#customized-snat>`__ Scenario: 1. Traffic which is initiated from on-prem to cloud spoke network sends to a virtual IP of cloud instance. In addition, cloud instance views a virtual IP of on-prem host. 2. Traffic which is initiated from cloud spoke network to on-prem sends to a virtual IP of on-prem host. In addition, on-prem views a virtual IP of cloud instance. 3. All virtual IPs are belonging to RFC 1918 range. Follow the steps below to set up for the scenario. Step 1. Prerequisite ------------------------- 1.1. `Upgrade <https://docs.aviatrix.com/HowTos/inline_upgrade.html>`__ the Aviatrix Controller to at least version UserConnect-5.4 1.2. Prepare a Real/Virtual CIDR mapping table for on-prem network and cloud network One of the key steps to solve overlapping network issue is to route a non-overlapping CIDR. Therefore, please prepare a virtual routable CIDR for your on-prem and spoke network. In this example, we practice a Virtual CIDR within RFC 1918 range. :: Real/Virtual CIDR mapping table example: ============== ============== ================ Real CIDR Virtual CIDR ============== ============== ================ Spoke VPC 10.3.0.0/16 10.203.0.0/16 On-Prem VPC 10.3.0.0/16 10.103.0.0/16 ============== ============== ================ 1.3. Find out the Real IPs of certain on-prem hosts and certain cloud instances to build a Real/Virtual IPs mapping table Since this solution is to tackle a specific use case where a customer needs a connectivity between certain on-prem hosts and certain cloud instances in overlapping CIDR, please find out those IPs and plan a Real/Virtual IPs mapping table for routing advertisement and NAT configuration. :: Real/Virtual IPs mapping table example: ================ ============== ================ Real IP Virtual IP ================ ============== ================ Cloud instance 10.3.0.86/32 10.203.0.86/32 On-Prem host 10.3.0.85/32 10.103.0.85/32 ================ ============== ================ Step 2. Build Aviatrix Global Transit HA Network with Active Mesh ------------------------- Deploy the topology by following the steps 1, 2, 3, 4, and 5 in `document <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`__ first - make sure `Active Mesh Mode <https://docs.aviatrix.com/HowTos/gateway.html?#activemesh-mode>`__ is enabled on both Aviatrix Transit Gateway and Spoke Gateway - make sure HA is deployed for both Aviatrix Transit Gateway and Spoke Gateway - make sure on-prem router advertises only the Real IP with /32 of on-prem host not the whole Real CIDR or Virtual IP/CIDR :: Example: on-prem router advertises 10.3.0.85/32 which is the Real IP of On-prem host Step 3. Perform Customize Spoke Advertised VPC CIDRs feature on Aviatrix Spoke gateway ------------------------- This action is to advertise the Virtual CIDR of cloud spoke network to on-prem via BGP session so that on-prem is able to route the Virtual IP of Cloud instance. Please refer to this `doc <https://docs.aviatrix.com/HowTos/gateway.html#customize-advertised-spoke-vpc-cidrs>`__ To configure: 3.1. Go to the Gateway page, click on the Aviatrix Spoke Gateway first. Click Edit. 3.2. Continue on to the Edit page, scroll to Customize Spoke Advertised VPC CIDRs. 3.3. Enter the Virtual CIDR of cloud spoke VPC that on-prem is able to route - make sure advertise the Virtual CIDR of cloud spoke VPC not the Virtual IP of specific cloud instance 3.4. Click the button "Save" |TRANSIT_ACTIVEMESH_SPOKE_CUSTOMIZED_SPOKE_ADVERTISE_VPC_CIDR| :: Example: Aviatrix Spoke gateway advertises 10.203.0.0/16 which is the Virtual CIDR of cloud spoke VPC Step 4. Attach Aviatrix Spoke to Aviatrix Transit Network ------------------------- Follow the `step 6 Join a Spoke GW to Transit GW Group <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#join-a-spoke-gw-to-transit-gw-group>`__ in Global Transit Network Workflow. Step 5. Configure Aviatrix DNAT function on Aviatrix Spoke Gateway for the traffic which is initiated from on-prem to cloud spoke network ------------------------- This action instructs the spoke gateway to translate a destination address from a Virtual IP of cloud instance to a Real IP of cloud instance in cloud spoke VPC. Please refer to `Aviatrix DNAT function doc <https://docs.aviatrix.com/HowTos/gateway.html#destination-nat>`__. To configure: 5.1. Go to the Gateway page and click on the Spoke Primary Gateway. Click Edit. 5.2. Scroll down to “Destination NAT” 5.3. Click Add/Edit DNAT 5.4. Click Add New 5.5. Enter fields for Src CIDR, Dst CIDR, Protocol, Connection, Mark, DNAT IPs and Exclude Route Table as below example. =================== ======================= **Field** **Value** =================== ======================= Source CIDR Real IP of on-prem host (i.e. 10.3.0.85/32) Source Port Leave it blank Destination CIDR Virtual IP of cloud instance (i.e. 10.203.0.86/32) Destination Port Leave it blank Protocol all Interface eth0 Connection Select the connection to Transit Gateway Mark A rule field to mark this traffic session (i.e. use 103085 to track source 10.3.0.85/32) DNAT IPs Real IP of cloud instance (i.e. 10.3.0.86) DNAT Port Leave it blank Exclude Route Table [IMPORTANT] Collect all your cloud routing table ids and fill them here =================== ======================= |DNAT_SPOKE_ONPREM_TO_CLOUD| 5.6. Click Save 5.7. Repeat steps 5.4, 5.5, and 5.6 for multiple entries. 5.8. Click Update to commit. Step 6. Configure Aviatrix Customized SNAT function on Aviatrix Spoke Gateway and Spoke HA Gateway for the traffic which is initiated from on-prem to cloud spoke network ------------------------- This action changes the packet’s source IP address from a Real IP of on-prem host to a Virtual IP representing on-prem host. Please refer to `Aviatrix Customized SNAT function doc <https://docs.aviatrix.com/HowTos/gateway.html#customized-snat>`__ To configure: 6.1. Go to the Gateway page, click on the Spoke Primary Gateway first. Click Edit. 6.2. Continue on to the Edit page, scroll to SNAT. Select Customized SNAT. 6.3. Select Customized SNAT 6.4. Click Add New 6.5. Enter fields for Protocol, Interface, Mark, SNAT IPs, and Exclude Route Table as below example. =================== ================================== **Field** **Value** =================== ================================== Source CIDR Leave it blank Source Port Leave it blank Destination CIDR Leave it blank Destination Port Leave it blank Protocol all Interface eth0 Connection Select None Mark Fill the number that we configure in the previous DNAT step 5 (i.e. 103085) SNAT IPs Virtual IP of on-prem host (i.e. 10.103.0.85) SNAT Port Leave it blank Exclude Route Table [IMPORTANT] Collect all your cloud routing table ids and fill them here =================== ================================== 6.6. Click Save 6.7. Repeat the above steps for more entries. 6.8. Click Enable SNAT to commit. |SNAT_SPOKE_PRIMARY_ONPREM_TO_CLOUD| 6.9. Go to Gateway page, click on the Spoke HA Gateway. Click Edit. 6.10. Repeat the above steps to configure Customized SNAT for Spoke HA Gateway as shown in the example below. |SNAT_SPOKE_HA_ONPREM_TO_CLOUD| Step 7. Configure Aviatrix DNAT function on Aviatrix Spoke Gateway for the traffic which is initiated from cloud spoke network to on-prem ------------------------- This action instructs the spoke gateway to translate a destination address from a Virtual IP of on-prem host to a Real IP of on-prem host. Please refer to `Aviatrix DNAT function doc <https://docs.aviatrix.com/HowTos/gateway.html#destination-nat>`__. To configure: 7.1. Go to the Gateway page and click on the Spoke Primary Gateway. Click Edit. 7.2. Scroll down to “Destination NAT” 7.3. Click Add/Edit DNAT 7.4. Click Add New 7.5. Enter fields for Src CIDR, Dst CIDR, Protocol, Interface, Mark, DNAT IPs and Exclude Route Table as below example. =================== ======================= **Field** **Value** =================== ======================= Source CIDR Real IP of cloud instance (i.e. 10.3.0.86/32) Source Port Leave it blank Destination CIDR Virtual IP of on-prem host (i.e. 10.103.0.85/32) Destination Port Leave it blank Protocol all Interface eth0 Connection Select None Mark A rule field to mark this traffic session (i.e. use 103086 to track source 10.3.0.86/32) DNAT IPs Real IP of on-prem host (i.e. 10.3.0.85/32) DNAT Port Leave it blank Exclude Route Table [IMPORTANT] Collect all your cloud routing table ids and fill them here =================== ======================= |DNAT_SPOKE_CLOUD_TO_ONPREM| 7.6. Click Save 7.7. Repeat steps 7.4, 7.5, and 7.6 for multiple entries. 7.8. Click Update to commit. Step 8. Configure Aviatrix Customized SNAT function on Aviatrix Spoke Gateway and Spoke HA Gateway for the traffic which is initiated from cloud spoke network to on-prem ------------------------- This action changes the packet’s source IP address from a Real IP of cloud instance to a Virtual IP representing cloud instance. Please refer to `Aviatrix Customized SNAT function doc <https://docs.aviatrix.com/HowTos/gateway.html#customized-snat>`__ To configure: 8.1. Go to the Gateway page, click on the Spoke Primary Gateway first. Click Edit. 8.2. Continue on to the Edit page, scroll to SNAT. Select Customized SNAT. 8.3. Select Customized SNAT 8.4. Click Add New 8.5. Enter fields for Protocol, Interface, Connection, Mark, SNAT IPs, and Exclude Route Table as below example. =================== ================================== **Field** **Value** =================== ================================== Source CIDR Leave it blank Source Port Leave it blank Destination CIDR Leave it blank Destination Port Leave it blank Protocol all Interface eth0 Connection Select the connection to Transit Gateway Mark Fill the number that we configure in the previous DNAT step 7 (i.e. 103086) SNAT IPs Virtual IP of cloud instance (i.e. 10.203.0.86) SNAT Port Leave it blank Exclude Route Table [IMPORTANT] Collect all your cloud routing table ids and fill them here =================== ================================== 8.6. Click Save 8.7. Repeat the above steps for more entries. 8.8. Click Enable SNAT to commit. |SNAT_SPOKE_PRIMARY_CLOUD_TO_ONPREM| 8.9. Go to Gateway page, click on the Spoke HA Gateway. Click Edit. 8.10. Repeat the above steps to configure Customized SNAT for Spoke HA Gateway as shown in the example below. |SNAT_SPOKE_HA_CLOUD_TO_ONPREM| Step 9. Verify traffic flow ------------------------- 9.1. Traffic from on-prem to cloud spoke network - Issue ICMP traffic from on-prem host to a Virtual IP of cloud instance |ONPREM_HOST_TO_CLOUD_INSTANCE| - Execute packet capture on the cloud instance |CLOUD_INSTANCE_PACKET_CAPTURE| 9.2. Traffic from cloud spoke network to on-prem - Issue ICMP traffic from cloud instance to a Virtual IP of on-prem |CLOUD_INSTANCE_TO_ONPREM_HOST| - Execute packet capture on the on-prem host |ONPREM_HOST_PACKET_CAPTURE| FAQ ------------------ Q1: Why we need to “mark” the NAT sessions? Ans: Basically, "mark" function in NAT is a unique number that is associated with specific packets. In this tech note, we leverage on it for the purpose of tracking session identified by the Source CIDR of DNAT and then utilizing it for the SNAT IPs of customized SNAT. It is an advanced option for users to configure NAT rule. Alternatively, users still can configure DNAT and customized SNAT rule without mark. Q2: Why we need to fill all VPC route table IDs for “Exclude Route Table”? Ans: As Aviatrix Global Transit HA Network design has a mechanism to handle cloud routing table updates, filling all VPC route table IDs for “Exclude Route Table” in NAT feature prevents extra routes to be injected in cloud routing table. .. |TRANSIT_ACTIVEMESH_SPOKE_OVERLAP_CIDR_TOPOLOGY| image:: transit_activemesh_spoke_overlap_cidr_media/topology.png :scale: 50% .. |TRANSIT_ACTIVEMESH_SPOKE_CUSTOMIZED_SPOKE_ADVERTISE_VPC_CIDR| image:: transit_activemesh_spoke_overlap_cidr_media/spoke_customized_spoke_advertise_vpc_cidr.png :scale: 30% .. |DNAT_SPOKE_ONPREM_TO_CLOUD| image:: transit_activemesh_spoke_overlap_cidr_media/dnat_spoke_onprem_to_cloud.png :scale: 50% .. |SNAT_SPOKE_PRIMARY_ONPREM_TO_CLOUD| image:: transit_activemesh_spoke_overlap_cidr_media/snat_spoke_primary_onprem_to_cloud.png :scale: 50% .. |SNAT_SPOKE_HA_ONPREM_TO_CLOUD| image:: transit_activemesh_spoke_overlap_cidr_media/snat_spoke_ha_onprem_to_cloud.png :scale: 50% .. |DNAT_SPOKE_CLOUD_TO_ONPREM| image:: transit_activemesh_spoke_overlap_cidr_media/dnat_spoke_cloud_to_onprem.png :scale: 50% .. |SNAT_SPOKE_PRIMARY_CLOUD_TO_ONPREM| image:: transit_activemesh_spoke_overlap_cidr_media/snat_spoke_primary_cloud_to_onprem.png :scale: 50% .. |SNAT_SPOKE_HA_CLOUD_TO_ONPREM| image:: transit_activemesh_spoke_overlap_cidr_media/snat_spoke_ha_cloud_to_onprem.png :scale: 50% .. |ONPREM_HOST_TO_CLOUD_INSTANCE| image:: transit_activemesh_spoke_overlap_cidr_media/onprem_host_to_cloud_instance.png :scale: 100% .. |CLOUD_INSTANCE_PACKET_CAPTURE| image:: transit_activemesh_spoke_overlap_cidr_media/cloud_instance_packet_capture.png :scale: 50% .. |CLOUD_INSTANCE_TO_ONPREM_HOST| image:: transit_activemesh_spoke_overlap_cidr_media/cloud_instance_to_onprem_host.png :scale: 100% .. |ONPREM_HOST_PACKET_CAPTURE| image:: transit_activemesh_spoke_overlap_cidr_media/onprem_host_packet_capture.png :scale: 100% .. disqus:: <file_sep> Reserve For On-Prem Use ========================== The Datacenter Cloud InterConnect (DCCX) feature works by dividing a VLAN or subnet into sub segments. Each sub segment becomes a CIDR block for VPC/VNet. If you want to reserve some of the sub segments for on-prem use, i.e., to launch VMs on these subnets, you can do so by reserving some CIDR blocks. One use case for this feature is for cloud burst. The VMs launched on a reserved subnet will treat instances in VPC/VNet as if they are on the same VLAN. If you have an application that requires the on-prem resource and in the cloud resource to be on the same subnet/VLAN, this deployment will satisfy that. .. Note:: This feature is available for R2.6 and later. .. disqus:: <file_sep> ================================================================== AWS China Startup Guide ================================================================== Welcome. Your Aviatrix product experience starts here. Click a link below to learn your use case or read an `Aviatrix Overview. <http://docs.aviatrix.com/StartUpGuides/aviatrix_overview.html>`_ `Remote User VPN <http://docs.aviatrix.com/HowTos/openvpn_features.html>`_ `VPC Egress Security <http://docs.aviatrix.com/HowTos/FQDN_Whitelists_Ref_Design.html>`_ `Site to Cloud VPN <http://docs.aviatrix.com/HowTos/site2cloud_faq.html>`_ `Encrypted Peering <http://docs.aviatrix.com/HowTos/peering_faq.html>`_ `Multicloud Peering <http://docs.aviatrix.com/HowTos/peering_faq.html>`_ The Aviatrix Controller provides a single pane of glass for all your secure networking tasks. You can run the Controller in your own VPC or let Aviatrix manage it in `our hosted service <https://www.aviatrix.com/trial/>`_. The following guide applies to running the Controller in your own environment in China. The first thing you need to do is to launch the Controller instance. We'll walk you through the following steps. By the end, you'll be ready for your first use case. Before you start, you need to have an `AWS account <https://aws.amazon.com/>`__. Create a new account or login to an existing IAM account. .. Important:: - We require this AWS IAM account to have permissions to create AWS access key, secret access key, IAM policies and launch EC2 instances. - The Controller instance must be launched on a public subnet in a VPC. .. Step 1. Locate the Controller AMI from AWS Community ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Login to AWS China, select the Beijing region, click launch EC2 instance from AWS Community AMIs and search for "aviatrix", as shown below. The Aviatrix Controller AMI name is Aviatrix_china_controller_051518_BYOL. |controller-ami-china| Step 2. Select Controller instance size ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Select t2.large for the Controller instance, as shown below. |instance-size| Step 3. Select VPC and subnet to launch ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Make sure you select a public subnet. We recommend you to enable termination protection. |select-subnet| Step 4. Add storage ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Make sure you specify 20GB as the storage size, as shown below. |add-storage| Step 5. Setup security group ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Open security group 443 to all, as shown below. (You can reduce the scope later) |security-group| Step 6. Launch the instance ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Review the instance and create a new key pair or use an existing key pair to launch the instance. Step 7. Add EIP ^^^^^^^^^^^^^^^^ Once the Controller instance is launched, you need to associate it with an EIP. Make sure this EIP has been granted legitimacy by the government. Associate the EIP with the Controller instance. Step 8. Connect to the Controller ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Now that the Aviatrix Controller instance has been launched, let's log in and go through a few init steps. Open a browser window to https://AviatrixControllerEIP .. tip:: You may receive a warning that the connection may not be secure. This is because the certificate is self-signed by the Controller. It is safe to continue to the page. .. |imageControllerBrowserWarning| Step 9. Initial Login ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 9.1 Login with the username `admin`. 9.2 For the password field, you can find the Controller instance's private IP address by going to the AWS EC2 console, clicking the Controller instance and locating its private IP address. 9.3 Enter your email address. This email will be used for alerts as well as password recovery (if needed). |imageControllerEnterEmail| 9.4. Next, you will be prompted to change the admin password. |imageControllerChangePassword| 9.5. Click `Skip` in the next page, unless the Controller instance VPC has an HTTP or HTTPS proxy configured for Internet access. |imageproxy-config| 9.6. Finally, the Controller will upgrade itself to the latest software version. Enter 3.3 and click run, as shown below. The process can take up minutes to hours. Read the tip below before you proceed. |imageControllerUpgrade-china| .. tip:: Since the Aviatrix software is hosted in AWS us-west-2, loading software to the Controller from AWS China could take a significantly longer time, from tens of minutes to up to an hour. Our experiences have been that if you upgrade software during the early morning hours in China (2am to 7am China time) the download is faster. Once complete, the login prompt will appear. Use the user `admin` and your new password to login. .. Step 10. Create A Primary Access Account ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 10.1 Select AWS China -------------------- Once logged back into the Controller, you should be on the `Onboarding` page. If not, click "Onboarding` on the navigation item. Then click on the AWS icon. |aws-china| 10.2 Enter Your Customer ID ----------------------------------------------------- .. Note:: Open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_ to get a trial license if you do not have one. .. Enter the `Customer ID` in the field and click `Save`. |imageEnterCustomerID| 10.3 Setup an Access Account ------------------------------------ Follow the instructions in `how to create IAM user and policy <http://docs.aviatrix.com/HowTos/accesskey.html>`_ to fill in the fields below. +-------------------------------+--------------------------------------------+ | Field | Expected Value | +===============================+============================================+ | Account Name | Enter a name that is unique on the | | | Controller. | | | Example name: `AWSOpsTeam`. | +-------------------------------+--------------------------------------------+ | AWS China Account Number | The IAM user account's 12 digit | | | AWS account number. | +-------------------------------+--------------------------------------------+ | AWS China Access Key ID | The IAM user account's access key id. | +-------------------------------+--------------------------------------------+ | AWS China Secret Key | The IAM user account's secret key. | +-------------------------------+--------------------------------------------+ Once complete, click the `Create` button at the bottom of the form, as shown below. |create-account| Next: Start a Use Case ^^^^^^^^^^^^^^^^^^^^^^^^^ Congratulations! You are now ready to establish connectivities to/from the cloud. Here are some of the things you can do: - `Build User SSL VPN <../HowTos/uservpn.html>`__ - `Build Egress Security <../HowTos/FQDN_Whitelists_Ref_Design.html>`__ - `Build Site to Cloud VPN <http://docs.aviatrix.com/HowTos/site2cloud_faq.html>`_ - `Build Multicloud Peering <http://docs.aviatrix.com/HowTos/GettingStartedAzureToAWSAndGCP.html>`_ - `Build Encrypted Peering <http://docs.aviatrix.com/HowTos/peering.html>`_ .. Warning:: Any resources created by the Controller, such as Aviatrix gateways, route entries, ELB, SQS queues, etc, must be deleted from the Controller console. If you delete them directly on AWS console, the Controller's view of resources will be incorrect which will lead to features not working properly. For technical support, please open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_. Limitations ^^^^^^^^^^^^^^^ - IAM role is not supported in the current release 3.3 in AWS China. - Next-Gen Transit Network is not supported in the current release 3.3 in AWS China. - AWS Ningxia region is not supported in the current release 3.3 in AWS China. - Native AWS Peering is not supported in the current release 3.3 in AWS China. .. add in the disqus tag .. disqus:: .. |controller-ami-china| image:: china-controller_media/controller-ami-china.png :scale: 100% .. |instance-size| image:: china-controller_media/instance-size.png :scale: 40% .. |select-subnet| image:: china-controller_media/select-subnet.png :scale: 40% .. |security-group| image:: china-controller_media/security-group.png :scale: 40% .. |add-storage| image:: china-controller_media/add-storage.png :scale: 40% .. |create-account| image:: china-controller_media/create-account.png :scale: 40% .. |imageControllerUpgrade-china| image:: china-controller_media/imageControllerUpgrade-china.png :scale: 50% .. |imageControllerBrowserWarning| image:: china-controller_media/controller_browser_warning.png :scale: 50% .. |imageAviatrixOnboardNav| image:: china-controller_media/aviatrix_onboard_nav.png :scale: 50% .. |aws-china| image:: china-controller_media/aws-china.png :scale: 50% .. |imageEnterCustomerID| image:: china-controller_media/customerid_enter.png :scale: 25% .. |imageCreateAccount| image:: china-controller_media/create_account.png .. |imageControllerEnterEmail| image:: china-controller_media/controller_enter_email.png :scale: 50% .. |imageControllerChangePassword| image:: china-controller_media/controller_change_password.png :scale: 50% .. |imageproxy-config| image:: china-controller_media/proxy_config.png :scale: 25% <file_sep> =============================================== Managed CloudN Workflows =============================================== Introduction ============ Aviatrix CloudN hardware appliance is deployed on-prem to connect to public cloud. It provides up to 25Gbps encryption performance over AWS Direct Connect and Azure Express Route. Aviatrix Managed CloudN enables you to manage CloudN hardware appliances by Aviatrix Controller as an `Aviatrix CloudN device <https://docs.aviatrix.com/HowTos/cloud_wan_faq.html>`_. Benefits: -------------------- - Ease of use: - Centrally manage all CloudN appliances from Aviatrix Controller without logging into each Standalone CloudN GUI individually for ongoing configuration and operation actions. - Simplify connection configuration by removing manually importing S2C IPsec configuration method as in Standalone CloudN. - Enhanced visibility and troubleshooting: - Perform running diagnostics, upload tracelog and upgrade on Managed CloudN device the same way as an Aviatrix gateway. - Support backup/restore function - Active Mesh support: - Managed CloudN automatically load balance traffic to both Aviatrix Transit Primary Gateway and backup gateway - Scalability: - Support scale-out fashion to achieve higher IPsec throughput .. note:: - Managed CloudN only supports High-Performance (Insane Mode) encryption connection. It works with Aviatrix Transit Gateways with Insane Mode enabled. - This solution applies to connections over AWS Direct Connect, Azure ExpressRoute, and the Internet. - This solution applies to over GCP InterConnect starting from 6.3. - This solution in GCP supports only one tunnel per Transit Gateway for over Internet scenario. For more information and benefits about CloudN, please see the below documents: `Insane Mode CloudN Deployment Checklist <https://docs.aviatrix.com/HowTos/CloudN_insane_mode.html>`_ `Insane Mode Encryption FAQ <https://docs.aviatrix.com/HowTos/insane_mode.html>`_ This document describes a step-by-step Managed CloudN deployment workflow for R6.2 and later. It covers the following topics. - Workflow on Aviatrix CloudN - Workflow on Aviatrix Controller - Traffic Flow Verification - Troubleshooting Tips - Upgrade - Backup/Restore - Workflow on cleanup - FAQ Topology ================== |managed_cloudn_topology| Prerequisites ==================== 1. `Order a CloudN appliance <https://docs.aviatrix.com/HowTos/CloudN_insane_mode.html#step-2-pre-deployment-request-form>`_ and install it properly in your data center or data center provider. 2. (Optional) Create and register an FQDN Name for Aviatrix Controller public IP. This is useful if the Controller has HA configured. 3. Remove the current connection. Skip this step if this is a brand new deployment. Remove/delete any Site2Cloud (IPsec) connection between Aviatrix Transit Gateway and Standalone CloudN if you have any in your existing Standalone CloudN deployment. 4. `Upgrade <https://docs.aviatrix.com/HowTos/inline_upgrade.html>`_ Aviatrix Controller to the latest version, at least version 6.2. 5. Deploy VPC/VNets, Aviatrix Multi-Cloud Transit Gateways, and Spoke Gateways. Follow this `step <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-a-transit-gateway>`_ to launch Aviatrix Transit Gateway with insane mode enabled. The recommended minimum size for Transit in AWS is c5n.4xlarge. Please refer to this `doc <https://docs.aviatrix.com/HowTos/insane_mode_perf.html>`_ for performance details. * (Optional) Follow this `step <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-a-spoke-gateway>`_ to launch Aviatrix Spoke Gateway with insane mode enabled. The recommended minimum size for Spoke with Insane Mode in AWS is c5.2xlarge. Please refer to this `doc <https://docs.aviatrix.com/HowTos/insane_mode_perf.html>`_ for performance details. Notes: Users has option to attach non-Insane Mode Spoke gateway to Insane Mode Transit Gateway. * (Optional) Follow this `step <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#join-a-spoke-gw-to-transit-gw-group>`_ to attach Aviatrix Spoke Gateway to Aviatrix Transit Gateway .. note:: In this example, Aviatrix Multi-Cloud Transit Gateway and Aviatrix Spoke Gateway with HPE are deployed in AWS platform. The workflow applies to Azure. Workflow on Aviatrix CloudN ============================= Opening Controller Inbound Ports ------------------------------------------------ CloudN is deployed inside a data center. It does not require any public IP addresses. However, you need to collect the public IP for the management interface (The ISP provided pubic IP) and open port 443 on the Controller for that public IP. For AWS accounts, update the Aviatrix Controller's inbound security group to allow TCP 443 from public IP address of the router of CloudN's MGMT interface. #. Open your AWS console and find the security group associated with Aviatrix Controller. #. Configure an inbound security rule to allow TCP 443 from public IP address provided by the ISP where CloudN's management interface egresses to Internet. .. important:: This public IP address needs to be static. Configuring NTP Sync and SMTP Services -------------------------------------------------------- #. Add a firewall rule to allow CloudN’s MGMT outbound UDP port 123 access to ntp.ubuntu.com or to a local NTP server. #. From the CloudN UI, go to Setting > Controller > System Time. Enter ntp.ubuntu.com or a local NTP server then select the Sync option. #. Do a manual sync to the NTP server. #. From the CloudN UI, go to Setting > Controller > Email, Setup SMTP settings to allow CloudN to send alert email. Logging into the CloudN GUI ---------------------------------------- #. Open a browser and navigate to the CloudN GUI with CloudN domain name/IP and port 443. #. Sign in with your CloudN login credentials. (Optional, Rare) Checking Whether CloudN Requires a Controller IP Migration --------------------------------------------------------------------------------------------- Skip this optional step if the Controller IP address has not been changed. #. Navigate to Troubleshoot on the left sidebar > Diagnostics > Network. #. Scroll down to the `Controller Public IP <https://docs.aviatrix.com/HowTos/Troubleshoot_Diagnostics.html#controller-public-ip>`_ section in the bottom right. #. Perform `Controller IP Migration <https://docs.aviatrix.com/HowTos/Troubleshoot_Diagnostics.html#controller-ip-migration>`_ function if the message in the Controller Public IP section guides users to execute it. .. note:: For private link connectivity such as AWS Direct Connect or Azure Express Route case, CloudN WAN interface is assigned a private IP, so the message in the Controller Public IP section displays the public IP of this Controller as NA. The Controller was not able to reach www.carmelonetworks.com through the WAN interface(eth0)." Managed CloudN Management Port Outbound Access -------------------------------------------------------------------------------------------------------------------------- You must use the specified FDQN, IP address, and ports for Managed CloudN (registered to the Controller) and Standalone CloudN (de-registered from the Controller) implementations. Please see `Required Access for External Sites <https://aviatrix.zendesk.com/hc/en-us/articles/4417312119437-Aviatrix-Products-Access-to-external-FQDN-required>`_. .. note:: You must be registered to access the Aviatrix Customer Support website. If you are not already registered, you can sign-up at https://support.aviatrix.com. You must be registered to access the Aviatrix Customer Support website. If you are not already registered, you can sign-up at https://support.aviatrix.com. To check basic connectivity to Internet from CloudN device and to troubleshoot reachability issue to these addresses, follow the steps below. 1. Navigate to Troubleshoot on the left sidebar > Diagnostics > Network. 2. Find the `Network Connectivity Utility <https://docs.aviatrix.com/HowTos/Troubleshoot_Diagnostics.html#network-connectivity-utility>`_ section. 3. Enter the following information in the fields provided. +--------------+--------------------------------------------------------------------+ | **Field** | **Value** | +--------------+--------------------------------------------------------------------+ | Hostname | Refer to the FQDN/IP address on the Aviatrix Support webstie. | +--------------+--------------------------------------------------------------------+ | Port | Refer to the PORT on the Aviatrix Support webstie. | +--------------+--------------------------------------------------------------------+ | Gateway Name | Controller | +--------------+--------------------------------------------------------------------+ | Protocol | TCP | +--------------+--------------------------------------------------------------------+ 4. Click **Go** to check connectivity. Registering with Aviatrix Controller FQDN Name ------------------------------------------------------- 1. Navigate to Settings on the left sidebar > Advanced > Registration or select the **Managed CloudN under UseCases** dropdown menu on the top. |cloudn_register_controller_fqdn_link_managed_cloudn| 2. Open the **Register CloudN as a Gateway** section. 3. Enter the Aviatrix Controller FQDN name. |cloudn_register_controller_fqdn| .. important:: It is highly recommended to register CloudN with Aviatrix Controller’s FQDN name instead of its IP address for allowing Controller HA operation (allows the controller to be assigned to a different IP address). When your Aviatrix Controller's FQDN is mapped to a private IP address, make sure that CloudN’s MGMT primary DNS server or secondary DNS server can resolve the FQDN to its private IP address. Registering CloudN to Aviatrix Controller via private networks is not a fully supported scenario; please discuss this with the Aviatrix team during the planning phase before you finalize the design for the Managed CloudN deployment. 4. Enter Aviatrix Controller Username/Password with an admin or CloudN user credential (any users in admin RBAC Groups or an RBAC Group with the CloudN permission enabled). 5. Enter the Gateway Name to represent this CloudN device. 6. Click **Register.** 7. Click **OK** to confirm. Wait about 40-60 seconds to complete the registration process. Workflow on Aviatrix Controller ======================================= 1. Log in to the Aviatrix Controller. 2. Check if a Managed CloudN device is connected to Aviatrix Controller properly. Navigate to CloudN > List/Edit and search for the Managed CloudN device. Make sure it is displayed as "registered" in the State column. |controller_managed_cloudn_registered_state| (Optional) Discover a Managed CloudN Device WAN Interface --------------------------------------------------------------------------------- This step is for building connections over the Internet. If you are building connections over Direct Connect or ExpressRoute, proceed to the next step. 1. Navigate to CloudN > Attach and find the 1. Find the Attach section. 2. Select the Managed CloudN device. 3. Click **Discover WAN Interfaces**. |controller_discover_wan_interfaces| 4. Select the WAN interface in the dropdown menu. 5. Update the WAN primary interface and IP if needed. 6. Click **Apply**. Attaching Managed CloudN ----------------------------------------- This step follows the instructions at `Attach a CloudN device to Aviatrix Transit Gateway <https://docs.aviatrix.com/HowTos/cloud_wan_workflow.html#option-1-attach-to-an-aviatrix-transit-gateway>`_. 1. Navigate to CloudN > Attach. 2. Scroll down to 2. Attach Device to Cloud. 3. Select the **Aviatrix Transit Gateway** radio button. 4. Enter the following information in the fields below. +-----------------------------------------+------------------------------------------------------------------------------------------+ | **Field** | **Value** | +-----------------------------------------+------------------------------------------------------------------------------------------+ | Device Name | Select the Managed CloudN device | +-----------------------------------------+------------------------------------------------------------------------------------------+ | Aviatrix Transit Gateway | Select an Aviatrix Transit Gateway | +-----------------------------------------+------------------------------------------------------------------------------------------+ | Connection Name | A unique name for the connection (i.e. Managed-CloudN-to-Aviatrix-Transit-GW-connection) | +-----------------------------------------+------------------------------------------------------------------------------------------+ | Aviatrix Transit Gateway BGP ASN | Only BGP is supported. Enter BGP ASN number on Aviatrix Transit Gateway. (i.e. 65019) | +-----------------------------------------+------------------------------------------------------------------------------------------+ |Device's BGP ASN | Only BGP is supported. Enter BGP ASN number on the Managed CloudN device. (i.e. 65056) | +-----------------------------------------+------------------------------------------------------------------------------------------+ | Algorithms | Leave this checkbox unmarked. | +-----------------------------------------+------------------------------------------------------------------------------------------+ | Enable Global Accelerator | Check the box to enable AWS Global Accelerator for the branch router to hop onto the | | | nearest AWS edge and traverse the AWS backbone to get to the Aviatrix Transit Gateway. | +-----------------------------------------+------------------------------------------------------------------------------------------+ | Pre-shared key | Leave this checkbox unmarked. | +-----------------------------------------+------------------------------------------------------------------------------------------+ | Local Tunnel IP | Leave this checkbox unmarked. | +-----------------------------------------+------------------------------------------------------------------------------------------+ | Remote Tunnel IP | Leave this checkbox unmarked. | +-----------------------------------------+------------------------------------------------------------------------------------------+ 5. Click **Attach.** |controller_attach_aviatrix_transit| Check Whether the Managed CloudN Device is Attached to Aviatrix Transit Gateway Properly ------------------------------------------------------------------------------------------------------------------ #. Navigate to CloudN > List/Edit. #. Search for the Managed CloudN device. #. Check the state is displayed as "attached" in the State column. |controller_managed_cloudn_attached_state| .. note:: The status "attached" here reflects only the management operation state, it does not reflect the attached connection state in real time. Please go to Site2Cloud page to monitor the connection status as shown below. Check Whether the Connection Status is Up -------------------------------------------------------- #. Navigate to Site2Cloud > Setup. #. Locate the connection which is created in the previous step (i.e. Managed-CloudN-to-Aviatrix-Transit-GW-connection). #. Check whether the connection status is Up as in the example below. |controller_managed_cloudn_s2c_up_state| Check Transit Gateway BGP status ------------------------------------------- #. Navigate to Multi-Cloud Transit > Advanced Config > BGP. #. Locate the connection which is created in the previous step (i.e. Managed-CloudN-to-Aviatrix-Transit-GW-connection). #. Check whether the Neighbor Status is established. Traffic Flow Verification ========================= In this example traffic flow verification is performed after the Site2Cloud connection(s) is up and the BGP connection(s) is established. The on-premise router is Cisco IOS with network loopback address 2.2.2.2/32. Aviatrix Transit VPC/VNet is 10.1.0.0/16. Aviatrix Spoke VPC/VNet is 192.168.1.0/24 and the private IP of the testing VM is 192.168.1.36/32. - Traffic from on-premise router Cisco IOS to cloud VM - Issue ICMP traffic from on-prem loopback interface to a Virtual IP of cloud instance |managed_cloudn_traffic_flow_verification_on_prem_router_issue_icmp| - Execute packet capture on the cloud instance |managed_cloudn_traffic_flow_verification_cloud_vm_tcpdump_icmp| - Traffic from cloud VM to on-premise router Cisco IOS - Issue ICMP traffic from cloud instance to on-prem loopback interface address |managed_cloudn_traffic_flow_verification_cloud_vm_issue_icmp| CloudN States ============== The Registered Devices table on the CloudN > List tab shows the state of the CloudN device and the reason for that state. - Registered: - The CloudN device is registered to the Aviatrix Controller and ready for attachment to a Transit Gateway. You can deregister the CloudN gateway if desired. - You can `reset the CloudN device to factory defaults <#workflow-on-reset-configuration>`_. - You can run diagnostics on a registered CloudN device. - Attached: - The CloudN device is attached to a Transit Gateway. This status only reflects the management operation state; it does not reflect the attached connection state in real time. To check connectivity, you can check connection status on the `Site2Cloud page <#check-whether-the-connection-status-is-up>`_; `check the BGP connection <#check-transit-gateway-bgp-status>`_; and `verify the traffic flow <#traffic-flow-verification>`_. - You can run diagnostics on an attached CloudN device. - You cannot deregister unless you detach the gateway first. - You can `reset the CloudN device to factory defaults <#workflow-on-reset-configuration>`_. - Check: The CloudN device is not connected to the Aviatrix Controller. You cannot run diagnostics, or deregister the device. You can investigate by doing the following: - Examine the security policy of the Controller instance and ensure that TCP port 443 is opened to traffic originating from the CloudN device public IP address. See `here <#opening-controller-inbound-ports>`_ for more information. - Examine the security policy of the CloudN device and make sure that TCP port 443 is opened to traffic originating from the Controller public IP address. This rule is inserted by the Controller during device creation. Please restore if it was removed. - Make sure network ACLs or other firewall rules are not configured to block traffic between the Aviatrix Controller and the CloudN device over TCP port 443. - Check basic connectivity to the internet from the CloudN device. See `here <#managed-cloudn-management-port-outbound-access>`_ for more information. .. note:: Aviatrix recommends upgrading the Controller to version 6.7 with a CloudN base image of version 6.6 to ensure that the CloudN states are rendered accurately. Troubleshooting Tips ==================== When an CloudN registers with an Aviatrix Controller properly as a Managed CloudN device, users can perform troubleshooting on a Managed CloudN device the same way as an Aviatrix gateway in the cloud via Aviatrix Controller GUI. .. note:: Direct access to CloudN's local HTTPs URL/UI is still allowed for only Troubleshoot/Diagnostic reasons; access to any other menu items is not recommended nor supported. Running Diagnostics -------------------- #. Navigate to CloudN > List/Edit in the Aviatrix Controller. #. Select the Managed CloudN device. #. Click **Diag** to display a dropdown menu. #. Click **Run**. #. Wait for a couple of minutes to complete the running diagnostics process. #. Click **Show** to display the report. #. Click **Submit** to upload the report to Aviatrix Support. |controller_troubleshooting_tips_running_diagnostics| Upload Tracelog --------------------------- #. Navigate to CloudN on the left sidebar > List/Edit. #. Search for the Managed CloudN device and select it. #. Click **Diag** to display a dropdown menu. #. Click **Upload Tracelog** to upload tracelog to Aviatrix Support. |controller_troubleshooting_tips_upload_tracelog| Download syslogs ------------------------- #. Navigate to CloudN on the left sidebar > List/Edit. #. Search for the Managed CloudN device and select it. #. Click **Diag** to display dropdown menu. #. Click on the button **Download Syslog**. |controller_troubleshooting_tips_download_syslogs| Force Upgrade ------------------------- See `Force Upgrade doc <https://docs.aviatrix.com/HowTos/Troubleshoot_Diagnostics.html#force-upgrade>`_. #. In the Aviatrix Controller, navigate to Troubleshoot on the left sidebar > Diagnostics > Gateway. #. Open the Force Upgrade section. #. Select the Managed CloudN device on the Gateway dropdown menu. #. Click **Upgrade** to force upgrade the Managed CloudN device. |controller_troubleshooting_tips_force_upgrade| Upgrade ======= When a CloudN registers with an Aviatrix Controller properly as a Managed CloudN device, the upgrade process on the Managed CloudN device is treated the same way as an Aviatrix gateway in the cloud when Aviatrix Controller is upgraded. Please refer to `Inline Software Upgrade doc <https://docs.aviatrix.com/HowTos/inline_upgrade.html>`_ for upgrading a Managed CloudN device from Aviatrix Controller. .. important:: * Once CloudN is registered to the Aviatrix Controller, if you wish to check the version of Managed-CloudNs, please go to Aviatrix controller > Settings > Maintenance > Upgrade > Gateway Upgrade Status. However, the software version you see from CloudN GUI locally would not change, and it stays with the version at the time when you register CloudN to Aviatrix controller. * With Managed CloudN, software upgrading directly from CloudN GUI is no longer needed, unless unexpected issues occur. In such case, please open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_. |correct_place_to_check_cloudN_version| Backup/Restore ============== When a CloudN registers with an Aviatrix Controller properly as a Managed CloudN device, the backup/restore process on the Managed CloudN device is processed the same way as an Aviatrix Gateway in the cloud when the backup/restore function is performed on Aviatrix Controller. Please see the `Controller Backup and Restore doc <https://docs.aviatrix.com/HowTos/controller_backup.html>`_ for details. .. note:: Performing backup/restore function for Managed CloudN device via CloudN GUI is not supported. Workflow on Cleanup =================== Detach a Managed CloudN device from Aviatrix Controller ------------------------------------------------------------------------------ Follow these steps to detach a Managed CloudN device from the Aviatrix Controller. #. In your Aviatrix Controller, navigate to CloudN on the left sidebar > Attach. #. Scroll down to Delete Function > 3 > Detach Device from Cloud. #. Select the connection from the Attachment Name dropdown menu. #. Click **Detach** to disconnect the connection. |controller_cloudwan_detach| Note that you can also deregister devices by navigating to CloudN on the left sidebar > List, selecting the connection from the list of Registered Devices, and clicking **Deregister**. |controller_cloudwan_deregister| .. note:: If these steps cannot convert a Managed CloudN device back to a Standalone CloudN state properly, please proceed to the Reset Configuration section. Workflow on Reset Configuration --------------------------------------------- The Reset Configuration feature enables users to remove all configuration on a Managed CloudN device from a corrupted state to a clean state. Please follow the steps below in the Resetting Configuration section. This Reset Configuration feature is the last resort if users are not able to convert a Managed CloudN device back to a Standalone CloudN state through the steps above. Resetting Configuration ^^^^^^^^^^^^^^^^^^^^^^^^ #. In your Aviatrix Controller, navigate to CloudN on the left sidebar > List/Edit. #. Search for the Managed CloudN device and select it. #. Click **Diag** to display dropdown menu. #. Click **Reset Configuration**. Wait for a few minutes for the process to complete. |controller_cloudwan_factory_reset| .. note:: Normally, when users reset a configuration, the Aviatrix Controller notifies Managed CloudN to perform this function. If Managed CloudN does not reset the configuration properly through the Aviatrix Controller, users need to execute the step below. (Optional) Perform feature "Reset Configuration" on CloudN GUI ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use the following steps to reset a device's configuration if you are unable to do so through your Aviatrix Controller. 1. Open a browser and navigate to the CloudN GUI with CloudN domain name/IP and port 443. 3. Sign in and navigate to Settings > Advanced > Registration or select **Managed CloudN** under UseCases dropdown menu on the top/ |cloudn_register_controller_fqdn_link_managed_cloudn| 3. Find the Reset Configuration section and click **Reset**. Wait a few minutes for the process to complete. |cloudn_factory_reset| .. important:: If you need any assistance to reset a configuration, please open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_. User Guide for Redundant DX Deployment ====================================== Active/Active ------------- |deployment_dual_dx_aa| The `Active/Active deployment model <https://docs.aviatrix.com/HowTos/CloudN_insane_mode.html#redundant-dx-deployment-active-active>`_ is recommended. In this deployment model, both CloudN appliances forward traffic and the underlying network links are fully utilized. .. important:: Aviatrix topology requirements: - Attach two CloudN appliances to Aviatrix Transit by following the workflows above. - Enable `BGP ECMP function <https://docs.aviatrix.com/HowTos/transit_advanced.html#bgp-ecmp>`_ on Aviatrix Transit. On-prem topology requirements: - If firewalls are deployed, make sure there is no asymmetric routing issues or the firewalls are capable of handling asymmetric routing issues. - LAN routers should advertise the same AS path length to both CloudN appliances and enable ECMP feature. Active/Standby -------------- |deployment_dual_dx| Aviatrix solution supports `Active/Standby deployment model <https://docs.aviatrix.com/HowTos/CloudN_insane_mode.html#redundant-dx-deployment-active-standby>`_, but one of the CloudN appliances and network connections stays at standby/idle mode. To deploy this topology, on-prem LAN router must advertise **longer BGP AS_PATH** to the Standby CloudN to ensure traffic direction from cloud to on-prem always routes to the Active CloudN when the connection is up. Once the connection on the Active CloudN is down, traffic will be directed towards the Standby CloudN based on BGP info. When the Active CloudN is recovered, traffic will switch back to the Active CloudN as it has **shorter BGP AS_PATH** length. Users can utilize `Connection AS Path Prepend <https://docs.aviatrix.com/HowTos/transit_advanced.html#connection-as-path-prepend>`_ for the traffic direction from on-prem to cloud depending on requirement. FAQ ==== Q: What is the terminology of Standalone CloudN and Managed CloudN? Ans: In this document, the term "Standalone CloudN" refers to a CloudN device is not managed by an Aviatrix Controller; "Managed CloudN" refers to a CloudN device that is registered/managed by an Aviatrix Controller. Q: Could a Managed CloudN be converted back to a Standalone CloudN? Ans: Yes. While this is not recommended practice, you should be able to convert a Managed CloudN device back to a Standalone CloudN by following the `Workflow on cleanup <https://docs.aviatrix.com/HowTos/CloudN_workflow.html#workflow-on-cleanup>`_. Q: Does Managed CloudN have Aviatrix High-Performance (Insane) mode supported? Ans: Yes. When a Managed CloudN device attaches to an Aviatrix Transit Gateway with HA function enabled, High-Performance (Insane) mode tunnels to both primary and backup Transit Gateways are built automatically. Q: Can Managed CloudN solution support Azure ExpressRoute? Ans: Yes, Managed CloudN runs over Azure ExpressRoute. Q: Can we build a mixed topology in the deployment where some connections are from Managed CloudN and others are from Standalone CloudN in one CloudN appliance? Ans: No. We don't support this mixed topology. Once you decide to deploy Managed CloudN solution, you need to make sure there is no IPsec tunnel between Aviatrix Transit Gateway and Standalone CloudN before registering the Standalone CloudN to Aviatrix Controller. Q: Can one Standalone/Managed CloudN appliance connect to multiple links Direct Connect or ExpressRoute? Ans: Yes. A CloudN appliance can build multiple of HPE connections to different Aviatrix Transit Gateways over multiple Direct Connect or ExpressRoute. Q: Can one Aviatrix Transit Gateway connect to multiple of Managed CloudNs? Ans: Yes. An Aviatrix Transit Gateway can build multiple of HPE connections to different Managed CloudNs. Q: Can one Aviatrix Transit Gateway build mixed connections to different Standalone CloudN and Managed CloudN? Ans: Yes. While this is not recommended practice, an Aviatrix Transit Gateway is able to build mixed connections to different Standalone CloudN and Managed CloudN. This deployment is for migration stage only. Q: How to update the new Aviatrix Controller public IP for Managed CloudN? Ans: - Refer to `step 2.6 Register with Aviatrix Controller FQDN Name <https://docs.aviatrix.com/HowTos/CloudN_workflow.html#step-2-6-register-with-aviatrix-controller-fqdn-name>`_. 1. Navigate to Settings > Advanced > Registration or select **Managed CloudN** under the UseCases dropdown menu on the top on CloudN GUI. 2. Find the Register CloudN as a Gateway section and enter the new Aviatrix Controller public IP. .. important:: It is highly recommended that a FQDN name is used instead of an IP address for enhanced security and controller HA. 3. Click **Register**. 4. Click **OK**. Migrating a Standalone CloudN to a Managed CloudN ================================================= 1. To upgrade a Standalone CloudN to a Managed CloudN, `upgrade <https://docs.aviatrix.com/HowTos/inline_upgrade.html>`_ the Aviatrix Controller and CloudN appliance to the latest version. .. note:: From Release 6.6a and onwards, to register CloudN with the Controller as Managed CloudN does not require to upgrade CloudN applicance to the Controller version. 2. Remove/delete any Site2Cloud (IPsec) connection between a Aviatrix Transit Gateway and Standalone CloudN. 3. Follow the instructions `above <https://docs.aviatrix.com/HowTos/CloudN_workflow.html#prerequisites>`_ for managed CloudN workflows. .. |managed_cloudn_topology| image:: CloudN_workflow_media/managed_cloudn_topology.png :scale: 80% .. |cloudn_register_controller_fqdn_link_managed_cloudn| image:: CloudN_workflow_media/cloudn_register_controller_fqdn_link_managed_cloudn.png :scale: 80% .. |cloudn_register_controller_fqdn| image:: CloudN_workflow_media/cloudn_register_controller_fqdn.png :scale: 40% .. |controller_managed_cloudn_registered_state| image:: CloudN_workflow_media/controller_managed_cloudn_registered_state.png :scale: 50% .. |controller_discover_wan_interfaces| image:: CloudN_workflow_media/controller_discover_wan_interfaces.png :scale: 60% .. |controller_attach_aviatrix_transit| image:: CloudN_workflow_media/controller_attach_aviatrix_transit.png :scale: 60% .. |controller_managed_cloudn_attached_state| image:: CloudN_workflow_media/controller_managed_cloudn_attached_state.png :scale: 50% .. |controller_managed_cloudn_s2c_up_state| image:: CloudN_workflow_media/controller_managed_cloudn_s2c_up_state.png :scale: 60% .. |managed_cloudn_traffic_flow_verification_on_prem_router_issue_icmp| image:: CloudN_workflow_media/managed_cloudn_traffic_flow_verification_on_prem_router_issue_icmp.png :scale: 100% .. |managed_cloudn_traffic_flow_verification_cloud_vm_tcpdump_icmp| image:: CloudN_workflow_media/managed_cloudn_traffic_flow_verification_cloud_vm_tcpdump_icmp.png :scale: 100% .. |managed_cloudn_traffic_flow_verification_cloud_vm_issue_icmp| image:: CloudN_workflow_media/managed_cloudn_traffic_flow_verification_cloud_vm_issue_icmp.png :scale: 100% .. |controller_troubleshooting_tips_running_diagnostics| image:: CloudN_workflow_media/controller_troubleshooting_tips_running_diagnostics.png :scale: 50% .. |controller_troubleshooting_tips_upload_tracelog| image:: CloudN_workflow_media/controller_troubleshooting_tips_upload_tracelog.png :scale: 50% .. |controller_troubleshooting_tips_download_syslogs| image:: CloudN_workflow_media/controller_troubleshooting_tips_download_syslogs.png :scale: 50% .. |controller_troubleshooting_tips_force_upgrade| image:: CloudN_workflow_media/controller_troubleshooting_tips_force_upgrade.png :scale: 50% .. |controller_cloudwan_detach| image:: CloudN_workflow_media/controller_cloudwan_detach.png :scale: 60% .. |controller_cloudwan_deregister| image:: CloudN_workflow_media/controller_cloudwan_deregister.png :scale: 60% .. |cloudn_factory_reset| image:: CloudN_workflow_media/cloudn_factory_reset.png :scale: 40% .. |controller_cloudwan_factory_reset| image:: CloudN_workflow_media/controller_cloudwan_factory_reset.png :scale: 60% .. |deployment_dual_dx| image:: insane_mode_media/deployment_dual_dx.png :scale: 30% .. |deployment_dual_dx_aa| image:: insane_mode_media/deployment_dual_dx_aa.png :scale: 30% .. |correct_place_to_check_cloudN_version| image:: ./CloudN_workflow_media/correct_place_to_check_cloudN_version.png :scale: 60% .. disqus:: <file_sep> =============================================== ActiveMesh Insane Mode Encryption Performance =============================================== This document provides Aviatrix ActiveMesh Insane Mode High-Performance Encryption (HPE) test benchmarks. For more information about Aviatrix Insane Mode, refer to `Insane Mode Encryption FAQ. <https://docs.aviatrix.com/HowTos/insane_mode.html>`_ AWS Performance Test Results ---------------------------------------------- Aviatrix ActiveMesh Insane Mode High-Performance Encryption (HPE) achieves line rate performance with encryption in AWS when Jumbo Frames are deployed (the default setting for AWS instances). The test benchmark baseline is the native AWS peering where no Aviatrix Gateways are deployed in the VPCs. Adding 500 stateful firewall rules have little impact to the performance. The test topologies are shown below. |test_topologies| The test is conducted by using iperf3 tool with TCP 128 streams. The two VPCs are in the same region. MTU = 9000 Bytes (AWS default setting) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |jumbo| MTU = 1500 Bytes ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |1500| Single Gateway in AWS Performance Test Results ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This test is done without HA enabled in either Spoke or Transit Gateways. The traffic is end-to-end from user instance > Spoke Gateway > Multi-Cloud Transit Gateway > Spoke Gateway> Instance. For MTU = 9000 Bytes, the result is shown in the diagram below. |single_gateway_jumbo| For MTU = 350 Bytes, the result is shown in the diagram below. |single_gateway_350B| T3 Instance Series Performance ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ========================== =============================== =============================== **Spoke Gateway** **Throughput Gbps (MTU 1500B)** **Throughput Gbps (MTU 9600B)** ========================== =============================== =============================== t3a.xlarge 6.12 9.82 t3a.medium 2.33 8.85 t3a.small 2.7 8.52 t3.large 3.34 9.5 t3.medium 3.03 9.6 t3.small 3.35 9.96 ========================== =============================== =============================== Azure Performance Test Results ------------------------------------------------ The performance results below are from tests conducted with the topology of Test VMs > Spoke > Transit > Spoke > Test VMs in the same region with active-mesh deployment. Test VMs' route tables are load balanced to point to either primary Spoke Gateways or HA Spoke Gateways to take advantage of the active-mesh deployment. The test topology is shown below. |azure_test_topology| =========================== =============================== **Transit Gateway** **Throughput with MTU 1500B** =========================== =============================== Standard_F48s_v2 24.52Gbps Standard_F32s_v2 21.56Gbps Standard_D32_v3 20.47Gbps Standard_D5_v2 20.56Gbps =========================== =============================== GCP Performance Test Results ------------------------------------------- The test topology is shown below with the following conditions: - VM <-> Spoke <-> Transit <-> Spoke <-> VM - HA enabled - HPE mode enabled |gcp_test_topology| N1 Series Performance ^^^^^^^^^^^^^^^^^^^^^^^^^^ ==================== =============================== **Transit Gateway** **Throughput Gbps (MTU 1500B)** ==================== =============================== n1-highcpu-4 3.12 n1-highcpu-8 6.54 n1-highcpu-16 11.58 n1-highcpu-32 19.97 ==================== =============================== N2 Series Performance ^^^^^^^^^^^^^^^^^^^^^^^^^ ==================== =============================== **Transit Gateway** **Throughput Gbps (MTU 1500B)** ==================== =============================== n2-highcpu-4 5.063 n2-highcpu-8 10.2 n2-highcpu-16 14.98 n2-highcpu-32 25.549 ==================== =============================== C2 Series Performance ^^^^^^^^^^^^^^^^^^^^^^^^^ ==================== =============================== **Transit Gateway** **Throughput Gbps (MTU 1500B)** ==================== =============================== c2-standard-4 5.792 c2-standard-8 9.44 c2-standard-16 18.48 c2-standard-30 25.52 c2-standard-60 32 ==================== =============================== .. note:: To deploy Aviatrix Gateways with N2 or C2 series successfully, you need to apply `CPU Quota Increase <https://cloud.google.com/compute/quotas#cpu_quota>`_ request to GCP support first. OCI Performance Test Results ------------------------------------ The performance results below are from tests conducted with the topology of Test VMs > Spoke > Transit > Spoke > Test VMs in the same region with active-mesh deployment. .. note:: Test VMs' route tables are load balanced to point to either primary Spoke Gateways or HA Spoke Gateways to take advantage of the active-mesh deployment. =========================== =============================== **Transit Gateway** **Throughput with MTU 1500B** =========================== =============================== VM.Standard2.2 0.5092Gbps VM.Standard2.4 1.057Gbps VM.Standard2.8 2.471Gbps VM.Standard2.16 4.99Gbps VM.Standard2.24 6.039Gbps =========================== =============================== =========================== =============================== **Transit Gateway** **Throughput with MTU 9000** =========================== =============================== VM.Standard2.2 2.584Gbps VM.Standard2.4 4.878Gbps VM.Standard2.8 10.75Gbps VM.Standard2.16 20.1199bps VM.Standard2.24 24.65Gbps =========================== =============================== How to Tune Performance -------------------------- Check MTU size ^^^^^^^^^^^^^^^^^^ To check MTU size, use Trace Path. 1. In Aviatrix Controller, go to **Troubleshoot** > **Diagnostics** > **Network**. 2. In Gateway Utility, select a gateway and specify a destination host name or IP address. 3. Click **Trace Path**. The MTU of the devices along the path is shown. Tune TCP window size ^^^^^^^^^^^^^^^^^^^^^^ For Linux machine, follow the `instructions here <https://wwwx.cs.unc.edu/~sparkst/howto/network_tuning.php>`_ to tune TCP window size. .. |insane_perf_setup| image:: insane_mode_perf_media/insane_perf_setup.png :scale: 30% .. |insane_perf_jumbo| image:: insane_mode_perf_media/insane_perf_jumbo.png :scale: 30% .. |single_gateway_jumbo| image:: insane_mode_perf_media/single_gateway_jumbo.png :scale: 30% .. |throughput_1500_25ms| image:: insane_mode_perf_media/throughput_1500_25ms.png :scale: 30% .. |c5n_throughput_1500B| image:: insane_mode_perf_media/c5n_throughput_1500B.png :scale: 30% .. |c5n_throughput_9000B| image:: insane_mode_perf_media/c5n_throughput_9000B.png :scale: 30% .. |throughput_1500B_peering| image:: insane_mode_perf_media/throughput_1500B_peering.png :scale: 30% .. |jumbo| image:: insane_mode_perf_media/jumbo.png :scale: 30% .. |1500| image:: insane_mode_perf_media/1500.png :scale: 30% .. |test_topologies| image:: insane_mode_perf_media/test_topologies.png :scale: 30% .. |azure_test_topology| image:: insane_mode_perf_media/azure_test_topology.png :scale: 30% .. |gcp_test_topology| image:: insane_mode_perf_media/gcp_test_topology.png :scale: 30% .. |single_gateway_350B| image:: insane_mode_perf_media/single_gateway_350B.png :scale: 30% .. disqus:: <file_sep> ========================================= AWS Managed Microsoft AD for Aviatrix ========================================= Summary ------- This document describes how to deploy an AWS Directory Service for Microsoft Active Directory for `Aviatrix Controller LDAP <https://docs.aviatrix.com/HowTos/AdminUsers_LDAP.html?highlight=ldap#controller-ldap-login-configuration>`__ and `OpenVPN LDAP <https://docs.aviatrix.com/HowTos/VPNUsers_LDAP.html#ldap-configuration-for-authenticating-vpn-users>`__ feature. The `AWS Directory Service for Microsoft Active Directory <https://docs.aws.amazon.com/en_us/directoryservice/latest/admin-guide/what_is.html>`__ is an AWS service if you need an actual Microsoft Active Directory in the AWS Cloud that supports Active Directory–aware workloads, or AWS applications and services such as Amazon WorkSpaces and Amazon QuickSight, or you need LDAP support for Linux applications. Please note that in the following steps, most involve following `AWS Managed Microsoft AD Test Lab Tutorials <https://docs.aws.amazon.com/en_us/directoryservice/latest/admin-guide/ms_ad_tutorial_test_lab_base.html>`__ to create LDAP service in AWS Cloud. |image9| Follow these steps to configure the AWS AD configuration in your environment and verify LDAP connection. #. Setting Up Your Base AWS Managed Microsoft AD in AWS #. Verify AWS AD Is Operational by using AD Explorer #. Verify AWS AD Is Operational by an Aviatrix Controller with LDAP login verification. #. Verify AWS AD Is Operational by an Aviatrix OpenVPN Server with LDAP login verification. Prerequisites ------------- In order to complete the steps in this guide, you'll need: 1. An AWS Account 2. An Aviatrix Controller which has already onboarded above AWS account Setting Up Your Base AWS Managed Microsoft AD in AWS ------------------------------------------------------------- Step A: Set Up Your AWS Environment for AWS Managed Microsoft AD #################### https://docs.aws.amazon.com/directoryservice/latest/admin-guide/microsoftadbasestep1.html Step B: Create Your AWS Managed Microsoft AD Directory in AWS #################### https://docs.aws.amazon.com/en_us/directoryservice/latest/admin-guide/microsoftadbasestep2.html Create your AWS Managed Microsoft AD directory. In this example, the following domain and dns are created Domain Name: aws-ad.aviatrixtest.com. Two domain Name servers are created by AWS AD: 172.31.28.253, 172.31.14.48 |image0| |image4| Step C: Deploy an EC2 Instance to Manage AWS Managed Microsoft AD #################### Follow these steps to configure Microsoft AD of your Windows Server EC2 Instance. 1. Deploy an EC2 Instance to Manage AWS Managed Microsoft AD `Check Detail Here <https://docs.aws.amazon.com/directoryservice/latest/admin-guide/microsoftadbasestep3.html>`__ 2. Manually Join a Windows Instance `Check Detail Here <https://docs.aws.amazon.com/directoryservice/latest/admin-guide/join_windows_instance.html>`__ .. note:: TIPS: Use these commands from a command prompt on the instance above %SystemRoot%\system32\control.exe ncpa.cpl => Make sure the two domain controller IP is in your dns setup %SystemRoot%\system32\control.exe sysdm.cpl ==> Join domain |image3| |image6| Step D: Configure LDAP After logging in to the EC2 Instance with AD authentication (aws-ad.aviatrixtest.com\Admin), configure another user "aduser" to AWS AD domain. |image7| .. _Verify_AWS_AD_AD_Explorer: Verify AWS AD Is Operational by using AD Explorer -------------------------- You can download Microsoft AD Explorer from this `link <https://docs.microsoft.com/en-us/sysinternals/downloads/adexplorer>`__ Verify LDAP information, for example Bind DN and Base DN, and store them for further Aviatrix Controller and OpenVPN LDAP authentication. |image2| |image1| .. _Verify_AWS_AD_AVX_CTRL: Verify AWS AD Is Operational by an Aviatrix Controller with LDAP login verification. -------------------------- In the Aviatrix Controller GUI, go to Setting > Controller > LDAP Login. Input the LDAP information from `AD Explorer <#Verify_AWS_AD_AD_Explorer>`__ and verify LDAP connection. |image8| .. _Verify_AWS_AD_AVX_OVPN: Verify AWS AD Is Operational by a Aviatrix OpenVPN Server with LDAP login verification. -------------------------- In the Aviatrix Controller GUI, go to Setting > Controller > LDAP Login. Input LDAP information from `AD Explorer <#Verify_AWS_AD_AD_Explorer>`__ and verify the LDAP connection. |image10| OpenVPN is a registered trademark of OpenVPN Inc. .. |image0| image:: HowTo_Setup_AWS_Managed_Microsoft_AD_for_Aviatrix_media/awsad-1.png .. |image1| image:: HowTo_Setup_AWS_Managed_Microsoft_AD_for_Aviatrix_media/awsad-ad-explorer-2.png .. |image2| image:: HowTo_Setup_AWS_Managed_Microsoft_AD_for_Aviatrix_media/awsad-ad-explorer-1.png .. |image3| image:: HowTo_Setup_AWS_Managed_Microsoft_AD_for_Aviatrix_media/dns_server_addresses.png .. |image4| image:: HowTo_Setup_AWS_Managed_Microsoft_AD_for_Aviatrix_media/awsad-2.png .. |image5| image:: HowTo_Setup_AWS_Managed_Microsoft_AD_for_Aviatrix_media/awsad-3.png .. |image6| image:: HowTo_Setup_AWS_Managed_Microsoft_AD_for_Aviatrix_media/awsad-ec2-1.png .. |image7| image:: HowTo_Setup_AWS_Managed_Microsoft_AD_for_Aviatrix_media/awsad-ec2-2.png .. |image8| image:: HowTo_Setup_AWS_Managed_Microsoft_AD_for_Aviatrix_media/awsad-avxctrl-ldap1.png .. |image9| image:: HowTo_Setup_AWS_Managed_Microsoft_AD_for_Aviatrix_media/tutorialmicrosoftadbase.png .. |image10| image:: HowTo_Setup_AWS_Managed_Microsoft_AD_for_Aviatrix_media/awsad-openvpn-ldap.png .. disqus:: <file_sep> ===================================================================== Aviatrix Gateway to Aviatrix Gateway ===================================================================== Overview -------------------- This document describes how to configure an IPsec tunnel between an Aviatrix Gateway and another Aviatrix Gateway using Aviatrix Site2Cloud. .. note:: There are only a couple of reasons to use Site2Cloud when connecting two Aviatrix Gateways: #. You have overlapping CIDR blocks but need to peer two VPC/VNets. #. The two Aviatrix Gateways are not part of the same Controller (i.e., one is at your customer and the other one is in your environment). If these reasons don't apply to you, you can use Aviatrix Encrypted Peering. Certificate-Based Authentication -------------------------------- If you want to use certificate-based authentication when establishing this connection: #. In the Aviatrix Controller for 'Gateway B', navigate to SITE2CLOUD > Certificate > CA Certificate and download the certificate. #. When following the procedure below, select this downloaded Aviatrix CA certificate when configuring the tunnel from Gateway A to Gateway B. .. note:: If both Aviatrix gateways are in the same Controller these steps are not required. Deployment Guide ----------------------------- There are two Aviatrix Gateways for this scenario. Since you are using the Site2Cloud feature, you must configure each side of the tunnel individually. We will refer to the gateways below as **Gateway A** and **Gateway B**. You can pick either gateway to be **Gateway A** or **Gateway B**. If you want to use certificate-based authentication, you must first download the Aviatrix CA certificate from Gateway B, to use when setting up the tunnel from Gateway A to Gateway B. Configure Tunnel from Gateway A to Gateway B ++++++++++++++++++++++++++++++++++++++++++++ #. Follow the steps in `this </HowTos/site2cloud.html>`__ guide. Use this table for specific field values. +-------------------------------+------------------------------------------+ | Field | Description | +===============================+==========================================+ | VPC ID/VNet Name | Select **Gateway A** VPC or VNet from the| | | drop down. | +-------------------------------+------------------------------------------+ | Remote Gateway Type | Aviatrix | +-------------------------------+------------------------------------------+ | Registered | Leave unchecked | +-------------------------------+------------------------------------------+ | Primary Cloud Gateway | Select **Gateway A** from the list | +-------------------------------+------------------------------------------+ | Remote Gateway IP Address | Enter the public IP address of | | | **Gateway B**. | +-------------------------------+------------------------------------------+ | Pre-shared Key or CA | If you leave the PSK Key blank one is | | Certificate | generated for you, or you select the | | | remote CA certificate and enter the | | | Remote Identifier | +-------------------------------+------------------------------------------+ #. Once complete, select the newly created tunnel in the list. #. Select **Aviatrix** for Vendor, **UCC** for Platform and **1.0** for Software. #. Click **Download Configuration**. You will use this file to create the other side of the tunnel. Configure Tunnel from Gateway B to Gateway A ++++++++++++++++++++++++++++++++++++++++++++ #. In the Site2Cloud section, click **+ Add New**. #. Click **Import**. #. Select the file downloaded in the previous section. #. Check the values that are pre-populated. #. Click **OK**. Test -------- Once complete, test the communication using the tunnel. Troubleshooting ---------------------- Wait 2-3 minutes for the tunnel to come up. If it does not come up within that time, check the IP addresses to confirm they are accurate. Additional troubleshooting is available in the **Diagnostics** tab. <file_sep> ===================================================================== Ingress Protection via Aviatrix Transit FireNet with Palo Alto in GCP ===================================================================== This document describes how to configure ingress in GCP with traffic inspection, deployed directly in FireNet. In this configuration you use the native GCP load balancers in FireNet. These load balancers are created after you enable Transit FireNet as part of the `Transit FireNet Workflow for GCP <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_gcp.html>`_. The solution described below shows how to implement network load balancer (NLB)-based ingress with Palo Alto firewalls in GCP. |gcp_ingress| .. note:: In this NLB-based deployment in GCP, the original source address is preserved. The firewall then has to NAT the traffic source to its LAN interface IP; that’s where the original source IP is rewritten (SNAT). This document provides a step-by-step guide for application ingress protection via Aviatrix Transit FireNet using Palo Alto firewalls for Aviatrix Controller version R6.6 and later. For more information about Transit FireNet, please see the following documents: `Transit FireNet FAQ <https://docs.aviatrix.com/HowTos/transit_firenet_faq.html>`_ `Firewall Network Design Patterns <https://docs.aviatrix.com/HowTos/firewall_network_design_patterns.html>`_ Design Considerations ===================== This document describes NLB-based ingress in GCP. However, there are options available for other traffic types. For HTTP/HTTPS load balancing, an HTTP(S) load balancer with Network Endpoint groups could be another option, although this method does not preserve the source IP address until the firewall is reached. For a limited list of supported ports you can also use a TCP proxy-based load balancer with Network Endpoint Groups. Currently in GCP you cannot place a HTTP(S) or other form of load balancer into a Spoke VPC, as load balancers are not tied to a subnet and would deliver traffic directly to backend services instead of Spoke gateways. A third-party appliance such as F5 could be used to do this in a spoke network if needed. Deployment Steps ==================== Deploy a Transit FireNet in GCP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Set up a Transit FireNet in GCP and enable centralized egress. For details on setting up Transit FireNet see the document below: `Transit FireNet Workflow <https://docs.aviatrix.com/HowTos/transit_firenet_workflow.html>`_ Set up Firewall Instances for Egress ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Set up the firewall instances according to the documentation here: `Example Config for Palo Alto Network VM-Series in GCP <https://docs.aviatrix.com/HowTos/config_paloaltoGCP.html>`_ Enable vendor integration with the firewalls according to the documentation here: `Setup API Access to Palo Alto Networks VM-Series <https://docs.aviatrix.com/HowTos/paloalto_API_setup.html>`_ Enable egress through the firewalls according to the documentation here: `Egress through firewall <https://docs.aviatrix.com/HowTos/firewall_advanced.html#egress-through-firewall>`_ The following screenshots show how to enable egress: |enable_egress1| |enable_egress2| Verify Health Probe Status ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In the GCP console open the Load balancing menu and check the health of the load balancers used by the Transit FireNet. These load balancers were created during the Transit FireNet setup for GCP. There will be one UDP and one TCP load balancer. Backends should show as healthy. |gcp_be_lb_health| Set up Palo Alto Firewalls for Ingress Load Balancing ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Update Management Profile --------------------------- Edit the management profile to restrict access to firewall management access over WAN and LAN interfaces to only health probes. Enable HTTP access since the legacy health probes in GCP only support HTTP and not HTTPS. The IP address ranges to add are: - 169.254.169.254 (legacy health probe for External load balancer) - 172.16.58.3/16 and 172.16.31.10/22 (health probes for Internal load balancer) |palo_alto_mfmt_profile_details| Add the management profile you have updated to the WAN interface of the firewall. |palo_alto_mgmt_profile| Create Ingress Load Balancer in GCP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Create a Load Balancer in GCP that points to the WAN interface of your firewalls. A Network Load Balancer can terminate any kind of application. a. Click **Create Load Balancer** on the Load balancing page. |gcp_create_lb_1| b. Select TCP Load Balancing > Start Configuration. |gcp_create_lb_2| c. Select the load balancer options as shown below: **From Internet to my VMs**, **Single region only**, and **Target Pool or Target Instance**. |gcp_create_lb_3| d. Enter a Name and select a Region (must match Transit FireNet’s region), click **Select Existing Instances** and select the firewall instances. |gcp_create_lb_4| e. In the Health Check area, create a health probe for the Load Balancer. Use port 80 and enter this path: /php/login.php. This path must be set for the health probe to succeed. Click **Save**. |gcp_create_lb_5| f. Click **Frontend configuration** on the Load Balancer Page and set up a frontend for the ingress public IP. - Set up one frontend per application (or per public IP needed). - Specify the port needed for the application. Note that you cannot modify this port later, so if you are unsure, set up 1-65535 as this allows all ports to be forwarded to the firewall for this IP address. - Click **Create** to create the load balancer. |gcp_create_lb_6| Set up Firewalls for Ingress Application Traffic ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Create NAT Rules ------------------ Now that the load balancer is created, you must create a NAT rule for the firewall to answer those probes destined for the frontend IP address of the load balancer. In the firewall UI, create a DNAT rule for each frontend IP, to ensure that the health check will work. Next, create a DNAT/SNAT rule for each application to DNAT/SNAT traffic to the actual application IP in the Spoke. The following screenshot shows an example for these rules. This example uses the following parameters: - Fronted IP: 172.16.58.3 - Ingress application port: 80 (this must always be 80 for the health probe NAT rule) - Firewall’s WAN interface IP address: 10.0.1.19 - Application IP in spoke: 10.0.2.18 You need to SNAT traffic to the firewall’s LAN port to make sure returning traffic hits the same firewall. Make sure you always add the health probe NAT rule above the ingress app rule, as that is more specific in case the application and the health probe use the same port. |palo_alto_dnat_1| Update Firewall Policy ------------------------ - Update the security policy on the firewall to enable access to the Frontend IP address of your load balancer from the health probe address (169.254.169.254) using HTTP (this will be the original health probe packet). - Set up the firewall's security policy to enable the application ingress traffic. Set up GCP Firewall Rules for Ingress ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Add an ingress firewall rule to the GCP firewall to allow ingress traffic to the firewall for the application. Use the tag avx-<egress_vpc_name>-gbl for matching the firewall instances. Allow the application’s port from 0.0.0.0/0 in. - Use the name of your egress VPC as a parameter in the tag's <egress_vpc_name>. In the example below the egress VPC name is "gcp-fw-egress-vpc" resulting in the tag name of "avx-gcp-fw-egress-vpc-gbl". |gcp_fwrule_ingress| |gcp_fwrule_ingress_2| Validate the Setup ~~~~~~~~~~~~~~~~~~~~ Check that the load balancer in the GCP console shows the backend as healthy for the firewalls. Note that when you reboot a firewall, it might take up to 30 minutes to respond to health checks on port 80. |gcp_health_check| Initiate traffic from the Internet toward your application hosted in the spoke VPC. To do so, use the frontend IP address of the load balancer you created and the defined frontend port. Your application should respond. .. |gcp_ingress| image:: ingress_protection_gcp_transit_firenet_pan_media/gcp_ingress.png :scale: 50% .. |enable_egress1| image:: ingress_protection_gcp_transit_firenet_pan_media/enable_egress1.png :scale: 50% .. |enable_egress2| image:: ingress_protection_gcp_transit_firenet_pan_media/enable_egress2.png :scale: 50% .. |gcp_be_lb_health| image:: ingress_protection_gcp_transit_firenet_pan_media/gcp_be_lb_health_status.png :scale: 60% .. |gcp_create_lb_1| image:: ingress_protection_gcp_transit_firenet_pan_media/gcp_create_lb_1.png :scale: 50% .. |gcp_create_lb_2| image:: ingress_protection_gcp_transit_firenet_pan_media/gcp_create_lb_2.png :scale: 50% .. |gcp_create_lb_3| image:: ingress_protection_gcp_transit_firenet_pan_media/gcp_create_lb_3.png :scale: 50% .. |gcp_create_lb_4| image:: ingress_protection_gcp_transit_firenet_pan_media/gcp_create_lb_4.png :scale: 50% .. |gcp_create_lb_5| image:: ingress_protection_gcp_transit_firenet_pan_media/gcp_create_lb_5.png :scale: 50% .. |gcp_create_lb_6| image:: ingress_protection_gcp_transit_firenet_pan_media/gcp_create_lb_6.png :scale: 50% .. |gcp_fwrule_ingress| image:: ingress_protection_gcp_transit_firenet_pan_media/gcp_fwrule_ingress.png :scale: 50% .. |gcp_fwrule_ingress_2| image:: ingress_protection_gcp_transit_firenet_pan_media/gcp_fwrule_ingress_2.png :scale: 50% .. |gcp_health_check| image:: ingress_protection_gcp_transit_firenet_pan_media/gcp_health_check.png :scale: 50% .. |palo_alto_dnat_1| image:: ingress_protection_gcp_transit_firenet_pan_media/palo_alto_dnat_1.png :scale: 50% .. |palo_alto_mgmt_profile| image:: ingress_protection_gcp_transit_firenet_pan_media/palo_alto_mgmt_profile.png :scale: 50% .. |palo_alto_mfmt_profile_details| image:: ingress_protection_gcp_transit_firenet_pan_media/palo_alto_mgmt_profile_details.png :scale: 50% .. disqus:: <file_sep> ========================================== Prerequisites for a Transit Network in AWS ========================================== Setting up a transit network in AWS is simple with `Aviatrix's Transit Network Workflow <http://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_. Before getting started with this workflow, make sure you have the following: #. **Transit VPC** | This is a VPC where your spokes will connect to transit to your on-premise environment. When setting up a new transit network architecture, this VPC is typically a new VPC. #. **Detached Virtual Private Gateway (VGW)** | This VGW is detached from any VPC and will remain detached. It is (or will be) connected to your on-premise environment via a Direct Connect or VPN connection. #. **Spoke VPC(s)** | These VPCs will make up the spoke(s) of the transit network. |image1| Transit VPC ########### The following AWS components should be created when setting up the transit VPC: * An internet gateway (IGW) [**igw-transit**] for the VPC. * A route table [**rt-transit-pub**] with a 0.0.0.0/0 route pointing to **igw-transit**. * One subnet with **rt-transit-pub** attached. * (Optional - HA) One subnet with **rt-transit-pub** attached in a different AZ. .. tip:: Use `Useful Tools -> Create a VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ to create a transit VPC. Make sure the option "Aviatrix Transit VPC" is selected. Virtual Private Gateway (VGW) ############################## Create a new VGW that will terminate your Direct Connect VIF or VPN connection to on-prem. Leave this VGW **detached** (it will be attached as part of the Transit Network Workflow). Spoke VPC(s) ############ The following AWS components should be created for each spoke VPC: * An internet gateway (IGW) [**igw-spoke-1**] for the VPC. * A route table [**rt-spoke-1-pub**] with a 0.0.0.0/0 route pointing to **igw-spoke-1**. * One subnet with **rt-spoke-1-pub** attached. * (Optional - HA) One subnet with **rt-spoke-1-pub** attached in a different AZ. * Any number of private subnets in any AZ in the VPC. Additional Information ###################### * `VPC with a public subnet <https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Scenario1.html>`__ (AWS Documentation) .. |image1| image:: transit_spoke_aws_requirements/transit_plus_spoke.png <file_sep> Enable SAML App for a group of users in G-Suite using Organization ------------------------------------------------------------------- 1. Follow `Google Idp for SAML Integration <https://docs.aviatrix.com/HowTos/SAML_Integration_Google_IdP.html#google-idp-for-saml-integration##openvpn-with-saml-authentication-on-okta-idp>`_ to create a **SAMLVPN** application. 2. Repeat the following steps to create users in G-suite Google Admin console and leave them under the root organization. 2.1. Go to G-suite Google Admin console, select **Users**. |g-suite-admin-users| 2.2. Click **Add new user**. |add-new-user-button| 2.3. Enter user information. In this example, **Aviatrix Support** is the root organization. |add-new-user| 2.4. Click **DONE**. |new-user-added| 3. Define a sub-organization **saml access org** within your root organization. 3.1. At G-suite Google Admin console, select **Organizational units**. |g-suite-admin| 3.2. Click **+** to add a new organization under your root organization. |manage-org| 3.3 Create a sub-organization, e.g., **saml access org**. |create-org| |saml-access-org| 4. Turn on **SAMLVPN** application for **saml access org**. 4.1. Go back to G-suite Google Admin console and select **Apps**. |g-suite-admin-apps| 4.2. Select **SAML apps**. |apps-settings| 4.3. Select the **SAMLVPN** App created in step 1. |saml-vpn-apps| 4.4. Click **EDIT SERVICE** to enable/disable **SAMLVPN** app for the selected organization. |open-SAMLVPN| 4.5. Turn off **SAMLVPN** for root organization (**Aviatrix Support**). |disable-SAMLVPN-rootorg| 4.6. Turn on **SAMLVPN** for **saml access org**. |enable-SAMLVPN-suborg| 5. Assign users to **SAMLVPN** app by moving users into **saml access org**. 5.1. Go back to G-suite Google Admin console and select **Users**. |g-suite-admin-users| 5.2. Select the user for SAMLVPN app (e.g., <NAME>) and click **Change organizational unit**. |change-org-button| 5.3. Select **saml access org**. |change-org-unit| 5.4. Confirm the change. |confirm-org-change| 5.5. Review the change. |select-dan-smith| |reopen-2-confirm-org| .. |g-suite-admin-users| image:: SSL_VPN_Google_SAML_Organization_media/g-suite-admin-console-users.png :scale: 70% .. |add-new-user-button| image:: SSL_VPN_Google_SAML_Organization_media/add-new-user-button.png :scale: 70% .. |add-new-user| image:: SSL_VPN_Google_SAML_Organization_media/add-new-user.png :scale: 70% .. |new-user-added| image:: SSL_VPN_Google_SAML_Organization_media/new-user-added.png :scale: 70% .. |g-suite-admin| image:: SSL_VPN_Google_SAML_Organization_media/g-suite-admin-console.png :scale: 70% .. |manage-org| image:: SSL_VPN_Google_SAML_Organization_media/organization-management.png :scale: 70% .. |create-org| image:: SSL_VPN_Google_SAML_Organization_media/create-organization.png :scale: 70% .. |saml-access-org| image:: SSL_VPN_Google_SAML_Organization_media/saml-access-org.png :scale: 70% .. |saml-vpn-apps| image:: SSL_VPN_Google_SAML_Organization_media/saml-vpn-apps.png :scale: 70% .. |g-suite-admin-apps| image:: SSL_VPN_Google_SAML_Organization_media/g-suite-admin-console-apps.png :scale: 70% .. |apps-settings| image:: SSL_VPN_Google_SAML_Organization_media/apps-settings.png :scale: 70% .. |open-SAMLVPN| image:: SSL_VPN_Google_SAML_Organization_media/open-SAMLVPN.png :scale: 70% .. |disable-SAMLVPN-rootorg| image:: SSL_VPN_Google_SAML_Organization_media/disable-SAMLVPN-rootorg.png :scale: 70% .. |enable-SAMLVPN-suborg| image:: SSL_VPN_Google_SAML_Organization_media/enable-SAMLVPN-suborg.png :scale: 70% .. |change-org-button| image:: SSL_VPN_Google_SAML_Organization_media/change-org-button.png :scale: 70% .. |change-org-unit| image:: SSL_VPN_Google_SAML_Organization_media/change-org-unit.png :scale: 70% .. |confirm-org-change| image:: SSL_VPN_Google_SAML_Organization_media/confirm-org-change.png :scale: 70% .. |select-dan-smith| image:: SSL_VPN_Google_SAML_Organization_media/select-dan-smith.png :scale: 70% .. |reopen-2-confirm-org| image:: SSL_VPN_Google_SAML_Organization_media/reopen-2-confirm-org.png :scale: 70% .. disqus:: <file_sep> ============================================ Aviatrix Gateway to Check Point(R77.30) ============================================ This document describes how to build an IPsec tunnel based Site2Cloud connection between Aviatrix Gateway and Check Point Firewall. To simulate an on-prem Check Point Firewall, we use a Check Point CloudGuard IaaS firewall VM at AWS VPC. .. note:: If you do not have access to AWS, you can simulate an on-prem Firewall by deploying the Palo Alto Firewall in any other cloud (such as Microsoft Azure, Google Cloud Platform, or Oracle Cloud Infrastructure). The network setup is as follows: **VPC1 (with Aviatrix Gateway)** *VPC1 CIDR: 10.0.0.0/16* *VPC1 Public Subnet CIDR: 10.0.1.0/24* *VPC1 Private Subnet CIDR: 10.0.2.0/24* **VPC2 (with Check Point Security Gateway)** *VPC2 CIDR: 10.10.0.0/16* *VPC2 Public Subnet CIDR: 10.10.0.0/24* *VPC2 Private Subnet CIDR: 10.10.1.0/24* Launching Check Point Security Gateway VM ============================================ Refer to the `vSEC Gateway for Amazon Web Services Getting Started Guide <http://supportcontent.checkpoint.com/documentation_download?ID=45816>`_ to launch a CheckPoint VM with at least two network interfaces. One interface serves as a WAN port and is in VPC2's public subnet. The other interface serves as a LAN port and is in VPC2's private subnet. Collect the public IP address of the WAN port. Creating a Site2Cloud Connection at Aviatrix Controller ====================================================== 1. Go to Gateway > New Gateway to launch an Aviatrix Gateway at VPC1's public subnet. Collect both public and private IP addresses of the Gateway. 2. Go to Site2Cloud and click **Add New** to create a Site2Cloud connection: =============================== ================================================================= **Field** **Value** =============================== ================================================================= VPC ID/VNet Name Choose VPC ID of VPC1 Connection Type Unmapped Connection Name Arbitrary (e.g. avx-cp-s2c) Remote Gateway Type Generic Tunnel Type UDP Algorithms Unmark this checkbox Encryption over DirectConnect Unmark this checkbox Enable HA Unmark this checkbox Primary Cloud Gateway Select Aviatrix Gateway created above Remote Gateway IP Address Public IP of CheckPoint-VM WAN port Pre-shared Key Optional (auto-generated if not entered) Remote Subnet 10.10.1.0/24 (VPC2 private subnet) Local Subnet 10.0.2.0/24 (VPC1 private subnet) =============================== ================================================================= 3. Go to the Site2Cloud page. From the Site2Cloud connection table, select the connection created above (e.g. avx-cp-s2c). Select **Generic** from the Vendor dropdown list and click **Download Configuration** to download the Site2Cloud configuration. Save the configuration file for configuring CheckPoint-VM. Downloading and Installing SmartConsole ====================================== 1. Using a browser, connect to the Gaia Portal of the CheckPoint-VM at https://CheckPoint-VM_Public-IP: 2. Click **Overview** at the left navigation bar, and then click **Download Now!** to download SmartConsole. |image0| 3. Install SmartConsole at your local machine and launch SmartDashboard. Creating Network Objects at SmartConsole ========================================= 1. At the Check Point SmartDashboard window, select the **Desktop** tab. Right click the **Networks** folder at the left navigation bar and select **Network**. 2. Create one network for private subnet of VPC2 (Check Point VPC). |image1| =============================== ================================================================= **Field** **Value** =============================== ================================================================= Name Arbitrary (e.g. CP-Private-Subnet) IPv4 Network Address VPC2 private subnet CIDR IPv4 Net mask VPC2 private subnet mask =============================== ================================================================= 3. Create one network for private subnet of VPC1 (Aviatrix Gateway VPC). |image2| =============================== ================================================================= **Field** **Value** =============================== ================================================================= Name Arbitrary (e.g. AVX-Private-Subnet) IPv4 Network Address VPC1 private subnet CIDR IPv4 Net mask VPC1 private subnet mask =============================== ================================================================= Configuring Check Point Security Gateway with VPN ================================================== 1. At the SmartDashboard window, select the **Desktop** tab and expand the **Check Point** folder at the left navigation bar. Note that your gateway VM with the name format "gw-xxxxxx" is automatically created. |image3| 2. Right-click the gateway name and select **Edit** from the menu. 3. At the Check Point Gateway > General Properties window: |image4| =============================== ================================================================= **Field** **Value** =============================== ================================================================= IPv4 Address Private IP of CheckPoint VM WAN port Test SIC Status Make sure the status is "communicating" Network Security Select **IPsec VPN** =============================== ================================================================= 4. At **Check Point Gateway - Topology** window, select **Manually defined** for VPN Domain. Select the network created when you created a network for private subnet of VPC2 (Check Point VPC). |image5| 5. At **Check Point Gateway - Topology** window, double-click "eth0" (Check Point WAN port). Select **External (leads out to the Internet)**. |image6| 6. At **Check Point Gateway - Topology** window, double click "eth1" (Check Point LAN port). Select **Internal (leads to the local network)**. |image7| 7. At the **Check Point Gateway - IPsec VPN - Link Selection** window, configure the parameters as follows: |image8| ========================================= ======================================================= **Field** **Value** ========================================= ======================================================= Statically NATed IP Public IP of Check Point WAN port Selected address from topology table Private IP of Check Point WAN port ========================================= ======================================================= 8. At the **Check Point Gateway - IPsec VPN - VPN Advanced** window, configure the parameters as follows: |image9| Configuring an Interoperable Device to Represent Aviatrix Gateway ================================================================== 1. At Check Point SmartDashboard window, select the **Desktop** tab. Right-click the **Networks** folder at the left navigation bar to create a new interoperable device. 2. At the Interoperable Device - General Properties window: |image10| =============================== ================================================================= **Field** **Value** =============================== ================================================================= Name Arbitrary (e.g. AVX-GW) IPv4 Address Public IP of Aviatrix Gateway =============================== ================================================================= 3. At the **Interopable Device - Topology** window, select **Manually defined** for VPN Domain. Select the network private subnet of VPC1 (Aviatrix Gateway VPC) you created above. |image11| 4. At the **Interopable Device - IPsec VPN - Link Selection** window, select **Always use this IP address > Main Address**. |image12| 5. At the **Interopable Device - IPsec VPN - VPN Advanced** window, select **Use the community settings**. |image13| Creating a VPN Community ========================== 1. At SmartDashboard **IPsec VPN** tab, select **Overview** from left navigation bar. Click **New** to create a Meshed Community. |image14| 2. At **Meshed Community Properties - General** window, create one community with a name (e.g. Site2Cloud-avx). |image15| 3. At **Meshed Community Properties - Participating Gateways** window, add both Check Point Security Gateway (e.g. gw-fe024c) and the interopable device created when you configured an interoperable device to represent the Aviatrix Gateway (e.g. AVX-GW) to this community. |image16| 4. At **Meshed Community Properties - Encryption** window, select the options according to the Site2Cloud configuration for configuring CheckPoint-VM you saved and downloaded above. |image17| 5. At **Meshed Community Properties - Tunnel Management** window, select **One VPN tunnel per Gateway pair** for **VPN Tunnel Sharing**. |image18| 6. At the **Meshed Community Properties - Advanced Settings - Shared Secret** window, enter **Shared Secret** by copying the **Pre-Shared Key** from the Site2Cloud configuration downloaded above. |image19| 7. At the **Meshed Community Properties - Advanced Settings - Advanced VPN Properties** window, enter the Phase1 and Phase2 parameters according to the Site2Cloud configuration downloaded above. |image20| Creating Firewall Rule for VPN Traffic ======================================= 1. At SmartDashboard window, select the **Firewall** tab. 2. Select **Policy** to add a new rule. |image21| =============================== ================================================================= **Field** **Value** =============================== ================================================================= VPN Select the Meshed VPN Community created above Install On Select Check Point Security Gateway =============================== ================================================================= 3. Click **Install Policy** button to push the firewall policy to the Check Point Security Gateway. |image22| Troubleshooting and Verifying at Check Point Security Gateway ================================================================ 1. At SmartDashboard window, from **SmartConsole** dropdown list, select **SmartView Monitor**. |image23| 2. At the SmartView Monitor window, select **VPNs** from **Gateway Status** and verify **Encrypted Traffic**. |image24| Troubleshooting and Verifying at Aviatrix Controller ======================================================== 1. At the Aviatrix Controller, go to the Site2Cloud page. Verify that the status of the Site2Cloud connection is up. |image25| 2. At the Site2Cloud - Diagnostics page, run various diagnostics commands. |image26| =============================== ================================================================= **Field** **Value** =============================== ================================================================= VPC ID/VNet Name VPC1 (Aviatrix Gateway VPC) ID Connection Name of Site2Cloud connection created above Gateway Name of Aviatrix Gateway Action One of the supported diagnostics commands =============================== ================================================================= For support, please open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_. .. |image0| image:: s2c_gw_cp_media/DownloadSmartConsole.PNG :width: 5.55625in :height: 3.26548in .. |image1| image:: s2c_gw_cp_media/Network1.PNG :width: 5.55625in :height: 3.26548in .. |image2| image:: s2c_gw_cp_media/Network2.PNG :width: 5.55625in :height: 3.26548in .. |image3| image:: s2c_gw_cp_media/Desktop-GW-Config.PNG :width: 5.55625in :height: 3.26548in .. |image4| image:: s2c_gw_cp_media/EditGW1.PNG :width: 5.55625in :height: 3.26548in .. |image5| image:: s2c_gw_cp_media/EditGW2.PNG :width: 5.55625in :height: 3.26548in .. |image6| image:: s2c_gw_cp_media/EditGW3.PNG :width: 5.55625in :height: 3.26548in .. |image7| image:: s2c_gw_cp_media/EditGW4.PNG :width: 5.55625in :height: 3.26548in .. |image8| image:: s2c_gw_cp_media/EditGW5.PNG :width: 5.55625in :height: 3.26548in .. |image9| image:: s2c_gw_cp_media/EditGW6.PNG :width: 5.55625in :height: 3.26548in .. |image10| image:: s2c_gw_cp_media/Interop1.PNG :width: 5.55625in :height: 3.26548in .. |image11| image:: s2c_gw_cp_media/Interop2.PNG :width: 5.55625in :height: 3.26548in .. |image12| image:: s2c_gw_cp_media/Interop3.PNG :width: 5.55625in :height: 3.26548in .. |image13| image:: s2c_gw_cp_media/Interop4.PNG :width: 5.55625in :height: 3.26548in .. |image14| image:: s2c_gw_cp_media/Community1.PNG :width: 5.55625in :height: 3.26548in .. |image15| image:: s2c_gw_cp_media/Community2.PNG :width: 5.55625in :height: 3.26548in .. |image16| image:: s2c_gw_cp_media/Community7.PNG :width: 5.55625in :height: 3.26548in .. |image17| image:: s2c_gw_cp_media/Community3.PNG :width: 5.55625in :height: 3.26548in .. |image18| image:: s2c_gw_cp_media/Community4.PNG :width: 5.55625in :height: 3.26548in .. |image19| image:: s2c_gw_cp_media/Community5.PNG :width: 5.55625in :height: 3.26548in .. |image20| image:: s2c_gw_cp_media/Community6.PNG :width: 5.55625in :height: 3.26548in .. |image21| image:: s2c_gw_cp_media/FW1.PNG :width: 5.55625in :height: 3.26548in .. |image22| image:: s2c_gw_cp_media/FW2.PNG :width: 5.55625in :height: 3.26548in .. |image23| image:: s2c_gw_cp_media/CPMonitor1.PNG :width: 5.55625in :height: 3.26548in .. |image24| image:: s2c_gw_cp_media/CPMonitor2.PNG :width: 5.55625in :height: 3.26548in .. |image25| image:: s2c_gw_cp_media/AVXMonitor1.PNG :width: 5.55625in :height: 3.26548in .. |image26| image:: s2c_gw_cp_media/AVXMonitor2.PNG :width: 5.55625in :height: 3.26548in .. disqus:: <file_sep> ===================================== Aviatrix CoPilot User Reference Guide ===================================== .. important:: This content has moved. Please see `Aviatrix CoPilot Product Documentation <https://docs.aviatrix.com/copilot/latest/index.html>`_ for CoPilot user reference information. <file_sep> ========================================================= Bootstrap Configuration Example for VM-Series in Azure ========================================================= Using the bootstrap option significantly simplifies VM-Series initial configuration setup. In this document, we provide a bootstrap example to set up an to allow HTTPS for Health Check Policy , "Allow All" firewall Policy and Egress NAT policy for the VM-Series to validate that traffic is indeed sent to the VM-Series for VNet-to-VNet traffic inspection. This example does not use Panorama. Please use 9.1.0 and above version for better results. Note that Panorama PAN-OS version should be the same or higher than the firewall VMs when they are added to the Panorama, like, 9.1.0 for both Panorama and VMs. For a manual setup, follow `manual setup example <https://docs.aviatrix.com/HowTos/config_PaloAltoAzure.html>`_. Creating a Storage Account and Private Container --------------------------------------------------------------- Log in to Azure's console and create a storage account and file share in the storage for bootstrap with a **unique** name, for example "pan bootstrap", using this `guide <https://docs.paloaltonetworks.com/vm-series/9-1/vm-series-deployment/bootstrap-the-vm-series-firewall/bootstrap-the-vm-series-firewall-in-azure.html>`_ Step 1 and 2 with the following structure: :: Storage Account (e.g. bootstrapstorage) File Share (e.g. pan-bootstrap) Config/ init-cfg.txt bootstrap.xml Content License Software |file-share-folder-example| Uploading Config Files ----------------------------------- Follow `Step 2.3 <https://docs.paloaltonetworks.com/vm-series/9-1/vm-series-deployment/bootstrap-the-vm-series-firewall/bootstrap-the-vm-series-firewall-in-azure.html>`_ to upload the configuration. Example Bootstrap.xml and config file is provided below. 1. The example bootstrap.xml file contains the "Allow All," Egress and API admin setup. To download the file, click :download:`bootstrap.xml <bootstrap_example_media/bootstrap-azure.xml>`. 2. For the example init-cfg.txt file, click :download:`init-cfg.txt <bootstrap_example_media/init-cfg.txt>`. .. Note:: In the example bootstrap.xml, you must specify custom usernames and passwords for the <https_interface_admin_username> and <api_admin_username>, and generate hash strings for the passwords. *3. Upload these two files to your config folder under Storage Account > File Shares. Launching the VM-Series Instance ---------------------------------------------- First follow `Step 3 <https://docs.paloaltonetworks.com/vm-series/9-1/vm-series-deployment/bootstrap-the-vm-series-firewall/bootstrap-the-vm-series-firewall-in-azure.html>`_ to get an access key which will be required at a time of VM-Series launch. Follow `this step <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#launching-and-associating-firewall-instance>`_ of the Aviatrix Firewall Network (FireNet) workflow. Fill in the required fields. Click **Advanced**. Fill in the following parameters. ================================ ====================== **Advanced Field** **Example Value** ================================ ====================== Bootstrap Storage Name Azure Storage Name (e.g. bootstrapstorage) Storage Access Key Azure Storage key (e.g. <KEY>) File-share Folder File Share Folder Name (e.g. pan-bootstrap) Share-directory (Optional) Config (Optional) ================================ ====================== Launch the VM-Series instance. Wait for 15 minutes for it to boot up and initialize. Login to the HTTPS interface of VM-Series management public IP with the username and password specified in the bootstrap.xml file. Configuring API Vendor Integration ----------------------------------------------------- In order for the Aviatrix Controller to automatically update firewall instance route tables, monitor the firewall instance health and manage instance failover, you need to setup API access permissions. Go to Controller > Firewall Network > Vendor Integration > Firewall. Note the following fields. - In the Firewall Login User Name field, use the username specified in the bootstrap.xml file. - In the Firewall Login Password field, use the password specified in the bootstrap.xml file. If you are manually configuring the firewall from scratch, follow `the instructions here <https://docs.aviatrix.com/HowTos/paloalto_API_setup.html>`_ to enable API access. Ready to Go ------------------- Now your firewall instance is ready to receive packets. The next step is to validate your configurations and polices using FlightPath and Diagnostic Tools (ping, traceroute etc.). Viewing the Traffic Log -------------------------------- You can view if traffic is forwarded to the firewall instance by logging in to the VM-Series console. Click **Monitor**. Start ping packets from one Spoke VNet to another Spoke VNet. Additional References ------------------------------------ Following links from Palo Alto Networks for PAN-OS 8.1 and 9.0 provides additional information. `Create the init-cfg.txt File <https://docs.paloaltonetworks.com/vm-series/9-0/vm-series-deployment/bootstrap-the-vm-series-firewall/create-the-init-cfgtxt-file.html#id8770fd72-81ea-48b6-b747-d0274f37860b>`_ `Bootstrap the VM-Series Firewall in Azure 9.1 <https://docs.paloaltonetworks.com/vm-series/9-1/vm-series-deployment/bootstrap-the-vm-series-firewall/bootstrap-the-vm-series-firewall-in-azure.html>`_ .. |file-share-folder-example| image:: bootstrap_example_media/file-share-folder-example.png :scale: 40% .. disqus:: <file_sep> =========================================================== Alibaba Cloud Account Credential Setup =========================================================== Creating an Alibaba Primary Access Account ===================================================== 1. Access your Alibaba account info in the Alibaba UI. Click on the User Icon so you can access the Alibaba Cloud Account ID, Cloud Access Key ID, and Cloud Secret Key. You need the Alibaba account information to create the Alibaba Primary Access Account in the Aviatrix Controller. |alibaba_user_icon| 2. In the Alibaba UI, create an AccessKey pair for authenticating the Aviatrix Controller. Click on the User Icon and navigate to AccessKey Management > Create Access Key. |alibaba_accesskey| 3. In the Aviatrix Controller, navigate to Accounts > Access Accounts and select Alibaba Cloud. Add an Account Name and enter the Alibaba Cloud Account ID, Cloud Access Key ID, and Cloud Secret Key. Optional - add any RBAC Groups that should have access to the Primary Access Account. Deploying the Aviatrix Gateway in your Alibaba Cloud ===================================================== You must satisfy the prerequisites in “Creating an Alibaba Primary Access Account” before Deploying the Aviatrix Gateway in your Alibaba Cloud. 1. Access your Alibaba account info in the Alibaba UI. Click on the User Icon and record your Alibaba Account ID. 2. Communicate your Alibaba Account ID to your Aviatrix Support representative. 3. Your Aviatrix Support representative shares the Aviatrix gateway image with your Alibaba account. 4. Verify your Alibaba account can access the Aviatrix gateway image. Go to Elastic Compute Service > Instances & Images > Images > Shared Image to view the image. |alibaba_share_image| 5. Create an Alibaba Primary Access Account in the Aviatrix Controller. 6. Deploy the Aviatrix Gateway in the Alibaba cloud. Alibaba Cloud Default Limitations ================================= - The EIP bandwidth limit is 200 Mbit/s. The Aviatrix Spoke to Transit and Transit to Spoke connections maximum bandwidth is 400 Mbit/s. You can purchase different plans to increase throughput and bandwidth. - A maximum of 48 routes in each route table is supported by default. If you require more routes in each route table, contact Alibaba Support. - The Alibaba API takes 1-2 seconds to add or delete one route in one VPC route table. No route update requests are accepted while a route is being added or deleted. - Outgoing traffic to public non-RFC1918 IP address from an instance with a public IP does not look at the VPC route table. Even non-RFC1918 routes are configured on VPC route table. If you want to improve this non-RFC1918 traffic routing behavior on public instance, contact Alibaba Support. .. |alibaba_user_icon| image:: aviatrix_account_alibaba_media/alibaba_user_icon.png :scale: 50% .. |alibaba_accesskey| image:: aviatrix_account_alibaba_media/alibaba_accesskey.png :scale: 50% .. |alibaba_share_image| image:: aviatrix_account_alibaba_media/alibaba_share_image.png :scale: 50% .. disqus:: <file_sep>========================================================= External Device to Palo Alto VM-Series ========================================================= This document describes how to build Transit connection between Aviatrix Transit Gateway and Palo Alto Networks Firewall. To simulate an on-prem Firewall, we use a VM-Series in an AWS VPC. Network setup is as following: VPC1 (with Aviatrix Transit Gateway) VPC1 CIDR: 10.5.0.0/16 VPC1 Public Subnet CIDR: 10.5.3.0/24 VPC1 Private Subnet CIDR: 10.5.2.0/24 VPC2 (with Palo Alto Networks VM-series) VPC2 CIDR: 10.0.0.0/16 VPC2 Public Subnet CIDR: 10.0.0.0/24 VPC2 Private Subnet CIDR: 10.0.1.0/24 Sample subnet advertised with the help of BGP - 192.168.0.24/32(loopback interface on PaloAlto) Configuration WorkFlow: 1. From the Controller go to Transit Network -> Setup -> Launch a Transit VPC GW. |image1| 2. Connect the transit VPC GW to Palo Alto. Go to Transit Network -> Setup -> Connect to VGW/External Device. Select External Device and input the following parameters. a. BGP Local AS number: ASN of the transit VPC GW b. BGP Remote AS number: ASN of the Palo Alto c. Remote Gateway IP Address: Palo Alto WAN interface public IP. |image2| .. note:: If using private IP as remote gateway IP, please make sure to check "Over DirectConnect". 3. Download the configuration by going to Site2Cloud -> Click on the Connection. Select generic and Download Configuration and configure on the router accordingly. |image3| The following is a sample configuration based on the site2cloud configuration above. |image4| 4. Log into Palo Alto Networks VM Series and configure it as following: a. Go to **Network > Interface > Tunnel**, click **Add** to create a new tunnel interface and assign the following parameters. |image5| =============================== ====================================== **Field** **Value** =============================== ====================================== Interface Name tunnel.45(any name) Virtual Router Select the existing **default** virtual router Security Zone Select the layer 3 internal zone from which traffic originates =============================== ====================================== .. note:: If the tunnel interface is in a zone different from the one where the traffic will originate, a policy needs to be created to allow the traffic to flow from the source zone to the zone containing the tunnel interface. For the tunnel created above assign the IP address by going to Network > Interface > IPv4 > assign the tunnel IP address from the configuration downloaded above. |image6| b. Go to **Network > Network Profiles > IKE Crypto**, click **Add** and define the IKE Crypto profile (IKEv1 Phase-1) parameters. |image7| c. Go to **Network > Network Profiles > IKE Gateways** to configure the IKE Phase-1 Gateway. These parameters should match on the site2cloud configuration downloaded at Step 4. |image8| =============================== ========================================= **Field** **Value** =============================== ========================================= Interface Palo Alto Networks WAN port Peer IP Address Aviatrix Gateway public IP Pre-shared Key Key from site2cloud configuration downloaded at Step 3 Peer Identification IP Address & Aviatrix Gateway public IP =============================== ========================================= .. note:: If using remote private IP on Step 2, Peer IP Address should be the remote private IP while Peer Identification should be remote public IP. |image9| =============================== ========================================= **Field** **Value** =============================== ========================================= IKE Crypto Profile Select the profile created at Step 4.b =============================== ========================================= d. Under **Network > Network Profiles > IPSec Crypto**, click **Add** to create a new profile. Define the IPSec crypto profile (IKEv1 Phase-2). These parameters should match on the site2cloud configuration downloaded at Step 4. |image10| e. Under **Network > IPSec Tunnels**, click **Add** to create a new IPSec Tunnel. At **General** window: |image11| =============================== ========================================= **Field** **Value** =============================== ========================================= Tunnel Interface Tunnel interface created at Step 4.a IKE Gateway IKE gateway created at Step 4.c IPSec Crypto Profile IPSec crypto profile created at Step 4.d =============================== ========================================= Note: There is no need to configure proxy-id f. Commit the configuration. We should see the IPSec tunnel is up in green. |image23| 5. Steps to configure BGP: a. Go to Network > Virtual Routers Default > BGP > peer group click add give any name(e.g bgppeering) and then click on the left bottom to add BGP peer |image13| b. Add Peer > Created name > Enter the Peer AS > Local address: tunnel interface and Tunnel interface IP address > Peer address: remote tunnel address |image14| |image15| c. After everything is created, the output looks like below, and Commit the configuration. Router ID is taken from the config file downloaded.(it should be the IP address of the tunnel created ) |image16| d. Create a redistribution profile: Network -> default -> Redistribution Profile -> Add -> Name: redis -> check Redist -> Source Type: connect |image12| e. Next click on redistribution rules and do the following: Network -> default -> BGP -> Redistribution Rules -> Click on Add -> select "redis" |image18| f. Configure Export: Select Export, Add a name in the Rules field, and Enable the Export rule. Add the Peer Group from which the routes will be imported. Select Match and define the options used to filter routing information. |image19| g. After the BGP route has been advertised it shows like the following image. Go to Network -> More runtime stats -> BGP -> RIB out. |image20| 6. At AWS portal, configure the VPC Route Table associated with the private subnet of VPC2. Add a route destinating to VPC1 private subnet with Palo Alto Networks VM LAN port as the gateway. 7. Go to Transit Network -> Advanced Config on the Controller and Click on Diagnostics and select the GW name from the dropdown list and select Show Ip bgp Command from the predefined Show list to verify the BGP Routes. |image22| .. |image1| image:: ./Transit_ExternalDevice_PaloAlto_media/1.png :width: 5.55625in :height: 3.26548in .. |image2| image:: ./Transit_ExternalDevice_PaloAlto_media/2.png :width: 7.00000 in :height: 5.00000 in .. |image3| image:: ./Transit_ExternalDevice_PaloAlto_media/3.png :width: 5.55625in :height: 3.26548in .. |image4| image:: ./Transit_ExternalDevice_PaloAlto_media/4.png :width: 7.00000 in :height: 5.00000 in .. |image5| image:: ./Transit_ExternalDevice_PaloAlto_media/5.png :width: 5.55625in :height: 3.26548in .. |image6| image:: ./Transit_ExternalDevice_PaloAlto_media/6.png :width: 5.55625in :height: 3.26548in .. |image7| image:: ./Transit_ExternalDevice_PaloAlto_media/7.png :width: 5.55625in :height: 3.26548in .. |image8| image:: ./Transit_ExternalDevice_PaloAlto_media/8.png :width: 5.55625in :height: 3.26548in .. |image9| image:: ./Transit_ExternalDevice_PaloAlto_media/9.png :width: 5.55625in :height: 3.26548in .. |image10| image:: ./Transit_ExternalDevice_PaloAlto_media/10.png :width: 5.55625in :height: 3.26548in .. |image11| image:: ./Transit_ExternalDevice_PaloAlto_media/11.png :width: 5.55625in :height: 3.26548in .. |image12| image:: ./Transit_ExternalDevice_PaloAlto_media/bgp11.png :width: 5.55625in :height: 3.26548in .. |image13| image:: ./Transit_ExternalDevice_PaloAlto_media/bgp1.png :width: 7.00000 in :height: 5.00000 in .. |image14| image:: ./Transit_ExternalDevice_PaloAlto_media/13.png :width: 7.00000 in :height: 5.00000 in .. |image15| image:: ./Transit_ExternalDevice_PaloAlto_media/bgp3.png :width: 7.00000 in :height: 5.00000 in .. |image16| image:: ./Transit_ExternalDevice_PaloAlto_media/bgp4.png :width: 7.00000 in :height: 5.00000 in .. |image18| image:: ./Transit_ExternalDevice_PaloAlto_media/bgp12.png :width: 5.55625in :height: 3.26548in .. |image19| image:: ./Transit_ExternalDevice_PaloAlto_media/bgp7.png :width: 7.00000 in :height: 5.00000 in .. |image20| image:: ./Transit_ExternalDevice_PaloAlto_media/bgp8.png :width: 7.00000 in :height: 5.00000 in .. |image21| image:: ./Transit_ExternalDevice_PaloAlto_media/bgp9.png :width: 7.00000 in :height: 5.00000 in .. |image22| image:: ./Transit_ExternalDevice_PaloAlto_media/bgp10.png :width: 7.00000 in :height: 5.00000 in .. |image23| image:: ./Transit_ExternalDevice_PaloAlto_media/14.png :width: 5.55625 in :height: 1.50000 in <file_sep> ###################################################### External PKI for OpenVPN Certificates ###################################################### **How to deploy a Certificate-based SSL VPN Server** The Aviatrix OpenVPN solution provides certificate-based SSL VPN user authentication in addition to other multi-factor authentication methods such as DUO, Okta, SAML and LDAP. This document describes the process of allowing users to connect to your Cloud instances via OpenVPN when the external PKI mechanism is used. Pre-requisites: Obtain the CA certificate, server certificate (for the OpenVPN gateway) and server key from your administrator. The CA certificate will be used to sign the server certificate and user certificate. Your CA certificate will need to contain the CRL Distribution Point URI or you can manually enter it during the configuration steps. Please note that once you enable the feature, it cannot be disabled. Please test the feature on a separate controller before trying it on a production environment. **Note: Certificates, key, and CRL will need to be in PEM format.** **Configuration steps:** 1. From the Aviatrix Controller, go to Settings > Advanced > Certificates page to make sure Certificates Checking is disabled. 2. Go to OpenVPN > Certificate. Choose the corresponding files for the CA Certificate, Server Certificate, and Server Key. 3. If your CA Certificate does not contain the CRL information, enter the CRL Distribution Point URI and the CRL Update Interval. By default, the CRL Update Interval is 60 minutes. 4. Click **Import** to complete the process. 5. Go to the Gateway page and click **+New Gateway** to create a new gateway. This new gateway will be created with those certificates and keys imported. Please refer to http://docs.aviatrix.com/HowTos/uservpn.html on how to create a gateway. 6. Upon successful gateway creation, go to the OpenVPN > Certificate page. 7. In the Download VPN Configuration box, select the VPC ID (where your gateway was created) and the LB Name. Click **Download** to obtain the OVPN file (for example None.ovpn).  Please note: Uploading the certificate files (ca.crt, server.key, server.crt crl uri) again will not update the certificates on gateways that are already deployed. **Client OVPN file** For each OpenVPN client, you will need to generate a certificate signed by the CA private key. Note that the CSR for the certificate must have the key usage attribute set to “e0” and the directive must be set to “TLS Web Client Authentication". X509v3 Key Usage e0 stands for Digital Signature, Non Repudiation, Key Encipherment should be enabled (No more, no less). With your client certificate and client key ready, edit the None.ovpn with a text editor. At the bottom of the None.ovpn, insert your client certificate and client key and save the file. -----END OpenVPN Static key V1----- </tls-auth> <cert> CLIENT-CERT                        << Replace your client certificate here </cert> <key> CLIENT-KEY                          << Replace your client key here </key>   Now your None.ovpn is ready for use. Download and install OpenVPN client on your laptop. Download links:  1. For Windows users, download the OpenVPN client from this link:        http://openvpn.net/index.php/open-source/downloads.html       Instructions: \ https://openvpn.net/index.php/open-source/documentation/howto.html 2. For MAC users, download Tunnelblick from this link:     `https://tunnelblick.net <https://tunnelblick.net/>`__       Instructions: https://openvpn.net/index.php/access-server/docs/admin-guides/183-how-to-connect-to-access-server-from-a-mac.html Once your OpenVPN client is installed, you can use the None.ovpn to connect to your SSL OpenVPN gateway. The common name field in the certificate will be used by the Controller to identify the user. **Sample scripts** The scripts provided here help you to generate client certificates with the correct attributes set: https://s3-us-west-2.amazonaws.com/aviatrix-download/PKI/scripts.zip Instructions are present in the zip file. Sample certificates for reference https://s3-us-west-2.amazonaws.com/aviatrix-download/PKI/sample_certs.zip To view the certificate information(Key usage bits) you can use: openssl x509 -in client.crt -text -noout You need to expose the crl.pem over HTTP/HTTPS to the Aviatrix Controller and Gateway so that they can retrieve them via URL. **Profiles** If you wish to use the profiles feature, you need to add users in the controller (OpenVPN > VPN Users). The username should match the common Name field in the client certificate. Note that you cannot add email here during user addition since certificates are generated externally. You can now associate these users to profiles under OpenVPN > Profiles. .. add in the disqus tag .. disqus:: <file_sep> ================================= Netflow Integration ================================= Aviatrix gateways can forward `Netflow <https://en.wikipedia.org/wiki/NetFlow>`_ data to your designated service point. Netflow v5 and v9 both are supported on gateways and cloudN. To enable Netflow, go to Aviatrix Controller's console -> click "Settings" on the main navigation bar -> click "Logging" -> scroll down to "Netflow Agent". Input the IP address and the port number of the destination Netflow service and click "Enable". .. disqus:: <file_sep> ========================================= Secure Networking with Micro-Segmentation ========================================= Micro-segmentation provides granular network security policy for distributed applications in the Cloud. Micro-segmentation enables network policy enforcement between application domains (app domains) you define in a single cloud or across multiple clouds. Users can configure policies to filter traffic between the applications residing in these domains. |microseg_topology| Use cases where you might implement micro-segmentation are: - Workload isolation: in a typical tiered application, you may want to isolate tiers that do not require access to each other. For example, in a Shopping Cart application, there could be workloads for product inventory, billing, and a Product Logging app. Since the Shopping Cart application does not need to communicate with the Product Logging app, this traffic should be blocked. - Quarantine compromised machines: You can isolate a compromised machine by placing it in its own app domain and blocking communication to that domain. Micro-Segmentation Components =============================== Micro-segmentation introduces two important configuration components—-app domains and policies. App Domains -------------- An app domain is a grouping of workloads, subnets, or VPC/VNets that require a uniform policy enforcement. For example, all servers running the product inventory database (as per the above workload isolation use case) can form an app domain. A Cloud resource can be part of multiple app domains. When you create your app domains, you can classify them based on: - CSP resource tags: these tags identify resources you can group. This is the preferred classification method, as this automatically includes new resources created in the Cloud with the same set of tags. - Resource attributes: classify by account or region. - IP addresses or CIDRs: for resources that are not tagged, you can directly specify IP addresses or CIDRs. .. note:: Aviatrix Gateway IP addresses will not be included in any app domain, even if an app domain filter matches an Aviatrix Gateway IP address. If a subnet or VPC/VNet is added to an app domain, the Aviatrix Gateway IP addresses are removed from the corresponding CIDRs. Policies ------------ After creating app domains, you create policies that consist of rules, to define the access control to apply on the traffic between those app domains. In the above workload isolation use case, all traffic (i.e., ports and protocols) between the ShoppingCart application and the Product Logging app must be blocked (Denied). You can decide which rules to enforce, and if you want to log the actions related to a rule. These rules are enforced (if enabled) on your Spoke gateways, and are executed against the Spoke gateways in the order that they are shown in the rule list. - Verify you have the required software versions of Aviatrix CoPilot, Aviatrix Controller, and gateways to use the micro-segmentation feature. See `Aviatrix Controller and Gateway Release Notes <https://docs.aviatrix.com/HowTos/Controller_and_Software_Release_Notes.html>`_ for details. - Network reachability should be configured between the VPCs that contain applications that require connectivity. You configure network reachability using Connected Transit/MCNS. See `here <https://docs.aviatrix.com/HowTos/transit_advanced.html#connected-transit>`_ for more information. - If you plan to use CSP tags in your app domains, Cloud resources must be tagged appropriately. Configuring Micro-Segmentation =============================== This section describes the micro-segmentation functional area of Aviatrix CoPilot. Creating App Domains ----------------------- An app domain contains one or more filters to identify CSP endpoints that map to an app domain. A filter specifies resource matching criteria. Matching criteria could be a CSP tag; a resource attribute (such as account name or region); or a list of IP prefixes. All conditions within the filter must be satisfied to be matched. A tag or resource attribute-based filter must be associated with a resource type (VPC/VNet, subnet, or VM). 1. In CoPilot, navigate to Security > Micro-Segmentation > App Domain. 2. Click +ADD DOMAIN. 3. Enter a name for the app domain. 4. If you want to add a resource type (VPC/VNet, virtual machine, or subnet), follow the below steps. If you want to enter IP addresses or CIDR ranges for your app domain, go to step 5. a. Click +Resource Type and select VPC/VNet, Virtual Machines, or Subnet. b. Enter the matching criteria for resources that will be part of this app domain. c. All CSP tags that you have defined for your Cloud resources are present in the list for you to select from. In GCP, only the instance labels are available for selection (network tags are not). Some tag examples are: Backup, Controller, Aviatrix-Created-Resource, and Type. d. If needed, add another resource type. Typically you will only have resources of the same type in an app domain (for example, you can have more than one VM based filter). e. You can also select resource attributes (Account Name and Region) if you want to match against all resources within an account or region. The values for the selected condition(s) are populated automatically. f. After entering your resource type, you can use the Preview Resources toggle switch to see the selected resources that map to the app domain. 5. If you prefer not to use specific tags in your resources, enter the VPC/VNet IP addresses or CIDRs in the field provided. Traffic across CIDRs between two app domains in the same VPC/VNet is not subject to micro-segmentation policies. 6. Click Save. The new app domain is now in the App Domain list. From here you can: - Click the app domain name to view it in read-only format - Click the pen icon to edit the app domain - See how many rules reference each app domain Creating Policies --------------------- After creating your app domains, you create policies (that consist of rules) to filter traffic sent between the selected source and destination app domains. The rules are executed in the order they appear in the list. An app domain traffic flow can belong to more than one rule. If this occurs, the priority of the rule determines the action that is taken first. 1. In CoPilot, navigate to Security > Micro-Segmentation > Policy. 2. On the Policy tab, click +RULE. 3. Enter a name for the rule. 4. Select the Source App Domains -- these domains originate (bi-directional) traffic. 5. Select the Destination App Domains -- these domains terminate (bi-directional) traffic. A micro-segmentation rule is inherently bi-directional, which means that rules for app domains will match both traffic from source to destination, as well as destination to source. An exception to this rule is that TCP connections initiated from the destination to the source will not be matched. 6. Select if the rule is allowed or denied. This determines the action to be taken on the traffic. 7. If the Enforcement slider is On (the default), the rule is enforced in the data plane. If the Enforcement slider is off, the packets are only watched. This allows you to observe if the traffic impacted by this rule causes any inadvertent issues (such as traffic being dropped). 8. If the Logging slider is On, information (such as five-tuple, source/destination MAC address, etc.) related to the action is logged. Since logging uses a lot of disk space, be careful when enabling logging on your rules. It is best to enable logging for a short period of time while you are debugging, and then disable logging again when you are finished. 9. Select the protocol used: TCP, UDP, ICMP, or Any. If you select TCP or UDP you can enter a port number or port range. As per the workload isolation use case above (blocking traffic between the Shopping Cart application and the Product Logging app), the rule would look like this: - Source app domain: Shopping Cart application - Destination app domain: Product Logging app - Action: Deny - Protocol: Any - Ports: 0-65535 (Any) - Logging: Off - Enforcement: On 10. Determine the rule order by selecting the following in the Place Rule list: - Above, Below, Top, or Bottom. If you select Above or Below, you must select the existing rule that is affected by the position of the new rule. - Priority; you then enter a Priority Number for the rule. If an existing rule already has that priority, it is bumped down in the list. Zero (0) is the highest priority number. After the rule is created you can click the arrow icon next to that rule in the Policy table to change the priority. 11. Click Save in Drafts. 12. Make additional modifications as needed by clicking the pencil icon next to the rule. 13. You can then review, commit, or discard the rule changes. Retaining Log Files ------------------- To configure how many days to keep your micro-segmentation logs, in CoPilot navigate to Settings > Advanced Settings and scroll down to Index Retention Manager. Use the slider next to Micro-segmentation Logs to select the number of days to retain your logs (default is five days). Viewing Raw Logs ---------------- Micro-segmentation supports per-packet logging when logging is enabled on a policy. For more information on consuming the raw logs, click `here <https://docs.aviatrix.com/HowTos/AviatrixLogging.html#id7>`_. Viewing Rule Statistics ------------------------- You can open a previously created rule to view the statistics related to the execution of that particular rule. You can view traffic statistics from the last hour, week, or month, or a custom time period. The resulting graph indicates if the traffic is Observed, Enforced & Allowed, or Enforced & Denied. Creating a Default Policy ------------------------- As a best zero trust security practice, you should add a deny rule that blocks traffic from all app domains to the universal 0.0.0.0/0 app domain. For example, if app domains A and B are configured to talk to each other, you may not want app domain C to be able to talk to app domain A or B. Creating this default rule helps with locking down configured app domains. This should be the last rule in the list. Policy Monitor -------------- Under Security > Micro-segmentation > Policy > Policy Monitor, you can filter packet logs for rules with logging enabled to determine why a rule may not be working as intended. You can filter based on the following information: timestamp, rule, source/destination IPs, protocol, source/destination port, action (allowed or dropped), and if the rule is enforced. The table refreshes every 15 seconds, and you can also refresh the table manually. CoPilot throttles the logs for each connection shown in Policy Monitor to one packet per minute in each direction. Configuring the Polling Interval ================================ The Aviatrix Controller periodically polls your CSPs to gather and inventory its resources. For example, if you modified your CSP tags, you may want to poll data more frequently so that CoPilot reflects those changes. In CoPilot navigate to Settings > Advanced Settings > Micro-Segmentation Settings> CSP Resource Poll Interval and enter the desired polling interval in minutes (default is 60). This can be a value between 1-180. Click Save. You can manually trigger a poll to fetch resources directly from your CSPs by clicking the Refetch CSP Resources button on the Micro-Segmentation tab. The poll may take several minutes to complete depending on the size of your environment. Limitations =========== - Micro-segmentation is supported on the following CSPs: AWS, AWS GovCloud, Azure, Azure Government, and GCP. - You can configure up to 500 app domains. - You can have up to 3000 unique CIDRs per app domain. - You can configure up to 20 filters per app domain (OR/ANY filters that are not the CIDR type). - You can configure up to ten ALL/AND match criteria per filter. - You can create up to 64 rules per policy. - The total number of CIDRs in all app domains cannot exceed 10,000. - Traffic between two app domains in the same VPC/VNet is not subject to micro-segmentation rules/policies. .. |microseg_topology| image:: microseg_media/microseg_topology.png :scale: 60% <file_sep> =========================================================================================== Survey of DevOps Tools =========================================================================================== This document lists a popular set of DevOps tools, what functions they serve and the protocols they run on. Notice that most of these DevOps tools are unencrypted by default. They do not have to run on TCP port 443 or 22. For example, Chef can run on TCP port 4321, 80, 443, 9683, 9463, 9090, 8000, 8983, 5432, 5672 and 16379, as shown below. |survey| Understandably implementing encryption for each tool adds complexity as a DevOps admin must deal with certificates and keys, and if you deploy a set of them, it becomes unmanageable. Check with your DevOps team and understand the running environment and risk. .. |survey| image:: opstools_survey_media/survey.png :scale: 30% .. disqus:: <file_sep> ====================================================================== Connect to Floating IP Addresses in Multiple AWS AZs ====================================================================== Overview -------- A subnet cannot span more than one availability zone (AZ) in AWS [1]_. Because of this, the IP address assigned to an instance in one AZ cannot be reassigned to another instance in a different AZ. Applications that require users to have a single IP address for connectivity, such as cloud-based NFS and CIFS services, need a way to failover to a different instance when the node fails. This fault tolerance is key to services like NetApp's ONTAP Cloud. A single AZ solution does not satisfy users' demands for a guarantee of an always-on solution. In order to overcome the AWS limitation, applications like NetApp Cloud rely on "floating" IPs addresses for failover between nodes in different AZs. Floating IP addresses are outside the range of the VPC CIDR. In order to route to these addresses within AWS, they must not overlap with any CIDR range in the same AWS region. Clients connect to the floating IP address rather than the IP address of the node itself. When a node failure (or even an entire AZ failure) is detected, the floating IP address is "moved" to an instance in another AZ. Problem ------- The floating IP solution works well if the client is in the same VPC as the server. However, if the client is not in the same VPC, AWS routing does not support routing to these IP addresses that are outside of the CIDR range for the VPC. Those packets will never exit the VPC. |imageProblem| Aviatrix Solution ----------------- Aviatrix solves this problem by handling routing of the floating IP addresses in the client VPC. All packets destined for the floating IP address(es) will be delivered to the Aviatrix Gateway. The gateway maintains an internal route table that points those packets to an Aviatrix gateway in the server VPC. |imageAviatrixSolution| Aviatrix Step-by-Step Deployment Guide for NetApp ------------------------------------------------- Overview ######## |imageNetappHA| What you will need: #. A shared services VPC where the Aviatrix central controller will be installed. #. AWS account credentials or the ability to create new IAM roles. This is how the Aviatrix Controller will connect to your AWS account. #. Access to the VPC where the client resides. #. Access to the VPC where the NetApp ONTAP Cloud is installed. Aviatrix Controller ################### If you have already installed an Aviatrix Controller, you can skip this step. #. Follow the steps in `this guide <../StartUpGuides/aviatrix-cloud-controller-startup-guide.html>`__ to install a Controller in a VPC of your choice (a shared services VPC, for example) Client VPC ########## Provision an Aviatrix Gateway in the VPC where your client application resides: .. note:: The Aviatrix gateway must be installed in a public subnet. If you do not have one created in the VPC where your client application resides, please create one before continuing. #. Login to your Aviatrix Controller #. Click on the `Gateways` item in the navigation menu #. Click on `+ New Gateway` to create a new Gateway #. Select the VPC and subnet and provide a name for this Gateway (e.g., "netapp-client") #. Leave the other options at their default values #. Click `OK` NetApp ONTAP Cloud VPC ###################### Next, create a Gateway in the VPC of your NetApp Cloud installation. .. note:: The Aviatrix gateway must be installed in a public subnet. If you do not have one created in the VPC where your NetApp Cloud is installed, please create one before continuing. #. Login to your Aviatrix Controller #. Click on the `Gateways` item on the navigation menu #. Click on `+ New Gateway` to create a new Gateway #. Select the VPC and subnet and provide a name for this Gateway (e.g., "netapp-ontap") #. Leave the other options at their default values #. Click `OK` For redundancy, enable HA: .. note:: The Aviatrix HA gateway must be installed in a public subnet. If you do not have one created in the VPC where your NetApp Cloud is installed, please create (another) one before continuing in a different AZ than the previous gateway. #. Login to your Aviatrix Controller #. Click on the `Gateways` item on the navigation menu #. Select the gateway just created (e.g., "netapp-ontap") #. Click on the `Edit` button above the table #. Below `Gateway for High Availability Peering`, select the public subnet that is in a different AZ from the earlier gateway #. Click `Create` Peer the Client VPC with the ONTAP VPC ######################################## First, set up a connection for traffic to go between the client and the ONTAP VPC: #. Login to your Aviatrix Controller #. Click on the `Peering` item on the navigation menu #. Click on `+ New Peering` to create a new peer #. Select `netapp-client` for `Gateway1` and `netapp-ontap` for `Gateway2` #. Click `OK` |imageAddPeer| Route Floating IP routes from client to the ONTAP VPC ######################################################## Next, set up a route for traffic for the floating IP addresses through the client gateway to the ONTAP gateway: #. Login to your Aviatrix Controller #. Click on the `Peering` item on the navigation menu #. Click on the `Transitive Peering` tab #. Click on `+ New Peering` to create a new transitive peer definition #. Select the `netapp-client` for the `Source Gateway` and `netapp-ontap` for the `NextHop Gateway` #. In the `Destination CIDR`, enter the list of floating IP addresses (comma-separated). For example, ``192.168.10.2/32, 192.168.10.3/32, 192.168.10.4/32``. #. Click `OK` |imageAddTransitivePeer| Add Floating IP routes to ONTAP Controllers ########################################### In the NetApp Cloud Manager, be sure to select the subnet(s) where the Aviatrix Gateway(s) is installed when `modifying AWS route tables <http://docs.netapp.com/occm/index.jsp?topic=%2Fcom.netapp.doc.onc-cloud-mgr-ug-330%2FGUID-7DD84149-4A73-4A1D-84FF-31F096781EF4.html>`__ with the routes to the floating IPs. Validate ######## Mount a share on an instance in the client VPC and test connectivity. The final architecture will look like this: |imageFinal| .. [1] https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_Subnets.html#vpc-subnet-basics .. [2] https://library.netapp.com/ecmdocs/ECMLP2484721/html/GUID-46865CCE-19CE-45C2-BEC4-2FA222CE9537.html#GUID-46865CCE-19CE-45C2-BEC4-2FA222CE9537__SECTION_0428B81160F7479CAC70E140483818F2 .. |imageAviatrixSolution| image:: netapp_floating_ips_media/floating_ip_aviatrix_solution.png .. |imageProblem| image:: netapp_floating_ips_media/floating_ip_generic_aws.png :scale: 75% .. |imageAddPeer| image:: netapp_floating_ips_media/add_peer.png :scale: 50% .. |imageFinal| image:: netapp_floating_ips_media/netapp_plus_aviatrix.png :scale: 75% .. |imageNetappHA| image:: netapp_floating_ips_media/netapp.png :scale: 75% .. |imageAddTransitivePeer| image:: netapp_floating_ips_media/add_transitive_peer.png <file_sep> #################################################################### How to Build a Zero Trust Cloud Network Architecture with Aviatrix #################################################################### What is Zero Trust network architecture? ======================================== Zero Trust architecture came from the realization that perimeter security solutions such as edge firewalls are not sufficient to prevent data breaches. Lateral movement inside a network to scan and obtain target data has been the approach in the recent serious attacks. The idea of Zero Trust is to build walls inside the datacenter by network segmentation to prevent lateral movement and always authenticate and authorize users for all data access. How to build a Zero Trust cloud network ====================================================== 1. Classify data by network segmentation ------------------------------------------ - Separating production data from dev and test is the first step. Giving them separate cloud accounts is the best practice to ensure isolation. - Different business groups should have separate cloud accounts. - The more fine grained accounts, the more micro segmentation goal is achieved. - There should be zero connections among these networks by default. In public clouds such as AWS, using the above principles to build your cloud network results in isolated islands of VPCs. If one VPC is breached, it is impossible to gain access to other VPCs, thus significantly reducing attack surface. `Aviatrix is a multi account platform <http://docs.aviatrix.com/StartUpGuides/aviatrix-cloud-controller-startup-guide.html>`_ that enables you to manage all cloud accounts from a single pane of glass. 2. Policy driven connectivity with stateful firewall rules ------------------------------------------------------------ - The connectivity between VPCs and on-prem networks should be policy driven. A network solution such as the AWS Global Transit Network with CSR is a polar opposite to Zero Trust architecture point of view as all VPCs and on-prem are built into a full mesh network. In contrast, - `AWS Global Transit Network with Aviatrix <http://docs.aviatrix.com/Solutions/aviatrix_aws_transitvpc.html>`_ meets Zero Trust architecture requirements where secure connection is established by organization policy. - In addition to policy driven network connections, there must be firewall rules that govern data flow and reduce the connection scope. For example, you should consider placing application and database in separate VPCs and setting up a stateful firewall rule to only allow traffic initiated from application to access the database, not the other way around. `Aviatrix gateway stateful firewall <http://docs.aviatrix.com/HowTos/gateway.html>`_ enforces and logs all network events. - Within a VPC, you can use AWS native security groups associated with instances to enforce policies for communications. 3. User access with authentication and authorization ------------------------------------------------------ - User access to cloud resources must be first authenticated. Certificate-only based authentication is a weak solution as a certificate can be stolen. Another insecure access method is Jump Host or Bastion stations. Multi factor authentication such as integrating with LDAP/DUO/OKTA and client SAML "Single Sign On" significantly improves authentication strengths. However, authentication alone is not sufficient, - A User's access cloud resources must be authorized. The finer grained control you apply, the less lateral movement a user can make even if access to the network is attained. With Zero Trust, you should only grant access to the required resources. - User access activities must be fully audited. Every user initiated TCP session in the cloud network must be logged for audit and inspection. The `Aviatrix Enterprise OpenVPN® Solution <http://docs.aviatrix.com/HowTos/openvpn_features.html>`_ is the strongest secure client solution in the marketplace built for the public cloud. 4. Summary ------------ Zero Trust architecture is "Never trust, always verify", a critical component to enterprise cloud adoption success. Aviatrix provides a rich set of capabilities that enables you to build a Zero Trust network for the public cloud. OpenVPN is a registered trademark of OpenVPN Inc. .. |image2| image:: media/image5.png :width: 7in :height: 4in :scale: 150% .. |image6| image:: media/image6.png :width: 7in :height: 4in :scale: 150% .. add in the disqus tag .. disqus:: <file_sep> ################################### Emails and Alert Configuration ################################### To help you manage important events in your account, the Aviatrix Controller sends alert emails for events such as: - Tunnel status change - Gateway status change - Account information changes - Other critical events, such as a full disk By default, alert emails are sent to the administrator of the Controller. Aviatrix strongly recommends that you use an email alias to notify a group of people rather then using an individual email address. If only one person receives the notifications, important alerts could be missed. To change the default email for alert notifications, see the section below. * By default, the source email address is <EMAIL>. * By default, the SMTP service is provided by a third-party, Sendgrid. Even though Aviatrix implements third-party risk monitoring, we are not responsible for Sendgrid controls. Aviatrix recommends that you configure your own SMTP service. Changing the Email Recipients of Alert Email Notifications ---------------------------------------------------------------------------------------- When you launch your Aviatrix Controller for the first time or log in after an upgrade, please provide the addresses for at least four new email accounts or email aliases that can receive important notification emails. 1. Go to Settings > Controller > select the **Email** tab. 2. Use the four fields on the page to enter the **new** email addresses or aliases of team members who should receive these emails: |email_notifications_page| * Administrator email alias (named something like "<EMAIL>") - Set up this email account to receive important account and certification information. * Security Admin Email Alias (named something like "<EMAIL>") - Set up this email account receive security and CVE (Common Vulnerabilities and Exposures) notification emails. * IT Admin Email Alias (named something like "<EMAIL>") - Set up this email account to receive field notices and critical notices. * IT Admin Email Alias (named something like "<EMAIL>") - Set up this email to receive system/tunnel status notification emails. 3. Click **Save** to save your changes. Managing Alert Bell Notifications ------------------------------------------------------ The Alert Bell is in the top right of your Controller. This Bell provides notifications about the following features: By default, Alert Bell notification is enabled for the following features: 1. **Overlapped CIDR Check** - Alert when BGP routes overlap in Site2Cloud. #. **Guard Duty Check** - Alert gets logged as Alert Bell notification and block malicious IP addresses when offending IPs are detected by Guard Duty. To learn more about Guard Duty integration with Aviatrix click `here <https://docs.aviatrix.com/HowTos/guardduty.html>`_. #. **Log Service Check** - This alarm generates a warning as a Alert Bell notification for remote syslog server down event. #. **Reach of Route Limit Check** - Alert when VPC and BGP route limits reach a threshold. #. **Blackhole Route Entry Check** - Alert when VPC route table has inactive routes. To learn more about Blackhole Routes click `here <https://docs.aviatrix.com/Support/support_center_controller.html?highlight=bell#what-are-blackholes-on-alert-bell>`_. |alert_bell_notify_| To change these Alert Bell settings, navigate to Settings > Controller > select the **Alert Bell** tab. Clearing Alert Bell Notifications ------------------------------------------------------ Alert Bell Notifications are cleared as follows, depending on their type: * System — System-type bell notifications are persisted in the Controller Database. You can manually clear the notifications by clicking **CLEAR ALL** in the notification dialog. * Activity — Activity-type bell notifications are user-session based **and are automatically cleared out when you log out of Controller**. You can manually clear the notifications during your session by clicking **CLEAR ALL** in the notification dialog. Changing the Email Notification Source (AWS) ---------------------------------------------------------- The following example uses Amazon Simple Email Service (SES): Note that newly created SES accounts are placed in an "AWS SES Sandbox" and will not be able to send emails to unverified domains/addresses until they have been removed from the Sandbox: https://docs.aws.amazon.com/ses/latest/DeveloperGuide/request-production-access.html Create SMTP Credentials: 1. Log into the AWS Console. 2. Click **SES Email Service**. 3. Click **SMTP Settings**. 4. Click **Create My SMTP Credentials**. |aws_ses| 5. Click **Download Credentials**. .. important:: Download these credentials now, as this password will not display again. Verify an Email Address: 1. Log into the Amazon SES Console > SESHome > IdentityManagement > EmailAddresses. 2. Click **Verify a New Email Address**. 3. In Verify a New Email Address, enter an email address you want to send messages from. Note this *must* be a valid email address. |aws_verify_email| 4. You will receive a verification email from AWS SES asking you to confirm that you are the owner of the email address. Click the verification link in the message. Configure the Aviatrix Controller to use AWS SMTP email server: 1. SMTP Server: email-smtp.us-east-1.amazonaws.com <note that this value is regional and may differ based on the region of your verified address(es). You can confirm this from AWS Console > Services > SES > SMTP Settings > Server Name> 2. Port: 587 3. Sender Email: <From Step 2: your verified email> 4. Sender Login: <From Step 1e: your SMTP Username> 5. Sender Password: <From step 1e: your SMTP Password> 6. Test Email: <From Step 2: your verified email> 7. Protocol: TLS 8. Click **Save**. Disabling Exception Notification Emails to Aviatrix ------------------------------------------------------------- Use the **Software exception notification** option to disable exception emails send to Aviatrix. To disable these notifications, go to Settings > Controller > Email, scroll down to find the software exception field, and click **Disable**.   .. |AwsEmailVerification| image:: alert_and_email_media/AwsEmailVerification.PNG :scale: 30% .. |ChangeEmailNotification| image:: alert_and_email_media/ChangeEmailNotification.PNG :scale: 30% .. |aws_ses| image:: alert_and_email_media/aws_ses.png :scale: 30% .. |aws_verify_email| image:: alert_and_email_media/aws_verify_email.png :scale: 30% .. |email_notifications_page| image:: alert_and_email_media/email_notifications_page.png :scale: 60% .. |alert_bell_notify_| image:: alert_and_email_media/alert_bell_notify_.png :scale: 60% .. disqus:: <file_sep> ####################################### IAM Roles for Secondary Access Accounts ####################################### When the Aviatrix Controller goes through the initial Onboarding process, the `primary access account <http://docs.aviatrix.com/HowTos/onboarding_faq.html#what-is-the-aviatrix-primary-access-account>`_ is created. Using the primary access account, the Controller can launch gateways and build connectivity in the VPCs that belong to this account. If the Controller needs to build connectivity in AWS accounts that are different from the Controller instance's AWS account, secondary access accounts need to be created. To create a secondary AWS access account on the Controller, you need to first create IAM roles, policies and establish a trust relationship to the primary AWS account. Follow the steps below to create IAM roles and policies for the AWS secondary access account. (If you like to customize the conditions of the policies published by Aviatrix, consult `this link. <http://docs.aviatrix.com/HowTos/customize_aws_iam_policy.html>`_) Setting up by CloudFormation Template =========================================================================== This is the recommended approach. Follow `the instructions <https://docs.aviatrix.com/HowTos/aviatrix_account.html#setup-additional-access-account-for-aws-cloud>`_ to use this setup option. Setting up a Secondary Account IAM Manually ========================================================================= **This is not a recommended approach as it takes a longer time and is error-prone.** Creating Two IAM Custom Policies ----------------------------------------------- 1. Create “aviatrix-assume-role-policy”: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #. Log in to the AWS management console with a secondary AWS account. #. Go to Services > IAM > Policies > Create Policy > **Create Your Own Policy**. #. Enter the policy name, **aviatrix-assume-role-policy** , and then copy and paste the policy text from `this link <https://s3-us-west-2.amazonaws.com/aviatrix-download/iam_assume_role_policy.txt>`__. #. Click **Valid Policy** to validate the policy. #. Click **Create Policy**. 2. Create “aviatrix-app-policy”: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #. Log in to the AWS console with your own account. #. Go to Services > IAM > Policies > Create Policy > Create Your Own Policy. #. Enter the policy name, **aviatrix-app-policy** , and then copy and paste the policy provided by `this link <https://s3-us-west-2.amazonaws.com/aviatrix-download/IAM_access_policy_for_CloudN.txt>`__. into “Policy Document” section. In this example, the policy name is “aviatrix-app-policy”, as shown below. #. Click **Create Policy**. 2. Creating Two IAM Roles ------------------------------------ Creating the “aviatrix-role-ec2” Role ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The role name MUST be exactly “\ **aviatrix-role-ec2**\ ”. 1. Navigate to AWS console > IAM service > Roles > Create role. |image3| 2. Select AWS Service > EC2 > EC2 > Next: Permissions. |image4| 3. Search for the policy **aviatrix-assume-role-policy**, and then select this policy. Click **Next Review**. |image5| 4. Enter the Role name **aviatrix-role-ec2** (the character match must be exact) then click **Create**. 5. Search/Check the role. You should see something like this for Role ARN: arn:aws:iam::575xxxxxx729:role/aviatrix-role-ec2 |image0| 7. Make a note of the above Role ARN string, it will be used to set up the Aviatrix Cloud Account later. Creating the "aviatrix-role-app" role ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This role is to be assumed by a granted AWS account. The Aviatrix Controller acquires the “assume role” capability authorized by its “aviatrix-role-ec2” role. It then assumes to this service role that is granted by its own AWS account or other AWS accounts to perform AWS APIs. 1. Go to the AWS console > IAM service > Roles > Create Role. 2. Select **Another AWS account** and enter your AWS account ID, then Click **Next:Permissions**. |image6| 3. Select the **aviatrix-app-policy** IAM policy, then click **Next: Review**. 4. Enter a Role Name, in this case **aviatrix-role-app**. Click **Create role**. You should see something like this for Role ARN: **arn:aws:iam::575xxxxxx729:role/aviatrix-role-app** 5. Make a note of the Role ARN string above. It will be used to set up the Aviatrix access account later. |image1| Establishing a Trust Relationship with Primary Account ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. note:: If you are using this manual process to setup primary access account (Controller's account), you do not need to establish a trust relationship. Skip this step. Grant the primary (Controller) AWS account access to the aviatrix-role-app in this secondary account: 1. Navigate to the AWS console > IAM service > Roles > aviatrix-role-app. 2. Click Trust Relationships > Edit Trust Relationship. 3. Edit the trust relationship as follows. Remember to enter both the primary account number and secondary account number. |image2| 4. Click **Update Trust Policy**. Notes for the Custom IAM Role Name Feature: ======================================= If the primary access account is using a custom EC2 IAM role name for the Controller, then any secondary IAM based access accounts must use an identical name for the EC2 IAM role. The primary and secondary access accounts must use identical names under the following conditions: * You are using custom IAM roles for the primary access account. * You are NOT using custom gateway IAM roles on the secondary account. Example: The Controller is using 'custom-role-app' and 'custom-role-ec2' on a secondary access account. Custom role 'custom-role-ec2' also exists on the primary account because that is where the Controller is hosted. When you launch a gateway under the secondary access account, the Controller takes the primary access account EC2 role name, in this case 'custom-role-ec2' and passes it to the API call to create the instance. The API call refers to a role on the secondary CSP account, not the role of the primary account. .. |image0| image:: IAM_media/image1.png :width: 6.50000in :height: 2.99931in .. |image1| image:: IAM_media/image2.png :width: 6.50000in :height: 3.31806in .. |image2| image:: IAM_media/image3.png :width: 4.67200in :height: 3.33379in .. |image3| image:: IAM_media/img_create_assume_role_step_01.png :width: 4.67200in :height: 3.33379in .. |image4| image:: IAM_media/img_create_assume_role_step_02_select_ec2_type_role.png :width: 4.67200in :height: 3.33379in .. |image5| image:: IAM_media/img_create_assume_role_step_03_attach_assume_role_policy.png :width: 4.67200in :height: 3.33379in .. |image6| image:: IAM_media/img_create_cross_account_role_step_01.png :width: 4.67200in :height: 3.33379in .. |imageCFCreate| image:: IAM_media/cf_create.png .. |imageCFSelectTemplate-S3| image:: IAM_media/imageCFSelectTemplate-S3.png .. |imageCFEnableTermProtection| image:: IAM_media/cf_termination_protection.png .. |imageCFCreateFinal| image:: IAM_media/cf_create_final.png .. add in the disqus tag .. disqus:: <file_sep> ===================================== Account with Access Key ===================================== This document describes how to set up an Aviatrix access account for AWS by using an IAM user access key and secret ID, instead of IAM roles. This approach is applicable to AWS China as Aviatrix does not support IAM role yet. Creating an IAM Policy ---------------------------- 1. Log in to the AWS console > IAM > Policies. Click **Create Policy**, and then click **JSON**. Delete the example JSON text. Copy and paste `the Aviatrix AWS policy <https://s3-us-west-2.amazonaws.com/aviatrix-download/IAM_access_policy_for_CloudN.txt>`_ to create a new IAM policy, as shown below. Give policy a name: aviatrix-role-app. |create-policy| Creating an IAM User ---------------------------- 1. Log in to the AWS Console > IAM > Users. 2. Click **Add user** to create a new IAM user and allow programmable access, as shown below. |add-iam-user| Attaching the Policy to the User --------------------------------------------------- Next, attach the created policy to this IAM user, as shown below. |attach-policy| Setting up an Access Key and Secret Access Key ---------------------------------------------------------------- Finally, create an access key and secret key to be used by the Aviatrix access account for this IAM user. |accesskey| .. |add-iam-user| image:: accesskey_media/add-iam-user.jpg :scale: 50% .. |create-policy| image:: accesskey_media/create-policy.png :scale: 50% .. |attach-policy| image:: accesskey_media/attach-policy.png :scale: 50% .. |accesskey| image:: accesskey_media/accesskey.png :scale: 50% .. disqus:: <file_sep> =========================================================================== IPSec =========================================================================== What is the MTU setting on the IPSec Tunnels between the Aviatrix Gateways? -------------------------------------------------------------------------------------------- All the IPSec tunnels have the TCP MSS set to 1370 bytes, by default, on Aviatrix gateway created in AWS, Azure and OCI. In GCP, the default value is 1330 bytes (from R6.1) due to previous experience with some GCP applications. If you are running any applications which do not support fragmentation, you might have issues - please adjust the MSS value on your gateways. MSS is the maximum size that the payload can be, after subtracting space for the IP, TCP, and other headers. It's typically a minimum of a 40 byte offset (40 bytes less) than MTU. A good primer on the relationship between segment size and application traffic is available to review here: `How TCP segment size can affect application traffic flow <https://medium.com/walmartglobaltech/how-tcp-segment-size-can-affect-application-traffic-flow-7bbceed5816e>`_ You can adjust the TCP MSS at “Aviatrix Console > Settings > Advanced > Tunnel > TCP MAXIMUM SEGMENT SIZE(MSS)” on the Aviatrix gateway. Please note that we **strongly** recommend that you do not set the MSS to a value higher than 1370 bytes. Why did my IPSec tunnel go down? -------------------------------------------------------------------------------------------- We configure our IPSec tunnels with Dead Peer Detection a.k.a. DPDs (sent every 10 seconds) and if do not see three consecutive DPDs, we declare that the tunnel is down and the gateway will try to renegotiate the IPSec tunnel. For reasons beyond the control of the gateway, such as network failure along the path and or the remote site going down, we occasionally will see the tunnels go down. If you have `external logging <https://docs.aviatrix.com/HowTos/AviatrixLogging.html>`_ turned on, you would be able to see the logs such as the following which will tell you when the tunnels have gone down. :: 2020-01-29T07:19:37.064245+00:00 ip-10-66-243-108 racoon: [xx.xx.xx.xx] INFO: DPD: remote (ISAKMP-SA spi=8d6ba0f7a74593d0:71fa69ac6b4afef3) seems to be dead. 2020-01-29T07:19:37.064354+00:00 ip-10-66-243-108 racoon: INFO: purging ISAKMP-SA spi=8d6ba0f7a74593d0:71fa69ac6b4afef3. . . 2020-01-29T07:19:44.199040+00:00 ip-10-66-243-108 racoon: INFO: initiate new phase 1 negotiation: 10.66.243.108[500]<=>xx.xx.xx.xx[500] . . 2020-01-29T07:20:49.311786+00:00 ip-10-66-243-108 racoon: INFO: IPsec-SA established: ESP/Tunnel 10.66.243.108[500]->xx.xx.xx.xx[500] spi=215564738(0xcd941c2) . . Please check and see if there were any issues in your network and if the remote end had any service down events. Typically these explain the IPSec tunnel temporary down events. <file_sep> .. raw:: html <style> /* override table no-wrap */ .wy-table-responsive table td, .wy-table-responsive table th { white-space: normal !important; } </style> ========================================= Okta Authentication with Okta API Token ========================================= Overview ----------------- There are two methods to authenticate a VPN user against Okta: using an Okta API Token or the `Aviatrix VPN SAML Client <https://docs.aviatrix.com/HowTos/VPN_SAML.html>`_. Okta API Token is a method where the Aviatrix VPN Gateway authenticates against Okta on behalf of VPN clients using the standard Okta API. When this method is used, you can continue to use a native OpenVPN® client such as Tunnelblick while enjoying MFA authentication. This document shows you how to set up authentication using Okta API Token. Follow these steps to configure Okta authentication and MFA on a User VPN Gateway in your environment: #. Obtain an `API token <#okta-api-token>`__ from your Okta account. #. Setup `Okta authentication <#setup-okta>`__. #. Create `VPN Users <#create-vpn-users>`__ for this Aviatrix Gateway. #. `Test <#validate>`__ connectivity. .. important:: Okta authentication can be enabled both at the Aviatrix Gateway launch time and after the Aviatrix Gateway is launched. We highly recommend you configure Okta after the gateway is launched. .. _okta_api_token: Obtaining the API Token from Okta ------------------------------------------- Follow the steps outlined in the `Okta documentation <https://developer.okta.com/docs/api/getting_started/getting_a_token>`__ to create a new API token. #. Log in into your Okta account as a **Super Admin.** This allows the privilege to create a Token for API access. #. Go to Security > API and click **Create Token**. Give the token a name (for example, Aviatrix). .. note:: Copy the generated token value. You’ll need this token to allow the Aviatrix Gateway to access Okta. |image1| .. _setup_okta: Setting up Okta Authentication ---------------------------------------- #. Follow the steps in `this guide <./uservpn.html>`__ to create a new Aviatrix VPN Gateway. #. When you are ready to configure Okta, log in to the Controller. At the main navigation bar, go to OpenVPN® > Edit Config > Modify Authentication. From the dropdown option, select **Okta**. |GWOktaMFA| #. Enter details about your Okta environment: +-----------------------+-------------------------------------------------+ | Field | Description | +=======================+=================================================+ | URL | Your Okta account login URL. (For example, | | | https://aviatrixtest.okta.com.) | +-----------------------+-------------------------------------------------+ | Token | The token value you copied earlier. | +-----------------------+-------------------------------------------------+ | Username Suffix | If provided, the VPN username | | | will be the account ID without the domain name. | | | | | | For example, if your Okta account is | | | "<EMAIL>" and | | | "aviatrixtest.com" is your Username Suffix, | | | the VPN username should be "demoaviatrix". | | | | | | If no value is provided for | | | this field, you must enter the full username | | | including domain name (for example, | | | "<EMAIL>"). | +-----------------------+-------------------------------------------------+ |GWOktaAdditionalFields| .. _create_vpn_users: Creating User(s) ----------------------- #. Log in to your Aviatrix Controller. #. Expand **OpenVPN** and select **VPN Users**. #. Click **+ Add New**. #. Select the VPC/VNet where the VPN was created in the previous step. #. Select the Aviatrix Gateway or Load Balancer. #. Enter the username. .. important:: This username must match the username in Okta. #. (Optional) Enter the user's email where the .ovpn file will be emailed. .. note:: If an email is not provided, users will need to download their .ovpn file from the Controller. #. (Optional) Select a profile for this user. #. Click **OK**. |AddVPNUser| .. _validate: Validating ------------------------- #. Use the .ovpn file emailed to your test account or download it from Aviatrix VPN Users. #. Add the configuration to your VPN client. #. Connect and log in. .. note:: Since Aviatrix Okta authentication uses API authentication, it uses the default sign on policy of Okta. If you have configured Multi-factor Authentication in Okta, then during VPN login, the end user needs to append his MFA token to the password during authentication. OpenVPN is a registered trademark of OpenVPN Inc. .. |image0| image:: How_to_setup_Okta_for_Aviatrix_media/image0.png :width: 3.5in :height: 0.5in .. |image1| image:: How_to_setup_Okta_for_Aviatrix_media/image1.jpg :width: 5.92708in :height: 3.34097in .. |image2| image:: How_to_setup_Okta_for_Aviatrix_media/image2.jpg :width: 5.80069in :height: 3.27431in .. |image3| image:: How_to_setup_Okta_for_Aviatrix_media/image3.jpg :width: 3.95417in :height: 4.14375in .. |GWOktaMFA| image:: How_to_setup_Okta_for_Aviatrix_media/gw_okta_mfa.png .. |GWOktaAdditionalFields| image:: How_to_setup_Okta_for_Aviatrix_media/gw_okta_options.png .. |AddVPNUser| image:: How_to_setup_Okta_for_Aviatrix_media/add_vpn_user.png .. disqus:: <file_sep> .. toctree:: :numbered: ============================================================================== Aviatrix Controller Login with SAML Authentication on Okta IDP ============================================================================== Overview ------------ This guide provides an example on how to configure Aviatrix Controller to authenticate against an Okta IDP. When SAML client is used, your Aviatrix controller acts as the Identity Service Provider (ISP) that redirects browser traffic from client to IDP (e.g., Okta) for authentication. Pre-Deployment Checklist ----------------------------- Before configuring SAML integration between Aviatrix and Okta, make sure the following is completed: #. `Aviatrix Controller <#aviatrix-controller>`__ is setup and running. #. Have a valid `Okta account <#okta-account>`__ with admin access. .. _aviatrix_controller: Aviatrix Controller ################### If you haven’t already deployed the Aviatrix controller, follow `the Controller Startup Guide <https://docs.aviatrix.com/StartUpGuides/aws_getting_started_guide.html>`_. .. _okta_account: Okta Account ############ A valid Okta account with admin access is required to configure the integration. Configuration Steps ------------------- Follow these steps to configure Aviatrix to authenticate against your Okta IDP: #. Create an `Okta SAML App <#okta-saml-app>`__ for Aviatrix #. Retrieve `Okta IDP metadata <#okta-idp-metadata>`__ #. Create Aviatrix `SAML SP Endpoint <#aviatrix-saml-endpoint>`__ #. `Test the Integration <#test-integration>`__ is Set Up Correctly #. `Validate <#validate-entire-process>`__ .. _okta_saml_app: Create an Okta SAML App for Aviatrix #################################### .. note:: This step is usually done by the Okta Admin. #. Login to the Okta Admin portal #. Follow `Okta documentation <https://developer.okta.com/standards/SAML/setting_up_a_saml_application_in_okta>`__ to create a new application. +----------------+----------------+ | Field | Value | +================+================+ | Platform | Web | +----------------+----------------+ | Sign on method | SAML 2.0 | +----------------+----------------+ |image0| #. General Settings +----------------+-----------------+----------------------------------------+ | Field | Value | Description | +================+=================+========================================+ | App name | Aviatrix | This can be any value. It will be | | | | displayed in Okta only. | +----------------+-----------------+----------------------------------------+ | | Aviatrix logo: | Aviatrix logo (optional) | | | | | | App logo | | |logoAlias1|_ | | | | | |logoAlias2|_ | | +----------------+-----------------+----------------------------------------+ | App visibility | N/A | Leave both options unchecked | +----------------+-----------------+----------------------------------------+ |image1| #. SAML Settings * General +----------------------+----------------------------------------------------+ | Field | Value | +======================+====================================================+ | Single sign on URL | ``https://[host]/flask/saml/sso/[Endpoint Name]`` | +----------------------+----------------------------------------------------+ | Audience URI | ``https://[host]/`` | | (SP Entity ID) | | +----------------------+----------------------------------------------------+ | Default RelayState | ``https://[host]/#/dashboard`` | +----------------------+----------------------------------------------------+ | Name ID format | Unspecified | +----------------------+----------------------------------------------------+ | Application username | Okta username | +----------------------+----------------------------------------------------+ ``[host]`` is the hostname or IP of your Aviatrix controller. ``[Endpoint Name]`` is an arbitrary identifier. This same value should be used when configuring SAML in the Aviatrix controller. The example uses ``aviatrix_saml_controller`` for ``[Endpoint Name]`` ``https://[host]/#/dashboard`` must be set as the Default RelayState so that after SAML authenticates, user will be redirected to dashboard. * Attribute Statements +----------------+-----------------+--------------------------------------+ | Name | Name format | Value | +================+=================+======================================+ | FirstName | Unspecified | user.firstName | +----------------+-----------------+--------------------------------------+ | LastName | Unspecified | user.lastName | +----------------+-----------------+--------------------------------------+ | Email | Unspecified | user.email | +----------------+-----------------+--------------------------------------+ |image2| .. _okta_idp_metadata: Retrieve Okta IDP metadata ########################## .. note:: This step is usually completed by the Okta admin. After the application is created in Okta, go to the `Sign On` tab for the application. Copy the URL from the *Identity Provider metadata* link. This value will be used to configure the Aviatrix SP Endpoint. |image4| Assign the application to your account |image5| .. _aviatrix_saml_endpoint: Create Aviatrix SAML Endpoint ############################# .. note:: This step is usually completed by the Aviatrix admin. #. Login to the Aviatrix Controller #. Click `Settings` in the left navigation menu #. Select `Controller` #. Click on the `SAML Login` tab #. Click `ADD NEW` button |image6| +-------------------------+-------------------------------------------------+ | Field | Value | +=========================+=================================================+ | IDP Metadata Type | URL | +-------------------------+-------------------------------------------------+ | IDP Metadata URL | ``Value copied from Okta`` (Paste the value | | | copied from Okta Sign On) | +-------------------------+-------------------------------------------------+ | Entity ID | Hostname | +-------------------------+-------------------------------------------------+ | Access | Use either admin or read-only | | | | +-------------------------+-------------------------------------------------+ |image9| #. Click `OK` .. _test_integration: Test the Integration #################### .. tip:: You will need to assign the new Okta application to a test user's Okta account before clicking `Test`. #. Click `Settings` in the left navigation menu #. Select `Controller` #. Click on the `SAML Login` tab #. Click the `Test` button next to ``SAML endpoint name`` |image7| #. You should be redirected to Okta. Login with your test user credentials. .. important:: If everything is configured correctly, once you have authenticated another windows should open with the test user's access. .. _validate_entire_process: Validate ######## #. Logout of the Aviatrix Controller #. Login to the Aviatrix Controller by clicking the `SAML Login` button |image8| #. You should be redirected to Okta. Login with your test user credentials. .. important:: If everything is configured correctly, once you have authenticated you will be redirected to the dashboard's controller. Configure Okta for Multifactor Authentication (OPTIONAL) ######################################################## Once you have successfully configured Okta IDP with Aviatrix SP, you can configure Okta for Multifactor Authentication. Please read this `article <https://support.okta.com/help/Documentation/Knowledge_Article/Multifactor-Authentication-1320134400>`__ from Okta on Multifactor setup. See this `article <https://support.okta.com/help/Documentation/Knowledge_Article/Configuring-Duo-Security-734413457>`__ if you're interested in using DUO in particular. OpenVPN is a registered trademark of OpenVPN Inc. .. |logoAlias1| replace:: Aviatrix logo with red background .. _logoAlias1: https://a.aviatrix.com/news/press-kit/logo-aviatrix-reverse.zip .. |logoAlias2| replace:: Aviatrix logo with transparent background .. _logoAlias2: https://a.aviatrix.com/news/press-kit/logo-aviatrix.zip .. |image0| image:: Controller_Login_Okta_SAML_media/image0.png .. |image1| image:: Controller_Login_Okta_SAML_media/image1.png .. |image2| image:: Controller_Login_Okta_SAML_media/image2.png .. |image3| image:: Controller_Login_Okta_SAML_media/image3.png .. |image4| image:: Controller_Login_Okta_SAML_media/image4.png .. |image5| image:: Controller_Login_Okta_SAML_media/image5.png .. |image6| image:: Controller_Login_Okta_SAML_media/image6.png .. |image7| image:: Controller_Login_Okta_SAML_media/image7.png .. |image8| image:: Controller_Login_Okta_SAML_media/image8.png .. |image9| image:: Controller_Login_Okta_SAML_media/image9.png .. disqus:: <file_sep> ============================================ Aviatrix Gateway to Sonicwall ============================================ This document describes how to build an IPsec tunnel based Site2Cloud connection between Aviatrix Gateway and Sonicwall. The network setup is as follows: **VPC/VNet-AVX (with Aviatrix Gateway)** *VPC/VNet CIDR: 10.0.0.0/16* **On-Prem (with Sonicwall)** *On-Prem Network CIDR: 10.16.100.0/24* Creating a Site2Cloud Connection at the Aviatrix Controller ====================================================== 1. Go to Gateway > New Gateway to launch an Aviatrix Gateway at the subnet (public subnet in AWS, GCP, or OCI) of VPC/VNet-AVX. Collect Gateway's public IP addresses (192.168.127.12 in this example). 2. Go to the Site2Cloud page and click **Add New** to create a Site2Cloud connection. =============================== ================================================================= **Field** **Value** =============================== ================================================================= VPC ID/VNet Name Choose VPC/VNet ID of VPC-AVX Connection Type Unmapped Connection Name Arbitrary (e.g. avx-sonicwall-s2c) Remote Gateway Type Sonicwall Tunnel Type UDP Algorithms Unmark this checkbox IKEv2 Unmark this checkbox Encryption over DirectConnect Unmark this checkbox Enable HA Unmark this checkbox Primary Cloud Gateway Select Aviatrix Gateway created above Remote Gateway IP Address Public IP of Sonicwall (192.168.3.11 in this example) Pre-shared Key Optional (auto-generated if not entered) Remote Subnet 10.16.100.0/24 (On-Prem Network CIDR) Local Subnet 10.0.0.0/16 =============================== ================================================================= Creating Address Objects for the VPN subnets ======================================== Navigate to Network > Address Objects > click **Add**. Creating an Address Object for the Local Network ------------------------------------------------------------------- =============================== ================================================================= **Field** **Value** =============================== ================================================================= Name Arbitrary e.g. Site2Cloud-local Zone LAN Type Network Network The LAN network range Network Mask/Prefix e.g. 255.255.255.0 =============================== ================================================================= |image0| Creating an Address Object for the Cloud Network --------------------------------------------------------------- =============================== ================================================================= **Field** **Value** =============================== ================================================================= Name Arbitrary e.g. site2cloud-cloud Zone WAN Type Network Network The Cloud network range Network Mask/Prefix e.g. 255.255.0.0 =============================== ================================================================= |image2| Configuring the VPN Tunnel ====================================================== Navigate to VPN > Settings > click **Add**. On the **General** tab fill in the following fields: =============================== ================================================================= **Field** **Value** =============================== ================================================================= Policy Type Site to site Authentication Method IKE using Preshared Secret Name Arbitrary (e.g. Aviatrix-GW) IPsec Primary Gateway Address The public IP of the Aviatrix Gateway IPsec Secondary Gateway Address The public IP of the Aviatrix HA Gateway if configured Shared Secret Arbitrary Confirm Shared Secret Re-enter Shared Secret Local IKE ID Leave blank Peer IKE ID Leave blank =============================== ================================================================= |image1| Assigning the Local and Remote Address Objects to the Tunnel ------------------------------------------------------------------------------- Select the **Network** tab and select the Address objects created above. Choose local network from list: e.g. Site2Cloud-local. 1. Select the **Proposals** tab and set the IKE and IPsec values. =============================== ================================================================= **Field** **Value** =============================== ================================================================= Exchange Main Mode DH Group Group2 Encryption AES-256 Authentication SHA1 Life Time (seconds) 28800 =============================== ================================================================= IPsec (Phase 2) Proposals =============================== ================================================================= **Field** **Value** =============================== ================================================================= Protocol ESP Encryption AES-256 Authentication SHA1 Enable Perfect Forward Secrecy Mark this checkbox DH Group Group 2 Life Time (seconds) 3600 =============================== ================================================================= |image4| * Note - If Secondary Peer IP is configured, then Peer IKE ID must be left blank or else failover will not work properly. |image5| Advanced Settings -------------------------------- * Click the **Advance** tab. * Mark the **Enable Keep Alive** checkbox. * Click **OK** to save. |image3| .. |image0| image:: s2c_sonicwall/sw_lan_address_obj.png .. |image1| image:: s2c_sonicwall/sw_single_vpn.png .. |image2| image:: s2c_sonicwall/sw_wan_address_obj.png .. |image3| image:: s2c_sonicwall/sw_prop_vpn.png .. |image4| image:: s2c_sonicwall/VPN%20Policy%202019-12-04%2012-35-26.4.png .. |image5| image:: s2c_sonicwall/sw_failover_vpn.png .. disqus:: <file_sep> ======================================================== How to Build Simple and Scalable Transit VPC Solution ======================================================== 1. Solution Overview ====================== Aviatrix provides a Transit VPC solution that is centrally managed and simple to deploy, as documented in `this link. <http://docs.aviatrix.com/Solutions/aviatrix_aws_transitvpc.html>`_. The solution requires no CCIE and crypto skills for maintenance and troubleshooting the network connectivity. The document below is obsolete. Refer to `this doc for the next gen transit solution <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_. One friction in this Transit VPC solution is that each time when a spoke VPC is stood up, the IPSEC tunnel between the transit VPC and on-prem needs to be modified to include the new spoke VPC CIDR. This modification of IPSEC tunnel involves on-prem network team and can take up a few weeks of time. This document guides you to build a large and scalable Transit VPC network over Internet that requires minimum modification to the on-prem edge router or firewall devices. The idea can also be applied to the case where the connectivity between transit VPC and on-prem is over AWS Direct Connect. The idea of this scalable Transit VPC solution is to configure the IPSEC tunnel once between the transit VPC and on-prem edge router or firewall. Subsequent spoke VPC connectivity to on-prem requires no change to this edge router or firewall. This solution enables CloudOps team to be self sufficient in building and operating the hybrid cloud network. 2. Cloud Address Planning ========================== The first step is to obtain from your network admin the on-prem address space in the most summarized form. For example, the on-prem network consists of 172.16.0.0/16. The next step is to work with your on-prem network admin to carve out one or a set of consecutive network address space that is not used anywhere by your company and reserve that as your cloud address space. For example, the address space could be 10.0.0.0/8. All spoke VPC CIDRs and Transit VPC will be subset of the reserved cloud address space (e.g. 10.220.0.0/16, 10.221.0.0/16 and etc). 3. Transit VPC to on-prem IPSEC Tunnel ======================================== The second step is to use this carved out cloud address space to build just one IPSEC tunnel between your on-prem network and the transit VPC. What you need to do is to specify the local network as the carved out and non-used address space. The remote network addresses should be your on-prem network address. 4. Spoke VPC to on-prem IPSEC Tunnel ===================================== Once you have built the Transit VPC to on-prem IPSEC tunnel, you no longer need to modify edge routers or firewalls for any spoke VPC to on-prem IPSEC tunnels. Aviatrix transitive routing feature takes care of each new spoke VPC when it needs to connect to on-prem. You simply configure an encrypted peering between the spoke VPC to the transit VPC and then configure transitive peering from the spoke VPC to your On-Prem network through the Transit VPC. 5. Configuration Workflow ========================== 5.1 Pre Configuration Checklist ------------------------------- Before configuring VPC peering, make sure the following prerequisites are completed. **Pre Configuration Check List** 1. Deploy the Aviatrix Controller 2. Check VPC Settings These prerequisites are explained in detail below. 5.1.1 Deploy the Aviatrix Controller ------------------------------------- The Aviatrix Controller must be deployed and setup prior to configuring VPC and site peering. Please refer to "Aviatrix Controller Getting Started Guide for AWS" on how to deploy the Aviatrix Controller. `Aviatrix Controller Getting Started Guide <https://s3-us-west-2.amazonaws.com/aviatrix-download/docs/aviatrix_aws_controller_gsg.pdf>`_ Check and make sure you can access the Aviatrix Controller dashboard and login with an administrator account. The default URL for the Aviatrix Controller is: https://<public ip of Aviatrix Controller> 5.1.2 Check VPC Settings ------------------------- - The VPC must have at least one public subnet to deploy the gateway. This means one subnet must be associated with a route table that has an IGW as its default route. - If your Transit VPC and Spoke VPCs are in the same region and you like to route the traffic over AWS peering, go to AWS console and configure the necessary AWS peering between the two VPCs. 5.2 Configuration Steps ----------------------- Make sure the pre-configuration steps in the previous section are completed before proceeding. The instructions in this section will use the following architecture. The CIDR and subnets may vary depending on your VPC setup; however, the general principals will be the same. |image0| In this example we have four Cloud VPCs: 1 Transit VPC, 3 Spoke VPCs and a corporate data center. The network will be configured such that all spoke nodes and on-prem will be able to communicate with each other via the Transit VPC. 5.2.1 Step a – Deploy Gateways ------------------------------ The first step is to deploy Aviatrix gateways in each VPC. **Instructions:** a.1. Login to the Aviatrix Controller Console a.2. Click on Gateway -> "New Gateway" ============== ==================== **Setting** **Value** ============== ==================== Cloud Type Choose AWS Account Name Choose the account name Region Choose the region where your VPC is located VPC ID Choose the VPC Gateway Name This name is arbitrary (ex. gw01) Public Subnet Select a public subnet where the gateway will be deployed Gateway Size t2.micro is fine for testing. Enable NAT Uncheck this box VPN Access Uncheck this box ============== ==================== a.3. Click “OK”. It will take a few minutes for the gateway to deploy. Do not proceed until the gateway is deployed. a.4. Repeat steps a.2 and a.3 for the additional 3 VPCs in this example. a.5. Done 5.2.2 Step b – Connect Spoke VPC to Transit VPC --------------------------------------------------- This step explains how to connect a Spoke VPC to the transit VPC. **Instructions:** b.1. From the Aviatrix Controller Console b.2. Click Peering -> Encrypted Peering b.3. Click "New Peering" b.4. Select the Transit VPC #0 gateway (Aviatrix GW #0) and Spoke VPC #1 gateway (Aviatrix GW #1) for the peering. Note: If the two VPCs are in the same region, you can check the box “over AWS Peering”. This would allow the encrypted peering to route traffic over native AWS peering, resulting in 10 times bandwidth saving. b.5. Click "OK" b.6 Repeat steps b.4 and b.5 for more scalable Spoke VPCs as Spoke VPC #2 gateway (Aviatrix GW #2) and Spoke VPC #3 gateway (Aviatrix GW #3) in this example. b.7 Done 5.2.3 Step c – Connect Corporate Data Center to Transit VPC ------------------------------------------------------------ This step explains how to connect the corporate data center to the Transit VPC. **Instructions:** c.1. From the Aviatrix Controller Console c.2. Click Site2Cloud -> Add New =============================== =================================================== **Setting** **Value** =============================== =================================================== VPC ID/VNet Name Choose Transit VPC ID Connection Type Unmapped Connection Name This name is arbitrary (ex. corpdatacenter) Remote Gateway Type Aviatrix (in this example) Tunnel Type UDP Algorithms Uncheck Encryption over DirectConnect Uncheck Enable HA Uncheck Primary Cloud Gateway Choose Transit VPC gateway Remote Gateway IP Address Public IP address of On-Prem gateway Pre-shared Key Optional Remote Subnet 172.16.0.0/16 (in this example) Local Subnet 10.0.0.0/8 (in this example) =============================== =================================================== c.3. Click button "OK" c.4. View List, click the row of Transit VPC ID and Connection Name (ex. corpdatacenter) from above. c.5. Check Vendor, Platform and Software of On-Prem gateway on Corporate Data Center. Note: If your On-Prem gateway is: I. a On-Prem Aviatrix gateway -> select "Aviatrix" (in this example) II. a Cisco ASA -> select "Cisco" III. a third party router or firewall -> select "Generic" c.6. Click button "Download Configuration" c.7. If the On-Prem gateway is a Aviatrix CloudN as in this example, go to site2cloud page of CloudN website and simply import the downloaded configuration file and click OK. c.8. This template file contains the necessary information to configure the On-Prem gateway. Once the On-Prem gateway is configured, the tunnel will automatically come up. c.9. Done 5.2.4 Step d – Configure Transitive Routing -------------------------------------------- This step explains how to configure transitive routing so that every spoke and on-prem node can communicate with each other via the transit VPC. **Instructions:** d.1. From the Aviatrix Controller Console d.2. Click Peering -> Transitive Peering d.2.1. For Spoke VPC #1: i. Click "+ New Peering" ii. Source Gateway: Aviatrix GW #1, Next Hop VPC: Aviatrix GW #0 (Transit VPC), Destination CIDR: 172.16.0.0/16 iii. Click "OK" d.2.2. For Spoke VPC #2: i. Click "+ New Peering" ii. Source VPC: Aviatrix GW #2, Next Hop VPC: Aviatrix GW #0 (Transit VPC), Destination CIDR: 172.16.0.0/16 iii. Click "OK" d.2.3. Repeat steps d.2.1 for more scalable Spoke VPCs as Spoke VPC #3 gateway (Aviatrix GW #3) in this example. d.3. Done Troubleshooting =============== To check a tunnel state, go to Site2Cloud, the tunnel status will be displayed at "status" column. To troubleshoot a tunnel state, go to Site2Cloud -> Diagnostics. .. |image0| image:: TransPeering_OnPrem_media/TransPeering_OnPrem_2.PNG :width: 5.03147in :height: 2.57917in .. disqus:: <file_sep> ============================== UDP LoadBalanced VPN using DNS ============================== This feature is available from `Aviatrix software version 2.7 <http://docs.aviatrix.com/HowTos/UCC_Release_Notes.html#r2-7>`_ and later. AWS Elastic Load Balancing (ELB) does not support UDP traffic. To overcome this, the AWS Route53 service is leveraged to direct user VPN traffic to UDP VPN gateways in a round robin algorithm. .. Note:: UDP based OpenVPN® provides a higher packet throughput than a TCP-based VPN solution. A UDP-based VPN solution runs on UDP 1194. If you plan to deploy this solution for on-prem users, make sure your corporate firewall is open on UDP 1194 for outbound traffic. Configuration Workflow ====================== .. Tip :: Upgrade to the latest version. Make sure you are running 2.7+. 1. Create VPN Gateways from Gateways Page. Make sure you have the **VPN Access** option **Enabled** and **Enabled ELB** option is **No** . 2. Create DNS Loadbalancers. a. Go to OpenVPN® > Advanced > UDP Loadbalancer. b. Click **+New**. i. Select the cloud type and account (Currently only supported on AWS). ii. Enter the hosted zone name ( This must exist prior in your AWS Route53). iii. VPN Service name is a unique identifier for the Loadbalancer. For example a service name "vpn1" and hosted zone "aviatrix.com" will create a DNS entry "vpn1.aviatrix.com." iv. Select the Gateways that need to be added to the Loadbalancer. If you don't see any gateways, you probably have created VPN Gateways with ELB enabled (which will load balance TCP-based VPN gateway or you have created a non-VPN gateway. (You did not enable **VPN Access** during gateway creation time.) If your gateway type is incorrect, delete the gateway and create it again. v. Click **OK** and this creates the UDP Loadbalancer. 3. Add VPN Users. a. Add VPN Users directly to the Loadbalancer by going to OpenVPN® > VPN Users. b. In the VPC ID/LB /DNS select the Loadbalancer created in Step 2. (For example: vpn.aviatrix.com.) c. Enter a username and email in the fields provided to create the VPN user. 4. (Optional) Edit the DNS Loadbalancer. a. You can add or delete gateways to the Loadbalancer after it has been created. OpenVPN is a registered trademark of OpenVPN Inc. .. disqus:: <file_sep> =============================================== Standalone CloudN Deployment Checklist =============================================== When Insane Mode is applied to improve encryption performance between on-prem and cloud, you need to deploy the Aviatrix hardware appliance CloudN. Making this use case work requires edge router configurations. This document lists the checklist you should follow in successfully deploying Insane Mode for hybrid connection. CloudN Insane Mode can be applied to hybrid connection by AWS Direct Connect or Azure Express Route. CloudN can also be applied to hybrid connection by Internet. One CloudN supports `multiple Transit Gateway connections. <https://docs.aviatrix.com/HowTos/insane_mode.html#can-one-cloudn-appliance-connect-to-multiple-connections-of-direct-connect-or-express-route>`_ Starting in Release 6.2, Managed CloudN is the supported deployment model where CloudN configuration and operations are managed by the Controller. 1. Understand deployment architecture, or how routing works in this use case. 2. Connection over AWS Direct Connect or Azure Express Route: if you use AWS Direct Connect or Azure Express Route to connect to your data center, the deployment architecture is demonstrated in the diagram below. The diagram uses AWS Direct Connect for illustration purposes, but the architecture applies to Azure Express Route. |insane_mode_howto_dx| The key ideas for this AWS scenario are: - The edge (WAN) router runs a BGP session to VGW (AWS) where the edge router advertises a CloudN WAN subnet network and the VGW advertises the Transit VPC CIDR. - CloudN LAN interface runs a BGP session to the edge router where the edge router advertises on-prem network address range to CloudN LAN interface. - CloudN WAN interface runs a BGP session to Aviatrix Transit Gateway in the Transit VPC where Aviatrix Transit Gateway advertises all Spoke VPC CIDRs to CloudN and CloudN advertises on-prem network to the Aviatrix Transit Gateway. Following are a few common deployment architectures. Single Aviatrix CloudN Appliance ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |deployment| And the sample configuration on an ISR is as follows. |ISR-sample-config| Aviatrix CloudN Appliance with HA ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |deployment_ha| Redundant DX Deployment (Active/Standby) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In this deployment model, Direct Connects and ExpressRoutes are being used in a Active/Standby mode. The Preferred path is indicated on the image. .. note:: The firewalls on the left side of the picture cannot handle asymmetric traffic, which may be the reason for having Direct Connect as Active/Standby. |deployment_dual_dx| Redundant DX Deployment (Active/Active) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In this deployment model, Direct Connects/Express Routes are Active / Active. One of the requirements would be for the firewall to handle asymmetric routing. |deployment_dual_dx_aa| Step 1.2 Connection over Internet ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If you use high speed Internet to connect to a data center, the deployment architecture is described as below. |insane_mode_howto_internet| Key ideas are listed below: - CloudN LAN and WAN interfaces do not use public IP addresses. It relies on edge router or Firewall NAT function and Internet connectivity. - CloudN LAN interface runs a BGP session to the edge router where the edge router advertises on-prem network address range to CloudN LAN interface. - CloudN WAN interface runs a BGP session to Aviatrix Transit Gateway in the Transit VPC/VNet where Aviatrix Transit Gateway advertises all Spoke VPC/VNet CIDRs to CloudN and CloudN advertises on-prem network to the Aviatrix Transit Gateway. Example deployment diagram ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |deployment_internet| Step 2. Pre-deployment Request Form ------------------------------------ After you understand the deployment architecture and decide to move forward for this deployment, the next step is to fill out the `CloudN Appliance Request Form. <https://s3-us-west-2.amazonaws.com/aviatrix-download/InsaneMode_CloudN_Prep.docx>`_ The Aviatrix support team configures a CloudN appliance based on your input in the Request Form, then ships the appliance. Deployment topology for Aviatrix CloudN is as follows: |InsaneBeta| The key information in the Request Form that you must fill are explained below. ===================== ================== =========== =============== =============== ================== ===================== ============================================================= CloudN Interface Private IP Address Subnet Mask Default Gateway MTU Size Primary DNS Server Secondary DNS Server Note ===================== ================== =========== =============== =============== ================== ===================== ============================================================= 1- WAN Not Required Not Required WAN port that connects edge router 2- LAN Not Required Not Required Not Required LAN port that connects edge router 3- MGMT Not Required Management port for CloudN configuration and software upgrade 4- HPE iLO Not Required Not Required Not Required HP Integrated Lights-Out ===================== ================== =========== =============== =============== ================== ===================== ============================================================= 2.1 Internet Access ~~~~~~~~~~~~~~~~~~~~~~~~ A CloudN appliance does not require a public IP address, but the management port requires outbound internet access on the management port for software upgrade. Please see `Required Access for External Sites <https://aviatrix.zendesk.com/hc/en-us/articles/4417312119437-Aviatrix-Products-Access-to-external-FQDN-required>`_. .. note:: You must be registered to access the Aviatrix Customer Support website. If you are not already registered, you can sign-up at https://support.aviatrix.com. 2.2 BGP Requirement ~~~~~~~~~~~~~~~~~~~~~~~ BGP is required between the LAN port of the appliance and the on-prem router for route propagation. Step 3. Deployment Checklist ----------------------------------- 3.1 Before Powering Up CloudN ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Before powering up CloudN, make sure: a. The CloudN WAN cable, LAN cable and Management cable are properly plugged in to ASR and switches. #. Check the interface of ASR to CloudN WAN interface, make sure Proxy ARP is enabled (ip proxy-arp). #. ASR DX (Direct Connect) or ExpressRoute interface should only advertise CloudN WAN interface subnet network to VGW. #. ASR LAN (Datacenter facing) interface does not advertise Transit VPC/VNet CIDR to datacenter. #. ASR to CloudN LAN interface advertises datacenter networks. #. The VGW is attached to the Transit VPC/VNet. #. AWS Transit VPC/VNet Route Propagation is enabled. #. If there is an edge firewall in front of the edge router, make sure the firewall opens UDP port 500 and UDP port 4500 for traffic from the CloudN WAN Interface. CloudN builds an IPsec tunnel between CloudN WAN interface and Aviatrix Transit Gateway. The BGP session between the two interfaces is inside the tunnel. 3.2 Power up CloudN ~~~~~~~~~~~~~~~~~~~~~~~ After you power up CloudN, first test that the CloudN interfaces are alive and connected properly by doing the following tests. a. From ASR, ping the CloudN LAN interface, WAN interface and Mgmt interface. #. CloudN mgmt interface can ping Internet (From CloudN cli console). 3.3 Upgrade CloudN to the Latest Software ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ a. Log in to the CloudN console. Open a browser console and type: https://CloudN_Mgmt_IP_Address. #. Log in with username "admin" and the password provided by your Aviatrix Support Representative (You can change the password later). #. Upgrade CloudN to the latest. 3.4 Configure NTP Sync and SMTP Services ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ a. Add a firewall rule to allow CloudN’s MGMT outbound UDP port 123 access to ntp.ubuntu.com or to a local NTP server. #. In the CloudN UI, go to Setting > Controller > System Time. Enter ntp.ubuntu.com or a local NTP server then select the Sync option. #. Do a manual sync to the NTP server. #. In the CloudN UI, go to Setting > Controller > Email. Setup the SMTP settings to allow CloudN to send alert emails. 3.5 Configure Insane Mode ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From the Controller in AWS, configure Transit Setup Step 3 to CloudN, make sure to select all the correct options. .. a. CloudN IP Address is the CloudN WAN IP address #. CloudN Neighbor IP Address is the ASR to the CloudN LAN interface IP address #. After configuration, download the configure file and import to CloudN. #. If there is HA, import to CloudN HA. 3.6 Troubleshooting Tips ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ a. Check on CloudN Console. Go to Site2Cloud, make sure the tunnel is up. #. Check on CloudN Console, Go to Troubleshoot > Diagnostics > BGP, make sure the tunnel is up. Check BGP learned routes. #. Check on the Controller. Go to Transit Network > Advanced Config > BGP, make sure BGP is learning routes. Also check Diagnostics to execute BGP commands. #. Check on the Controller. Go to Controller > Site2Cloud and check the Site2Cloud and BGP status. .. |tunnel_diagram| image:: insane_mode_media/tunnel_diagram.png :scale: 30% .. |insane_tunnel_diagram| image:: insane_mode_media/insane_tunnel_diagram.png :scale: 30% .. |insane_transit| image:: insane_mode_media/insane_transit.png :scale: 30% .. |insane_datacenter| image:: insane_mode_media/insane_datacenter.png :scale: 30% .. |datacenter_layout| image:: insane_mode_media/datacenter_layout.png :scale: 30% .. |deployment| image:: insane_mode_media/deployment.png :scale: 30% .. |deployment_ha| image:: insane_mode_media/deployment_ha.png :scale: 30% .. |deployment_internet| image:: insane_mode_media/deployment_internet.png :scale: 30% .. |deployment_dual_dx| image:: insane_mode_media/deployment_dual_dx.png :scale: 30% .. |deployment_dual_dx_aa| image:: insane_mode_media/deployment_dual_dx_aa.png :scale: 30% .. |ISR-sample-config| image:: insane_mode_media/ISR-sample-config.png :scale: 50% .. |insane_routing| image:: insane_mode_media/insane_routing.png :scale: 30% .. |insane_mode_howto_dx| image:: insane_mode_media/insane_mode_howto_dx.png :scale: 30% .. |insane_mode_howto_internet| image:: insane_mode_media/insane_mode_howto_internet.png :scale: 30% .. |InsaneBeta| image:: insane_mode_media/InsaneBeta.png :scale: 30% .. disqus:: <file_sep> ========================================================= Example Config for Check Point VM in Azure ========================================================= In this document, we provide an example to set up the Check Point Security Gateway instance for you to validate that packets are indeed sent to the Check Point Security Gateway for VNet-to-VNet and from VNet to internet traffic inspection. .. note:: Firewall and Security Gateway word will be used interchangeably in this document. Both refers to Check Point Security Gateway product. Prerequisites ---------------- Before you start, make sure you understand on: - Basic Check Point Architecture - Check Point Security Management The following Check Point AMIs and software versions are supported in Azure by Aviatrix. ================================================================================== ==================== **Supported AMI Name** **Software Version** ================================================================================== ==================== CloudGuard IaaS Single Gateway - BYOL R80.40, R80.30 CloudGuard IaaS Single Gateway Threat Prevention & SandBlast (NGTX) - PAYG R80.40, R80.30 CloudGuard IaaS Single Gateway with Thread Prevention (NGTP) - PAYG R80.40, R80.30 CloudGuard IaaS Standalone (Gateway + Management) - BYOL R80.40 ================================================================================== ==================== .. important:: - Check Point Standalone does not require Security Management to manage polices. - Gateway NGTP and NGTX both requires Security Management to configure Security Gateway Polices. Check Point Reference Architecture ----------------------------------------------- It is absolutely paramount at this stage to understand the basic Check Point architecture to configure Check Point Security Gateway properly. Please see a reference architecture: |cp_arch_reference| As per the reference shown above the following steps will be required to configure security polices successfully: 1. Launch Check Point Security Gateway - Configure Interfaces and Static Routes and other specific Security Gateway configuration. #. Download, install, and configure Check Point Security Management (Optional) #. Download, install, and configure Check Point Smart Console - Launch Smart Console using Security Manager IP, add/authenticate one or more security gateways, configure security rules/polices, and push it to security gateways. Please follow the below steps to launch and configure Check Point Security Gateway in Azure. If you are looking to deploy Check Point in AWS environment, your starting point is `here <https://docs.aviatrix.com/HowTos/config_CheckPointVM.html>`_. Launching Check Point Firewall from Aviatrix Controller ----------------------------------------------------------------------- The Aviatrix Firewall Network (FireNet) workflow launches a Check Point Security Gateway instance at `this step <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#launching-and-associating-firewall-instance>`_. Go to the Aviatrix Controller > Firewall Network > Setup > Step 2a. Here is the Security Gateway information in this example for your reference. Please adjust it depending on your requirements. ========================================== ========== **Example setting** **Example value** ========================================== ========== Firewall Image Check Point CloudGuard IaaS Single Gateway R80.40 - PAYG (NGTP) Firewall Image Version 8040.900294.0593 Firewall Instance Size Standard_D3_v2 Egress Interface Subnet Select the subnet whose name contains "Public-FW-ingress-egress". Username admin (no alternatives) Authentication Method Password Password <PASSWORD> SIC Key Input a good SIC Key. Attach Check ========================================== ========== .. important:: SIC (Secure Inter-communication) Key needs to be noted somewhere and will be required to add Security Gateway inside the Security Manager. .. note:: Check Point Security Gateway instance has only 2 interfaces as described below. Additionally, firewall instance eth1 is on the same subnet as FireNet gateway eth2 interface. ======================================================== =============================== ================================ **Check Point VM instance interfaces** **Description** **Inbound Security Group Rule** ======================================================== =============================== ================================ eth0 (on subnet -Public-FW-ingress-egress) Egress or Untrusted interface Allow ALL eth1 (on subnet -dmz-firewall-lan) LAN or Trusted interface Allow ALL (Do not change) ======================================================== =============================== ================================ After the launch is complete, Aviatrix Controller automatically initiates the Security Gateway on-boarding process, configure interfaces and program RFC 1918 routes in Check Point Security Gateway. Logging in to Check Point Firewall Gaia Portal ------------------------------------------------------- After launch is complete, the Controller displays the Check Point Security Gateway with its public IP address of management/egress interface to login to the Check Point Gaia's console. Go back to the Controller, Firewall Network > Setup > Step 2a and Click on the Management UI as shown below. The URL takes you to the Check Point Security Gateway Gaia Portal you just launched. |avx-firewall-step7a_UI| .. note:: Please try to use different browser (e.g. Firefox) if the Management UI link is not opening on your default browser. Log in to the Gaia Portal with admin and password specified at launch time. Go to Network Management > Network Interfaces to review eth0 (WAN) and eth1 (LAN) configuration as shown below. |cp_firewall_interfaces| Review static routes RFC 1918 which is configured on LAN port, the purpose of those static route is to send the packets back to the Gateway (GW). Those static routes could be reviewed on the Network Management > IPv4 Static Routes page. |cp_firewall_static_routes| Routes can also be reviewed by clicking **Monitoring** on the Network Management > IPv4 Static Routes page. |cp_firewall_routes_monitoring| .. important:: Please make sure HTTPS (TCP 443 port) must be allowed in Check Point Security Gateway. By default, TCP 443 port is enabled in Security Gateway. This port will be used for Security Gateway health check. (Optional) Firewall Vendor Integration ------------------------------------------------- Go to the Aviatrix Controller > Firewall Network > Vendor Integration and complete the step as shown below: |cp_firewall_vendor_integration| Click **Save**, **Show** and **Sync** respectively. This automatically set up the non-RFC 1918 routes between Aviatrix Gateway and Vendor’s firewall instance in this case Check Point. This can also be done manually through Cloud Portal and/or Vendor’s Management tool. Downloading and Installing the SmartConsole ----------------------------------------------------------- Deploying and Installing Check Point Security Management ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The Check Point Security Gateway launched in the step 1 requires a management console (Check Point Security Manager) for managing one or more Security Gateways. Deploy and install the **Check Point Security Management** from Azure Marketplace in Azure's Console. .. important:: Check Point Security Management CloudGuard version should be R80.40. Check Point Security Manager deployment and installation steps are not part of this guide, and it has to be done manually. Log in to the Check Point Security Manager and download the SmartConsole on Windows-based computer. Option 1: Click **Download Now!** with the message Manage Software Blades using SmartConsole on the Overview page as below. |cp_security_manager| Option 2: Download it by using this link `R80.40 <https://supportcenter.Check Point.com/supportcenter/portal?action=portlets.DCFileAction&eventSubmit_doGetdcdetails=&fileid=101086>`_ Installing SmartConsole and Login ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Check Point's SmartConsole is a Windows-based application used to configure and manage polices. These polices can be applied to one or more Security Gateways. Install the SmartConsole and log into it with the Gaia Portal username, password, and IP Address of the Check Point's Security Manager. |smart_console_login| Configuring and Add Check Point Gateway in SmartConsole ------------------------------------------------------------------------- (Optional) Configure Security Gateway Secure Inter-Communication (SIC) Key ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Please skip this step if you remember the SIC Key provided during the Security Gateway launch from Aviatrix Controller. If you do not remember or wants to generate a new SIC Key then please follow this step. Check Point Gateway needs to be configured with one-time secure password in order to establish the secure communication with Check Point Security Management Portal. SSH to Check Point Gateway in order to configure One-time Secure Password. :: %ssh admin@ip-address The authenticity of host 'ip-address' can't be established. ECDSA key fingerprint is <KEY> Are you sure you want to continue connecting (yes/no/[fingerprint])? yes Failed to add the host to the list of known hosts (/Users/ahmednaail/.ssh/known_hosts). This system is for authorized use only. Password: You have logged into the system. By using this product you agree to the terms and conditions as specified in https://www.Check Point.com/download_agreement.html CLINFR0771 Config lock is owned by admin. Use the command 'lock database override' to acquire the lock. cp-firewall-sc-azure> lock database override cp-firewall-sc-azure> set expert-password Enter new expert password: Enter new expert password (again): cp-firewall-sc-azure> expert Enter expert password: Warning! All configurations should be done through clish You are in expert mode now. [Expert@cp-firewall-sc-azure:0]# cpconfig This program will let you re-configure your Check Point products configuration. Configuration Options: ---------------------- (1) Licenses and contracts (2) SNMP Extension (3) PKCS#11 Token (4) Random Pool (5) Secure Internal Communication (6) Enable cluster membership for this gateway (7) Check Point CoreXL (8) Automatic start of Check Point Products (9) Exit Enter your choice (1-9) :5 Configuring Secure Internal Communication... ============================================ The Secure Internal Communication is used for authentication between Check Point components Trust State: Initialized but Trust was not established Would you like to change the Activation Key? (y/n) [n] ? y Note: This operation will stop all Check Point Services (cpstop). Are you sure you want to continue? (y/n) [n] ? y Enter Activation Key: Retype Activation Key: initial_module: Compiled OK. initial_module: Compiled OK. Hardening OS Security: Initial policy will be applied until the first policy is installed The Secure Internal Communication was successfully initialized Configuration Options: ---------------------- (1) Licenses and contracts (2) SNMP Extension (3) PKCS#11 Token (4) Random Pool (5) Secure Internal Communication (6) Enable cluster membership for this gateway (7) Check Point CoreXL (8) Automatic start of Check Point Products (9) Exit Enter your choice (1-9) :9 Thank You... Terminate SSH session. Adding Check Point Security Gateway in SmartConsole ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ At this point, we have a One-time secure password (SIC Key) which will be used to add a Gateway inside Check Point Security Manager. Now go back to SmartConsole and Add a Gateway as shown below: |smartconsole_add_gateway| Click on Wizard Mode |cp_gw_creation_wizard| Next provide the GW information as shown in the table: ======================= =============================================== **Field** **Value** ======================= =============================================== Gateway Name Configure any name Gateway Platform Select CloudGuard IaaS Gateway IP * Static IP Address Provide Check Point Gateway IP address ======================= =============================================== |gw_general_properties| Next step is to establish a secure communication with a Gateway. ======================= =============================================== **Field** **Value** ======================= =============================================== Gateway' Name Provide you Gateway Name (Case-Sensitive) One-time Password Use same Password which you set during SSH session with Gateway Trust State Default Values ======================= =============================================== .. important:: If you see an error during communication establishment process that says, "Failed to connect to Security Gateway. SIC has not been established ...". Please SSH to your Gateway again and follow the same process mentioned in step 4, and try again to establish a communication with Security Gateway. |trusted_communication| Click "OK" and "Finish". |get_topology| |cp_wizard_summary| Review the Gateway Summary and click **OK**. |cp_gw_summary| At this point if all the steps are followed properly then you should see a Gateway under the Gateways & Servers tab. |cp_gw_added| Configuring Basic traffic Policy to Allow Traffic VNet to VNet ------------------------------------------------------------------------------ In this step, we will configure a basic traffic security policy that allows traffic to pass through the Security Gateway. Go to Security Policies > Access Control > Policy and configure a policy by either modifying the default Cleanup rule or Add a new rule above the default rule. ======================= =============================================== **Field** **Value** ======================= =============================================== Name Configure any name for this policy (i.e. allow-all) Source Any Destination Any VPN Any Service & Applications Any Action Accept Track Log ======================= =============================================== |basic_allowall_policy| Click **Install Policy** in Smart Console on top left corner, and then **Install** to commit the settings. |install_allowall_policy| |policy_installed| After validating that your traffic is being routed through your Security Gateway instances, you can customize the security policy to tailor to your requirements. [Optional] Configure Basic Traffic Policy to Allow Traffic VNet to Internet ----------------------------------------------------------------------------------------- In this step, we will configure a basic traffic security policy that allows internet traffic to pass through the firewall. .. important:: Enable `Egress inspection <https://docs.aviatrix.com/HowTos/firewall_network_faq.html#how-do-i-enable-egress-inspection-on-firenet>`_ feature on FireNet. 1. First of all, go back to the Aviatrix Controller. Navigate to Firewall Network > Advanced. 2. Click the skewer/three dot button. 3. Scroll down to Egress through Firewall and click **Enable**. 4. Verify the Egress status on the Firewall Network > Advanced page. |cp_egress_inspection| Second, go back to the Check Point SmartConsole. Navigate to the Gateways & Servers page and then double-click on the gateway itself to enable NAT function as the following screenshot. 1. Click **NAT**. 2. Enable **Hide internal networks behind the Gateway's external IP** checkbox. 3. Click **OK**. 4. Click **Install Policy**. |cp_policy_vpc_to_internet_nat_enabled| .. important:: NAT function needs to be enabled on the Check Point FW interface eth0 for this VNet to Internet policy. Please refer to `Check Point's NAT instruction <https://sc1.Check Point.com/documents/R76/CP_R76_Firewall_WebAdmin/6724.htm>`_ for details. **[Optional]** If you have default Cleanup rule, then navigate to the page Security Policies > Access Control > Policy and inject a new rule for Internet Policy on top of the default Cleanup rule. ======================= =============================================== **Field** **Value** ======================= =============================================== Name Configure any name for this policy (i.e. Internet-Policy) Source Any Destination Select the object with All_internet VPN Any Service & Applications Any Action Accept Track Log ======================= =============================================== Click **"Install Policy** and then **Install** to commit the settings. |cp_policy_vpc_to_internet| After validating that your traffic is being routed through your Security Gateway instances, you can customize the security policy to tailor to your requirements. Ready to Go ---------------- Now your Security Gateway instance is configured and ready to receive packets. Next step is to validate your configurations and polices using FlightPath and Diagnostic Tools (ping, traceroute etc.). Viewing Traffic Log -------------------------- You can view if traffic is forwarded to the firewall instance by logging in to the Check Point Firewall SmartConsole. Go to the Logs & Monitors page. For VNet to VNet traffic: ~~~~~~~~~~~~~~~~~~~~~~~~~ Launch one instance in PROD Spoke VNet and DEV Spoke VNet. Start ping packets from a instance in DEV Spoke VPC to the private IP of another instance in PROD Spoke VPC. The ICMP traffic should go through the firewall and be inspected in firewall. |cp_view_traffic_log_vpc_to_vpc| [Optional] For VNet to Internet traffic: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Launch a private instance in the Spoke VNet (i.e. PROD Spoke VNet) and start ping packets from the private instance towards Internet (e.g 8.8.8.8) to verify the egress function. The ICMP traffic should go through, and get inspected on firewall. .. important:: The Egress Inspection is only applicable to all VNets that deploys non-public-facing applications. If you have any Spoke VNet that has public facing web services, you should not enable Egress Inspection. This is because Egress Inspection inserts a default route (0.0.0.0/0) towards Transit GW to send the Internet traffic towards firewall to get inspected. Azure's System Default Route pointing towards Internet will be overwritten by User-defined default route inserted by the Controller. |cp_view_traffic_log_vpc_to_internet| .. |cp_arch_reference| image:: config_Checkpoint_media/cp_arch_reference.png :scale: 40% .. |avx-firewall-step7a_UI| image:: config_Checkpoint_media/avx-firewall-step7a_UI.png :scale: 35% .. |cp_firewall_interfaces| image:: config_Checkpoint_media/cp_firewall_interfaces.png :scale: 35% .. |cp_firewall_static_routes| image:: config_Checkpoint_media/cp_firewall_static_routes.png :scale: 35% .. |cp_firewall_routes_monitoring| image:: config_Checkpoint_media/cp_firewall_routes_monitoring.png :scale: 35% .. |cp_firewall_vendor_integration| image:: config_Checkpoint_media/cp_firewall_vendor_integration.png :scale: 40% .. |cp_security_manager| image:: config_Checkpoint_media/cp_security_manager.png :scale: 35% .. |smart_console_login| image:: config_Checkpoint_media/smart_console_login.png :scale: 40% .. |smartconsole_add_gateway| image:: config_Checkpoint_media/smartconsole_add_gateway.png :scale: 35% .. |cp_gw_creation_wizard| image:: config_Checkpoint_media/cp_gw_creation_wizard.png :scale: 50% .. |gw_general_properties| image:: config_Checkpoint_media/gw_general_properties.png :scale: 40% .. |trusted_communication| image:: config_Checkpoint_media/trusted_communication.png :scale: 40% .. |get_topology| image:: config_Checkpoint_media/get_topology.png :scale: 40% .. |cp_wizard_summary| image:: config_Checkpoint_media/cp_wizard_summary.png :scale: 40% .. |cp_gw_summary| image:: config_Checkpoint_media/cp_gw_summary.png :scale: 40% .. |cp_gw_added| image:: config_Checkpoint_media/cp_gw_added.png :scale: 40% .. |basic_allowall_policy| image:: config_Checkpoint_media/basic_allowall_policy.png :scale: 35% .. |install_allowall_policy| image:: config_Checkpoint_media/install_allowall_policy.png :scale: 30% .. |policy_installed| image:: config_Checkpoint_media/policy_installed.png :scale: 35% .. |cp_egress_inspection| image:: config_Checkpoint_media/cp_egress_inspection.png :scale: 30% .. |cp_policy_vpc_to_internet_nat_enabled| image:: config_Checkpoint_media/cp_policy_vpc_to_internet_nat_enabled.png :scale: 30% .. |cp_policy_vpc_to_internet| image:: config_Checkpoint_media/cp_policy_vpc_to_internet.png :scale: 30% .. |cp_view_traffic_log_vpc_to_vpc| image:: config_Checkpoint_media/cp_view_traffic_log_vpc_to_vpc.png :scale: 35% .. |cp_view_traffic_log_vpc_to_internet| image:: config_Checkpoint_media/cp_view_traffic_log_vpc_to_internet.png :scale: 30% .. disqus:: <file_sep> ================================== OCI IAM Least Privilege Policy ================================== When the Aviatrix Controller uses Oracle Cloud Infrastructure APIs to manage networking, gateway, and firewall resources, the following IAM Policies can be implemented for least privilege. In OCI, IAM is managed through groups and policies. The policy boundary can span a single compartment or an entire tenancy. If you wish to limit the Controller access permissions, you can do so by creating a group with a set of policies used by the Controller as shown below and scope the policy to the compartment. This document describes what the minimal set of policies are. `Oracle Cloud IAM documentation <https://docs.oracle.com/en-us/iaas/data-safe/doc/iam-policies.html>`_ covers more IAM concepts and technical implementation details. Aviatrix Minimal Required OCI IAM Policy Bound by Compartment -------------------------------------------------------------------------------------------- * Allow group <YOUR GROUP NAME> to manage volume-family in compartment <YOUR COMPARTMENT> * Allow group <YOUR GROUP NAME> to manage instance-family in compartment <YOUR COMPARTMENT> * Allow group <YOUR GROUP NAME> to manage virtual-network-family in compartment <YOUR COMPARTMENT> * Allow group <YOUR GROUP NAME> to inspect all-resources in compartment <YOUR COMPARTMENT> * Allow group <YOUR GROUP NAME> to inspect app-catalog-listing in compartment <YOUR COMPARTMENT> * Allow group <YOUR GROUP NAME> to read app-catalog-listing in compartment <YOUR COMPARTMENT> * Allow group <YOUR GROUP NAME> to manage app-catalog-listing in compartment <YOUR COMPARTMENT> To use this policy: 1. Assign the OCI User to the policy group. 2. Onboard the OCI User. Follow the OCI account onboarding instructions for the OCI user `here <https://docs.aviatrix.com/HowTos/oracle-aviatrix-cloud-controller-onboard.html>`_. .. note:: If you are deploying Transit FireNet that requires OCI Marketplace agreement, for example, Palo Alto VM-Series firewalls, you will need to log in as the user created and accept the agreement from the vendor in the compartment and region and version for the firewall deployment. See the screenshots below for reference. |pan_fw_subscribe| |pan_fw_accepted_agreement| .. |pan_fw_subscribe| image:: oci_iam_policy_media/pan_fw_subscribe.png :scale: 30% .. |pan_fw_accepted_agreement| image:: oci_iam_policy_media/pan_fw_accepted_agreement.png :scale: 30% .. disqus:: <file_sep> =============================== Multi-Cloud Global Transit FAQ =============================== Why should I choose Transit Architecture? ---------------------------------------------------------- Transit architecture is about building connectivity between the cloud and on-prem in the most agile manner possible. In the Transit architecture, there is one connection (not including the backup) between on-prem and a Transit VPC/VNet. Everything else (the Spoke VPC/VNets to on-prem traffic) is routed through the Transit VPC/VNet. The alternative to Transit architecture (often referred to as "flat" architecture) is to build one connection, either IPsec over the Internet or Direct Connect, each time you spin up a new VPC or VNet in the cloud. This requires changes at the on-prem edge, which requires a change control process that takes days to weeks. How do I configure a global Transit Network with the Aviatrix Solution? ------------------------------------------------------------------------------------------- If you plan to deploy an AWS Transit Gateway (TGW) based transit network, follow the `Aviatrix Transit Gateway Orchestrator Workflow <https://docs.aviatrix.com/HowTos/tgw_plan.html>`_. If you plan to deploy in Azure or deploy Aviatrix gateways in the Spoke VPC/VNets, follow the instructions `here. <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ Should the Aviatrix Transit Network all be deployed in ActiveMesh mode? ------------------------------------------------------------------------------------------ Yes. All Aviatrix Transit Network should be deployed in ActiveMesh mode. To learn more, check out `ActiveMesh FAQ <https://docs.aviatrix.com/HowTos/activemesh_faq.html>`_. Should I deploy one Transit Group for Dev and one for Prod? -------------------------------------------------------------------------- If your reason for two Transit hubs is security and a smaller blast radius, you need not worry about these when using the Aviatrix solution. Simply create two Security Domains in your deployment. I have two regions and two Direct Connects. How do I build a Multi-Region Transit solution? ------------------------------------------------------------------------------------------------------------------ Starting from release 4.1, `inter region transit network <https://docs.aviatrix.com/HowTos/tgw_design_patterns.html#connecting-transit-gateways-in-multi-regions-multi-cloud>`_ can be connected directly. Follow the instructions `here <https://docs.aviatrix.com/HowTos/transit_gateway_peering.html#transit-gateway-peering>`_. I have more than 100 VPCs. How do I overcome AWS Route Limits (100)? -------------------------------------------------------------------- When `AWS VGW carries more than 100 routes <https://aws.amazon.com/premiumsupport/knowledge-center/troubleshoot-bgp-vpn/>`_, its BGP session will crash unexpectedly, resulting in your network outage. Azure network has similar limitations, the following techniques work for both cloud providers. These are the options Aviatrix solution provides: 1. Summarizing Spoke VPC/VNet Routes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Enable `Spoke VPC route summarization <https://docs.aviatrix.com/HowTos/transitvpc_faq.html#how-to-summarize-spoke-vpc-cidr-ranges>`_ so that Transit GW advertise as few routes to VGW as possible. As long as you can limit the number of total routes on the VGW to less than 100, the Transit Network can support as many Spoke VPC/VNets as you need. Aviatrix Controller sends out alert/warning messages when it determines that the total routes carried by the VGW exceeds 80. This is to alert you to start reducing routes carried by the VGW to avoid potential network outage. This alert message is sent each time there is a route VGW advertised from VGW to Transit GW. 2. Bypassing VGW ~~~~~~~~~~~~~~~~ To permanently solve the route limit problem and not have to worry about summarizing routes at all and ever, use `External Device Option <https://docs.aviatrix.com/HowTos/transitgw_external.html>`_ to connect to on-prem directly over Direct Connect or the Internet. I have a few high bandwidth applications. How do I deploy them in a Transit solution? ------------------------------------------------------------------------------------------------------------- Aviatrix's `Insane Mode solution <https://docs.aviatrix.com/HowTos/insane_mode.html>`_ provides 10Gbps Transit network throughput. How can I fit an Egress Firewall into the Aviatrix Transit solution? ----------------------------------------------------------------------------------- There are two types of requirements. Egress Control Policies ~~~~~~~~~~~~~~~~~~~~~~~~ If your compliance requires egress policies and you have currently implemented AWS NAT gateways, consider using `Aviatrix Egress Control <https://docs.aviatrix.com/HowTos/FQDN_Whitelists_Ref_Design.html>`_. Aviatrix Egress Control is the most efficient way to provide a FQDN filter for all TCP/UDP protocols. What are the automation methods for a Transit Network? ------------------------------------------------------------------------- There are multiple resources to help you automate Transit Network setup. Note that if you are building a Transit Network following the workflow, you should `use Terraform <https://www.terraform.io/docs/providers/aviatrix>`_. Does the Aviatrix Transit Network support HA? ------------------------------------------------------------- Yes. Aviatrix Transit Gateways operates in `ActiveMesh mode <https://docs.aviatrix.com/HowTos/activemesh_faq.html>`_. Why are AWS t2 series instance types not recommended for Production deployment on a Transit GW? ------------------------------------------------------------------------------------------------------------------------------ When a t2 series Transit GW communicate with VGW over IPsec, there is a 3% packet drop for packet size less than 150 bytes by Transit GW due to an issue with AWS Xen hypervisor and the kernel version GW is using. This will be fixed in a future release. Note that this packet drop issue does not affect Spoke Gateways. How do I Resize a Transit GW instance? ------------------------------------------------------ Go to the Gateway page on the left sidebar > Transit GW and click **Edit**. Scroll up to Gateway Resize. Select the desired size and click **Change**. Resizing a Transit GW requires the gateway instance to be stopped and started again in a different size. There will be network time for traffic between cloud and on-prem. There should be no downtime for traffic between VPC/VNets as cloud-to-cloud traffic does not go through the Transit GW. During resizing, traffic will be switched to the backup Transit GW if HA is enabled, this will also switch Spoke to Transit traffic if Spoke VPC/VNet has HA enabled. Resizing a Transit GW will cause network downtime. How do I know which Transit GW a Spoke GW is sending traffic to? -------------------------------------------------------------------------------------------- You can tell which Transit GW carries the network traffic from a specific Spoke VPC/VNet by selecting Multi-Cloud Transit > BGP on the left sidebar. Select the Transit GW and click **Detail**. If the list of the Advertised Networks includes the Spoke VPC/VNet CIDR, this Transit GW routes traffic from the Spoke to on-prem; if it does not, check out the backup Transit GW. How can I route VPC/VNet Egress Internet-bound traffic to on-prem to go through the corporate firewall? ----------------------------------------------------------------------------------------------------------------------------- If you advertise 0.0.0.0/0 to VGW, Spoke VPCs will have that route point to the Transit GW and route egress Internet traffic to VGW and back to on-prem. Make sure you do not have NAT enabled on the Spoke GW or AWS NAT service enabled in the VPC/VNet. How do I know if the tunnel between the VGW and the Transit GW is up? ----------------------------------------------------------------------------------------- Go to Site2Cloud on the left sidebar. The tunnel status is displayed for each connection. How do I find out what routes being propagated from on-prem? ---------------------------------------------------------------------------------- On-prem routes are propagated to the VGW which in turn propagates to the Transit GW. There are two ways to see what learned routes are by the Transit GW: 1. Go to Site2Cloud, select the connection you specified at Step 3 during the Transit Network Workflow. Scroll down, you will see the Learned Network. Search for a learned route by typing a specific CIDR. #. Go to Peering > Transitive Peering. Click the box next to Destination CIDR column for a specific Spoke VPC/VNet GW. The Learned Routes are displayed and searchable. #. Go to Multi-Cloud transit > BGP > select a Transit GW, and click **Detail**. How do I find out BGP information on a Transit GW? ------------------------------------------------------------------ Go to Multi-Cloud Transit > BGP > Diagnostics, mark the checkbox for Predefined Show List. A list of BGP commands will be displayed. If you turn on debug command, make sure to turn it off when debug is finished to ensure the Transit GW is not flooded with debug messages. Excessive debug messages reduce throughput. How do I delete a Spoke GW? ---------------------------------------- Go to the Gateway page, select the gateway you wish to delete, and click **Delete**. An instance in a Spoke VPC/VNet cannot communicate with On-Prem Network. How do I troubleshoot? --------------------------------------------------------------------------------------------------------------------------------- There are many reasons why an instance in a Spoke VPC/VNet cannot communicate with an on-prem host or VM. The following troubleshooting steps may be helpful. 1. Make sure the `connection between VGW and Transit GW <http://docs.aviatrix.com/HowTos/transitvpc_faq.html#how-do-i-know-if-the-tunnel-between-vgw-and-transit-gw-is-up>`_ is up. #. Make sure the CIDR of the on-prem problem subnet (where VM or host is not reachable from a Spoke VPC/VNet instance) is propagated to Spoke VPC/VNet, that is, make sure Spoke VPC/VNet where the problem instance is deployed has `connectivity <http://docs.aviatrix.com/HowTos/transitvpc_faq.html#how-do-i-find-out-what-routes-being-propagated-from-on-prem>`_ to the problem subnet in on-prem network. #. Run traceroute by using an Aviatrix gateway as a test EC2. Launch a t2.micro instance Aviatrix Gateway from the `Gateway <http://docs.aviatrix.com/HowTos/gateway.html#gateway>`_ at the navigation bar (this gateway is going to be used as a test EC2 instance). Once this gateway is launched, you can run a `traceroute <http://docs.aviatrix.com/HowTos/troubleshooting.html#network-traceroute>`_ from this gateway (test EC2 instance) to the on-prem problem VM. (When the test is done, remember to delete the gateway to conserve consumption.) #. Do a traceroute from the on-prem problem VM or host to the Aviatrix Gateway test EC2 launched from the above steps. #. You can do a packet capture by going to Troubleshoot > Diagnostics > PACKET CAPTURE. Select the right tunnel interface and run packet capture. #. If the above tests pass, you should check security group settings on the instance and the destination VM. How do I build encryption over Direct Connect? --------------------------------------------------------------- AWS provides native solutions to add VPN capability between VGW and on-prem over Direct Connect. This improves security as data in motion is encrypted. Follow `the instructions here <https://aws.amazon.com/premiumsupport/knowledge-center/create-vpn-direct-connect/>`_ for this capability. We build an encryption between Aviatrix Transit GW and a VGW and between a Transit GW and a Spoke GW to provide an end-to-end encryption protection. How do I build redundancy between VGW and on-prem? ---------------------------------------------------------------------------- AWS provides a few native options for redundancy between VGW and on-prem. You can build redundant active/active VPN connections, redundant active/active DX connections and DX with backup VPN connections. `Read this doc <https://aws.amazon.com/answers/networking/aws-multiple-data-center-ha-network-connectivity/>`_ for implementation details. How do I deploy a user VPN Use Case on Transit Network solution? ----------------------------------------------------------------------------------- We recommend you to deploy `user VPN <http://docs.aviatrix.com/HowTos/uservpn.html>`_ in a shared service VPC/VNet. If this shared service VPC/VNet has connectivity to all other VPC/VNets, a user can reach any instances in these VPC/VNets as long as his/her profile policy allows. Does Transit Network support Azure VNet? ------------------------------------------------------ Starting from Release 3.3, you can launch a Spoke Gateway in Azure VNet. A best practice is to set up the Azure VNet the same way you usually do with AWS VPC: two types of subnets, public subnets and private subnets with respective routing tables, where the Spoke Gateway is launched in public subnet. .. tip:: Note that in Azure there is no explicit concept of public subnet. The idea here is to set up separate subnets and respective routing tables for the Aviatrix Gateway and user VMs. For convenience, we use the term "public subnet" to describe the subnet where Aviatrix Spoke gateway is launched. Such separation of subnets and routing tables provides you with the flexibility if you plan to use Spoke gateway also for FQDN functions. Why do I receive BGP Overlapping Address Alert emails? ----------------------------------------------------------------------- When Aviatrix Controller detects that on-prem propagated routes overlap or are a superset of Spoke VPC/VNet CIDR ranges, it sends an email to an admin, alerting a potential misconfiguration. Such email is sent once when a route change event occurs, for example, when BGP routes are flapping. The feature is enabled by default. If you wish not to receive the alert email, you can disable it. Go to Multi-Cloud Transit > BGP > Configuration and find the BGP Overlapping Alert Email setting. Click on the toggle switch to change the status to **Disabled**. How do I summarize Spoke VPC/VNet CIDR ranges? ----------------------------------------------------------------- If you have a large number of Spoke gateways attached to a Transit GW that you are concerned about exceeding the route limit a VGW can carry (100), you can summarize the Spoke VPC/VNet CIDRs. Before you configure summarization, make sure your Transit network meets the `prerequisite <https://docs.aviatrix.com/HowTos/transitvpc_faq.html#what-is-the-prerequisite-to-summarize-spoke-vpc-cidrs>`_. Go to Multi-Cloud Transit > Advanced Config > Edit Transit, select the Transit GW. (This Transit GW is created when you complete `Step 1 at the Transit Network workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-a-transit-gateway>`_.) After you select Transit GW, scroll down to "Manual BGP Advertised Network List", as shown below. Enter the summarized CIDR ranges and click **Change BGP Manual Spoke Advertisement**. You can enter a list of CIDRs separated by commas. |bgp_summarize| To disable this feature, simply remove the list to make the entry empty and then click **Change BGP Manual Spoke Advertisement**. How to move a Spoke Gateway to a different AZ? ------------------------------------------------------------- Follow the steps below: 1. `Detach the Spoke Gateway <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#remove-a-spoke-gw-from-a-transit-gw-group>`_ from the Transit Network group. #. Delete the Spoke Gateway. #. Launch a new Spoke Gateway in the desired AZ following the Transit Network solution workflow. #. `Attach <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#join-a-spoke-gw-to-transit-gw-group>`_ the Spoke Gateway. What is the prerequisite to summarize Spoke VPC/VNet CIDRs? --------------------------------------------------------------------------------- If you see the error below when configuring `Spoke VPC/VNet CIDR manual summarization <https://docs.aviatrix.com/HowTos/transitvpc_faq.html#how-to-summarize-spoke-vpc-cidr-ranges>`_, your Transit network is not ready for summarization. |bgp_summarize_error| The prerequisite for manual advertising is that all traffic from Spoke to Transit must be either on primary gateway path or backup gateway path. Before fixing the error, click the Peering page on the left sidebar. In the example shown below, spoke1 primary gateway is in Active state, however spoke2-hagw is in Active state. |spoke_to_transit_inconsistent| This inconsistency can be fixed by force switching spoke2 VPC/VNet to use the primary gateway, as shown below. |force_switchover_spoke2| Before you can summarize Spoke VPC/VNet CIDRs, you must make sure Spoke gateways all use either the primary gateway or all use the backup gateway if backup is enabled. How do I build Spoke-to-Spoke connectivity via Transit? --------------------------------------------------------------------- Starting from release 3.5, Transit network supports `Connected mode. https://docs.aviatrix.com/HowTos/transitvpc_designs.html#connected-transit-design_` where Spoke to Spoke connectivity is built automatically. How do a Spoke Gateway and VPC/VNet Private DNS work together? ---------------------------------------------------------------------------------------- All Aviatrix Gateways use a well-known public DNS server for their hostname resolutions. This is necessary as the gateway must access services such as AWS SQS to retrieve messages from the Controller and the accessibility cannot depend on underline connectivity. This is true even when a VPC has private DNS configured via its DHCP options, that is, while all EC2 instances use the private DNS to resolve hostnames, Aviatrix gateways use a well known public DNS for its own hostname resolution needs. On the other hand, Aviatrix also provides a feature `"Use VPC/VNet DNS Server" <https://docs.aviatrix.com/HowTos/gateway.html#use-vpc-vnet-dns-server>`_ which allows you to force the Aviatrix gateways to use a private DNS server. This is useful in certain use cases, for example, the organizations' Splunk server is hosted on prem with a private IP address. Another use case is when Aviatrix Egress FQDN is enabled for non-HTTP/HTTPS ports, the Aviatrix gateway must use the VPC/VNet's DHCP option in order to accurately obtain the IP address of a given hostname. There is a caveat when the "Use VPC/VNet DNS Server" is applied to a Spoke gateway where the custom DNS server is on-prem or is only reachable through the IPsec tunnels. If the Spoke Gateway has HA enabled, it will have an issue when the "Use VPC/VNet DNS Server" feature is applied to the primary Spoke Gateway. After the initial configuration, the system should work as intended. However, if a primary Spoke Gateway fail over to backup gateway, and the system attempts to fail back again, it will have a problem. The reason is that the Aviatrix primary gateway, after the first failover, has lost connectivity to the private DNS since the tunnel is down. However, the primary gateway must first obtain messages from the AWS SQS sent by the Controller to execute and reestablish the tunnel. Therefore, the Spoke Gateway will be stuck and the tunnel will remain down. The situation can be resolved by disabling the "Use VPC/VNet DNS Server" on the Spoke Gateway. As a rule of thumb, in a Transit Network, if you would like to have the Aviatrix Gateways use a private DNS server, this DNS server must be reachable regardless of the network tunnel status. How does the Aviatrix Transit Network Solution Differ from Cisco's CSR-Based Solution? ----------------------------------------------------------------------------------------------------------- They differ in the following areas: - **Central Control** - With the Aviatrix solution, the Aviatrix Controller is the single pane of glass for all networking in the cloud. - **AWS Transit Gateway Integration** If you have AWS deployment, Aviatrix Transit integrates with an AWS TGW seamlessly for high bandwidth Spoke VPC connection. Customers who do not require end to end encryption can now use the TGW native service to connect the Spoke VPCs. - **Network Segmentation** In the CSR-based solution, all Spoke VPCs have connectivity to each other through the Transit GW, even though these Spoke VPCs belong to different AWS accounts or business teams. In contrast, in the Aviatrix solution the Spoke VPC/VNets have no connectivity to each other, by default. Connectivity is built by design. With the TGW integration, you can customize the `Security Domains <https://docs.aviatrix.com/HowTos/tgw_faq.html#what-is-a-security-domain>`_ to meet your segmentation requirements. - **Connectivity Efficiency** In the Aviatrix solution, traffic between any two Spoke VPC/VNets can be routed via TGW or directly, as opposed to going through the instance based Transit GW as required by the CSR-based solution. Decoupling the different traffic streams reduces performance bottlenecks and removes single failure points. - **No unwanted route propagation** Since Spoke VPC/VNets run BGP in CSR solution, if a Spoke VPC/VNet also connects to a partner network via VGW, the partner network routes could be propagated to your own on-prem network. - **Simplicity** In Aviatrix's solution, BGP is only deployed between Transit GW and VGW. No Spoke VPCs run BGP. Simplicity leads to stability. Workflow-based, step-by-step instructions help you build out a Transit VPC/VNet solution in minutes. - **Monitoring** The Aviatrix solution integrates with Splunk, Sumo, remote syslog, ELK and DataDog to forward events from gateways to your favorite central logging service. - **Scalable** AWS has various limits in its infrastructure, such as a route entry limit of 100. This limits how many on-prem CIDRs and VPC CIDRs can be carried on a Transit GW. The Aviatrix solution overcomes that limitation. For a fun read, here is a `blog on the differences <https://www.aviatrix.com/blog/aviatrix-global-transit-solution-differ-csr-solution/>`_ If I already have a Transit to External Device connection using IKEv1, could I create another one using IKEv2? ---------------------------------------------------------------------------------------------------------------------------------------- Starting from 6.3 release, Aviatrix supports the feature `Transit to External Device Using IKEv2 <https://docs.aviatrix.com/HowTos/UCC_Release_Notes.html#multi-cloud-transit-network>`_. The prerequisite for IKEv2 is that you need to create the first Transit to External Device connection with IKEv2 enabled. If your current Transit gateway already has a connection using IKEv1 either is created by attaching the Spoke Gateway or is built in Multi-Cloud Transit > Attach/Detach tab, you need to delete it first before creating the Transit to External Device connection with IKEv2. How do I troubleshoot a Transit to External Device connection with IKEv2 issue? ------------------------------------------------------------------------------------------------- Refer to `Troubleshooting IPsec VPN connection with IKEv2 <https://docs.aviatrix.com/HowTos/troubleshooting_ipsec_vpn_connection_with_ikev2.html>`_ .. |bgp_summarize| image:: transitvpc_faq_media/bgp_summarize_transit_adv_page.png :scale: 60% .. |bgp_summarize_error| image:: transitvpc_faq_media/bgp_summarize_error_adv_page.png :scale: 60% .. |force_switchover_spoke2| image:: transitvpc_faq_media/force_switchover_spoke2.png :scale: 30% .. |spoke_to_transit_inconsistent| image:: transitvpc_faq_media/spoke_to_transit_inconsistent.png :scale: 30% .. disqus:: <file_sep> ============================================================ Transit Network Segmentation FAQ ============================================================ What is Multi-Cloud Transit Segmentation? -------------------------------------------------------- Aviatrix Multi-Cloud Transit Segmentation provides network isolation through network domains and connection policies to Aviatrix Transit network where both Spoke and Transit networks deploy Aviatrix Gateways across multi-region and multi-cloud. In releases prior to 6.7, the term "security domain" was used. This has been renamed to "network domain". The concept is described in the below diagram. |transit_segmentation| Where Spokes associated with the blue domain can communicate with each other while Spokes associated with the green domain can communicate with each other. But there is no cross communication between blue domain and green domain unless there is connection policy. The concept is the same as `Network Domains <https://docs.aviatrix.com/HowTos/tgw_faq.html#what-is-a-security-domain>`_ and `Connection Policies <https://docs.aviatrix.com/HowTos/tgw_faq.html#what-is-a-connection-policy>`_ defined in TGW Orchestrator, except this is implemented with Aviatrix Transit where both Spokes and Transit VPC/VNet deploy Aviatrix gateways. (Note the segmentation works with Azure native Spoke VNets.) What is a Network Domain in Multi-Cloud Transit? ------------------------------------------------------- A Network Domain is an Aviatrix enforced network of VPC/VNet members, where VPC/VNets in the Network Domain can communicate with each other, and VPC/VNets not in the network domain cannot communicate with VPC/VNets in the Network Domain. One or more Spoke VPC/VNets are members in a network domain. Spokes in a network domain can communicate with each other via an Aviatrix Transit Gateway. The Aviatrix Controller dynamically programs and updates both VPC/VNet route tables so that instances in different Spoke VPC/VNets in the same domain can communicate with each other. Two network domains are not connected, i.e., a Spoke in one domain has no connectivity to another Spoke in a different domain. Connection policy must be specified to connect the two domains so that Spokes in each domain can communicate with each other. The Network Domain also applies to the hybrid connection from Aviatrix Transit Gateway to on-prem or remote sites. Each BGP peer or connection can be associated with one Network Domain. What is a Connection Policy? ------------------------------------------ A connection policy is a rule enforced by Aviatrix for cross Network Domain connectivity. What are the benefits of using Network Domains and Connection Policies? ---------------------------------------------------------------------------------------------- The key use case for building Network Domains is to segment traffic for enhanced security posture. Using Network Domains and Connection Policies allow you to identify groups of Spokes and Edges with the same requirements from a networking point of view and then apply connection policies at the group level. This avoids having to individually specify connections at the Spoke level. The Aviatrix Controller takes care of route programming of all route tables. Can an Aviatrix Transit Network Domain work with TGW Orchestrator Network Domain? ------------------------------------------------------------------------------------- They do not work together at this time, however we have plan to integrate them in the future. How do I set up Multi-Cloud Transit Segmentation? ------------------------------------------------------------------- Follow the `Transit Segmentation Workflow. <https://docs.aviatrix.com/HowTos/transit_segmentation_workflow.html>`_. How many Network Domains are supported in Multi-Cloud Transit Segmentation? ------------------------------------------------------------------------------- The maximum number of Network Domains on each Aviatrix Transit Gateway is 200. What is the difference in implementation of Segmentation between Release 6.1 and Release 6.0? ------------------------------------------------------------------------------------------------- In Release 6.1 and later, each Network Domain is implemented as an individual route table on the Aviatrix Transit Gateway. This allows better handling for the default route (0.0.0.0/0) traffic if different domains require different egress next hop. In addition, duplicate Spoke CIDRs attached to different Aviatrix Transit Gateways can co-exist if they belong to different domains. What is the limitation of Segmentation? ------------------------------------------ - Duplicated CIDRs that cross domains or cross transits may not work all the time. Aviatrix does not support duplicated CIDRs that cross domains or cross transits. - Overlapping CIDRs advertised from on-prem to different Spoke network domains connected to one Aviatrix Transit Gateway is not supported. .. |transit_segmentation| image:: transit_segmentation_faq_media/transit_segmentation.png :scale: 30% .. |security_domain| image:: tgw_overview_media/security_domain.png :scale: 30% .. |domain_policy_diagram| image:: tgw_overview_media/domain_policy_diagram.png :scale: 30% .. |tgw_view| image:: tgw_overview_media/tgw_view.png :scale: 30% .. |tgw_transit_vpc_compare| image:: tgw_overview_media/tgw_transit_vpc_compare.png :scale: 30% .. |tgw_transit_orchestrator_compare| image:: tgw_overview_media/tgw_transit_orchestrator_compare.png :scale: 30% .. |edge_segmentation| image:: tgw_overview_media/edge_segmentation.png :scale: 30% .. |tgw_approval| image:: tgw_overview_media/tgw_approval.png :scale: 30% .. disqus:: <file_sep> ============================================================================ Configuration Example for Multi-Cloud Transit Integration Azure VNG VPN ============================================================================ This document describes the configuration workflow for the following network diagram. |vpn_topology| where there are two Spoke VNets, one with Aviatrix Spoke gateway (192.168.3.11/16) and one native Spoke VNet (192.168.3.11/16) Prerequisite ==================== `Upgrade <https://docs.aviatrix.com/HowTos/inline_upgrade.html>`_ Aviatrix Controller to at least version 6.3. .. tip:: We highly recommend you to ceate Azure Transit VNET by utilizing Aviatrix feature `Create a VNet <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ with Aviatrix FireNet VNet option enabled. Create a VNG in this Transit VNet. Connect VNG on On-Prem ======================================================================================================= If you have already created VNG in Transit VNet, skip this section. This section covers an example of building a VPN tunnel with Cisco IOS. For more information about Azure VPN, please check out the below documents: - Refer to `Azure VPN Documentation <https://docs.microsoft.com/en-us/azure/vpn-gateway/vpn-gateway-multi-site>`_ - Refer to `Azure VPN Gateway BGP Example <https://docs.microsoft.com/en-us/azure/vpn-gateway/bgp-howto>`_ - Refer to `Azure S2S Example <https://docs.microsoft.com/en-us/azure/vpn-gateway/tutorial-site-to-site-portal>`_ Adjust the topology depending on your requirements. Step 1.1 Create Virtual Network Gateway ---------------------------------------- 1. Login to Azure Portal and search "Virtual Network Gateway". 2. Click "Add" to create a new Virtual Network Gateway (VNG) |create_VNG| +------------------------------+-------------------------------------------+ | Field | Description | +------------------------------+-------------------------------------------+ | Subscription | Select a **Azure Subscription** | +------------------------------+-------------------------------------------+ | Name | Any Name | +------------------------------+-------------------------------------------+ | Region | Select Region e.g. West US2 | +------------------------------+-------------------------------------------+ | Gateway type | Select **VPN** | +------------------------------+-------------------------------------------+ | VPN type | Select **Route-based** | +------------------------------+-------------------------------------------+ | SKU | Any (e.g. VpnGw1) | +------------------------------+-------------------------------------------+ | Generation | Any | +------------------------------+-------------------------------------------+ | Virtual Network | Select **Transit FireNet Gateway VNet** | +------------------------------+-------------------------------------------+ | Public IP address | Any | +------------------------------+-------------------------------------------+ | Public IP address name | Any | +------------------------------+-------------------------------------------+ | Enable active-active mode | Any (By default Disabled) | +------------------------------+-------------------------------------------+ | Configure BGP | Select **Enabled** and give any ASN | +------------------------------+-------------------------------------------+ .. note:: This step may take up to 45 minutes to complete. 3. Once VNG is created. Go to Azure Portal -> Virtual Network Gateway -> Configuration and note down **Public IP Address** and **Default Azure BGP peer IP address** Step 1.2 Create Azure Local Network Gateways (LGW) ------------------------------------------------------------------- 1. Login to Azure Portal and search "Local network gateways". 2. Click "Add" to create a new Local Network Gateway |LGW_example| +------------------------------+-------------------------------------------+ | Field | Description | +------------------------------+-------------------------------------------+ | Name | Any | +------------------------------+-------------------------------------------+ | IP Address | Any e.g. Cisco IOS Public IP 172.16.31.10| +------------------------------+-------------------------------------------+ | Configure BGP settings | Check BGP checkbox | +------------------------------+-------------------------------------------+ | BGP ASN | Any (e.g. 65002) | +------------------------------+-------------------------------------------+ | BGP peer IP address | Any (e.g. 192.168.1.1) | +------------------------------+-------------------------------------------+ | Subscription | Select valid subscription | +------------------------------+-------------------------------------------+ | Resource group | Any or Create new | +------------------------------+-------------------------------------------+ | Location | Any (e.g. West US2) | +------------------------------+-------------------------------------------+ Step 1.3 Create a VPN Connection ---------------------------------------------------------------------- 1) Login to Azure Portal and search "Virtual network gateways" 2) Click on VNG created earlier 3) Select Connections 4) Click "Add" |Connection_Example| +------------------------------+-------------------------------------------+ | Field | Description | +------------------------------+-------------------------------------------+ | Name | Any | +------------------------------+-------------------------------------------+ | Connection type | Select Site-to-Site (IPSec) | +------------------------------+-------------------------------------------+ | Virtual network gateway | Select VNG just created | +------------------------------+-------------------------------------------+ | Local network gateway | Select LNG just created | +------------------------------+-------------------------------------------+ | Shared key (PSK) | Enter the value that matches the value | | | `Internet Key Exchange Configuration` | | | > **Pre-Shared Key** | +------------------------------+-------------------------------------------+ | Use Azure Private IP address | Uncheck | +------------------------------+-------------------------------------------+ | Enable BGP | Check | +------------------------------+-------------------------------------------+ | IKE Protocol | Select IKEv2 | +------------------------------+-------------------------------------------+ 5) Select the VPN you just created and click the Download Configuration button along the top. At the dialog, select Cisco for the Vendor, IOS for the Device family and firmware version 15.x (IKEv2) Click Download Configuration. You will use this file to create the other side of the tunnel. .. note:: Cisco IOS configuration is not accurate. Please modify it before use it. Cisco IOS sample configuration used in this example: :: Current configuration : 5983 bytes ! hostname Cisco-IOS ! username ec2-user privilege 15 ! crypto ikev2 proposal CSR-VPN-proposal encryption aes-cbc-256 integrity sha1 group 2 ! crypto ikev2 policy CSR-VPN-policy match address local 10.100.0.20 proposal CSR-VPN-proposal ! crypto ikev2 keyring CSR-VPN-keyring peer 172.16.17.32 address 172.16.17.32 pre-shared-key <key> ! ! crypto ikev2 profile CSR-VPN-profile match address local 10.100.0.20 match identity remote address 172.16.17.32 255.255.255.255 authentication remote pre-share authentication local pre-share keyring local CSR-VPN-keyring lifetime 3600 dpd 10 5 on-demand ! ! ! crypto ipsec transform-set CSR-VPN-TransformSet esp-gcm 256 mode tunnel ! crypto ipsec profile CSR-VPN-IPsecProfile set transform-set CSR-VPN-TransformSet set ikev2-profile CSR-VPN-profile ! ! ! interface Loopback11 ip address 1.1.1.1 255.255.255.255 ! interface Tunnel11 ip address 192.168.1.1 255.255.255.255 ip tcp adjust-mss 1350 tunnel source 10.100.0.20 tunnel mode ipsec ipv4 tunnel destination 172.16.17.32 tunnel protection ipsec profile CSR-VPN-IPsecProfile ! interface VirtualPortGroup0 vrf forwarding GS ip address 192.168.35.101 255.255.255.0 ip nat inside no mop enabled no mop sysid ! interface GigabitEthernet1 ip address dhcp ip nat outside negotiation auto no mop enabled no mop sysid ! router bgp 65002 bgp log-neighbor-changes neighbor 172.16.58.3 remote-as 65515 neighbor 172.16.58.3 ebgp-multihop 255 neighbor 172.16.58.3 update-source Tunnel11 ! address-family ipv4 network 1.1.1.1 mask 255.255.255.255 network 10.100.0.20 network 192.168.1.1 neighbor 172.16.58.3 activate exit-address-family ! iox ip forward-protocol nd ip tcp window-size 8192 ip http server ip http authentication local ip http secure-server ! ip nat inside source list GS_NAT_ACL interface GigabitEthernet1 vrf GS overload ip route 0.0.0.0 0.0.0.0 GigabitEthernet1 10.100.0.1 ip route 192.168.127.12 255.255.0.0 Tunnel11 ip route 172.16.58.3 255.255.255.255 Tunnel11 ip route vrf GS 0.0.0.0 0.0.0.0 GigabitEthernet1 10.100.0.1 global ! end Connect Aviatrix Transit Gateway with VNG ============================================================================ Refer to `Global Transit Network Workflow Instructions <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ for the below steps. Please adjust the topology depending on your requirements. Step 2.1 Deploy Aviatrix Multi-Cloud Transit Gateway and HA in Azure ----------------------------------------------------------------------- - Follow this step `Deploy the Transit Aviatrix Gateway <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html#step-2-deploy-the-transit-aviatrix-gateway>`_ to launch Aviatrix Transit gateway and enable HA with insane mode enabled in Azure Transit VNET. Insane mode is not required but an optional feature to increase throughput. - Instance size of at least Standard_D5_v2 will be required for `Insane Mode Encryptions <https://docs.aviatrix.com/HowTos/gateway.html#insane-mode-encryption>`_ for higher throughput. Please refer to this `doc <https://docs.aviatrix.com/HowTos/insane_mode_perf.html>`_ for performance detail. - Enable `Transit FireNet Function <https://docs.aviatrix.com/HowTos/transit_firenet_workflow.html#enable-transit-firenet-function>`_ Step 2.2 Connect Transit FireNet Gateway with VNG ------------------------------------------------------------------------------ This step assumes VNG is already deployed in the Transit VNet. - Go to Multi-Cloud Transit -> Step 3 Connect to VGW / External Device / Aviatrix CloudN / Azure VNG - Select **Azure VNG** radio button - Select **Primary Aviatrix Transit Gateway** in the drop down menu. Note if VNG has not been deployed in the Transit VNet, this step cannot complete. - VNG Name will populate automatically - Click **Connect** |vng_step| Step 2.3 Check Effective routes info on Azure portal ------------------------------------------------------- - Login Azure Portal - Search for "Network interfaces" on the search bar - Select Aviatrix Transit Gateway's interface - Navigate to the page "Effective routes" by clicking the link "Effective routes" under the section "Support + troubleshooting" - Check route entry for On-prem pointing Next Hop Type **Virtual network gateway** |azure_effective_routes_routing_entry| Attach Spoke VNet to Aviatrix Transit Gateway ============================================================================ Step 3.1 Deploy Aviatrix Spoke Gateway in Spoke VNet -------------------------------------------------------- - Create Azure VNET for Aviatrix Spoke Gateway by utilizing Aviatrix feature `Create a VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ or manually deploy it in cloud portal or feel free to use existing virtual network. Step 3.2 Launch Spoke Gateway and HA -------------------------------------- - Follow this step `Deploy Spoke Gateways <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_azure.html#step-3-deploy-spoke-gateways>`_ to launch Aviatrix Spoke gateway and enable HA with insane mode enabled in Azure Spoke VNET. Insane mode is optional. - Instance size of at least Standard_D5_v2 will be required for `Insane Mode Encryptions <https://docs.aviatrix.com/HowTos/gateway.html#insane-mode-encryption>`_ for higher throughput. Please refer to this `doc <https://docs.aviatrix.com/HowTos/insane_mode_perf.html>`_ for performance detail. Step 3.3 (Optional) Create Spoke VNet --------------------------------------------------- - If you do not have any Spoke VNet, create one by using Aviatrix feature `Create a VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ or manually do so in Azure portal. Step 3.3 Attach Spoke Gateways to Transit Network -------------------------------------------------- - Follow this step `Attach Spoke Gateways to Transit Network <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_azure.html#step-4-attach-spoke-gateways-to-transit-network>`_ to attach Aviatrix Spoke Gateways to Aviatrix Transit Gateways in Azure - Follow step `Attach Native Azure VNET to Transit Network <https://docs.aviatrix.com/HowTos/transit_firenet_azure_native_spokes_workflow.html?highlight=Transit%20Firenet%20Native%20Azure%20Spoke%20workflow#step-3-attach-native-spoke-vnets-to-transit-network>`_ to attach Azure Native VNET Spoke to Aviatrix Transit Gateway. Ready to go! ============ Now you should be able to send traffic from cloud to on-prem as well as on-prem to cloud over Azure Express Route. For FireNet deployment, follow the `Transit FireNet workflow <https://docs.aviatrix.com/HowTos/transit_firenet_workflow.html>`_. Troubleshooting ================= This section covers the end-to-end packet for troubleshooting purposes. This section covers the following: - Packet Flow when Inspection is disabled and traffic initiated from on-prem - Packet Flow when Inspection is disabled and traffic initiated from cloud - Packet Flow when Inspection is enabled and traffic initiated from cloud - Packet Flow when Inspection is enabled and traffic initiated from on-prem Before we start the packet walk hop by hop first make sure IPSec tunnel is connected and BGP session is up Azure Portal ------------- |VNG_VPN_IPSec| Cisco IOS ---------- Interface output to make sure all interfaces and tunnels are up. |ip_int_br| "Show ip bgp summary" shows BGP session status and if IOS learning any routes via BGP |bgp_su_output| Check IPSec IKEv2 tunnel status |crypto_IOS_output| Traffic Initiated from On-Prem and Inspection is disabled ----------------------------------------------------------- In this example, following VNETs in Azure will be used: - Azure Aviatrix Transit VNET (i.e. 192.168.127.12/16) - Azure Aviatrix Spoke VNETs (i.e. 192.168.3.11/16) |traffic_onprem_to_cloud_disable_inspection| Traffic flow from on-prem Cisco IOS Router with 10.100.0.0/16 subnet and Loopback 1.1.1.1/32 to Cloud Azure Native Spoke VNET (10.50.0.0/16) Lets start at Cisco IOS and verify if Spoke CIDR is learned and what is the Next Hop to reach to Spoke VNET. |sh_ip_bgp| Next Hop of Spoke VNET should be VPN termination point so it should be the IP address of VNG. - Login to Azure Portal and search "Virtual network gateways" - Go to Virtual network gateways, select Virtual Network Gateway created earlier - Click Configuration inside VNG and verify the IP address of Next Hop |verify_vng_ip| Traffic reached at VNG which is terminated at the Cloud. Now login to Azure Portal -> All resources -> VNG Route table to check what is the Next hop to reach Spoke VNET. |vng_rt| VNG route table showing next hop 172.16.17.3234 which is a IP of Loadbalancer |LB_IP| Next we need to check the LB rules and see what is the LB backend pool name |lb_rules| Once we know pool name then we go to Backend Pool and check the next hop IP address |be_pool| LB should be pointing to Transit Gateway. Go Aviatrix Controller console and verify the private IP address of Aviatrix Transit FireNet Gateway. |transit_ip| Next go to transit and check if Transit has route to reach to Spoke VNET |tr_rt| Transit is showing it is going via IP 172.16.31.10. How do we verify that IP?? |subnet_sn| |subnet_sn_1| Traffic Initiated from Cloud and Inspection is disabled ----------------------------------------------------------- In this example, following VNETs in Azure will be used: - Azure Aviatrix Transit VNET (i.e. 192.168.127.12/16) - Azure Aviatrix Spoke VNETs (i.e. 192.168.3.11/16) |traffic_cloud_to_onprem_disable_inspection| Traffic flow from Cloud Azure Native Spoke VNET (10.50.0.0/16) to on-prem Cisco IOS Router with 10.100.0.0/16 subnet and Loopback 1.1.1.1/32 Lets start from Spoke and verify if IOS routes are learned and what is the Next Hop to reach to on-prem. |spk_rt| Spoke showing next-hop as transit 172.16.31.10 (Transit FireNet Gateway) |tr_rt_ns| Transit FireNet Gateway showing the destination 1.1.1.1/32 via eth2 (172.16.58.3). In order to verify the next hop, we need to Transit FireNet Gateway interface eth2 and capture the subnet name to verify the pool address. |subnet_name| |subnet_ns| Once traffic reach to VNG, we can verify that now VNG routing table is showing the destination IP via VPN tunnel. |azure_effective_routes_routing_entry| .. |vpn_topology| image:: transit_gateway_integration_with_expressroute_media/vpn_topology.png :scale: 60% .. |traffic_onprem_to_cloud_disable_inspection| image:: transit_gateway_integration_with_expressroute_media/traffic_onprem_to_cloud_disable_inspection.png :scale: 60% .. |azure_effective_routes_routing_entry| image:: transit_gateway_integration_with_expressroute_media/azure_effective_routes_routing_entry.png :scale: 40% .. |vng_step| image:: transit_gateway_integration_with_expressroute_media/vng_step.png :scale: 40% .. |create_VNG| image:: transit_gateway_integration_with_expressroute_media/create_VNG.png :scale: 40% .. |LGW_example| image:: transit_gateway_integration_with_expressroute_media/LGW_example.png :scale: 40% .. |Connection_Example| image:: transit_gateway_integration_with_expressroute_media/Connection_Example.png :scale: 40% .. |VNG_VPN_IPSec| image:: transit_gateway_integration_with_expressroute_media/VNG_VPN_IPSec.png :scale: 40% .. |sh_ip_bgp| image:: transit_gateway_integration_with_expressroute_media/sh_ip_bgp.png :scale: 40% .. |crypto_IOS_output| image:: transit_gateway_integration_with_expressroute_media/crypto_IOS_output.png :scale: 40% .. |bgp_su_output| image:: transit_gateway_integration_with_expressroute_media/bgp_su_output.png :scale: 40% .. |ip_int_br| image:: transit_gateway_integration_with_expressroute_media/ip_int_br.png :scale: 40% .. |verify_vng_ip| image:: transit_gateway_integration_with_expressroute_media/verify_vng_ip.png :scale: 40% .. |vng_rt| image:: transit_gateway_integration_with_expressroute_media/vng_rt.png :scale: 40% .. |LB_IP| image:: transit_gateway_integration_with_expressroute_media/LB_IP.png :scale: 40% .. |lb_rules| image:: transit_gateway_integration_with_expressroute_media/lb_rules.png :scale: 40% .. |be_pool| image:: transit_gateway_integration_with_expressroute_media/be_pool.png :scale: 40% .. |transit_ip| image:: transit_gateway_integration_with_expressroute_media/transit_ip.png :scale: 40% .. |tr_rt| image:: transit_gateway_integration_with_expressroute_media/tr_rt.png :scale: 40% .. |traffic_cloud_to_onprem_disable_inspection| image:: transit_gateway_integration_with_expressroute_media/traffic_cloud_to_onprem_disable_inspection.png :scale: 40% .. |spk_rt| image:: transit_gateway_integration_with_expressroute_media/spk_rt.png :scale: 40% .. |tr_rt_ns| image:: transit_gateway_integration_with_expressroute_media/tr_rt_ns.png :scale: 40% .. |subnet_sn| image:: transit_gateway_integration_with_expressroute_media/subnet_sn.png :scale: 40% .. |subnet_sn_1| image:: transit_gateway_integration_with_expressroute_media/subnet_sn_1.png :scale: 40% .. |subnet_ns| image:: transit_gateway_integration_with_expressroute_media/subnet_ns.png :scale: 40% .. |subnet_name| image:: transit_gateway_integration_with_expressroute_media/subnet_name.png :scale: 40% .. disqus:: <file_sep> ============================================= Aviatrix Overview ============================================= What Do We Do? ================ Aviatrix is a cloud native networking company. Unlike any other networking vendors, the Aviatrix software platform understands the cloud provider's native constructs. This allows you to leverage and control the native constructs directly using the cloud provider's APIs extending their capabilities and integrating them into our software to provide organizations with turn key solutions accelerating your cloud journey. |aviatrix_overview| We focus on solving common networking problems faced by enterprises on their public cloud journey while providing a common control plane that provides multi-account/multi-cloud automation, advanced transit services, security services, troubleshooting capabilities, and visibility that you need. Some common enterprise use cases are shown below: - Datacenter to cloud (`Aviatrix Transit Network solution <http://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_) - Scalable Firewall deployment in the cloud (`Firewall Network <https://docs.aviatrix.com/HowTos/firewall_network_faq.html>`_) - Cloud to cloud VPN (`Encrypted peering <http://docs.aviatrix.com/HowTos/peering.html>`_ connectivity in a cloud and multi cloud ) - User to cloud VPN (`Remote user VPN (OpenVPN® based SSL VPN solution) <http://docs.aviatrix.com/HowTos/uservpn.html>`_ for developers) - Site to cloud VPN (`Branch and customer sites to cloud <http://docs.aviatrix.com/HowTos/site2cloud_faq.html>`_) - Multicloud VPN (`Multicloud Peering <http://docs.aviatrix.com/HowTos/GettingStartedAzureToAWSAndGCP.html>`_) We also provide security features for workloads/applications in the cloud: - `Gateway inline L4 stateful firewall. <http://docs.aviatrix.com/HowTos/tag_firewall.html>`_ - `Egress Security. <http://docs.aviatrix.com/HowTos/FQDN_Whitelists_Ref_Design.html>`_ - `High Speed Secure Access to AWS S3 <https://docs.aviatrix.com/HowTos/sfc_faq.html>`_. In addition, we have specific network solutions for `cloud migration <http://docs.aviatrix.com/HowTos/ipmotion.html>`_ and agile `datacenter extension <http://docs.aviatrix.com/Solutions/aviatrix_aws_meshVPC.html>`_ to cloud for vmware workloads. You can automate Aviatrix deployment by `Terraform configurations <https://docs.aviatrix.com/HowTos/aviatrix_terraform.html>`_. What are the complexities in cloud networking? --------------------------------------------------- Networking is a well established industry, what makes networking in the cloud new again? It's the complexity. The complexity of the cloud networking comes from the following areas and they only grow as time goes on: 1. Unprecedented Scale ^^^^^^^^^^^^^^^^^^^^^^^^^ - Cloud networks (VPC/VNET/VCNs) are many orders of magnitude in quantity than datacenters, driven by business billing/accounting and variable isolation requirements. - Multiple account ownership is a new concept for networking significantly increasing the number of cloud networks. - Multi-cloud strategies are the new industry norm enterprise will eventually require workloads spread across multiple cloud providers where they run best. 2. Security ^^^^^^^^^^^^^^^^ - As mission critical applications move to the cloud, security requirements applied to datacenter are catching up to the cloud. - Security consist of 5 types: - Egress to Internet: backend applications require API access to public hosted services. - On-prem and cloud: data moving between two security zones. - East and West: data moving between cloud networks. - Ingress: Accessing applications in the cloud. - Data security: Encryption for data in motion & at rest. 3. Unprecedented Performance ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - As more enterprise data and workloads traverse cloud networks, the enterprise needs to account for performance requirements in their cloud architecture. 4. Skills Gap ^^^^^^^^^^^^^ - Each cloud offers completely different terminology, APIs, semantics, and implementation details to provide networking. - Businesses cannot invest equally in time and effort to achieve skill parity across multiple cloud providers making it difficult to expand and pivot strategy. - New generation of operational engineers are short in sophisticated networking skills. Older networking engineers are short in API skills. 5. Interoperability ^^^^^^^^^^^^^^^^^^^^^ - Enterprise datacenters have compliance and established practices. Connecting to the on-prem sites of different businesses is complex due to the large set of legacy networking and security products. Why Should You Consider Us? ============================= Customers find that the most compelling value of our product is simplicity, both at configuration time and operation time. Simplicity is easier said than done in networking as it is by nature complex, so how can one achieve that? Here is how we do it: - **Abstraction** Abstraction is key to achieving simplicity at configuration time. Abstraction is about hiding layers and layers of complex network protocols, it is also about being use-case-driven at presentation layer by combining multiple networking components and features. APIs and Terraform templates also benefit from this abstraction as fewer of them need to be managed. - **Service Extension** As part of the product offering, we provide service integration to Splunk, SumoLogic, Datadog, Duo, Okta, SAML IDPs and firewall appliance deployment. - **Centrally Managed** A single pane of glass to manage all your cloud accounts and cloud network scattered in different regions and clouds. Hitless software upgrade eliminates operation downtime and maintenance window. - **Flexible Consumption Model** We offer pay-as-you-go metered images available on cloud providers' marketplace. No contract negotiation and no upfront commitment. Start instantly and turn it off at any time if you decide not to continue. For example, we hide the platform differences between AWS, Azure and GCP, so that you have the same experience when networking to any of them or between them. As another example, we hide the complexity of building IPsec so that you have the same experience when you build an IPsec tunnel as you would with AWS native peering: a couple of clicks or a couple of APIs. Taking this one step further, not only is the connectivity setup, the underlying route entry is configured too so that you have a turn key solution. Beyond simplicity, Aviatrix solutions solve many problems better than other products in each use case. This document summarizes these problems. Links to configuration documents are listed at the end of each section. Our goal is to become your go-to vendor for all things cloud networking. What Features Are Supported in Which Cloud? ----------------------------------------------- +--------------------------------------+---------+-----------+---------+---------+------------------+--------------------+ | **Feature** | **AWS** | **Azure** | **GCP** | **OCI** | **AWS GovCloud** | **Azure GovCloud** | +--------------------------------------+---------+-----------+---------+---------+------------------+--------------------+ | Marketplace Launch | Yes | Yes | Yes | Yes | Yes | Yes | +--------------------------------------+---------+-----------+---------+---------+------------------+--------------------+ | Multi Accounts | Yes | Yes | Yes | Yes | Yes | Yes | +--------------------------------------+---------+-----------+---------+---------+------------------+--------------------+ | Aviatrix Transit Network Spoke | Yes | Yes | Yes | Yes | Yes | Yes | +--------------------------------------+---------+-----------+---------+---------+------------------+--------------------+ | Aviatrix Transit Network Edge | Yes | Yes | Yes | Yes | Yes | Yes | +--------------------------------------+---------+-----------+---------+---------+------------------+--------------------+ | Firewall Network | Yes | Yes | Yes | Yes | Yes | Yes | +--------------------------------------+---------+-----------+---------+---------+------------------+--------------------+ | Transit Gateway Peering | Yes | Yes | Yes | Yes | Yes | Yes | +--------------------------------------+---------+-----------+---------+---------+------------------+--------------------+ | Native Peering | Yes | Yes | N/A | No | Yes | Yes | +--------------------------------------+---------+-----------+---------+---------+------------------+--------------------+ | FQDN Egress Control | Yes | Yes | Yes | Yes | Yes | Yes | +--------------------------------------+---------+-----------+---------+---------+------------------+--------------------+ | Stateful Firewall | Yes | Yes | Yes | Yes | Yes | Yes | +--------------------------------------+---------+-----------+---------+---------+------------------+--------------------+ | Advanced NAT | Yes | Yes | Yes | Yes | Yes | Yes | +--------------------------------------+---------+-----------+---------+---------+------------------+--------------------+ | Remote Access User VPN | Yes | Yes | Yes | Yes | Yes | Yes | +--------------------------------------+---------+-----------+---------+---------+------------------+--------------------+ | Site to Cloud VPN | Yes | Yes | Yes | Yes | Yes | Yes | +--------------------------------------+---------+-----------+---------+---------+------------------+--------------------+ | Insane Mode Encryption | Yes | Yes | Yes | Yes | Yes | Yes | +--------------------------------------+---------+-----------+---------+---------+------------------+--------------------+ | Logging Service Integration | Yes | Yes | Yes | Yes | Yes | Yes | +--------------------------------------+---------+-----------+---------+---------+------------------+--------------------+ | FlightPath Expert Diagnostics | Yes | Yes | Yes | No | Yes | Yes | +--------------------------------------+---------+-----------+---------+---------+------------------+--------------------+ | IPv6 | Yes | No | No | No | No | No | +--------------------------------------+---------+-----------+---------+---------+------------------+--------------------+ | PrivateS3 (unique to AWS) | Yes | No | No | No | Yes | No | +--------------------------------------+---------+-----------+---------+---------+------------------+--------------------+ | Controller Security Group Management | Yes | Yes | Yes | No | Yes | Yes | +--------------------------------------+---------+-----------+---------+---------+------------------+--------------------+ | Managed CloudN | Yes | Yes | Yes | Yes | Yes | Yes | +--------------------------------------+---------+-----------+---------+---------+------------------+--------------------+ What Features Are Supported in Which China Region Cloud? -------------------------------------------------------- `Features supported table in China region <https://docs.aviatrix.com/HowTos/aviatrix_china_overview.html#what-features-are-supported-in-which-china-region-cloud>`_ How To Launch Aviatrix? ========================= Our product, Aviatrix Secure Networking Platform, consists of two components, Controller and gateway. Gateways are launched from the Controller browser console by using your cloud account credentials with cloud provider APIs. The Controller image is available in `AWS Marketplace, <http://docs.aviatrix.com/StartUpGuides/aviatrix-cloud-controller-startup-guide.html>`_ `Azure Marketplace, <http://docs.aviatrix.com/StartUpGuides/azure-aviatrix-cloud-controller-startup-guide.html>`_ `GCloud <http://docs.aviatrix.com/StartUpGuides/google-aviatrix-cloud-controller-startup-guide.html>`_ and `OCI <https://docs.aviatrix.com/StartUpGuides/oracle-aviatrix-cloud-controller-startup-guide.html>`_. Datacenter to Cloud: Aviatrix Next-Gen Transit Network ========================================================= Aviatrix Transit Network solution solves many problems when connecting datacenters to a growing number of VPC/VNets. These problems are listed below: a. **AWS Transit Gateway** AWS released Transit Gateway (TGW), I need to migrate my current CSR-based Transit VPC solution. #. **No Route Propagation** AWS Transit Gateway (TGW) does not propagate on-prem learned routes to Spoke VPC route table, it requires manual programming. #. **Transit Solution for Azure** We have multiple Azure VNETs now, we need to form a transit network and connect them to on-prem and to AWS Transit network. #. **Change Control** Each time a new VPC is stood up, a change control process has to take place to modify the edge router for Direct Connect or IPsec over Internet. This is not agile and the risk of errors in configuration is not acceptable. #. **BGP** The CSR-based Global Transit solution runs VGW in each spoke VPC/VNet which runs a BGP session to Transit hub. This is operationally challenging to manage and troubleshoot. The BGP in VGW is a black box and invisible to the outside. #. **Not Secure** All spoke VPC/VNets in the CSR-based Global Transit solution have connectivity to each other through BGP route propagation. There is no network segmentation. The blast radius is my entire cloud network and datacenters. This is not acceptable by the security team. #. **Reach Route Limit** AWS has route entry limits of 100 per each routing table. Combining the number of VPC CIDRs and the list of on-prem CIDRs, this route limit is fast approaching or already a problem. #. **Extra Charge** In the CSR-based solution, traffic from one spoke VPC/VNet to another spoke VPC/VNet traverses through one transit and sometimes two transit hubs, resulting in 2x or 3x egress charge. #. **Too Complex** The CloudOps is a team of 6 engineers managing 34 AWS services, the skill set and resources it takes to manage the CSR-based Transit network is beyond what we want to handle. #. **10Gbps Transit** My current Transit network performance is capped at 1.25Gbps, our network requires much higher bandwidth. Follow this `self qualification process <https://www.aviatrix.com/blog/aviatrix-global-transit-solution-differ-csr-solution/>`_ to help your team decide if Aviatrix is the right solution for you. For how to setup the solution, follow up with `this doc. <http://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ Bring Firewall to Cloud: Aviatrix Firewall Network ============================================================= Here are the challenges of deploying firewalls in the cloud. a. **Complexity** Our security posture requires a firewall appliance for VPC/VNet to VPC/VNet traffic inspection, but we don't like the idea of building IPsec tunnels between networking device and firewalls. #. **Functionality** We need VPC/VNet to VPC/VNet traffic inspection, but traffic cannot be source NATed. #. **Performance** With centralized firewall deployment, a single firewall appliance is not sufficient to meet the performance requirement. Read `Aviatrix Firewall Network <https://docs.aviatrix.com/HowTos/firewall_network_faq.html>`_ for more details. Cloud to Cloud Peering ============================ The Aviatrix encrypted peering solution builds IPsec tunnels to connect two VPC/VNets. It solves these problems: a. **Regulation** My industry and regulations require packets in motion to be encrypted. AWS intra peering has no encryption. AWS inter region peering has one shared key. This is not acceptable. #. **Reach Route Limit** AWS has route entry limits of 100 per each routing table. Combining the number of VPC CIDRs and the list of on-prem CIDRS, this route limit is fast approaching or already a problem. #. **Multi Cloud** My workloads in AWS need connectivity to workloads in Azure or Google. #. **Defense in Depth** My CloudOps tools communicate to instances with data that is not encrypted. I need encryption for traffic between Shared Service VPC/VNet to workload VPC/VNet. #. **Require 10Gbps Encrypted Throughput** I need encryption for all data in motion and I need the performance to be up to 10Gbps. #. **Policy** We need to enforce stateful policies between two VPC connections. AWS native peering does not support policies. Aviatrix peering solution can be found `here. <http://docs.aviatrix.com/HowTos/peering.html>`_ User to Cloud Access ============================== Giving developers, contractors, and partners around the globe direct access to VPC/VNet is the best way to reduce access latency and improve productivity. Making it secure, high performance and manageable are keys to the solution. The Aviatrix user to cloud solution is based on OpenVPN®. The solution solves these problems: a. **Bastion Station** Bastion Station or Jump Host is a hack and insecure to allow developers to access cloud. Not acceptable. #. **Too Many Certs** If each VPC/VNet runs a SSL VPN gateway and there are 50 VPC/VNets, each developer needs to carry 50 VPN certificates and must learn which certificate to use to access which VPC/VNet. This is not acceptable. #. **Large Group** We have over 500 developers, we need a VPN solution that scales beyond a single instance based VPN solution. #. **OKTA** We are looking for a VPN solution that integrates with OKTA or DUO. #. **Blocked by Firewall** We have a Linux machine in the office that needs to behave like a VPN client. We need a VPN solution that runs on TCP port 443 to allow this machine to go through the corporate firewall. #. **Global Workforce** We have developers in multiple geo locations and cannot have them all land in the cloud in the same region. Latency will kill the user experience. #. **SAML Client** We are looking for an OpenVPN® based VPN solution with SAML client support. The Aviatrix user VPN solution can be found `on this link. <http://docs.aviatrix.com/HowTos/uservpn.html>`_ One feature in the solution that customers like the most is `Profile Based Access Control. <http://docs.aviatrix.com/HowTos/openvpn_features.html#authorization>`_ Site to Cloud Connectivity over Internet ========================================= If you run a SaaS service that needs to securely move data from your customer sites to the cloud, or your enterprise has hundreds of branch offices that need to connect to the cloud, building a secure tunnel to the cloud directly over the Internet is the most economical way as you leverage the Internet infrastructure already in place. In this case, the cloud provider's native VPN solution falls short by a long shot. The Aviatrix site2cloud solution solves these problems: a. **Traffic Black Hole** When the tunnel on the primary gateway is down, VPC/VNet route entry still points to the primary gateway, it does not point to the backup gateway. . #. **AWS VPN Gateway Limitation** AWS VPN gateway supports 10 connections per VPC. I have more than 10 sites, the native solution is not usable. #. **Azure VPN Gateway Limitation** Azure VPN gateway supports only 1 VPN connection for IKEv1. My office firewall device only supports IKEv1. #. **No Visibility** Cloud provider's VPN gateway is a black box, there is no visibility for troubleshooting. #. **No Manual** I have to configure and manage hundreds or thousands of IPsec tunnels, the manual way by using traditional vendors such as Cisco ASA and CSR is not possible. #. **Overlapping IP addresses** We run a SaaS operation, the CIDR blocks at your customer sites are not controlled by us. If a customer CIDR block overlaps with our operation VPC/VNet CIDR, we have to find a way to NAT the address. The cloud provider native solution is not usable in this case. #. **Encryption Algorithm Mismatch** As SaaS operators, we cannot control what VPN device a customer wishes to use. My end of VPN termination needs to have the flexibility to interoperate with customer equipment. The native solution does not have that flexibility. #. **Too Slow to Onboard a Customer** VPN runs on UDP port 500/4500, my customers have to request corporate firewall ports to open, is there a way to run IPsec tunnel on TCP 443? #. **Traffic Direction Problem** My SaaS service requires traffic to be initiated from the cloud to the customer site, AWS VPN gateway cannot support this traffic pattern. We have to setup a separate machine to constantly ping to keep the tunnel up! #. **Downtime Problem** Some appliances force all IPsec tunnels to reset and go down when a new tunnel is being established, which affects business continuity and is not acceptable when the number of sites go beyond 10. #. **Skill Problem** We don't have a team of CCIEs to handle the load. To learn how to set up Aviatrix Site2Cloud, follow up with `this link. <http://docs.aviatrix.com/HowTos/site2cloud.html>`_ Gateway Inline L7 FQDN for Egress Control ================================================== This solution is about adding security control to private workloads or applications accessing Internet. AWS and Azure provide a NAT gateway or NAT service, but it is limited in scope. A traditional firewall is either too complex or too expensive to be deployed per VPC/VNet. Aviatrix L7 FQDN filter solves these problems: a. **No policies** AWS NAT Gateway has no inbound/outbound policies. I have to configure security groups in each instance that needs Internet access. #. **Only IP Based Rules** AWS NAT instance provides security groups, but it is IP address based and limits to 50 rules. My application needs to make API calls to Office 365 and that site alone resolves to hundreds of changing IP addresses. Using a Security group is not an acceptable solution. #. **Compliance** Our applications process PCI data and requires egress security policies. #. **Firewall for Each VPC/VNet is Too Complex** My cloud instances are workloads and programs, they make API calls to known destinations. Deploying a traditional firewall that requires certs and keys to decrypt every packet for inspection is too complex and an overkill. #. **Firewall for Each VPC/VNet is Too Expensive** Traditional firewall of IDS/IPS is too expensive to be deployed per VPC/VNet. #. **Whitelisting** All I need is to be able to white list or black list the well known destinations by specifying them as fully qualified domain names (FQDN) for my http and https traffic. Support wild card or regex is a bonus. #. **Only for HTTP/HTTPS** Azure's Firewall service does not support FQDN filtering on SSH and SFTP services. Follow up with more details on `Aviatrix FQDN filter solution. <http://docs.aviatrix.com/HowTos/FQDN_Whitelists_Ref_Design.html>`_ Gateway inline L4 Stateful Firewall ==================================== Whenever there is traffic going through Aviatrix gateway, you can apply an IP address based stateful firewall policies. This reduces the need to have to configure security groups of each instances in the VPC/VNet for traffic between VPC/VNets. There is no limit as to how many rules you can apply on Aviatrix gateway. Aviatrix solution solves these problems: a. **Security Rule Limits** A cloud instance's security group has a limit of 50 rules. How do I get around that? #. **Enforce Security Policies** Developers don't always follow the best practice when it comes to security, enforcing policies at the gateway takes that worry away. #. **Regulation** We cannot use the AWS VPC Peering as it does not allow us to apply policies. We need an infrastructure presence that not only provides security but also enforce policies. To learn how to setup the L4 firewall, `follow the doc. <http://docs.aviatrix.com/HowTos/tag_firewall.html>`_ High Speed Secure Access to AWS S3 (PrivateS3) ================================================ Aviatrix PrivateS3 provides control and visibility for AWS S3 upload/download while leveraging the high speed private connections. It solves the following problems. a. **Prevent Data Leakage** We attempt to use AWS Direct Connect for high speed access to S3, but doing so anyone in the company can upload data to their own S3 buckets. #. **Palo Alto Firewall not usable** Palo Alto Firewall FQDN uses DNS name resolution which does not work on S3 as it has hundreds of thousands of IP addresses and as such the firewall is not usable. To learn more, `follow the PrivateS3 FAQ <https://docs.aviatrix.com/HowTos/sfc_faq.html>`_ Extending Workloads to Cloud ============================== Not all your workloads require the bandwidth and latency that calls for a Direct Connect transport. For your Dev and QA or many applications, an existing Internet connectivity is sufficient. Even better, Aviatrix provides a unique solution in which you do not even need to make changes to the edge router. `Learn how this solution works. <http://docs.aviatrix.com/Solutions/aviatrix_aws_meshVPC.html>`_ OpenVPN is a registered trademark of OpenVPN Inc. .. |aviatrix_overview| image:: aviatrix_overview_media/aviatrix_overview2.png :scale: 25% .. |aviatrix_backbone| image:: aviatrix_overview_media/aviatrix_backbone.png :scale: 30% .. |FullMesh_overview| image:: aviatrix_overview_media/FullMesh_overview.png :scale: 50% .. |image1| image:: AviatrixCloudControllerStartupGuide_media/image002.png :width: 4.80625in :height: 3.21803in .. |image2| image:: AviatrixCloudControllerStartupGuide_media/image003.png :width: 5.33067in :height: 2.04513in .. |image3| image:: AviatrixCloudControllerStartupGuide_media/image004.png :width: 4.92712in :height: 2.20352in .. |image4| image:: AviatrixCloudControllerStartupGuide_media/image005.png :width: 5.53494in :height: 3.11814in .. |image5| image:: AviatrixCloudControllerStartupGuide_media/image006.png :width: 5.21042in :height: 2.60298in .. |image6| image:: AviatrixCloudControllerStartupGuide_media/image007.png :width: 4.61664in :height: 4.22847in .. add in the disqus tag .. disqus:: <file_sep> ========================================================= Aviatrix Transit Gateway Encrypted Peering ========================================================= Transit Gateway Peering connects two or more Aviatrix Transit Gateways in a partial or full-mesh manner, as shown in the diagram below. The Aviatrix Transit Gateways may be deployed in AWS or Azure, where each Transit GW connects a group of Spoke VPC/VNets. As a result of Transit Gateway Peering, two groups of Spoke VPC/VNets can communicate with each other via the Transit Gateways. |multi-region| The instructions are as follows. 1. Launch Two Aviatrix Transit Gateways. If you have not done so, follow the instructions `here <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-a-transit-gateway>`_ to launch an Aviatrix Transit GW. Repeat to launch more Transit GWs. Starting from Release 4.3, InsaneMode is supported on Transit Gateway Peering. Enable Transit Gateway Peering InsaneMode by launching the gateway with InsaneMode. .. tip:: The Aviatrix Transit GWs are typically launched during the workflow of the TGW Orchestrator and Transit Network. If the transit cluster does not need to connect to on-prem, skip `the step 3 <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#connect-the-transit-gw-to-aws-vgw>`_ that connects to VGW/CloudN/External Device. 2. Establish Transit GW Peering by navigating to Transit Network > Transit Peering > Add New. Select one of each Transit Gateway and click **OK**. There are a few optional and advanced options as described below. Excluded Network CIDRs ^^^^^^^^^^^^^^^^^^^^^^^^^^ Excluded Network CIDRs is an optional field. When the field is empty, a Transit Gateway propagates all learned routes from both Spoke VPC/VNets and on-prem. The use case for this field is if there are conflicting or identical CIDRs on both sides of the Transit Gateways, the peering action will be rejected. Using the filter option prevents the overlapped CIDRs from being propagated to the other Transit Gateway. Input a list of CIDRS separated by comma. You can edit this field after the Transit Peering took place. Go to Transit Network > Transit Peering, highlight the peering connection. Click the 3 dots skewer and click **Edit** to modify the Excluded Network CIDR list. The diagram below illustrates how Excluded Network CIDRs can be used in a two region deployment. In this case, 10.20.0.0/16 appears on both sides as VPC/VNet CIDR. To allow Transit Peering to proceed, configure on both Transit Gateways Excluded Network CIDRs with 10.20.0.0/16. |excluded_network_cidrs| Excluded TGW Connections ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This feature applies to TGW hybrid connections. This is because TGW does not preserve BGP information in its learned routes. When you use AWS Transit Gateway (TGW) to connect to on-prem via DXGW or VPN, there are situations where on-prem advertise the same network CIDRs to TGW in two different regions. When you connect the two regions by the Aviatrix Transit Gateway Peering, the network CIDR overlapping problem will occur. This feature allows you to not to advertise certain TGW hybrid attachment (DXGW and VPN) to the remote Aviatrix Transit Gateway and therefore the remote TGW. In the dropdown menu, highlight the TGW hybrid connections (The input box is empty if there is no such connection.), multi-select the connections. The selected connections are excluded to advertise to the remote site. You can edit this field after the Transit Peering took place. Go to Transit Network > Transit Peering, highlight the peering connection. Click the 3 dots skewer and click **Edit** to modify the Excluded Connection list. The diagram below illustrate the use case for this feature. In the diagram, both on-prem connects to TGW and advertise 10.0.0.0/8. Transit Gateway Peering will fail because there are conflict routes. You solve the problem by configuring on both Transit Gateways to exclude 10.0.0.0/8. With this configuration, Site-1 still accesses Prod-1/Prod-2 and Dev-1/Dev-2 via the local regional TGW and Site-2 accesses Prod-3/Prod-4 and Dev-3/Dev-4 via its local regional TGW. |excluded_tgw_connections| Peering over Private Network ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This advanced option only appears and applies to when the two Multi-Cloud Transit Gateways is each launched in Insane Mode and each is in a different cloud type. For example, one Multi-Cloud Transit Gateway in AWS and the other in Azure. Peering over Private Network function is an optional field. When this checkbox is checked, users are able to build Aviatrix Transit Gateway peering over multi-cloud where there is private network connectivity. One of the use cases is two Aviatrix Transit Gateways deployed in two different public clouds where each has its private connectivity such as AWS Direct Connect and Azure ExpressRoute connecting to on-prem or a co-location. By building a Transit Gateway private peering, Aviatrix Transit Gateway forwards traffic over the private links to the other Aviatrix Transit Gateway and beyond. For example configuration workflow, check out this doc `Aviatrix Transit Gateway Peering over Private Network Workflow <https://docs.aviatrix.com/HowTos/transit_gateway_peering_with_private_network_workflow.html>`_. Peering over Public Network ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Aviatrix Transit Gateway Peering over the public network expands transit gateway peering across Cloud service providers over the internet by using Aviatrix Insane Mode High Performance Encryption (HPE) tunneling. Aviatrix Insane Mode HPE enables high throughput performance and high performance encrypted peered connections between the intercloud transit gateways. For more information about Insane Mode HPE tunneling, refer to `Insane Mode Encryption FAQ <https://docs.aviatrix.com/HowTos/insane_mode.html>`_. To establish peered transit gateways over the internet, refer to `Multi-cloud Transit Gateway Peering over Public Network Workflow <https://docs.aviatrix.com/HowTos/transit_gateway_peering_over_public_network_workflow.html>`_. Single-Tunnel mode ^^^^^^^^^^^^^^^^^^^^^ Single-Tunnel mode applies to Transit Gateway peering over private network when two multi-cloud Transit Gateways are launched in Insane Mode. For example, one multi-cloud Transit Gateway is in AWS and the other in Azure. When Single-Tunnel mode is selected, instead of building up to 50 IPSec tunnels (as in Insane Mode) between the two multi-cloud Transit Gateways, only a single tunnel connection is established. One use case is where the underlying private network is a low speed (up to 4Gbps) link across the two cloud types. By using the Single-Tunnel mode, you do not pay the Insane Mode license charges. When the multi-cloud Transit Gateways enable HA on both cloud types, the aggregate throughput via Single-Tunnel mode can reach 4Gbps. Default Route Propagation Behavior -------------------------------------------------- If centralized egress is enabled by local TGW FireNet or Transit FireNet, the default route 0.0.0.0/0 is **not** propagated to the remote Aviatrix Transit Gateway via Transit Peering. On the other hand, if on-prem advertise the default route to the Aviatrix Transit Gateway, this default route is propagated to the remote Aviatrix Transit Gateway via Transit Peering. Spoke-to-Spoke Peering Monitoring ------------------------------------- The Peering page is only used only to create and delete peered spoke-to-spoke connections in ActiveMesh mode. To view the status of the connection, go to the Multi-Cloud Transit > List > Spoke page. .. |multi-region| image:: tgw_design_patterns_media/multi-region.png :scale: 30% .. |excluded_tgw_connections| image:: transit_gateway_peering_media/excluded_tgw_connections.png :scale: 30% .. |excluded_network_cidrs| image:: transit_gateway_peering_media/excluded_network_cidrs.png :scale: 30% .. disqus:: <file_sep> ============================================================== Migrating a CSR Transit to AWS Transit Gateway (TGW) ============================================================== This document assumes that you have deployed a `CSR Transit solution <https://aws.amazon.com/answers/networking/aws-global-transit-network/>`_ with Transit hub CSR instances and VGWs in Spoke VPCs. The steps below provide instructions to migrate a live CSR deployment to Aviatrix with the Transit Gateway Orchestrator. The objectives here are: - No change to any on-prem network. - No change to the connectivity between AWS VGW and on-prem. (either over DX or over Internet or both) - Re-use AWS VGW deployed in CSR based Transit hub VPC if possible. - No change to existing VPC infrastructure. - Minimum operation downtime. There are a couple of patterns during the migration phase, consider the one that meets your requirements. .. Note:: This document assumes you have already `launched an Aviatrix Controller <http://docs.aviatrix.com/StartUpGuides/aviatrix-cloud-controller-startup-guide.html>`_. .. Before the migration process starts, plan out what security domains you need to create and which security domains should connect other domains. If you are not sure and need to transition, proceed with no worries. The security domains can be added and modified at any time. 1. `Launch a Transit Gateway <https://docs.aviatrix.com/HowTos/tgw_plan.html#creating-an-aws-tgw>`_. 2. If you have plans for custom security domains, follow `these instructions <https://docs.aviatrix.com/HowTos/tgw_plan.html#creating-a-new-security-domain>`_ to create them. Then, `build connection policies <https://docs.aviatrix.com/HowTos/tgw_plan.html#building-your-domain-connection-policies>`_. If you do not intend to build custom security domains, skip this section. 3. `Launch an Aviatrix Transit GW and enable HA in the Transit hub VPC <https://docs.aviatrix.com/HowTos/tgw_plan.html#setting-up-an-aviatrix-transit-gw>`_. As a best practice, create a new Transit hub VPC to deploy the Aviatrix Transit GW. 4. This step has two options: - Option A: `Connect Aviatrix Transit GW to VGW <http://docs.aviatrix.com/HowTos/transitvpc_workflow.html#connect-the-transit-gw-to-aws-vgw>`_. At this point, VGW starts to advertise to the Aviatrix Transit GW. Make sure you specify a different "AS" number for the BGP session of the Aviatrix Transit GW connection to the VGW. Also note that if the Transit GW and the VGW are in the same account and same VPC, VGW must be detached from the VPC. A diagram for this migration path is shown below: |tgw_csr_migrate_pattern1| - Option B: Connect Aviatrix Transit GW to CSR. There are certain situations where you need to keep the CSR as the connection point to on-prem (for example, you need to use CSR route summarization feature to control routes to VGW to be under 100.). In such scenario, use `External Device <https://docs.aviatrix.com/HowTos/transitgw_external.html>`_ option in `Transit VPC workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ to create an IPSec and BGP connection to CSR, as shown in the diagram below. After all Spoke VPCs are migrated, delete the connection to CSR, connect the Aviatrix Transit GW to VGW. |tgw_csr_migrate_pattern2| 5. Remove a Spoke VPC. Select one Spoke VPC that has VGW deployed. Remove the VPC Transit Network tag. This will effectively detach the Spoke VPC from the CSR Transit Network. Make sure the above Spoke VPC CIDR route entry has been removed from the Transit Network. 6. `Attach a Spoke VPC <https://docs.aviatrix.com/HowTos/tgw_build.html#attaching-a-vpc-to-a-tgw>`_ to the corresponding security domain. 7. Repeat steps 5 and step 6 for the remaining Spoke VPCs. 8. Remove the Transit Hub VGW CSR tag after all Spoke VPCs have been migrated to Aviatrix Transit GW. This effectively detaches the VGW from CSR. The effective operation downtime for each Spoke VPC is the time between the Transit Network tag being removed for the Spoke VPC and the Spoke VPC being attached to Aviatrix Transit GW. It should be a few minutes. .. |tgw_csr_migrate_pattern1| image:: tgw_csr_migrate_media/tgw_csr_migrate_pattern1.png :scale: 30% .. |tgw_csr_migrate_pattern2| image:: tgw_csr_migrate_media/tgw_csr_migrate_pattern2.png :scale: 30% .. disqus:: <file_sep> ======================================== Docker Container Access ======================================== Introduction ============ Project Skyhook by Aviatrix enables VPN users to access remote Docker containers in a multi-host Swarm cluster built on a VXLAN overlay network in the same manner to access remote cloud instance. (A host is a cloud instance.) With Aviatrix encrypted peering capability that connects VPC/VNets securely across regions and clouds, a multi-host Docker swarm cluster can span across multiple VPC regions and multiple clouds, such as AWS, Azure and Google. Users can use Aviatrix enterprise OpenVPN® capability to connect to the cloud, then from your desktop access remote containers in a swarm cluster in the same manner as accessing instances. VPN users from desktop, for example, can use “curl” or run a browser session directly to a remote container running a web service. Without Aviatrix solution, it requires complex port mapping to access a remote Docker container. It is not possible today, from your desktop, to access a remote container in a VXLAN overlay network. In addition, administrators can leverage already built in multi-factor authentication and user profile defined access control to grant or deny access to a container or container application port. In this reference design, we are going to show you how to enable and use this capability. This document assumes some familiarity with Aviatrix Cloud Native Networking product, Docker Swarm cluster and VXLAN multi-host networking. If not, no worries, read on and proceed, we have compiled instructions for you. Skyhook: Docker Container Access ================================ Aviatrix Docker Container Access solution can be deployed as shown below: |image0| In the diagram above, the left most VPC (172.31.0.0/16), the “VPN landing VPC”, is the one hosting the Swarm primary/secondary managers, consul (Discovery backend) and a few Swarm nodes. Read `this link <http://docs.aviatrix.com/HowTos/Docker_Swarm.html>`__ on how to create a Swarm Cluster that you’ll need later. Instances in the rest of the VPCs are part of the swarm cluster nodes that span across multiple VPC regions and to Azure and Google by using Aviatrix encrypted peering capability. The Aviatrix Solution Benefits ============================== Aviatrix gateways are deployed and managed by an Aviatrix Cloud Connect Controller (the pink color instance in the diagram) which itself is a cloud instance or VM. Aviatrix benefits are highlighted below: - Aviatrix solution enables users to remotely access swarm containers as well as instances. Once VPN in, users can use native desktop commands such as “curl” without complex port mapping and “docker exec…” type of commands. - Multi-factor authentication and user profile based access control enable fine granular security. - Aviatrix VPN gateways are supported by ELB for high availability and scalability. - Extensive logging allows administrators to have complete visibility of network event and user browsing history. - With Aviatrix encrypted peering, we can easily span Swarm cluster across different regions, and cloud providers (AWS, Azure, and Google GCE). - The gateway is launched from a central controller web console with a few clicks. Configuration Workflow ====================== Before you start, make sure you have the latest software by checking the Dashboard. If an alert message displays, click Upgrade to download the latest software. As a prerequisite, you must create a Swarm overlay network cluster first. You need to record the Docker Swarm Cluster Consul IP address, the Overlay Network Name (e.g. multi-host-overlay), and the Overlay Network Address (e.g. 10.0.0.0/16). Please refer for instructions on how to create a Swarm Cluster. The configuration workflow is as follows, with major steps highlighted. 1. Setup secure VPC access and connectivity infrastructure This step setup a secure environment so that all your instances and containers can be accessed and communicated securely with private IP addresses. If you are going to start with all containers in one VPC (172.31.0.0/16 as shown in the diagram), launching an Aviatrix VPN gateway and create a VPN user for secure remote access to the instances in the VPC. On the other hand, if you like to try to run containers span across multiple VPCs, launch encrypted peering gateways and Aviatrix VPN gateways to create the necessary network infrastructure for secure access and secure connectivity among instances. Note you must launch separate peering gateway and VPN gateways. In either case, check out `this reference design <http://docs.aviatrix.com/HowTos/Cloud_Networking_Ref_Des.html>`__ for instructions. 2. Create a Docker swarm cluster Follow `the instructions <http://docs.aviatrix.com/HowTos/Docker_Swarm.html>`__ to create a Docker swarm cluster and create some containers. First VPN to the landing VPC, then ssh into each swarm node (instance) with its private IP address. With Aviatrix VPN access capability and encrypted peering, your entire swarm cluster can be deployed on private subnets with private IP addresses. 3. Enable overlay network access if you have selected “Split Tunnel” mode when creating VPN gateways at step 1, you need to add the VXLAN overlay network 10.0.0.0/16 to allow your laptop to tunnel the address range to the VPC, Follow the steps below: Go to VPC/VNet -> Edit Configuration, - click Modify Split Tunnel. - At VPC/VNet Name field, select the landing VPC (the one with CIDR 172.31.0.0/16) - At Additional CIDRs, add 10.0.0.0/16 to the CIDR strings separated with comma. - (If you have Nameservers and Search Domains, fill in these fields so you can access containers with names.) - Click Modify. 4. Enable Docker Container Access. Go to VPC/VNet -> VPN Access -> Skyhook:Docker Container Access - Click on “Enable” for the gateway you just created (e.g. avx-vpngw01). - Fill in the Docker Swarm Cluster Consul IP address, the Overlay Network Name (e.g. multi-host-overlay), and the Overlay Network Address (e.g. 10.0.0.0/16). - Click “Enable” to confirm the request. - **Important notes** – If there are more than one VPN gateways, make sure you enable Docker Container Access for each one and the same configuration should be applied to all VPN gateways. 5. Verify your setup Now you should be able to access your containers. Use your desktop VPN client to VPN into the VPC. You can try a few things. Note you need to use the container overlay IP address for accessing, in this reference design, all containers overlay IP address is in the 10.0.0.0/16 range. - If you have one container that runs a web server, you should be able to access the web server from your desktop browser, run a command “wget” from a Linux machine, or run a command “curl” from a OSX machine. - If one container has been loaded with ssh access capability, you can ssh directly into the container from your desktop. - Ping the container overlay IP address. 6. Adding a new swarm node You can still add a new swarm node later, just follow the same instruction as described in `this link <http://docs.aviatrix.com/HowTos/Docker_Swarm.html>`__. Important note: for a container on a Google GCE instance, you must enable “IP forwarding” when you launch the Google GCE instance. Troubleshooting =============== 1. If you failed to enable Docker Container Access for a gateway, make sure the Docker Swarm Consul IP address is reachable from your gateway. Check the security group associated with the instances. 2. If there are more than one VPN gateway, make sure you enable Docker Container Access for each one and the same configuration should be applied to all VPN gateways; otherwise, you may experience inconsistent behaviors. 3. After you disabled the Docker Container Access for a VPN gateway, if you try to enable it immediately, it may fail. This is because the Swarm Consul still has the node entry in the DB and it needs time to discover that the node is gone. Simply wait for a few minutes until the TTL expired and the key-value store cleans up the old entry automatically. For support, please open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_ For feature request and feedback, click Make a wish at the bottom of each page. Enjoy! OpenVPN is a registered trademark of OpenVPN Inc. .. |image0| image:: ContainerAccessRefDes_media/image1.png .. disqus:: <file_sep> =========================================================================================== Connect Networks With Overlap CIDRs =========================================================================================== The Scenario ------------------ This tech note illustrates an example solution to a specific use case. In this use case, a customer needs to connect certain on-prem hosts to certain virtual machine (EC2/GCE) instances in a VPC/VNet over an IPsec tunnel over the Internet, but the on-prem network range overlaps with the VPC/VNet CIDR range, and the requirement from the customer is that no NAT function will be performed on the customer side. In addition, traffic can be initiated from either side. Note that this solution works for specific hosts and virtual machine instances on each side. The scenario is described in the following diagram, where VPC/VNet-2 represents an on-prem environment. |overlap| :: VPC/VNet-1 CIDR = 10.17.0.0/20, instance-1 in VPC/VNet-1 has an IP address 10.17.4.179. VPC/VNet-2 CIDR = 10.17.0.0/20, instance-2 in VPC/VNet-2 has an IP address 10.17.7.81. The Solution ------------------ The solution is to build a Site2Cloud IPsec tunnel between VPC/VNet-1 and VPC/VNet-2 and apply both source NAT (SNAT) and destination NAT (DNAT) on VPC/VNet-1 gateway. The packet flow is demonstrated as below: 1. instance-1 sends a packet to instance-2 with a virtual destination IP address, for example 172.16.0.43. From instance-1's point of view, the destination instance is a virtual address - 172.16.0.43. #. When the packet arrives at the VPC/VNet-1 gateway, the gateway does DNAT on the packet to translate the virtual destination IP address to 10.17.7.81 which is the instance-2 physical IP address. #. The gateway at VPC/VNet-1 then translates the packet source IP address (10.17.4.179) to a virtual source IP address, say it is 192.168.0.43. #. The packet then arrives at VPC/VNet-2 with destination IP address 10.17.7.81 and source IP address 192.168.0.43. From instance-2's point of view, instance-1's address is a virtual IP address - 192.168.0.43. #. When instance-2 sends a packet to instance-1, the destination is the virtual IP address 192.168.0.43. #. When the packet arrives at the VPC/VNet-1 gateway over the IPsec tunnel, the VPC/VNet-1 gateway translates its destination IP address from virtual address 192.168.0.43 to 10.17.4.179. #. The VPC/VNet-1 gateway then translates the source IP address of the packet from 10.17.7.81 to virtual address 172.16.0.43. The Configuration Steps ---------------------------- Following the Site2Cloud Workflow to Launch Gateways ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Log in to your Aviatrix Controller and select **Site2Cloud** on the left sidebar. Follow step 1 to launch a gateway in the VPC/VNet-1. (You can follow the `gateway launch instructions in this <http://docs.aviatrix.com/HowTos/gateway.html>`_. Leave optional parameters unchecked.) For the above example, we also launch a gateway in VPC/VNet-2 to emulate an on-prem environment. Creating a Site2Cloud Tunnel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Go to Controller > Site2Cloud. Click **+Add New**. Fill the form and click **OK**. Select **Unmapped** for the Connection Type field. VPC/VNet-1 gateway-1 side ######################### For the VPC/VNet-1 gateway side, the Local Subnet field should be 192.168.0.43/32, and the Remote Subnet field should be 10.17.7.81/32, as shown below. |vpc1_to_vpc2_ipsec| VPC/VNet-2 gateway-2 side ########################## On the VPC/VNet gateway-2 side, the IPsec is a standard configuration. For the VPC/VNet-2 gateway side, the Local Subnet field should be 10.17.7.81/32, and the Remote Subnet field should be 192.168.0.43/32, as shown below. |vpc2_to_vpc1_ipsec| Wait for the tunnel to come up. Normally you'll need to download the configuration, but in this example, since both ends of the network are on the VPC/VNet, you can simply configure each Site2Cloud tunnel. Make sure the pre-shared Keys are the same for both ends. In the above example, we used "Aviatrix101#" as our pre-shared key. Configuring DNAT on Gateway-1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This step is to configures the gateway to translate the destination IP address 172.16.0.43 to the real private IP address 10.17.7.81, before routing happens. At the main navigation bar, click **Gateway**. Highlight the gateway, in this case, the VPC/VNet-1 gateway, and click **Edit**. Scroll down to Destination NAT. Follow the instructions `here <https://docs.aviatrix.com/HowTos/gateway.html#destination-nat>`_ to configure, as shown below. |dnat| Configuring SNAT on Gateway-1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This step is to translate the packet source IP address after routing happens. In this example, the address is translated from 10.17.7.81 to 172.16.0.43 for packets going from on-prem (VPC/VNet-2) to VPC/VNet-1, and 10.17.4.179 to 192.168.4.43 for packets going from VPC/VNet-1 to on-prem (VPC/VNet-2). For the same VPC/VNet-1 gateway, configure SNAT as shown below. Notice we entered "Dst CIDR" as qualifier to reduce the scope of the rule as a good practice. The reason that the address is 10.17.7.81/32 is that the destination has already been translated after the DNAT rule before routing happens. |snat| Testing Site2Cloud Connection --------------------------------------------------------- Make sure your instance's Security Groups inbound rules are configured properly. From instance-1, you should be able to ping instance-2 by "ping 172.16.0.43". From instance-2, you should be able to ping instance-1 by "ping 192.168.0.43" .. |overlap| image:: connect_overlap_cidrs_media/overlap.png :scale: 30% .. |vpc1_to_vpc2_ipsec| image:: connect_overlap_cidrs_media/vpc1_to_vpc2_ipsec.png :scale: 30% .. |vpc2_to_vpc1_ipsec| image:: connect_overlap_cidrs_media/vpc2_to_vpc1_ipsec.png :scale: 30% .. |dnat| image:: connect_overlap_cidrs_media/dnat.png :scale: 30% .. |snat| image:: connect_overlap_cidrs_media/snat.png :scale: 30% .. disqus:: <file_sep> ################################### Discover Unencrypted Traffic ################################### (AWS Only) Not all the application instances in an AWS VPC run on the TLS protocol. The `DevOps Tools Survey <https://docs.aviatrix.com/HowTos/opstools_survey.html>`_ shows that the majority of the DevOps tools are not encrypted. The Discover Unencrypted Flows tool enables you to discover all traffic sent and received by instances in an AWS VPC via the VPC flow log. Then, this tool downloads the VPC flow log files and displays them. It enables VPC flow log in the specified VPC, region and account and creates an S3 bucket to store the flow log files. After the tool receives the first batch of flow log files, it returns the findings and also disables the VPC flow log and removes the S3 bucket created. Traffic sessions that destined to TCP port 443 (HTTPS) and TCP port 22 (SSH) are excluded from the display. Note traffic that runs on UDP port 500/4500 are known as IPsec protocol and as such is indeed encrypted, but the tool displays them. This process typically takes 5 - 6 minutes to complete. .. |edit-designated-gateway| image:: gateway_media/edit-designated-gateway.png :scale: 50% .. disqus:: <file_sep> ============================ Site2Cloud FAQs ============================ What does Site2Cloud do? ---------------------------------- Site2Cloud builds an encrypted connection between two sites over the Internet in an easy-to-use and template-driven manner. Its workflow is similar to AWS VGW or Azure VPN. On one end of the tunnel is an Aviatrix Gateway. The other end could be an on-prem router, firewall, or another public cloud VPC/VNet, that the Aviatrix Controller does not manage. What are the use cases for Site2Cloud? ---------------------------------------- Here are common use cases: - **SaaS provider to its customer site** If you need to move data continuously and securely from customer or partner sites to your SaaS service hosted in AWS, Azure, or Google, building an encrypted tunnel between the customer site and your SaaS service is required. - **Branch offices to cloud** If you have branch offices that need to access applications hosted in AWS or Azure, using Site2Cloud is the most economical way to build a secure tunnel. You can use your existing Internet connection and not have to pay extra to SD-WAN vendors to go through their cloud. Why should I consider using Aviatrix Site2Cloud? -------------------------------------------------------------- For a comparative analysis of why you should use Aviatrix, refer to `Site to Cloud Connectivity over Internet <http://docs.aviatrix.com/StartUpGuides/aviatrix_overview.html#site-to-cloud-connectivity-over-internet>`_. In addition, Aviatrix provides a simple point-and-click user interface for you to build and manage a large deployment. How do I configure Site2Cloud? -------------------------------------------- To set up a Site2Cloud connection, refer to `Site2Cloud IPsec VPN Instructions <http://docs.aviatrix.com/HowTos/site2cloud.html>`_. Does Site2Cloud support HA? ------------------------------------------ Yes. Enable HA when configuring a Site2Cloud connection. What are the encryption algorithms supported? --------------------------------------------------------------- ==================================== ================================================================================================================================ **Type** **Value** ==================================== ================================================================================================================================ Phase 1 Authentication SHA-1, SHA-512, SHA-384, SHA-256 Phase 1 DH Groups 1, 2, 5, 14, 15, 16, 17, 18, 19, 20, 21 (20 & 21 IKEv2 Only) Phase 1 Encryption AES-256-CBC, AES-256-GCM-64, AES-256-GCM-96, AES-256-GCM-128, AES-192-CBC, AES-128-CBC, AES-128-GCM-64, AES-128-GCM-96, AES-128-GCM-128, 3DES Phase 2 Authentication HMAC-SHA-1, HMAC-SHA-512, HMAC-SHA-384, HMAC-SHA-256, NO-AUTH Phase 2 DH Groups 1, 2, 5, 14, 15, 16, 17, 18, 19, 20, 21 (20 & 21 IKEv2 Only) Phase 2 Encryption AES-128-CBC, AES-192-CBC, AES-256-CBC, AES-256-GCM-64, AES-256-GCM-96, AES-256-GCM-128, AES-128-GCM-64, AES-128-GCM-96, AES-128-GCM-128, 3DES, NULL-ENCR ==================================== ================================================================================================================================ Is IKEv2 supported? --------------------- Yes. How frequently are keys rotated? ------------------------------------------- Re-key for IKE phase 1 is every 8 hours. Re-key for IKE phase 2 is every hour. Can you configure a Site2Cloud connection using the same public IP address for the remote gateway and the remote subnet? ------------------------------------------------------------------------------------------------------------------------------------------------------------ Yes. In a Site2Cloud connection, the same IP address in the remote gateway peer and the remote subnet is supported. This is useful when configuring a Site2Cloud connection to a third-party environment where only one public IP is exposed. This feature is supported only for policy-based unmapped Site2Cloud connections in AWS and GCP for standalone gateways, not ActiveMesh gateways. Are there configuration examples with other devices? -------------------------------------------------------------------- Aviatrix Site2Cloud supports all types of on-prem, firewall, and router devices that terminate VPN connections. Below are the configuration examples for specific devices. - `Azure VPN Gateway <./avxgw_azurevpngw_site2cloud.html>`_ - `AWS VGW <./site2cloud_awsvgw.html>`_ - `pfSense IPsec VPN <./CloudToPfSense.html>`__ - `Palo Alto Next-Gen Firewall (PAN) <./S2C_GW_PAN.html>`__ - `Check Point Firewall <./S2C_GW_CP.html>`__ - `Cisco ASA <./S2C_GW_ASA.html>`__ - `FortiGate <./site2cloud_fortigate.html>`__ - `Cisco Meraki MX64 <./site2cloud_meraki.html>`__ - `Cisco ISR <./S2C_GW_IOS.html>`__ - `Cisco Meraki vMX100 <./site2cloud_meraki_vmx100.html>`_ - `Aviatrix Gateway <./site2cloud_aviatrix.html>`_ Are there any Tech Notes on solving overlapping IP addresses? ----------------------------------------------------------------------------- Below are the Tech Notes that demonstrate how to solve overlapping IP addresses. - `Site2Cloud with customized SNAT <https://docs.aviatrix.com/HowTos/s2c_vgw_snat.html>`_. - `Site2Cloud for overlapping IP addresses <https://docs.aviatrix.com/HowTos/s2c_overlapping_subnets.html>`_. - `Site2Cloud to public IP addresses <https://docs.aviatrix.com/HowTos/s2c_for_publicIP.html>`_. - `How to build site to site connection <https://docs.aviatrix.com/HowTos/site_to_site_vpn.html>`_ - `Connecting offices to multiple VPCs using AWS Peering <https://docs.aviatrix.com/HowTos/simpletransit.html>`_ - `Connect Networks with Overlap CIDRs <https://docs.aviatrix.com/HowTos/connect_overlap_cidrs.html>`_ - `Connect Overlapping VPC to On-prem <https://docs.aviatrix.com/HowTos/connect_overlap_vpc_via_VGW.html>`_ How to troubleshoot Site2Cloud connection with IKEv2? ------------------------------------------------------------------------ Refer to `Troubleshooting IPsec VPN connection with IKEv2 <https://docs.aviatrix.com/HowTos/troubleshooting_ipsec_vpn_connection_with_ikev2.html>`_. .. |image1| image:: FAQ_media/image1.png .. disqus:: <file_sep> ========================================================= TGW Plan ========================================================= The AWS Transit Gateway (TGW) Orchestrator Plan is the first stage in deploying a AVX Transit Network using AWS Transit Gateway. After you go through the Plan stage configuration, you can proceed to the `Build stage <https://docs.aviatrix.com/HowTos/tgw_build.html>`_ to attach VPCs. For background information, see the `AWS Transit Gateway Orchestrator FAQ <https://docs.aviatrix.com/HowTos/tgw_faq.html>`_. The plan stage consists of 4 sections: 1. **Create AWS Transit Gateway**. This is the only must-do section in Plan before you start to Build (attach VPCs). See the Creating an AWS TGW section below. In this section, an AWS Transit Gateway and three connected Security Domains are created. #. **Create Segmented Network**. This is an optional section. It consists of the Creating a New Security Domain and Building Your Domain Connection Policies sections below. This section creates your own additional Security Domains and define Connection policies. This section is entirely modular and you can modify at any time. #. **Create hybrid, multi-region or multi-cloud Connection**. This is an optional section. It consists of the Setting up an Aviatrix Transit GW, Preparing an Aviatrix Transit GW for TGW Attachment, and Attaching an Aviatrix Transit GW to TGW sections below. This section launches an Aviatrix Transit Gateway at the edge VPC, builds a hybrid connection to on-prem or another Aviatrix Transit gateway cluster, or deploys Transit DMZ . If you need hybrid connectivity, setting up an Aviatrix Transit GW, preparing an Aviatrix Transit GW for TGW Attachment, and attaching an Aviatrix ransit GW to TGW must all be executed and in sequence to complete this section. This section is entirely modular and you can modify at any time. #. **TGW Native Edge Connections**. This is an optional section. It creates TGW VPN, TGW DXGW and TGW Inter Region Peering. It consists of the steps described in the Setting up an AWS Transit Gateway VPN Connection and Downloading the VPN Configuration sections below. In the planning stage, think about what network segmentation you need to achieve. For example, do you need to segment Dev/QA VPCs from your Prod VPCs, i.e., no connectivity is allowed between these VPCs in each group? The plan stage creates Transit Gateway and Transit Gateway route tables in AWS. There is no charge either by AWS or Aviatrix. If you have not decided on network segmentation, no worries. Proceed to build a full mesh network by using the `Default_Domain <https://docs.aviatrix.com/HowTos/tgw_faq.html#what-is-the-default-domain>`_. .. tip:: You can modify your plan at any time. Simply return to the Plan page and create security domains and change connection policies. The Transit Gateway Orchestrator Plan workflow provides step-by-step instructions to define and set up your policies. Creating an AWS TGW ------------------------------------------- In order to use AWS Transit Gateway service, you must first create a AWS Transit Gateway. This step creates a AWS Transit Gateway in a specified region with a specified AWS account, the Aviatrix Controller also automatically creates the `Default_Domain <https://docs.aviatrix.com/HowTos/tgw_faq.html#what-is-the-default-domain>`_, the `Shared_Service_Domain <https://docs.aviatrix.com/HowTos/tgw_faq.html#what-is-the-default-domain>`_ and the `Aviatrix_Edge_Domain <https://docs.aviatrix.com/HowTos/tgw_faq.html#what-is-the-aviatrix-edge-domain>`_ and the corresponding AWS Transit Gateway route tables. |create_tgw| Note that the three domains are connected, implying that if you attach a VPC to the Default Domain or Shared Service Domain, the VPCs can communicate with each other and can access on-prem through the Aviatrix Edge Domain. ========================================== ========== **Setting** **Value** ========================================== ========== Account Name An `Aviatrix account <http://docs.aviatrix.com/HowTos/aviatrix_account.html#account>`_ that corresponds to an IAM role or account in AWS. Region One of the AWS regions TGW Name The name of the AWS Transit Gateway AWS Side AS Number TGW ASN number. Default AS number is 64512. ========================================== ========== After AWS Transit Gateway is created, you can validate by going to `View page <https://docs.aviatrix.com/HowTos/tgw_faq.html#what-can-be-displayed-at-the-view-page>`_ and seeing what has been created. -------------------------------------------------------------------------------------------------------------------- This section includes creating a new security domain and building your domain connection policies to plan a segmented network. Creating a New Security Domain -------------------------------------------------- If you plan to build a `default network (full mesh) <https://docs.aviatrix.com/HowTos/tgw_design_patterns.html#Full-mesh-network-design>`_, skip this section. You can make changes to your network segmentation at any time, simply come back to this page. If you plan to build a segmented network, use this section to create a new `Security Domain <https://docs.aviatrix.com/HowTos/tgw_faq.html#What-is-a-Security-Domain>`_ and setup `connection policies <https://docs.aviatrix.com/HowTos/tgw_faq.html#what-is-a-connection-policy>`_. In the example below, a new domain called prod_domain is created. |new_domain| ========================================== ========== **Setting** **Value** ========================================== ========== TGW Name The name of the AWS Transit Gateway Security Domain Name Specify a unique domain name: for example, Dev_Domain. Aviatrix Firewall Domain Check this box if this domain is for Aviatrix FireNet. Native Egress Domain Check this box if this domain is for non-Aviatrix FireNet based central Internet bound traffic. Native Egress Domain is not recommended as it only supports an active-standby firewall deployment. Native Firewall Domain Check this box if this domain is for non-Aviatrix FireNet based firewall traffic inspection. Native Firewall Domain is not recommended as it only supports an active-standby firewall deployment. ========================================== ========== Building Your Domain Connection Policies ---------------------------------------------------- This step specifies the connection relationship of one domain to others. Two connected domains imply that VPCs in each domain can communicate with each other despite the fact that they are in different domains. The Aviatrix Controller takes care of both VPC route table and AWS Transit Gateway route table programming and updates. Highlight a domain on the left panel and click **Add**, the domain will appear to the right. In the example shown below, the intention is to connect the newly created prod_domain in the Creating a new Security Domain section above to the Aviatrix_Edge_Domain so that VPCs in the prod_domain can communicate with on-prem servers and hosts. |connect_domain_1| Continue from the above example, you can connect prod_domain to Shared_Service_Domain, as shown below. |connect_domain_2| Click the View page under AWS Transit Gateway Orchestrator and click each expandable circle to see what has been created, as shown below. |plan_view| ----------------------------------------------------------------------------------------------------------------------- This section is for hybrid, multi-region or multi-cloud connections. It sets up connection to an on-prem data center over Direct Connect or the Internet. Setting up an Aviatrix Transit GW ------------------------------------------------------------------ This section is about deploying Aviatrix Transit Gateways in a VPC and attach the VPC to TGW. From TGW point of view, this VPC is a Spoke VPC attached to TGW, however from Controller point of view, the Aviatrix Transit Gateway is the packet forwarding engine to on-prem or to another Aviatrix Transit Gateway. The direct attachment architecture allows the Aviatrix Transit Gateways to forward packets to TGW and Spoke VPCs at the rate of 50Mbps as specified by TGW. The use case for this deployment is to use Aviatrix Transit Gateway to connect to on-prem or to peer with another Aviatrix Transit Gateway. If you intend to use `TGW DXGW to connect to on-prem <https://docs.aviatrix.com/HowTos/tgw_plan.html#setup-aws-transit-gateway-direct-connect>`_ , `TGW VPN to connect to on-prem <https://docs.aviatrix.com/HowTos/tgw_plan.html#setup-aws-transit-gateway-vpn-connection>`_ or use `native TGW Peering to connect to regions <https://docs.aviatrix.com/HowTos/tgw_plan.html#tgw-inter-region-peering>`_ , skip this section. This section is modular, return to this section anytime if your requirements change later. .. tip:: We strongly recommend creating a new Transit VPC at `Useful Tools -> Create a VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_. Select **Aviatrix Transit VPC**. If you would like to use an existing VPC and its network CIDR is too small (not enough of /28 unused CIDR segments), use AWS Edit VPC CIDR feature to create a new /23 subnet to deploy the Aviatrix Transit Gateway in TGW use case. To deploy the Aviatrix Transit Gateways, take a detour and complete Step 1 & 2 in the `Transit Network workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_. If you intend to use Aviatrix Transit Gateway to connect to on-prem. Also complete `Step 3 <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#connect-the-transit-gw-to-aws-vgw>`_. When complete, return to this section and continue to the next step in this workflow to Enable Aviatrix Transit GW to TGW. Preparing the Aviatrix Transit GW for TGW Attachment -------------------------------------------------------------------- The Aviatrix Transit GW created in the Setting up an Aviatrix Transit GW section above does not build an IPsec tunnel to an AWS Transit Gateway. The networking between AWS Transit Gateway and the Aviatrix Transit GW is via the AWS VPC infrastructure. This step designates an Aviatrix Transit GW to be used in conjunction with the AWS Transit Gateway. It creates a second Ethernet interface eth1 on the Aviatrix Transit GW for sending and receiving packets from AWS Transit Gateway. It also creates two subnets, -tgw-ingress and -tgw-egress and two respective route tables in the edge VPC to route packets to and from AWS Transit Gateway. |prepare_tgw_attach| ========================================== ========== **Setting** **Value** ========================================== ========== Cloud Type AWS or AWS Gov Cloud Aviatrix Transit Gateway Name Select a Transit GW from the dropdown menu. ========================================== ========== Attaching an Aviatrix Transit GW to TGW ------------------------------------------------------------------ This step attaches the Aviatrix Edge VPC to the AWS Transit Gateway and the Aviatrix Edge Domain, thus allowing the Aviatrix Transit GW to send and receive packets from AWS Transit Gateway. In this step, route entries are added to the two created private subnet route tables as described in the table below. ========================================== =============== ================== ================= **subnet** **route table** **route entry** **description** ========================================== =============== ================== ================= -tgw-egress (for eth1) -tgw-egress 0.0.0.0/0 -> TGW for traffic from Aviatrix Transit GW to TGW -tgw-ingress -tgw-ingress 0.0.0.0/0 -> eth1 for traffic from TGW to Aviatrix Transit GW ========================================== =============== ================== ================= .. Note:: There is no IPsec tunnel between AWS Transit Gateway and the Aviatrix Transit GW, the Aviatrix GW behaves as an EC2 instance in a Spoke VPC (The Aviatrix Edge VPC) attached to the AWS Transit Gateway, as shown in the diagram below. Such a setup allows Aviatrix edge VPC to leverage the high performance provided by AWS Transit Gateway. |transit_complete| After you finish these steps, your hybrid connection using Aviatrix Transit Gateway for TGW setup is complete. In the above example, if you have any Spoke VPCs attached to the prod_domain, EC2 instances should be able to communicate with on-prem. (Make sure instance security groups and any on-prem firewalls are configured properly.) ------------------------------------------ This section consists of TGW native VPN, Direct Connect, and TGW Inter Region Peering functions. Since TGW does not propagate learned routes from DXGW or VPN to Spoke VPCs, Aviatrix Controller solves this problem by periodically polling the TGW route table and programming the learned routes to attached Spoke VPCs. Setup AWS Transit Gateway VPN Connection -------------------------------------------------------- Setting up a VPN Connection ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This function configures a native TGW VPN. It takes two steps: first configure, then download the configuration. This step creates a VPN connection from TGW in a selected Security Domain. ========================================== ========== **Setting** **Value** ========================================== ========== AWS Transit Gateway Name The name of a TGW created by `TGW Plan <https://docs.aviatrix.com/HowTos/tgw_plan.html#create-aws-tgw>`_ by Aviatrix Controller Connection Name A unique name for the VPN connection Remote Public IP Remote site public IP address Dynamic (BGP) or Static Use BGP to connect to remote site or static IP Remote CIDRs When Static is selected, enter a list of CIDRs separated by comma. Remote AS Number When Dynamic is selected, enter the AS number of the remote site. Security Domain Name Select a Security Domain to associate the VPN attachment with Learned CIDR Approval Select the option to enable `Approval <https://docs.aviatrix.com/HowTos/tgw_approval.html>`_. This option applies to Dynamic (BGP) mode only. Global Acceleration Select the option to enable AWS Accelerated VPN ========================================== ========== Downloading the VPN Configuration ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Refresh the screen to see the newly created VPN connection. If Static VPN is configured, you must go to the AWS Console > VPC > Site-to-Site VPN Connections to download the configuration file. If Dynamic VPN is configured, click **Download** to download the configuration. Setting up AWS Transit Gateway Direct Connect ---------------------------------------------------------- This section configures a native Direct Connect from TGW. This step can take more than 10 minutes for the connection to be ready. Setting up Direct Connect ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This step assumes that you have created Direct Connect Gateway and Transit Virtual Interface from AWS Console. .. Note :: You may need to `update the Controller IAM policies <https://docs.aviatrix.com/HowTos/iam_policies.html#updating-iam-policies>`_ for this function. ========================================== ========== **Setting** **Value** ========================================== ========== AWS Transit Gateway Name The name of a TGW created by `TGW Plan <https://docs.aviatrix.com/HowTos/tgw_plan.html#create-aws-tgw>`_ Direct Connect Gateway Account Name The Aviatrix Access Account name that created AWS Direct Connect Gateway AWS Direct Connect Gateway The AWS Direct Connect Gateway you created from AWS Console Allowed Prefix A list of comma-separated CIDRs for DXGW to advertise to remote (on-prem) Security Domain Name Select a Security Domain to associate the VPN attachment with Learned CIDR Approval Select the option to enable `Approval <https://docs.aviatrix.com/HowTos/tgw_approval.html>`_. This option applies to Dynamic (BGP) mode only. ========================================== ========== Updating Direct Connect Network Prefix ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Use this step to update the Allowed Prefix to advertise to on-prem. TGW Inter Region Peering --------------------------------- TGW inter-region peering is a feature where Controller orchestrates AWS TGW peering. In addition, the Controller programs and propagates network CIDR of Spoke VPCs and Edge Domains in a Security Domain to the remote TGW deployment, thus providing the end-to-end turnkey solution. It takes two steps to connect two Security Domains in two regions. .. tip:: Your Controller may not have the latest IAM policies to execute TGW peering, go to Accounts > Access Accounts. Select the account where TGW is deployed and click **Update Policy**. Do so for all TGW accounts if you wish to TGW build inter-region peering. Creating a TGW Peering Attachment ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This step connects two TGWs in different regions using AWS native TGW Peering. It automatically creates two Security Domains associated with each TGW and respective attachment ID. ========================================== ========== **Setting** **Value** ========================================== ========== Cloud Type 1 Select AWS or AWS GovCloud Region 1 Select a region where the one TGW is deployed AWS Transit Gateway Name 1 Select an AWS TGW Created `here <https://docs.aviatrix.com/HowTos/tgw_plan.html#create-aws-tgw>`_ Cloud Type 2 Select AWS or AWS GovCloud Region 2 Select a region where the peering TGW is deployed AWS Transit Gateway Name 2 Select an AWS TGW Created `here <https://docs.aviatrix.com/HowTos/tgw_plan.html#create-aws-tgw>`_ ========================================== ========== Inspecting Inter Region Traffic ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Starting from Release 6.1, the Security Domain associated with each TGW Peering attachment is available for user. The Security Domain has the name `peering_<TGW NAME>`. For example, for the TGW with name tgw-1, the peering Security Domain is `peering_tgw-1`. You can specify FireNet inspection policy on this Security Domain. When you do so, it implies that any cross-region traffic is inspected. Use TGW > Plan > Add/Modify Connection Policies to connect the peering domain with FireNet Domain. Note to avoid double inspections by two FireNet gateways associated with each TGW, configure the connection policy between peering domain and FireNet domain on only one TGW. Building Connection Policies ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ After step a is completed, go to `Add/Modify Connection Policies <https://docs.aviatrix.com/HowTos/tgw_plan.html#build-your-domain-connection-policies>`_. Refresh the page. The peered TGW with its Security Domains should appear on Not Connected panel. Select one remote Security Domain and click **Add**. Repeat this step for all intended connections, as shown in the diagram below. |tgw_peer| In the diagram above, Dev-1 Domain of TGW-1 has connection policy to Dev-2 Domain of TGW-2. Any VPCs in Dev-1 Domain can communicate with VPCs in Dev-2 Domain. Similarly, Prod-1 Domain of TGW-1 has connection policy to Prod-2 Domain of TGW-2. Any VPCs in Prod-1 Domain can communicate with VPCs in Prod-2 Domain. However, Dev-1 cannot communicate with Prod-2 if there is no connection policy between them. -------------------------------------------------------------------------------------- This section consists of delete functions. .. note:: To delete an Aviatrix Transit GW attached to a AWS Transit Gateway, go through the Setting up a VPN Connection and Updating Direct Connect Network Prefix sections below. Then, go to Controller Gateway page to terminate the gateway instance. Setting up AWS Transit Gateway Connect ---------------------------------------------------- Detaching Aviatrix Transit GW from TGW ---------------------------------------------------- This step is the opposite of the Attaching an Aviatrix Transit GW to TGW section above. It removes the private subnet route entries respectively. Disabling Aviatrix Transit GW for TGW Function ------------------------------------------------------------------ This step deletes the eth1 interface and other resources associated with the Aviatrix Transit GW from AWS Transit Gateway Orchestrator. Deleting a Security Domain ------------------------------------- This step deletes a security domain created in the Creating a New Security Domain section above. Deleting an AWS TGW ----------------------------- This step deletes the AWS Transit Gateway. .. |create_tgw| image:: tgw_plan_media/create_tgw.png :scale: 30% .. |connect_domain_1| image:: tgw_plan_media/connect_domain_1.png :scale: 30% .. |connect_domain_2| image:: tgw_plan_media/connect_domain_2.png :scale: 30% .. |new_domain| image:: tgw_plan_media/new_domain.png :scale: 30% .. |plan_view| image:: tgw_plan_media/plan_view.png :scale: 30% .. |transit_gw| image:: tgw_plan_media/transit_gw.png :scale: 30% .. |transit_dmz| image:: tgw_plan_media/transit_dmz.png :scale: 30% .. |transit_complete| image:: tgw_plan_media/transit_complete.png :scale: 30% .. |prepare_tgw_attach| image:: tgw_plan_media/prepare_tgw_attach.png :scale: 30% .. |tgw_peer| image:: tgw_plan_media/tgw_peer.png :scale: 30% .. disqus:: <file_sep> ################################### Security Patches ################################### Applying a Security Patch ========================== To apply a patch: 1) Backup your Aviatrix Controller. For more information, see `Controller Backup and Restore <https://docs.aviatrix.com/HowTos/controller_backup.html>`_. 2) Apply the security or software patch on the controller. From the Aviatrix Controller, navigate to Settings > Maintenance > SecurityPatches or SoftwarePatches and click on **UpdateAvailablePatches**. You should see the new patch in the display. 3) Apply the patch by clicking on the icon on the right and selecting **Apply Patch** from the popup menu. 4) Validate the update by clicking on the icon on the right and selecting **Patch Status** and scrolling down to bottom of page. 5) Backup your Aviatrix Controller again to save the new configuration. 4. Security Patch ------------------- **Date** 11/01/2021 **Subject**: AVI-2021-0005 Apache Request Smuggling Vulnerability Security Patch. **Issues**: This patch addresses vulnerabilities fixed by Apache version 2.4.51. Aviatrix released new AMIs for AWS on 10/13/21 to address vulnerabilities (`CVE-2021-40438 <https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-40438>`_ and `CVE-2021-33193 <https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-33193>`_). You are fully covered if you migrated your Controller to use the new AMIs mentioned in `Controller Images: AWS AMI – Version 100621 <https://docs.aviatrix.com/HowTos/image_release_notes.html#controller-images-aws-ami-version-100621-10-13-21>`_, following the instructions for `existing customers to perform a Controller image upgrade <https://Migration_From_Marketplace.html>`_. This patch will address the same issue without requiring a Controller migration. For Controllers running in AWS, Aviatrix recommends that you migrate your Controllers as instructed in `Existing Customers - Controller Image upgrade (Migration) <https://Migration_From_Marketplace.html>`_. For Controllers running in cloud service providers other than AWS (Azure, GCP, etc.), you can apply this security patch. To apply the security patch: #. Secure a maintenance window and execute the following during the maintenance window. #. Go to your Controller (any version) management console. #. Go to Settings > Maintenance > Backup & Restore. Make sure you have a backup of your current settings. #. Go to Settings > Maintenance > Security Patches and click on "Update available patches". #. From the list of patches, apply the "AVI-2021-0005 Apache Request Smuggling Vulnerability" patch. #. Back up your Controller again. (CloudN standalone mode) To apply the security patch if you have CloudN running in a standalone mode, Aviatrix suggests you run the following in a maintenance window: #. Go to CloudN > Maintenance > Security Patches and click on "Update available patches". #. Please make sure that CloudN has outbound access to 0.0.0.0/0 for ports 80 and 443 before applying the patch. #. From the list of patches, apply the "AVI-2021-0005 Apache Request Smuggling Vulnerability" patch. (CloudN in CaaG mode) To apply the security patch if you have CloudN running in a CaaG mode, Aviatrix suggests you run the following during a maintenance window: #. Detach CaaG from the Transit Gateway. #. Deregister the CaaG Gateway. #. Reload the CloudN UI page. #. Go to CloudN > Maintenance > Security Patches and click on "Update available patches". #. Please make sure that CloudN has outbound access to 0.0.0.0/0 for ports 80 and 443 before applying the patch. #. From the list of patches, apply the "AVI-2021-0005 Apache Request Smuggling Vulnerability" patch. #. Register CaaG back to the Controller. #. Attach CaaG back to the Transit Gateway. 3. Security Patch ------------------- **Date** 10/25/2021 **Subject**: AVI-2021-0006 Critical Vulnerability Security Patch **Issues**: This security patch contains a fix for a Controller vulnerability. This security patch was made available Monday, October 25th, 2021 at 05:00PM PST. The critical vulnerability addressed by this patch was privately disclosed to Aviatrix and is not known to be exploited. It affects services of our Controller available on port 443 and would allow an unauthenticated attacker to execute code on the controller. This could be mitigated by limiting access to the https/port 443 of the Controller, or by running a Web Application Firewall (WAF) in front of it. For more information about securing Controller access, see https://docs.aviatrix.com/HowTos/FAQ.html#how-do-i-secure-the-controller-access. Aviatrix strongly recommends you install the **AVI-2021-0006 Critical Vulnerability Security Patch**. To apply a security patch, please refer to the following steps: * First, do a backup on your Controller in “Controller/Settings/Maintenance/Backup&Restore/Backup Now” * Go to “Controller/Settings/Maintenance/Security Patches” and click on “Update Available Patches” * You should see a new patch called: “AVI-2021-0006 Critical Vulnerability Security Patch” * Apply the patch, by clicking on the icon on the right and selecting “Apply Patch” * Take a backup again at “Controller/Settings/Maintenance/Backup&Restore/Backup Now” **Note:** * The security patch does not impact the data path or control path and can be executed without a maintenance window * This patch can be applied on releases 6.2 and higher * Aviatrix **strongly recommends** you to upgrade to releases 6.4 or higher. Please check out the `release notes <https://docs.aviatrix.com/HowTos/UCC_Release_Notes.html>`_ and follow the `upgrade instructions <https://aviatrix.zendesk.com/hc/en-us/articles/4403944002829-Aviatrix-Controller-Upgrade>`_ 2. Security Patch ------------------- **Date** 10/11/2021 **Security Note for 6.5.1936, 6.4.2869, 6.3.2526, and 6.2.2052** **Subject**: Security release for Aviatrix versions 6.5.1936, 6.4.2869, 6.3.2526, and 6.2.2052. **Issues**: The latest 6.5, 6.4, 6.3, and 6.2 versions contain fixes for two vulnerabilities. **AVX-15638** – Corrected vulnerability that could result in a Denial-of-Service (DoS) in Aviatrix's controller API which allows an attacker to fill the disk of the controller. The API vulnerability is blocked in the latest controller software versions. For more information, see `CVE-2021-40870 <https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-40870>`_ **AVX-15740** - The latest version of the Aviatrix AWS CloudFormation stack improves security by removing 0.0.0.0 entry on port 443 so the Aviatrix controller is not open to the world by default. However, this means related gateway IP entries need to be added to the security group when a new gateway is deployed for the gateway to talk to controller. To achieve this automatically, the Controller Security Group Management feature will be auto enabled when a user creates the first AWS account. If you are performing the manual backup and restore procedure, please inherit all the original security groups in the newly launched controller. Mitigation: Please upgrade to the latest release. For detailed instructions related to this security upgrade, please see https://aviatrix.zendesk.com/hc/en-us/articles/4410621458317. -If you are running 6.2, upgrade to 6.2.2052 or later. Aviatrix strongly recommends you upgrade to 6.4.2869 or later, 6.2 `EoL <https://support.aviatrix.com/Aviatrix-EOL-Policy>`_ is 01/23/2022. -If you are running 6.3, upgrade to 6.3.2526 or later. Aviatrix strongly recommends you upgrade to 6.4.2869 or later, 6.3 `EoE <https://support.aviatrix.com/Aviatrix-EOL-Policy>`_ was 01/31/2022. -If you are running 6.4, upgrade to 6.4.2869 or later. -If you are running 6.5, upgrade to 6.5.1936 or later. 1. Security Patch ------------------- **Date** 09/11/2021 **Security Note for 6.2.2043, 6.3.2490, 6.4.2838, and 6.5.1922** **Subject**: Security release for Aviatrix versions 6.5, 6.4, 6.3, and 6.2. **Issues**: The latest 6.5, 6.4, 6.3, and 6.2 versions contain fixes for several vulnerabilities in the controller API: - Several APIs used to upload configurations of certain services did not verify the authentication of the service or user executing the API call properly. - `CVE-2021-40870 <https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-40870>`_: Similar APIs designed to upload files from authenticated users did not properly sanitize their destination input, which could eventually allow an unauthenticated user to execute arbitrary code via directory traversal. - Fix for Aviatrix issue AVX-14852 described in Aviatrix FN 0032: In rare occasions, Controller backup file could get corrupted, resulting in gateways being shown as “down” if used for a Controller restore. **Mitigation**: Please upgrade to the latest release. For instructions, go to `support.aviatrix.com <https://support.aviatrix.com/>`_ and search for *Aviatrix Controller Upgrade*. - If you are running 6.2, upgrade to 6.2.2043 or later. Aviatrix strongly recommends you upgrade to 6.4.2838 or later, 6.2 `EoL <https://support.aviatrix.com/Aviatrix-EOL-Policy>`_ is 01/23/2022. - If you are running 6.3, upgrade to 6.3.2490 or later. Aviatrix strongly recommends you upgrade to 6.4.2838 or later, 6.3 `EoE <https://support.aviatrix.com/Aviatrix-EOL-Policy>`_ was 01/31/2022. - If you are running 6.4, upgrade to 6.4.2838 or later. - If you are running 6.5, upgrade to 6.5.1922 or later. **Credit**: Aviatrix would like to thank the team at Tradecraft (https://www.wearetradecraft.com/) for the responsible disclosure of these issues. ================================================================= ==================== ======================================================= **Patch Name** **Version** **Description** ================================================================= ==================== ======================================================= Increase File Descriptor limit 5.4 or earlier This patch will fix the VPN connection issue. Before this patch openVPN do not have permission to open more than 1024 connections socket and it hangs if more than 1024 sockets are open. This patch is only applicable to Gateways, and not required after UserConnect-4.3. Enable support for FIPS 140-2 6.0 or earlier Enable support for FIPS 140-2 Module. Click `here <https://docs.aviatrix.com/HowTos/fips140-2.html>`_ for more details. This patch is only applicable to Aviatrix Gateways. Remove old UI 6.0 or earlier This patch will remove the unnecessary web server components from old UI pages which could be accessible without requiring a credentials. Patch applied to Avitrix Controller only. X-XSS-Protection and X-Content-Type-Options Headers 5.2+ X-XSS-Protection and X-Content-Type-Options Headers did not configure properly without the patch. Applicable to Aviatrix Gateway and Controller both. SAML XML signature wrapping vulnerability 6.0 or earlier The SAML implementation in the Aviatrix controller was vulnerable to XML Signature Wrapping without the patch. Without the patch, an attacker with any signed SAML assertion from the Identity Provider can establish a connection even if that SAML assertion has expired or is from a user who is not authorized to access Aviatrix. Applicable to Aviatrix Controller only. ================================================================= ==================== ======================================================= <file_sep> ================================================================= How to Connect Office to Multiple AWS VPCs with AWS Peering ================================================================= This document describes a common use case where a customer needs to connect her on-prem office to a group of VPCs securely so that developers can connect to the instances in VPC and work on applications. In this case, the customer does not want to build an IPSEC tunnel to each VPC, nor does she want to build a full blown `Global Transit Network <http://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_. |simpletransit| Fortunately since traffic is always initiated from the on-prem office as there are no servers in the office, there is a simple solution to connect many VPCs with one single IPSEC tunnel by leveraging the Aviatrix Site2Cloud feature and AWS Peering. Below are the steps to configure. Planning and Prerequisites --------------------------- 1. If you have not launched an Aviatrix Controller, start with the `Aviatrix startup guide <http://docs.aviatrix.com/StartUpGuides/aviatrix-cloud-controller-startup-guide.html>`_ #. If this is your first time using Aviatrix, make sure you go through the Aviatrix Controller on-boarding process. 1. Launch a gateway in the transit VPC ------------------------------------------- Go to the Gateway page to launch a gateway in the transit VPC that servers to move traffic between a Spoke VPC and on-prem network. The gateway must be launched on a public subnet where its associated route table has a route 0.0.0.0/0 that points to AWS IGW. .. important:: Make sure you enable NAT when launch the gateway in the transit vpc. ========================================== ========== **Setting** **Value** ========================================== ========== Cloud Type AWS Gateway Name simple-transit-gw Account Name OpsTeam Region us-west-2 VPC ID transit VPC ID Public Subnet The public subnet where the transit GW instance is deployed Gateway Size GW `instance size <http://docs.aviatrix.com/HowTos/gateway.html#select-gateway-size>`_ Specify a Reachable DNS Servier IP Address Leave it unselected Enable NAT check Add/Edit Tags `Additional AWS Tags <http://docs.aviatrix.com/HowTos/gateway.html#add-edit-tags>`_ for the Transit GW instance ========================================== ========== Below is a screenshot of the setup. Note that NAT is enabled. |transit-gw-launch| 2. Setup a Site2Cloud tunnel to on-prem office -------------------------------------------------- After the gateway is launched successfully, go to Site2Cloud to create a new IPSEC tunnel between the transit VPC and on-prem office. ========================================== ========== **Setting** **Value** ========================================== ========== VPC ID/VNet Name transit vpc in the drop down Connection Type Unmapped Connection Name a unique name to identify the connection Remote Gateway Type select one type from a drop down Tunnel Type select UDP Algorithm leave it unchecked Encryption over ExpressRoute/DX leave it unchecked Enable HA leave it unchecked Primary Cloud Gateway select the transit gateway launched in step 1 Remote Gateway IP Address the public IP address of the on-prem firewall device Pre-shared Key leave it unchecked Remote Subnet the on-prem office CIDR list separated by comma Local Subnet all spoke VPC CIDR list separated by comma Save Template leave it unchecked ========================================== ========== Below is a screenshot of the setup. Note that the local subnet is a list of all Spoke VPC CIDRs. |transit-to-on-prem| 3. Download the Configuration Template --------------------------------------- After the above Site2Cloud connection is created, select the connection. Select a Vendor Generic if the on-prem firewall device is not Aviatrix nor Cisco. Click Download Configuration. |download-s2c-config| After you download the IPSEC configuration template, use the template to configure your on-prem device. 4. Connect Spoke to Transit ---------------------------- Once the site2cloud tunnel is up, it's time to use AWS Peering to build connectivity between a Spoke VPC and the transit VPC. Go to Peering -> AWS Peering, click New Peering. Select a spoke VPC and the transit VPC, and click OK. The AWS Peering will be established and the routing tables will be programmed by the Controller. |aws-peering| 5. Congratulations! ------------------------------------------------ Now you can test connectivity by initiating a "Ping" or "SSH" from office host machine or your laptop to an EC2 instance in a Spoke VPC. 6. Add More Spoke VPCs --------------------------------------- Each time you add a new Spoke VPC, you need to edit the site2cloud tunnel to include the new Spoke VPC CIDR in the remote CIDR field, as shown below. Similarly, you may need to edit your on-prem device to include the new Spoke VPC. |edit-transit-to-onprem-for-spoke2| .. |simpletransit| image:: simpletransit_media/simpletransit.png :scale: 50% .. |transit-gw-launch| image:: simpletransit_media/simple-transit-gw-launch.png :scale: 50% .. |transit-to-on-prem| image:: simpletransit_media/transit-to-on-prem.png :scale: 50% .. |download-s2c-config| image:: simpletransit_media/download-s2c-config.png :scale: 50% .. |aws-peering| image:: simpletransit_media/aws-peering.png :scale: 50% .. |edit-transit-to-onprem-for-spoke2| image:: simpletransit_media/edit-transit-to-onprem-for-spoke2.png :scale: 50% .. disqus:: <file_sep> .. raw:: html <style> /* override table no-wrap */ .wy-table-responsive table td, .wy-table-responsive table th { white-space: normal !important; } </style> ================================= Egress FQDN FAQ ================================= Why is Egress Control Filter needed? ======================================== |egress_overview| For Internet-bound egress traffic, specifying an outbound policy at the IP address level is not sufficient, as the domain names of a site can be translated to many different IP addresses. An NAT gateway does not offer security group functions; it relies on security groups by each instance. An NAT instance's security group does not have enough entries to support the large set of IP address lists. The egress filtering needs to happen at Layer 7. On the other hand, workloads in AWS are mostly applications or programs where it is deterministic which outbound APIs the application program calls. For example, an application runs API queries to *www.salesforce.com* for data retrieving and runs API queries to *www.google.com* for app authentication. In these cases, making sure that only these sites are allowed for egress traffic is sufficient from a security point of view. Note that this is very different from on-prem situations where end user traffic and application traffic are mingled together; you may need a full-fledged firewall for Internet-bound traffic. Another use case is for PCI DSS compliance. PCI DSS specifies that if you handle any payment and sensitive data, there must be firewall policy enforcement at the egress. In the cloud, the logical egress point is per VPC/VNet. What does the Aviatrix FQDN feature do? ======================================== Aviatrix Fully Qualified Domain Name (FQDN) is a security service specifically designed for workloads or applications in the public cloud. It filters Internet-bound egress traffic initiated from workloads in a VPC/VNet. This service is centrally managed by the Controller and executed by an Aviatrix Gateway instance in the VPC/VNet in the distributed architecture.. Aviatrix FQDN filters any TCP and UDP traffic including HTTP, HTTPS, and SFTP traffic. The filtering function allows only the destination host names (whitelist) specified in the list to pass and drop all other destinations. Each destination is specified as fully qualified domain name. For example, if you only allow Internet bound traffic to `www.salesforce.com <http://www.salesforce.com>`__, you can list the domain name www.salesforce.com in the whitelist. For HTTP/HTTPS (TCP port 80/443), FQDN feature also supports wild cards, such as \*. In this example, you can specify \*.salesforce.com to allow traffic to any domain names that end in "salesforce.com." How does it work? ================= The function is transparent to individual instances and is carried out inline without requiring any certificate or keys to decrypt the traffic. Non-HTTP/HTTPS traffic can also be filtered based on exact domain names. Use cases are secure file transfer (SFTP) to external sites, secure login in (SSH) to external sites. A tag is defined as a list of FQDNs and it is created and managed on the Controller console. One or more gateways may be attached to a tag; each gateway can be attached to more than one tag. Any updates to a tag on the Controller automatically triggers updates to all gateways attached to the tag. Multiple tags can be defined for the Controller. The domains in the tag are the destinations that are allowed for traffic to pass. For configuration details, refer to `this doc. <https://docs.aviatrix.com/HowTos/FQDN_Whitelists_Ref_Design.html>`_ How do I enable 2 AZ HA for FQDN gateways? ============================================ Go to the Gateway page, highlight the gateway, and click **Edit**. At Gateway for High Availability Peering, select a subnet (a public subnet for AWS, GCP, and OCI) in the dropdown menu and click **Create**. A backup gateway with the name extension -hagw will be created. Note that this takes a few minutes of time. For FQDN function, the primary gateway and backup gateway load balance the Internet bound traffic from different subnets based on a route table. How do I enable 3 AZ HA for FQDN gateways? ============================================ Her are the steps to enable 3 AZ HA FQDN gateways: 1. Launch an Aviatrix gateway in AZ1. #. Launch an Aviatrix gateway in AZ2. #. Launch an Aviatrix gateway in AZ3. #. Attach the same FQDN tag to each gateway launched in the steps above. #. Enable the FQDN tag. Following the instructions above, Aviatrix Controller will try to load balance the route tables to point to the gateways with AZ affinity. When a gateway fails, the Controller will reprogram the VPC/VNet route table to redistribute the traffic to the remaining gateways. How does Aviatrix Egress FQDN compare to Squid and other solutions? =============================================================================== Squid is a popular open-source software that can be configured to do transparent HTTP/HTTPS filtering. Squid does not process non-HTTP/HTTPS traffic. For example, if you need to filter on a SFTP site that runs on TCP port 22, Squid does not work. Below is a more comprehensive comparison between Aviatrix FQDN and Squid. The table below also compares with other solutions such as AWS NAT Gateway, AWS Network Firewall, and Azure Firewall. ============================================= ============================================================= =============== ===================== ================ ============= **Functions** **Aviatrix FQDN** AWS NAT Gateway AWS Network Firewall Azure Firewall **Squid** ============================================= ============================================================= =============== ===================== ================ ============= Requires instance configuration No No No No No HTTP and HTTPS FQDN filter Yes (support wildcard) No Yes Yes Yes non-HTTP/HTTPS FQDN filter Yes No No No No Requires dedicated subnet No No Yes Yes No Multi AZ High Availability Yes (load balanced) Yes Yes Yes No Centrally Managed Yes Yes Yes Yes No Egress Discovery `Yes <https://docs.aviatrix.com/HowTos/fqdn_discovery.html>`_ No No No No API support Yes Yes Yes Yes No Terraform support Yes Yes Yes No No Out-of-box log integration Yes No Yes Yes No Allow specified destination to bypass filter Yes No No No No Allow specified source CIDR to apply to rule Yes No No No No Allow specified source CIDR to bypass filter Yes No No No No Out of box visibility on sessions Yes No No No No Search a specified rule match history Yes No No No No Vendor product support Yes Yes Yes Yes No ============================================= ============================================================= =============== ===================== ================ ============= How do I troubleshoot FQDN problems? ====================================== If you have problems with FQDN on a specific gateway, follow the instructions below to troubleshoot: 1. Make sure the corresponding AWS or Azure route table has the route entry 0.0.0.0/0 which points to the gateway instance. #. To verify that the above step is set up properly, disable the FQDN function of the problem gateway by detaching it from the associated tag, and run a ping test to www.yahoo.com from an instance in the private subnet to make sure Internet egress works. #. Attach the problem gateway to the tag. Make sure the tag has Enabled button on. Make sure the Whitelist or Blacklist is selected as intended. #. Check the tag to make sure it has the intended URL configured. #. Run a wget test from a private instance in the VPC/VNet to a URL configured in the tag. #. Use Step 4 at Egress FQDN View Log, select the problem gateway and download the log. Review the log file and analyze if the intended URL is in the log entry, why it is being accepted or denied. #. Note: if a tag has the White list option selected, all URLs in the tag will be accepted. On the other hand, if a tag has a Black list option selected, all URLs in the tag will be dropped. #. If none of the above work, try to Disable and Enable the tag again. This will restart the FQDN function on all attached gateways. #. If all above steps failed, get help from the Aviatrix support team and upload `tracelog <https://docs.aviatrix.com/HowTos/troubleshooting.html#upload-tracelog>`_. Any vendor specific comments to be noted? --------------------------------------------------------------------------------------------- Any GCE instance (excluding Controller-created gateways) that needs to participate in egress control (FQDN, SNAT and FW Egress) have to be tagged as "avx-snat-noip". The GCE network tag "avx-snat-noip" can be associated during GCE instance creation or by editing an existing instance. What happens if I enable FQDN and there are route tables that have an existing default route? -------------------------------------------------------------------------------------------------------------------- When enabling egress filtering on a VPC/VNet, each subnet's route table is reviewed. If there is an existing default route (0.0.0.0/0) in the route table, the following logic is used: +----------------------+-----------------------------------------------------+ | Target | Aviatrix action | +======================+=====================================================+ | **igw-*** | Ignore this route table | +----------------------+-----------------------------------------------------+ | anything other than | Update the **Target** to point to the AVX GW ENI | | **igw-*** | and remember the current value of **Target**. | | | (see note below) | +----------------------+-----------------------------------------------------+ .. note:: If the Gateway is detached from the VPC/VNet (via the egress configuration page), the route table will be updated with the original values. Can FQDN gateway be deployed in a central place? ----------------------------------------------------------------- Yes. Available in Release 5.0 and later, Aviatrix FQDN gateway can be deployed centrally in the TGW environment as shown in the diagram below. |fqdn_in_firenet| One use case is if you need to limit the public IP addresses to a third-party public service. Follow the `Firewall Network workflow <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#c-launch-associate-aviatrix-fqdn-gateway>`_ to deploy. How do FQDN and Stateful Firewall work together? ------------------------------------------------------------------- If FQDN service is enabled on a gateway for any TCP port 80 and 443 traffic, all forwarding traffic to destination TCP port 80 and 443 are processed by FQDN engine and the decision to drop or accept the session is reached by FQDN engine. Stateful firewall can only process traffic destined to non TCP port 80 and 443. In what order are the FQDN rules processed? -------------------------------------------------------------- Since you can create multiple tags with each consisting of a list of FQDN rules, the Controller must merge these rules in a specific order before sending these rules to FQDN gateway for processing. The Controller merges all FQDN rules by this order: 1. If the rule ACTION is Deny, it is placed in the first block for processing, that is, they are processed first. #. Within each block (Deny, Allow, Base Policy), the more specific rules are processed or examined first. For example, salesforce.com is more specific than *.salesforce.com therefore salesforce.com is processed first. #. Each rule has a verdict, Accept or Drop. When the FQDN processing engine finds a match, the verdict is reached and the packet is either dropped or accepted. The processing engine does not continue on to the next rule. FQDN Option for Exact Match ---------------------------------------------------- This is a new feature where if a FQDN rule does not have * an exact match is expected. If this global option is not enabled, FQDN rules use regex to match any FQDN names that are subset of the name. For example, if salesforce.com is a rule and Exact Match option is enabled, finance.salesforce.com is not a match and will be dropped. .. |egress_overview| image:: FQDN_Whitelists_Ref_Design_media/egress_overview.png :scale: 30% .. |fqdn| image:: FQDN_Whitelists_Ref_Design_media/fqdn.png :scale: 50% .. |fqdn-new-tag| image:: FQDN_Whitelists_Ref_Design_media/fqdn-new-tag.png :scale: 50% .. |fqdn-add-new-tag| image:: FQDN_Whitelists_Ref_Design_media/fqdn-add-new-tag.png :scale: 50% .. |fqdn-enable-edit| image:: FQDN_Whitelists_Ref_Design_media/fqdn-enable-edit.png :scale: 50% .. |fqdn-add-domain-names| image:: FQDN_Whitelists_Ref_Design_media/fqdn-add-domain-names.png .. |fqdn-attach-spoke1| image:: FQDN_Whitelists_Ref_Design_media/fqdn-attach-spoke1.png :scale: 50% .. |fqdn-attach-spoke2| image:: FQDN_Whitelists_Ref_Design_media/fqdn-attach-spoke2.png :scale: 50% .. |export| image:: FQDN_Whitelists_Ref_Design_media/export.png :scale: 50% .. |fqdn_in_firenet| image:: firewall_network_workflow_media/fqdn_in_firenet.png :scale: 30% .. add in the disqus tag .. disqus:: <file_sep> .. raw:: html <style> /* override table no-wrap */ .wy-table-responsive table td, .wy-table-responsive table th { white-space: normal !important; } </style> ================================= Stateful Firewall FAQ ================================= What is the Aviatrix Stateful Firewall? -------------------------------------------------- Aviatrix Stateful Firewall is a feature on the Aviatrix Gateway. It is a L4 stateful firewall that filters network CIDR, protocol, and port on the packet forwarding path. The stateful firewall allows each individual rule to be defined as Allow, Deny and Force Drop, in addition to a base rule. .. note:: Aviatrix recommends that you not use the Stateful Firewall feature in HA pairs because the gateways do not synchronize the firewall state. Is there a limitation on the number of tags? ---------------------------------------------------------- There is no limitation on the number of tags. How do I configure a stateful firewall? ------------------------------------------------------- Follow the instructions described `here <https://docs.aviatrix.com/HowTos/tag_firewall.html>`_. .. |egress_overview| image:: FQDN_Whitelists_Ref_Design_media/egress_overview.png :scale: 30% .. |fqdn| image:: FQDN_Whitelists_Ref_Design_media/fqdn.png :scale: 50% .. |fqdn-new-tag| image:: FQDN_Whitelists_Ref_Design_media/fqdn-new-tag.png :scale: 50% .. |fqdn-add-new-tag| image:: FQDN_Whitelists_Ref_Design_media/fqdn-add-new-tag.png :scale: 50% .. |fqdn-enable-edit| image:: FQDN_Whitelists_Ref_Design_media/fqdn-enable-edit.png :scale: 50% .. |fqdn-add-domain-names| image:: FQDN_Whitelists_Ref_Design_media/fqdn-add-domain-names.png .. |fqdn-attach-spoke1| image:: FQDN_Whitelists_Ref_Design_media/fqdn-attach-spoke1.png :scale: 50% .. |fqdn-attach-spoke2| image:: FQDN_Whitelists_Ref_Design_media/fqdn-attach-spoke2.png :scale: 50% .. |export| image:: FQDN_Whitelists_Ref_Design_media/export.png :scale: 50% .. |fqdn_in_firenet| image:: firewall_network_workflow_media/fqdn_in_firenet.png :scale: 30% .. add in the disqus tag .. disqus:: <file_sep>========================================================= Transit Connection to FortiGate over the internet. ========================================================= 1.From the Controller go to Transit Network -> Setup -> Launch a Transit VPC GW. |image1| 2.Connect the transit VPC GW to FortiGate. Go to Transit Network -> Setup -> Connect to VGW/External Device. Select External Device and input the following parameters. a. BGP Local AS number: ASN of the transit VPC GW b. BGP Remote AS number: ASN of the Fortinet Fortigate c. Remote Gateway IP Address: Fortinet Fortigate external interface's public IP |image2| 3.Download the configuration by going to Site2Cloud -> Click on the Connection. Select generic. Download Configuration and configure on the remote firewall accordingly. |image3| The following is a sample configuration based on the site2cloud configuration above. |image4| 4.Login into FortiGate and configure it as the following. 4.a In the VPN menu, select IPsec Tunnels 4.b click + Create New, select custom Populate the fields according to your preferences. **VPN Setup** +-------------------------------+------------------------------------------+ | Field | Expected Value | +===============================+==========================================+ | Name | Any name | +-------------------------------+------------------------------------------+ | Template Type | Custom | +-------------------------------+------------------------------------------+ |image5| **Network** +-------------------------------+------------------------------------------+ | Field | Expected Value | +===============================+==========================================+ | IP Version | IPv4 | +-------------------------------+------------------------------------------+ | Remote Gateway | Static IP Address | +-------------------------------+------------------------------------------+ | IP Address | Public IP address of Aviatrix Gateway | +-------------------------------+------------------------------------------+ | Interface | Select the external port/interface | +-------------------------------+------------------------------------------+ | Local Gateway | Disabled | +-------------------------------+------------------------------------------+ | Mode Config | Unchecked | +-------------------------------+------------------------------------------+ | NAT Traversal | Recommended: Enable | +-------------------------------+------------------------------------------+ | Keepalive Frequency | Any value | +-------------------------------+------------------------------------------+ | Dead Peer Detection | On Demand | +-------------------------------+------------------------------------------+ |image6| **Authentication** +-------------------------------+------------------------------------------+ | Field | Expected Value | +===============================+==========================================+ | Method | Pre-shared Key | +-------------------------------+------------------------------------------+ | Pre-shared Key | Enter the value from the downloaded | | | configuration in step3 | +-------------------------------+------------------------------------------+ | IKE Version | 1 | +-------------------------------+------------------------------------------+ | IKE Mode | Main (ID protection) | +-------------------------------+------------------------------------------+ |image7| **Phase 1 Proposal** .. important:: The following values from the Aviatrix Site2Cloud configuration are needed below: #. In the Aviatrix Controller, click on site2cloud connection. #. Click on the 3 dashed lines next to `Connect Detail` |image8| +-------------------------------+------------------------------------------+ | Field | Expected Value | +===============================+==========================================+ | Encryption | Match value from the config file | | | downloaded at step3 | +-------------------------------+------------------------------------------+ | Authentication | Match value from the config file | | | downloaded at step3 | +-------------------------------+------------------------------------------+ | Diffie-Hellman Group | Match value from the config file | | | downloaded at step3 | +-------------------------------+------------------------------------------+ | Key Lifetime (seconds) | 28800 | +-------------------------------+------------------------------------------+ | Local ID | | +-------------------------------+------------------------------------------+ |image9| **XAUTH** +-------------------------------+------------------------------------------+ | Field | Expected Value | +===============================+==========================================+ | Type | Disabled | +-------------------------------+------------------------------------------+ |image10| **Phase 2 Selectors** *New Phase 2* +-------------------------------+------------------------------------------+ | Field | Expected Value | +===============================+==========================================+ | Name | Any string value | +-------------------------------+------------------------------------------+ | Comments | Any string value | +-------------------------------+------------------------------------------+ | Local Address | 0.0.0.0/0 | +-------------------------------+------------------------------------------+ | Remote Address | 0.0.0.0/0 | +-------------------------------+------------------------------------------+ |image11| *Advanced* .. important:: The following values from the Aviatrix Site2Cloud configuration are needed below: #. In the Aviatrix Controller, select the Site2Cloud configuration. #. Click on the 3 dashed lines next to `Connect Detail` |image12| +-------------------------------+------------------------------------------+ | Field | Expected Value | +===============================+==========================================+ | Encryption | Match value from the config file | | | downloaded at step3 | +-------------------------------+------------------------------------------+ | Authentication | Match value from the config file | | | downloaded at step3 | +-------------------------------+------------------------------------------+ | Diffie-Hellman Group | Match value from the config file | | | downloaded at step3 | +-------------------------------+------------------------------------------+ | Key Lifetime | Seconds | +-------------------------------+------------------------------------------+ | Seconds | 28800 | +-------------------------------+------------------------------------------+ |image13| #. Click `OK` 4.d Click -> Network -> Interfaces. Click on the Tunnel created above (e.g. aviatrix-gatew)-> assign the IP address from the configuration file downloaded at step 3 |image14| 4.e Configure IPv4 Policy In **Policy & Objects**, select **IPv4 Policy**. Create 2 new IPv4 policies: * Outbound traffic |image15| * Inbound traffic |image16| .. note:: The reference to `port2` in the screenshots should be replaced with your own interface name that represents the internal facing interface. .. note:: Be sure to select **accept** for `action` and select **all** for `service` 4.f Bring Up IPSec Monitor In **Monitor** > **IPSec Monitor**, select the Aviatrix tunnel, and click **Bring Up**. The tunnel status should change to up as shown below |image18| 5.Configure BGP: Click -> Network -> BGP Configure as below: RouterID : Tunnel IP address taken from the configuration file downloaded at step3 Neighbors: Remote tunnel IP address and ASN Networks: All the networks needs to be advertised via BGP (here 10.0.3.0 is the local network of FortiGate) |image21| 6.Go to Transit Network -> Advanced Config on the Controller and Click on Diagnostics and select the GW name from the dropdown list and select Show Ip bgp Command from the predefined Show list to verify the BGP Routes. |image19| |image20| .. |image1| image:: ./Transit_ExternalDevice_FortiGate/1.png :width: 7.00000 in :height: 5.00000 in .. |image2| image:: ./Transit_ExternalDevice_FortiGate/2.png :width: 7.00000 in :height: 5.00000 in .. |image3| image:: ./Transit_ExternalDevice_FortiGate/3.png :width: 7.00000 in :height: 5.00000 in .. |image4| image:: ./Transit_ExternalDevice_FortiGate/4.png :width: 7.00000 in :height: 5.00000 in .. |image5| image:: ./Transit_ExternalDevice_FortiGate/5.png :width: 5.55625in :height: 3.26548in .. |image6| image:: ./Transit_ExternalDevice_FortiGate/6.png :width: 5.55625in :height: 3.26548in .. |image7| image:: ./Transit_ExternalDevice_FortiGate/7.png :width: 5.55625in :height: 3.26548in .. |image8| image:: ./Transit_ExternalDevice_FortiGate/8.png :width: 5.55625in :height: 3.26548in .. |image9| image:: ./Transit_ExternalDevice_FortiGate/9.png :width: 5.55625in :height: 3.26548in .. |image10| image:: ./Transit_ExternalDevice_FortiGate/10.png :width: 100% .. |image11| image:: ./Transit_ExternalDevice_FortiGate/11.png :width: 5.55625in :height: 3.26548in .. |image12| image:: ./Transit_ExternalDevice_FortiGate/12.png :width: 7.00000 in :height: 5.00000 in .. |image13| image:: ./Transit_ExternalDevice_FortiGate/13.png :width: 7.00000 in :height: 5.00000 in .. |image14| image:: ./Transit_ExternalDevice_FortiGate/14.png :width: 7.00000 in :height: 5.00000 in .. |image15| image:: ./Transit_ExternalDevice_FortiGate/15.png :width: 100% .. |image16| image:: ./Transit_ExternalDevice_FortiGate/16.png :width: 100% .. |image18| image:: ./Transit_ExternalDevice_FortiGate/18.png :width: 7.00000 in :height: 5.00000 in .. |image19| image:: ./Transit_ExternalDevice_FortiGate/19.png :width: 7.00000 in :height: 5.00000 in .. |image20| image:: ./Transit_ExternalDevice_FortiGate/20.png :width: 7.00000 in :height: 5.00000 in .. |image21| image:: ./Transit_ExternalDevice_FortiGate/bgp.png :width: 100% <file_sep> ################################### CoPilot ################################### This document describes the **CoPilot** configurations under Settings in Aviatrix Controller. It includes these sections: - `CoPilot Association`_ - `CoPilot Security Group Management`_ - `Delete Deployed CoPilot Instance`_ CoPilot Association =========================== When “Status” is enabled, the CoPilot with the "IP Address/Hostname" you specify is associated with the Controller. **IP Address/Hostname** Enter the public or private IP address of your CoPilot instance. The IP address specified here is used for connectivity between the controller and CoPilot for intra-platform communication (such as API message exchanges). If Copilot is located in the same VPC/VNet as your controller, specifying a private IP can increase bandwidth and potentially save on cost. **Public IP (Optional)** If you specified the private IP address of your CoPilot instance in "IP Address/Hostname", you can optionally enter the public IP address of your CoPilot instance here. The public IP address is used for external administration access to CoPilot, used for switching between Controller and CoPilot (for your browser to open a new tab when opening CoPilot from the Controller app icon). If this field is blank, the IP address specified in “IP Address/Hostname” is used for administration access to CoPilot. |image0| CoPilot Security Group Management =================================== CoPilot Security Group Management is available starting from Controller release 6.8. The feature is available for AWS and Azure CSPs. When “Status” is enabled (default), the Controller creates a security group for the specified CoPilot virtual machine to manage its inbound security-group rules. The Controller adds rules to the security group for each gateway IP for the following: - UDP port 5000 (default) — Enable Syslog for CoPilot Egress FQDN & Audit Data (from each gateway). Gateways send remote syslog to CoPilot. - TCP port 5000 (default) — (**If using private mode**) Enable Syslog for CoPilot Egress FQDN & Audit Data (from each gateway). Gateways send remote syslog to CoPilot. - UDP port 31283 (default, port is configurable) — Enable Netflow for CoPilot FlowIQ Data (from each gateway). Gateways send Netflow to CoPilot. The Controller adds the above rules for: - New gateways launched from the Controller *after* the feature is enabled. - Existing gateways launched from the Controller *before* the feature was enabled. When “Status” is disabled, the Controller removes all gateway-specific inbound rules that it previously added to the CoPilot security group. **Attention:** The CoPilot Security Group Management feature is automatically disabled if the AWS security group quota or Azure Network Security Group (NSG) rule limit is reached. In this case, you must request an increase for the security group quota/limit from AWS/Azure and then re-enable the CoPilot Security Group Management feature. **It is recommended that you monitor and increase the AWS/Azure security group quota before the rule limit is reached**. Please refer to the AWS/Azure product documentation for information about viewing security group quotas/limits. The CoPilot Security Group Management feature adds gateway IP rules to customer-attached CoPilot security groups as well as CoPilot-created security groups. CoPilot comes with a base security group when it is first launched; the feature does not remove rules that were manually added to the base security group. To enable the CoPilot Security Group Management feature: 1. In your Controller, go to Settings > CoPilot > CoPilot Association and set the slider to **Enabled**. Enter the CoPilot private IP address in the IP Address/Hostname field, its public IP address in the Public IP (Optional) field, and click **Save**. 2. On the same page, for CoPilot Security Group Management, verify the slider is set to **Enabled**. 3. In **Cloud Type**, select the CSP in which your CoPilot is deployed (AWS or Azure). 4. In **Access Account Name**, select the Controller account. 5. In **Region**, select the region in which your CoPilot is deployed. 6. In **VPC ID**, select the ID of the VPC/VNet in which your CoPilot is located. 7. In **CoPilot Instance**, select the ID of the CoPilot instance for which you want the controller to manage security groups. For a clustered CoPilot deployment, this is the ID of the Main Server CoPilot instance. You can log in to the CSP portal to obtain the instance ID of the CoPilot instance. After you select the VPC in the previous step, all the instances (virtual machines) in that VPC are shown in the drop down menu. From that list, you can identify the CoPilot instance (VM) that was created on the CSP environment. 8. Click **Submit**. Delete Deployed CoPilot Instance =================================== If you deployed your CoPilot from the Controller user interface, you can delete the existing CoPilot — simple or fault tolerant (cluster) deployment — using this option. You would delete the existing CoPilot, for example, if you accidentally deployed it in the wrong VPC. If you used the CoPilot instance for some time, note that you will lose all historical data in the instance when you delete it. Select the deployment type and click **Delete**. The CoPilot instance(s) is terminated in the cloud provider environment. If you deployed your CoPilot by using Terraform scripts or from the CSP marketplace, see the discussion about deleting CoPilot instances in *Aviatrix CoPilot Deployment Guide*. .. |image0| image:: CoPilot_media/image0.png :scale: 30% .. disqus:: <file_sep> =========================================================================================== CloudFormation Condition Function Example =========================================================================================== AWS CloudFormation is a popular tool to automate AWS resource management. There are situations when you need to create a resource or specify a property based on the value of input parameters. You may use `Condition Functions <https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-conditions.html>`_ to address such types of requirement. Here is an example of how to use Conditions in a CloudFormation script. In this example, we want to specify "unlimited", a CPU credit property that only applies to t2/t3 series instances when a user selects such instance type. If the user input is not t2 series, for example, m4 series, the CPU credit property cannot be specified as it does not exist. The code to define a condition that tests if the input parameter is t2.large, t2.xlarge or t2.2xlarge is as follows. :: "Conditions": { "AviatrixIAMRoleNotExist": { "Fn::Equals": [ { "Ref": "IAMRoleParam" }, "New" ] }, "T2SeriesTrue": { "Fn::Or": [ {"Fn::Equals" : [{"Ref" : "InstanceTypeParam"}, "t2.large"]}, {"Fn::Equals" : [{"Ref" : "InstanceTypeParam"}, "t2.xlarge"]}, {"Fn::Equals" : [{"Ref" : "InstanceTypeParam"}, "t2.2xlarge"]} ] } }, Where T2SeriesTrue is the condition to test out if input parameter InstanceTypeParam is one of the t2 series. Note "Fn::Or" is used to allow multiple choices, if any of them is True, the condition returns True. The code to use the condition to specify the CPU Credit type is as follows: :: "CreditSpecification": { "Fn::If" : [ "T2SeriesTrue", {"CPUCredits": "unlimited"}, {"Ref": "AWS::NoValue"} ] } where if condition T2SeriesTrue is True, CPUCredits will be set to "unlimited", otherwise it is not specified. To view the entire CloudFormation script that is used to launch the Aviatrix Controller, visit the `repo on github. <https://github.com/AviatrixSystems/aws-controller-launch-cloudformation-templates/blob/master/cloudformation-templates/avx-awsmp-BYOL.template>`_ .. |inter_region_latency| image:: inter_region_latency_media/inter_region_latency.png :scale: 30% .. disqus:: <file_sep> =========================================================== Azure Account Credential Setup =========================================================== 1. Overview ============= Aviatrix Controller uses Azure APIs extensively to launch Aviatrix gateways, configure encrypted peering and other features. In order to use Azure API, you need to first create an Aviatrix `Access Account <https://docs.aviatrix.com/HowTos/aviatrix_account.html>`_ on the Aviatrix Controller. This access account corresponds to a valid Azure subscription with API credentials. You need to create an access account for each subscription. This document describes, for a given subscription, how to set up your Azure account credentials and onboard this Azure account to your Aviatrix Controller. Then, your Aviatrix Controller can execute APIs on that subscription. .. note:: These instructions apply generally to both Azure commercial and Azure Government clouds for onboarding Azure accounts to your Controller. Note that some screenshots may show regions that are only available for commercial Azure accounts. Commercial Azure offers multiple regions worldwide while Azure Government offers four US regions: (US) USGov Virginia, (US) UsGov Arizona, (US) UsGov Iowa, and (US) UsGov. For more information about Azure regions, click `here <https://azure.microsoft.com/en-us/global-infrastructure/geographies/#overview>`_. 2. API and Permission Setup ======================================== Setting up Azure permission for Aviatrix involves the following steps. #. Registering Aviatrix Controller Application with Azure Active Directory #. Assigning a role to the Aviatrix Controller Application #. Creating a Secret Identifier #. Setting API Permissions for the Aviatrix Controller Application #. Onboarding Your Azure Access Account in the Aviatrix Controller As you complete the first four steps, find and save these four values: your **Azure Subscription ID**, **Directory ID**, **Application ID**, and **Application Key value** (from your Client secret) to complete the last step, onboarding your Azure Access Account in the Aviatrix Controller. **Important:** Complete the following steps in order. Registering Your Aviatrix Controller Application ------------------------------------------------------- 1. Log into the `Azure portal <https://portal.azure.com>`_ and click **All services**. Search for “Azure Active Directory” and click on “Azure Active Directory.” 2. Click **App registrations** on the left (not App registrations (Legacy)). Click **+ New registration** near the top of the page. |image03| 3. Enter a clear and memorable name for your Aviatrix Controller application, select **Accounts in this organizational directory only,** and then click **Register** at the bottom of the page. The page displays details of your Aviatrix Controller application registration. 4. Copy the **Application ID** and **Directory ID** into a Notepad file and save the file. You will use the name of your Aviatrix Controller application and these ID values later to onboard your Azure access account in the Aviatrix Controller. Assigning a Role to the Aviatrix Application ------------------------------------------------------------ After registering your Aviatrix Controller as an app, assign this app a role to set up the connection between your Azure account and your Aviatrix Controller. 1. Log in to the Azure portal, click **All services** in the top left, and search for "Subscriptions." 2. Copy the Subscription ID to the Notepad file where you saved the Application ID and Directory ID. |image12| 3. Click the **Subscription Name** to open the subscription. 4. On the Subscriptions page, select **Access control (IAM)** on the left. 5. On the Access control (IAM) page, click **+ Add** > **Add role assignment**. 6. Under Add role assignment, select the **Contributor** role for this app. If the Contributor role is too broad, you can later replace it with a custom role with specific permissions. Refer to `Use Azure IAM Custom Role <https://docs.aviatrix.com/HowTos/azure_custom_role.html>`_ for instructions. 7. Click **+ Select members**. On the right, under Select members, in the Select search field, enter "aviatrix" into the field provided to search for the Aviatrix Controller app that you registered in the `Registering Your Aviatrix Controller Application <https://docs.aviatrix.com/HowTos/Aviatrix_Account_Azure.html#registering-your-aviatrix-controller-application>`_ section. Your app should appear in the list below. Select your Aviatrix Controller app and click **Select** towards to the bottom. |image13| 8. On the Add role assignment page, click **Review + assign** in the bottom left. Your Aviatrix Controller app is now assigned a Contributor role for this Azure subscription. As an alternative to steps 3-8 above, you can run the following PowerShell commands from your Azure AZ PowerShell module, or Azure Cloud Shell, to set up the Contributor role: .. code-block:: json az ad sp create-for-rbac --name "name you want to use here" --role="Contributor" --scopes=/subscriptions/xxxx-xx-xxxx-xxxx (replace Xs with subscription id) az ad sp list --show-mine --output table Creating a Secret Identifier ------------------------------------------------------------ After registering your Aviatrix Controller as an app and assigning it the Contributor role, create a Secret identifier. Azure Active Directory uses this Secret identifier to authenticate the Aviatrix Controller application. 1. Navigate back to All services > Azure Active Directory > App registrations and select the application you registered early. 2. Select **Certificates & secrets** on the left. Then, click **+New client secret**. 2. On the right, under Add a client secret, enter: * **Description** - Aviatrix * **Expires** - Select a time period that complies with your organization's security standards 3. Click **Add** towards the bottom. 4. The page displays your new Client secret. Copy the secret **Value** to the Notepad file where you saved your **Account ID**, **Directory ID**, and **Subscription ID**. These four values are necessary to onboard this Azure account in the Aviatrix Controller. Setting API Permissions for the Aviatrix Controller Application ------------------------------------------------------------ The API permission provides the Aviatrix Controller application permission to access Azure APIs. #. Navigate back to All services > Azure Active Directory > App registrations. #. Click on the Aviatrix Controller application link. #. From the left sidebar, select **API permissions**; then click **+ Add a permission**. #. Under Request API permissions, click **Azure Service Management**. #. On the Request API permissions for Azure Service Management page, under Permissions, select **user_impersonation.** You can now use the four values you saved to onboard your Azure account in your Aviatrix Controller. ========================================== ====================== Access Account Setup Input Field Value ========================================== ====================== Subscription ID From the `"Assigning a Role to the Aviatrix Application" <https://docs.aviatrix.com/HowTos/Aviatrix_Account_Azure.html#assigning-a-role-to-the-aviatrix-application>`_ section Directory ID From the `"Registering Your Aviatrix Controller Application" <https://docs.aviatrix.com/HowTos/Aviatrix_Account_Azure.html#registering-your-aviatrix-controller-application>`_ section Application ID From the `"Registering Your Aviatrix Controller Application" <https://docs.aviatrix.com/HowTos/Aviatrix_Account_Azure.html#registering-your-aviatrix-controller-application>`_ section Client Secret Value From the `"Creating a Secret Identifier" <https://docs.aviatrix.com/HowTos/Aviatrix_Account_Azure.html#creating-a-secret-identifier>`_ section ========================================== ====================== Onboarding Your Azure Access Account in the Aviatrix Controller ------------------------------------------------------------------------------- #. Open your Aviatrix Controller. From the left sidebar, select **ONBOARDING**. #. Select Microsoft Azure from the list of Cloud Service Providers (CSPs). Make sure to select **Microsoft Azure**, not Azure Government. #. Enter an Account Name for this Azure subscription. This name labels the account in the Aviatrix Controller and does not need to be a specific value from your Azure account. #. In the fields provided, enter the four values you saved in a Notepad file: the ARM Subscription ID, Directory ID, Application ID, and Application Key. Then, click **CREATE**. Your Primary Access Account for Azure should be successfully onboarded. To troubleshoot onboarding issues, see the `Aviatrix support website <http://support.aviatrix.com>`_ or `contact Aviatrix Support <http://https://aviatrix.com/contact>`_. Additional References ======================= If you need additional information, refer to `How to: Use the portal to create an Azure AD application and service principal that can access resources <https://docs.microsoft.com/en-us/azure/active-directory/develop/howto-create-service-principal-portal>`_ on Azure documentation. Azure China notes ================== Deploying the Aviatrix Gateway in the Azure China Cloud ----------------------------------------------------------- Prerequisites: You must already have a Microsoft Azure China account and Aviatrix Controller in AWS China to deploy an Aviatrix Gateway in the Azure China Cloud. 1. Create the Aviatrix Controller in your AWS China Cloud. Go to Onboarding and select Azure China. 2. Enter the Aviatrix Customer ID. 3. Enter the Certificate Domain. 4. Create the Primary Access Account. 6. Deploy Aviatrix Gateway from the Gateway page in the Aviatrix Controller or the Multi-Cloud Transit Solution page. For more information, see “What is a China ICP License?” .. |image01| image:: AviatrixAccountForAzure_media/az-ad-01.PNG :width: 5.20313in :height: 1.50209in .. |image02| image:: AviatrixAccountForAzure_media/az-ad-directory-id-02.PNG :width: 5.65600in :height: 2.39763in .. |image03| image:: AviatrixAccountForAzure_media/Image03.png :width: 70% .. |image04| image:: AviatrixAccountForAzure_media/Image04.png :width: 100% .. |image05| image:: AviatrixAccountForAzure_media/az-ad-list-all-apps-05.PNG :width: 5.65600in :height: 2.39763in .. |image06| image:: AviatrixAccountForAzure_media/Image06.png :width: 100% .. |image07| image:: AviatrixAccountForAzure_media/Image07.png :width: 100% .. |image08| image:: AviatrixAccountForAzure_media/Image08.png :width: 100% .. |image09| image:: AviatrixAccountForAzure_media/Image09.png :width: 100% .. |image10| image:: AviatrixAccountForAzure_media/Image10.png :width: 100% .. |image11| image:: AviatrixAccountForAzure_media/az-ad-sub-role-11.PNG :width: 5.65600in :height: 2.39763in .. |image12| image:: AviatrixAccountForAzure_media/az-ad-sub-list-12.PNG :width: 6.98958in :height: 3.02083in .. |image13| image:: AviatrixAccountForAzure_media/az-ad-sub-contrib-13.PNG :width: 6.98958in :height: 3.02083in .. |image14| image:: AviatrixAccountForAzure_media/Image14.png :width: 100% .. |image15| image:: AviatrixAccountForAzure_media/Image15.png :width: 100% .. add in the disqus tag .. disqus:: <file_sep> ================ Service Chaining ================ Service Chaining is the capability to combine multiple services in tandem in a VPC. For example, if EC2-initiated traffic needs to be inspected before being sent to another VPC, you can do so by deploying a third-party firewall function along with Aviatrix peering gateway, as shown in the diagram below. |image0| In the diagram, the firewall (FW) has trusted interface and untrusted interface (WAN). User EC2 instances are on private subnets. These private subnets have default gateway points to the firewall’s trusted interface (so that all egress traffic are sent through the firewall). To accomplish this, you need to go to AWS console, under VPC route tables create an route entry 0.0.0.0/0 to point firewall’s untrusted interface. Note this untrusted interface should be on the same subnet as Aviatrix peering gateway. Configuration Workflow ====================== Before you start, make sure you have the latest software by checking the Dashboard. If an alert message (!New) appears, click !New to download the latest software. We assume you already know how to deploy Aviatrix solution, if you need help, check out this `reference design <https://s3-us-west-2.amazonaws.com/aviatrix-download/Cloud-Controller/Cloud+Networking+Reference+Design.pdf>`__. Firewall function configuration is outside the scope of the reference design. The Service Chaining configuration workflow is as follows, with major steps highlighted. 1. Create a gateway in VPC-1 Go to Gateway -> New Gateway to create a gateway in VPC-1. Note the gateway must be launched on the same subnet as the firewall untrusted interface. 2. Enable Service Chaining in VPC-1 Go to Advanced Config -> Service Chaining -> Add New. - For Route Table ID field, select the route table that associates the subnet where firewall untrusted interface and gateway are deployed on. - For Downstream IP field, type the private IP address of the firewall untrusted interface. 1. Repeat step 1 for VPC-2. 2. Repeat step 2 if VPC-2 also needs firewall function. 3. Create VPC Peering Go to Peering -> Encrypted Peering +New Peering, enter the two gateways to create the peering. 1. All EC2 initiated traffic from VPC-1 that is destined to VPC-2 will go through firewall function for inspection before they are sent to VPC-2. 2. Note: You can create more peering connections from VPC-1, all traffic will be inspected. 3. For support, please open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_ 4. Enjoy! .. |image0| image:: SerChain_media/image1.png :width: 6.50000in :height: 2.11250in .. add in the disqus tag .. disqus:: <file_sep> ========================================================= Bootstrap Configuration Example for VM-Series in AWS ========================================================= Using the bootstrap option significantly simplifies VM-Series initial configuration setup. In this document, we provide a bootstrap example to set up an "Allow All" and Egress NAT policy for the VM-Series to validate that traffic is indeed sent to the VM-Series for VPC-to-VPC traffic inspection. This example does not use Panorama. Please use 9.0.3.xfr and above .xfr version for better results. Please refer to `PAN-OS 9.0.3 XFR for VM-Series <https://live.paloaltonetworks.com/t5/Blogs/PAN-OS-9-0-3-XFR-for-VM-Series-Now-Available/ba-p/290908>`_ . Note that Panorama PAN-OS version should be the same or higher than the firewall VMs when they are added to the Panorama, like, 9.0.3.xfr for both Panorama and VMs. For a manual setup, follow the `manual setup example <https://docs.aviatrix.com/HowTos/config_paloaltoVM.html>`_. Creating an IAM Role and Policy ---------------------------------------------- 1. Log in to AWS console and create an IAM role with the name: for example, "bootstrap-VM-S3-role." 2. Attach an IAM policy with the name: for example, "bootstrap-VM-S3-policy." The policy has the following statements. :: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:ListBucket" ], "Resource": [ "arn:aws:s3:::*" ] }, { "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": [ "arn:aws:s3:::*" ] } ] } Creating the bootstrap Bucket Structure ------------------------------------------------------- In AWS S3, at the top level create a bucket for bootstrap with a **unique** name, for example "bootstrap-bucket," with the following structure: :: bootstrap-bucket/ config/ init-cfg.txt bootstrap.xml content/ license/ software/ |bootstrap_bucket| Uploading Config Files -------------------------------- 1. The example bootstrap.xml file contains the "Allow All", Egress and API admin setup. To download the file, click :download:`bootstrap.xml <bootstrap_example_media/bootstrap.xml>`. 2. For the example init-cfg.txt file, click :download:`init-cfg.txt <bootstrap_example_media/init-cfg.txt>`. .. Note:: In the example bootstrap.xml, you must specify custom usernames and passwords for the <https_interface_admin_username> and <api_admin_username>, and generate hash strings for the passwords. 3. Upload these two files to your config folder in the bootstrap-bucket. Launching the VM-Series instance --------------------------------------------------- Follow the Aviatrix Firewall Network (FireNet) workflow to `this step <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#launching-and-associating-firewall-instance>`_. Fill in the required fields. Click **Advanced**. Fill in the following parameters. ================================ ====================== **Advanced Field** **Example Value** ================================ ====================== IAM Role bootstrap-VM-s3-role Bootstrap Bucket Name bootstrap-bucket (must be a unique name in S3) ================================ ====================== Launch the VM-Series instance. Wait for 15 minutes for it to boot up and initialize. Login to the HTTPS interface of VM-Series management public IP with the username and password specified in the bootstrap.xml file. Configuring API Vendor Integration ---------------------------------------------- In order for the Aviatrix Controller to automatically update firewall instance route tables, monitor the firewall instance health and manage instance failover, you need to setup API access permissions. Go to Controller -> Firewall Network -> Vendor Integration -> Firewall. Note the following fields. - Firewall Login User Name field, use the username specified in the bootstrap.xml file. - Firewall Login Password field, use the password specified in the bootstrap.xml file. If you are manually configuring the firewall from scratch, follow `the instructions here <https://docs.aviatrix.com/HowTos/paloalto_API_setup.html>`_ to enable API access. Ready to Go ---------------------------- Now your firewall instance is ready to receive packets. The next step is to specify which Security Domain needs packet inspection by defining a connection policy that connects to the firewall domain. This is done by `here <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#specify-security-domain-for-firewall-inspection>`_ in the Firewall Network workflow. For example, deploy Spoke-1 VPC in Security_Domain_1 and Spoke-2 VPC in Security_Domain_2. Build a connection policy between the two domains. Build a connection between Security_Domain_2 to Firewall Domain. Launch one instance in Spoke-1 VPC and Spoke-2 VPC. From one instance, ping the other instance. The ping should go through. Viewing the Traffic Log ---------------------------------- You can view if traffic is forwarded to the firewall instance by logging in to the VM-Series console. Click Monitor. Start ping packets from one Spoke VPC to another Spoke VPC where one or both of Security Domains are connected to Firewall Network Security Domain Additional References ------------------------------ Following links from Palo Alto Networks for PAN-OS 8.1 and 9.0 provides additional information. `Create the init-cfg.txt File <https://docs.paloaltonetworks.com/vm-series/9-0/vm-series-deployment/bootstrap-the-vm-series-firewall/create-the-init-cfgtxt-file.html#id8770fd72-81ea-48b6-b747-d0274f37860b>`_. `Bootstrap the VM-Series Firewall on AWS 9.0 <https://docs.paloaltonetworks.com/vm-series/9-0/vm-series-deployment/bootstrap-the-vm-series-firewall/bootstrap-the-vm-series-firewall-in-aws.html>`_ `Bootstrap the VM-Series Firewall on AWS 8.1 <https://docs.paloaltonetworks.com/vm-series/8-1/vm-series-deployment/bootstrap-the-vm-series-firewall/bootstrap-the-vm-series-firewall-in-aws.html>`_ .. |bootstrap_bucket| image:: bootstrap_example_media/bootstrap_bucket.png :scale: 30% .. disqus:: <file_sep> ################################### VPC Tracker ################################### The VPC Tracker collects and helps you manage your network CIDR ranges at a central place. This feature eliminates the need to keep an Excel sheet on all your AWS VPC/Azure VNet network address allocations. No gateway launches are required. 1. First, add all your other accounts for `AWS <https://docs.aviatrix.com/HowTos/aviatrix_account.html>`_ and `Azure <https://docs.aviatrix.com/HowTos/Aviatrix_Account_Azure.html>`_ to the Controller. The VPC Tracker will retrieve the information. 2. To see what the VPC Tracker has recorded, select Useful Tools > VPC Tracker on the left sidebar. If you are not seeing all of your VPC/VNets, click refresh to have the VPC tracker search for unfound VPCs. Click **OK**. Refreshing may take some time depending on the number of VPCs and Accounts on your Controller. Currently, the VPC Tracker can record network CIDRs in AWS, Azure, Site2Cloud remote network CIDRs, and Transit Network on-prem CIDRs. All VPCs and VNets with at least one instance will be displayed. The VPC Tracker auto-updates once a day and will only list VPC/VNets which have at least one instance deployed in them. You can conduct an on-demand update by clicking the refresh button. If you are planning to `create a new VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_, you can first check CIDR overlap by entering the CIDR block and click **Test**. The result displays the overlapping CIDRs for your reference. .. |edit-designated-gateway| image:: gateway_media/edit-designated-gateway.png :scale: 50% .. disqus:: <file_sep> ========================================== Forward Logs to a Central Logging Server ========================================== Overview ======== Aviatrix supports forwarding logs from the gateway(s) to a central logging server for processing. This is particularly useful for connecting to services such as Datadog or for processing the logs prior to being sent to another log service such as Splunk. Step-by-step Deployment Guide ============================= Solution Overview ----------------- In addition to direct integrations with services like Splunk and Sumologic, the Aviatrix Controller supports forwarding logs to another syslog server. If your logging provider requires that you process the data before it is sent to it, you can forward these logs to a Linux server that will handle the processing and forwarding. This solution guide will walk you through configuring this. Steps to complete: |imageOverview| #. Create an `EC2 instance <#step1>`__ that will receive logs from all gateways #. Configure `rsyslogd <#step2>`__ on the instance #. `Configure Aviatrix <#step3>`__ to forward logs your new instance #. Update the `security group <#step4>`__ for the instance to allow traffic from each Aviatrix Gateway #. Implement `processing logic <#step5>`__ (or use one provided by Aviatrix) to process and forward the logs .. _step1: Create an EC2 instance ---------------------- #. Create a new EC2 instance to receive logs from the gateways .. _step2: rsyslogd -------- #. Install rsyslogd .. code-block:: shell sudo add-apt-repository ppa:adiscon/v8-stable sudo apt-get update sudo apt-get install rsyslog .. note:: (see http://www.rsyslog.com/ubuntu-repository/ for more details) #. Configure rsyslogd to accept messages on your desired port #. SSH and login to the EC2 instance #. Check that the /etc/rsyslogd.conf is listening on UDP or TCP port. Optionally, update the port. .. code-block:: shell # provides UDP syslog reception $ModLoad imudp $UDPServerRun 10514 .. note:: Use any port you wish here. .. _step3: Enable Log Forwarding in Aviatrix Controller -------------------------------------------- #. Login to your Aviatrix Controller #. Expand the `Settings` navigation group #. Click on `Logging` #. Scroll down to the `Remote Syslog` section. Click on the `Disabled` button to enable remote syslog. #. Enter the data +------------------+-----------------------------------------------------+ | Field | Value | +==================+=====================================================+ | Server | Enter the IP address of the EC2 instance created | | | in earlier step. | +------------------+-----------------------------------------------------+ | Port | Enter the port of the listening service | +------------------+-----------------------------------------------------+ | Cert | Upload the certificate (optional) | +------------------+-----------------------------------------------------+ | Protocol | Select TCP or UDP | +------------------+-----------------------------------------------------+ | Optional Custom | Enter a rsyslog template. See below for more | | Template | details. | +------------------+-----------------------------------------------------+ #. Click `Enable` .. _step4: Update Security Group of Receiving Instance ------------------------------------------- Allow inbound traffic on the selected UDP/TCP port to the EC2 instance you created earlier. .. _step5: Implement Processing Logic -------------------------- Implement the logic to process the incoming logs and forward to the log service. A few examples are provided below. Write Logs to S3 ################ #. Install `AWS CLI <https://docs.aws.amazon.com/cli/latest/userguide/installing.html>`__ .. note:: You may need to install the package ``python-pip`` first #. Create a directory on the local file system (e.g., /var/log/aviatrix) .. code-block:: shell sudo mkdir /var/log/aviatrix #. Change the ownership of this directory to allow the rsyslogd user to write files to this directory .. code-block:: shell sudo chown syslog:adm /var/log/aviatrix sudo chmod 750 /var/log/aviatrix #. Create a new rsyslogd configuration file ``/etc/rsyslog.d/22-aviatrix.conf`` with the following configuration: .. code-block:: shell :msg, contains, "Aviatrix" /var/log/aviatrix/gateways.log # comment out the following line to allow Aviatrix messages through. & stop #. (optional) Reload rsyslogd configuration .. code-block:: shell sudo /etc/init.d/rsyslogd force-reload #. Create a script to move the log files to S3. There is a template below: .. code-block:: shell #!/bin/sh DIR=/var/log/aviatrix if [ ! -d ${DIR} ]; then exit 1; fi DESTDIR=s3://mybucket current_time=$(date +%Y-%m-%dT%H-%M-%S) new_filename=gateways.${current_time}.log # rename the file if [ -f ${DIR}/gateways.log ]; then sudo mv ${DIR}/gateways.log ${DIR}/${new_filename} if [ $? -ne 0 ]; then exit 2; fi # HUP rsyslogd to start logging to new file sudo killall -HUP rsyslogd if [ $? -ne 0 ]; then exit 3; fi fi # copy any outstanding file(s) to s3 bucket cd ${DIR} for f in $(ls); do if [ "$f" != "gateways.log" ]; then aws s3 cp ${DIR}/$f ${DESTDIR}/${new_filename} if [ $? -eq 0 ]; then sudo rm -f ${DIR}/$f fi fi done #. Create a crontab entry to run this script as often as desired Datadog ####### For Datadog integration, please see `this <https://github.com/AviatrixSystems/ThirdPartyLogIntegration>`__ Github repository. Use the following `Optional Custom Template`: .. code:: shell constant(value="tenant-identifier") constant(value="\t") property(name="timereported") constant(value="\t") property(name="msg") constant(value="\n") .. |imageOverview| image:: log_forwarder_media/overview.png <file_sep> .. raw:: html <style> div[class='highlight'] pre { white-space: pre-wrap; } </style> ============================================================================== Azure AD IdP for SAML Integration ============================================================================== Overview ------------ This guide provides an example on how to configure Aviatrix to authenticate against Azure AD IdP. When SAML client is used, your Aviatrix controller acts as the Identity Service Provider (ISP) that redirects browser traffic from client to IdP (e.g., Azure AD) for authentication. Before configuring SAML integration between Aviatrix and Azure AD, make sure you have a valid Azure AD Premium subscription account with administrator access. Configuration Steps ------------------- Follow these steps to configure Aviatrix to authenticate against your Azure AD IdP: Step 1. Create a `temporary Aviatrix SP Endpoint <#aviatrix-endpoint>`__ in the Aviatrix Controller Step 2. Create an `Azure AD SAML Application <#azuread-saml-app>`__ for Aviatrix in the Azure Portal's Premium Subscription Account Step 3. Retrieve the `Azure AD IdP metadata <#azuread-idp-metadata>`__ Step 4. Update the `Aviatrix SP Endpoint <#azuread-update-saml-endpoint>`__ in the Aviatrix Controller Step 5. `Test the Integration <#azuread-test-integration>`__ is Set Up Correctly .. _aviatrix_endpoint: Step 1. Create an Aviatrix SP Endpoint ######################################## Visit one of the following links based on your use case and follow step1 (Create temporary Aviatrix SP Endpoint for Aviatrix) from the link's Configuration section: If integrating Azure AD IdP with `Controller Login SAML Config <https://docs.aviatrix.com/HowTos/Controller_Login_SAML_Config.html#config-31>`_ If integrating Azure AD IdP with `OpenVPN with SAML Authentication <https://docs.aviatrix.com/HowTos/VPN_SAML.html#config-31>`_ This step will ask you to pick a short name to be used for the SAML application name ``[Endpoint Name]``. In the notes below we will refer to this as **aviatrix_azuread**. It can be any string that will identify the SAML application you create in the IdP. We will use the string you select for the SAML application name to generate a URL for Azure AD to connect with Aviatrix. This URL is defined below as **SP_ACS_URL**. This URL should be constructed as: ``https://<<<your controller ip or host name>>>/flask/saml/sso/<<<aviatrix_azuread>>>`` .. tip:: Replace **<<<your controller ip or host name>>>** with the actual host name or IP address of your controller and **<<<aviatrix_azuread>>>** with the ``[Endpoint Name]`` you chose to refer to the SAML application. .. _azuread_saml_app: Step 2. Create an Azure AD SAML App for Aviatrix ################################################ **Connect to Azure** Login to your Azure portal **Create Custom SAML Application** #. Go to the Azure Active Directory service #. Select **Enterprise Applications** under **Manage** navigation menu item #. Click **+ New application** |imageAddAppsMenu| .. note:: You must be an administrator to add new Enterprise Applications. #. Click **Non-gallery application** |imageAddAppNonGallery| #. Enter a Display Name .. note:: Custom applications requires an Azure AD Premium subscription. |imageAddAppSetName| #. Click **Add** **Assign Users to this Application** #. Click **Users and groups** below **Manage** #. Click **+ Add user** #. Select a User and Role #. Click **Assign** |imageAssignUser| **Single Sign-on Configuration** Click **Single sign-on** below **Manage** **Application Domain and URLs** #. Select **SAML-based Sign-on** from the **Single Sign-on Mode** drop down #. Fill out the fields +----------------------------+-----------------------------------------+ | Field | Value | +============================+=========================================+ | Identifier (Entity ID) | ``https://<<<your controller>>>`` | +----------------------------+-----------------------------------------+ | Reply URL | **SP_ACS_URL** | +----------------------------+-----------------------------------------+ | Show Advanced URL settings | checked | +----------------------------+-----------------------------------------+ | Sign on URL | **SP_ACS_URL** | +----------------------------+-----------------------------------------+ | Relay State | (leave blank) | +----------------------------+-----------------------------------------+ The links for the SAML Identifier, Reply URL, and Sign on URL should point to the Application Gateway domain instead of the Aviatrix controller. **User Attributes** #. Enter **user.mail** for **User Identifier** #. Click **View and edit all other user attributes** #. Add the following **SAML Token Attributes** (please find the right values from your Azure user details to match firstname, lastname and email). You can also add "Profile" and send the profile name of a VPN profile - at this time,we only support attaching one profile per user via SAML +------------------+-----------------------------------------+------------+ | NAME | VALUE | NAMESPACE | +==================+=========================================+============+ | FirstName | user.givenname | (blank) | +------------------+-----------------------------------------+------------+ | LastName | user.surname | (blank) | +------------------+-----------------------------------------+------------+ | Email | user.mail | (blank) | +------------------+-----------------------------------------+------------+ |imageUserAttrs| #. Verify that the Namespace URI is blank like so for each claim. |imageAttributeURI| .. _azuread_idp_metadata: Step 3. Retrieve the Azure AD IdP metadata ########################################## **SAML Signing Certificate** #. Find the **Metadata XML** link #. Click the link to download the file |imageSAMLMetadata| The XML file contents will be provided to the Aviatrix SP endpoint later on. **Save Application** Click **Save** .. _azuread_update_saml_endpoint: Step 4. Update the Aviatrix SP Endpoint ####################################### .. note:: This step is usually completed by the Aviatrix admin. Azure AD IdP provides IdP Metadata through text obtained in `Retrieve Azure AD IdP metadata (Step 3) <#azuread-idp-metadata>`_. Azure AD IdP requires a custom SAML request template. Continue with updating Aviatrix SAML Endpoint by visiting one of the following links based on your use case: #. If integrating Azure IdP with `Controller Login SAML Config <https://docs.aviatrix.com/HowTos/Controller_Login_SAML_Config.html#config-34>`_ #. If integrating Azure IdP with `OpenVPN with SAML Authentication <https://docs.aviatrix.com/HowTos/VPN_SAML.html#config-34>`_ +----------------------------+-----------------------------------------+ | Field | Description | +============================+=========================================+ | Endpoint Name | ``[Endpoint Name]`` | +----------------------------+-----------------------------------------+ | IPD Metadata Type | Text | +----------------------------+-----------------------------------------+ | IdP Metadata Text/URL | Paste in the metadata XML file contents | | | `downloaded earlier <#azuread-idp-metadata>`_. | +----------------------------+-----------------------------------------+ | Entity ID | Select `Hostname` | +----------------------------+-----------------------------------------+ | Access | Select admin or read-only access | +----------------------------+-----------------------------------------+ | Custom SAML Request | Checked | | Template | | +----------------------------+-----------------------------------------+ .. note:: Each endpoint only supports one type of access. If you need admin and read-only access, create two separate SAML apps. `Hostname` is the default for Entity ID, but if you have other apps using the same hostname, use a custom Entity ID. |imageAvtxUpdateSAMLEndpoint| #. Copy the following into the **Custom SAML Request Template** field: .. code-block:: xml <?xml version="1.0" encoding="UTF-8"?> <samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ID="$ID" Version="2.0" IssueInstant="$Time" Destination="$Dest" ForceAuthn="false" IsPassive="false" ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" AssertionConsumerServiceURL="$ACS"> <saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">$Issuer</saml:Issuer> </samlp:AuthnRequest> .. note:: This is required to connect with Azure AD. If you don't do this, you will receive an error message when testing. #. Click **OK** .. _azuread_test_integration: Step 5. Test the Integration ############################ .. tip:: Be sure to assign users to the new application in Azure AD prior to validating. If you do not assign your test user to the Aviatrix SAML application, you will receive an error. Continue with testing the integration by visiting one of the following links based on your use case: 1. If integrating Azure AD IdP with `Controller Login SAML Config <https://docs.aviatrix.com/HowTos/Controller_Login_SAML_Config.html#config-35>`__ #. Click `Settings` in the left navigation menu #. Select `Controller` #. Click on the `SAML Login` tab 2. If integrating Azure AD IdP with `OpenVPN with SAML Authentication <https://docs.aviatrix.com/HowTos/VPN_SAML.html#config-35>`__ #. Expand `OpenVPN®` in the navigation menu and click `Advanced` #. Stay on the `SAML` tab You can quickly validate that the configuration is complete by clicking on the **Test** button next to the SAML endpoint. |imageAvtxTestButton| .. |imageAddAppsMenu| image:: azuread_saml_media/azure_ad_new_app.png .. |imageAddAppNonGallery| image:: azuread_saml_media/azure_ad_new_app_non_gallery.png .. |imageAvtxSAMLEndpoint| image:: azuread_saml_media/avx_controller_saml.png .. |imageAvtxUpdateSAMLEndpoint| image:: azuread_saml_media/azure_ad_update.png .. |imageSPMetadataURL| image:: azuread_saml_media/sp_metadata_button.png .. |imageAvtxTestButton| image:: azuread_saml_media/avtx_test_button.png .. |imageAddAppSetName| image:: azuread_saml_media/azure_ad_add_new_step_1.png .. |imageAssignUser| image:: azuread_saml_media/azure_ad_assign_user.png .. |imageUserAttrs| image:: azuread_saml_media/azure_ad_saml_user_attrs.png .. |imageSAMLSettings| image:: azuread_saml_media/azure_ad_saml_settings.png .. |imageSAMLMetadata| image:: azuread_saml_media/azure_ad_saml_metadata.png .. |imageAttributeURI| image:: azuread_saml_media/azure_ad_claim_edit.png <file_sep>Welcome to Aviatrix Docs ======================== All Aviatrix product documentation can be found here. If you cannot find what you need, please reach out to us via `Aviatrix Support Portal <https://support.aviatrix.com>`_. .. _main website: http://aviatrix.com .. _GitHub: https://github.com/AviatrixSystems/Docs While all content is searchable, the site is organized into the following sections: * :ref:`Getting Started` * :ref:`Onboarding and Accounts` * :ref:`Gateway` * :ref:`Transit Network` * :ref:`Transit Gateway Orchestrator` * :ref:`Firewall Network` * :ref:`CloudN` * :ref:`Peering` * :ref:`Site2Cloud` * :ref:`Monitoring` * :ref:`Copilot` * :ref:`OpenVPN® <OpenVPN>` * :ref:`Security` * :ref:`UsefulTools` * :ref:`Settings` * :ref:`Downloads` * :ref:`Release Notes` * :ref:`Upgrade Aviatrix` * :ref:`Security Updates` * :ref:`Field Notices` * :ref:`Tech Notes` * :ref:`Good To Know` * :ref:`Support Center` .. _Getting Started: .. toctree:: :maxdepth: 1 :caption: Getting Started StartUpGuides/aviatrix_overview StartUpGuides/aws_getting_started_guide StartUpGuides/azure-aviatrix-cloud-controller-startup-guide StartUpGuides/oracle-aviatrix-cloud-controller-startup-guide StartUpGuides/google-aviatrix-cloud-controller-startup-guide StartUpGuides/aviatrix_operations HowTos/meter_pricing HowTos/FAQ .. _Onboarding and Accounts: .. toctree:: :maxdepth: 1 :caption: Onboarding and Accounts HowTos/onboarding_faq HowTos/aviatrix_account HowTos/HowTo_IAM_role HowTos/iam_policies HowTos/aviatrix_iam_policy_requirements HowTos/customize_aws_iam_policy HowTos/Aviatrix_Account_Azure HowTos/aviatrix_account_alibaba HowTos/azure_custom_role HowTos/CreateGCloudAccount HowTos/oracle-aviatrix-cloud-controller-onboard HowTos/AdminUsers_DuoAuth HowTos/CompanionGateway HowTos/Quick_Tour HowTos/accesskey HowTos/account_audit HowTos/rbac_faq HowTos/oci_iam_policy .. _Gateway: .. toctree:: :maxdepth: 1 :caption: Gateway HowTos/gateway Solutions/gateway_ha HowTos/gateway_audit HowTos/default_route_faq .. _Transit Network: .. toctree:: :maxdepth: 1 :caption: Multi-Cloud Transit Network HowTos/transitvpc_faq HowTos/transitvpc_workflow HowTos/transit_gateway_peering HowTos/bgp HowTos/transitgw_external HowTos/spokegw_external HowTos/transit_approval HowTos/transit_advanced HowTos/transitvpc_designs HowTos/transit_list HowTos/azure_transit_designs HowTos/transit_segmentation_faq HowTos/transit_segmentation_workflow HowTos/activemesh_faq HowTos/activemesh_design_notes HowTos/activemesh_beta HowTos/insane_mode HowTos/insane_mode_perf HowTos/CloudN_insane_mode HowTos/migrate_tgw_orchestrator_to_aviatrix_transit HowTos/integrate_transit_gateway_with_expressroute HowTos/transit_gateway_external_device_bgp_over_gre_high_performance_workflow HowTos/transit_gateway_external_device_bgp_over_lan_workflow HowTos/transit_gateway_external_device_bgp_over_lan_azure_workflow HowTos/transit_gateway_external_device_bgp_over_lan_gcp_workflow .. _Transit Gateway Orchestrator: .. toctree:: :maxdepth: 1 :caption: AWS Transit Gateway Orchestrator HowTos/tgw_faq HowTos/tgw_plan HowTos/tgw_build HowTos/tgw_list HowTos/tgw_approval HowTos/tgw_design_patterns HowTos/tgw_csr_migrate HowTos/diy_tgw_migrate_to_aviatrix_tgw HowTos/transitgw_external HowTos/transitvpc_workflow HowTos/transitvpc_design HowTos/tgwconnect .. _Firewall Network: .. toctree:: :maxdepth: 1 :caption: Firewall Network (FireNet) HowTos/firewall_network_faq HowTos/firewall_network_workflow HowTos/transit_firenet_faq HowTos/transit_firenet_workflow HowTos/transit_firenet_design_patterns HowTos/firewall_advanced HowTos/paloalto_API_setup HowTos/ingress_firewall_example HowTos/Azure_ingress_firewall_example HowTos/ingress_protection_firenet_paloaltogcp HowTos/config_paloaltoVM HowTos/config_PaloAltoAzure.rst HowTos/config_paloaltoGCP HowTos/config_paloaltoOCI HowTos/bootstrap_example HowTos/pan_bootstrap_example_azure HowTos/config_FortiGateVM HowTos/config_FortiGateAzure HowTos/fortigate_bootstrap_example HowTos/fortigate_bootstrap_example_azure HowTos/config_CheckPointVM HowTos/config_CheckPointAzure HowTos/checkpoint_bootstrap_azure HowTos/config_PFsense HowTos/config_Barracuda.rst HowTos/firewall_network_design_patterns .. _CloudN: .. toctree:: :maxdepth: 1 :caption: CloudN HowTos/edge-faq HowTos/edge-design-patterns HowTos/edge-2.0-workflow HowTos/CloudN_workflow HowTos/cloud_wan_workflow .. _Security: .. toctree:: :maxdepth: 2 :caption: Security HowTos/stateful_firewall_faq HowTos/tag_firewall HowTos/fqdn_faq HowTos/FQDN_Whitelists_Ref_Design HowTos/fqdn_discovery HowTos/fqdn_viewlog HowTos/guardduty HowTos/public_subnet_filtering_faq HowTos/sfc_faq HowTos/privateS3_workflow HowTos/secure_networking_microsegmentation .. _Peering: .. toctree:: :maxdepth: 1 :caption: Peering HowTos/peering_faq HowTos/peering HowTos/TransPeering HowTos/Cluster_Peering_Ref_Design HowTos/GettingStartedAzureToAWSAndGCP HowTos/peering_over_routelimit .. _Site2Cloud: .. toctree:: :maxdepth: 1 :caption: Site2Cloud HowTos/site2cloud_faq HowTos/site2cloud HowTos/site2cloud-cacert HowTos/avxgw_azurevpngw_site2cloud HowTos/site2cloud_aviatrix HowTos/site2cloud_awsvgw HowTos/site2cloud_oracledrg HowTos/S2C_GW_PAN HowTos/S2C_GW_CP HowTos/S2C_GW_CP_88 HowTos/S2C_GW_ASA HowTos/S2C_GW_IOS HowTos/site2cloud_sonicwall HowTos/CloudToPfSense HowTos/site2cloud_fortigate HowTos/site2cloud_meraki HowTos/site2cloud_meraki_vmx100 HowTos/S2C_GW_JuniperSRX HowTos/cloudn-site2cloud HowTos/site2cloud_case_study HowTos/EncrOverExpRoute HowTos/connect_overlap_cidrs_routebasedipsec HowTos/overlapping_network_solutions HowTos/connect_overlap_cidrs HowTos/connect_overlap_vpc_via_VGW HowTos/periodic_ping .. _Monitoring: .. toctree:: :maxdepth: 1 :caption: Monitoring HowTos/Monitoring_Your_Network .. _CoPilot: .. toctree:: :maxdepth: 1 :caption: CoPilot HowTos/copilot_release_notes HowTos/copilot_release_notes_images HowTos/copilot_overview HowTos/copilot_getting_started HowTos/copilot_reference_guide HowTos/copilot_faq HowTos/copilot_reference .. _OpenVPN: .. toctree:: :maxdepth: 2 :caption: OpenVPN® HowTos/uservpn HowTos/openvpn_faq HowTos/openvpn_features HowTos/openvpn_design_considerations HowTos/Cloud_Networking_Ref_Des HowTos/GeoVPN HowTos/DNSVPN HowTos/VPNUsers_LDAP HowTos/HowTo_Setup_Okta_for_Aviatrix HowTos/duo_auth HowTos/VPN_SAML HowTos/UserSSL_VPN_Okta_SAML_Config HowTos/UserSSL_VPN_Google_SAML_Config HowTos/UserSSL_VPN_OneLogin_SAML_Config HowTos/UserSSL_VPN_AWS_SSO_SAML_Config HowTos/UserSSL_VPN_Azure_AD_SAML_Config HowTos/UserSSL_VPN_Centrify_SAML HowTos/Anonymous_Browsing HowTos/DevSandbox HowTos/External_PKI_for_OpenVPN_Certificates HowTos/user_accelerator HowTos/ipv6_multivpc_vpn HowTos/uservpn-TGW HowTos/Setup_Okta_SAML_Profile_Attribute HowTos/Setup_PingOne_SAML_Profile_Attribute HowTos/azure_saml_auth_vpn_access .. _UsefulTools: .. toctree:: :maxdepth: 1 :caption: Useful Tools HowTos/vpc_tracker HowTos/create_vpc HowTos/discover_flows .. _Settings: .. toctree:: :maxdepth: 1 :caption: Settings HowTos/controller_backup HowTos/controller_ha HowTos/selective_upgrade HowTos/inline_upgrade HowTos/AviatrixLogging HowTos/alert_and_email HowTos/advanced_config HowTos/AdminUsers_LDAP HowTos/netflow HowTos/cloudwatch HowTos/Controller_Login_SAML_Config HowTos/controller_certificate HowTos/fips140-2 HowTos/controller_config HowTos/Migration_From_Marketplace HowTos/controller_migration HowTos/gateway-image-migration HowTos/privatemode .. _Troubleshoot: .. toctree:: :maxdepth: 1 :caption: Troubleshoot HowTos/Troubleshoot_Logs HowTos/Troubleshoot_Diagnostics HowTos/error-msgs HowTos/azuregwlaunch HowTos/Troubleshoot_ELB_Status HowTos/flightpath .. _Downloads: .. toctree:: :maxdepth: 1 :caption: Downloads Downloads/samlclient .. _Release Notes .. toctree:: :maxdepth: 1 :caption: Release Notes HowTos/Controller_and_Software_Release_Notes HowTos/image_release_notes HowTos/copilot_release_notes HowTos/copilot_release_notes_images HowTos/Aviatrix_VPN_Client_Release_Notes .. _Upgrade Aviatrix .. toctree:: :maxdepth: 2 :caption: Upgrade Aviatrix HowTos/selective_upgrade .. _Security Updates: .. toctree:: :maxdepth: 1 :caption: Security Updates HowTos/PSIRT_Advisories HowTos/Security_Patches HowTos/Security_update_policy .. _Field Notices: .. toctree:: :maxdepth: 1 :caption: Field Notices HowTos/field_notices .. _Tech Notes: .. toctree:: :maxdepth: 1 :caption: Tech Notes HowTos/AWS_NetworkLoadBalancer_Onsite_And_In_Cloud HowTos/DatadogIntegration StartUpGuides/aws_manual_startup_guide HowTos/site_to_site_vpn HowTos/controller_security_for_SAML HowTos/azure_saml_auth_vpn_access HowTos/simpletransit HowTos/s2c_vgw_snat HowTos/s2c_overlapping_subnets HowTos/s2c_for_publicIP HowTos/transit_for_publicIP HowTos/transit_solution_activemesh_spoke_snat_dnat_rfc1918 HowTos/meraki_to_transit HowTos/reserve_onprem HowTos/HowTo_Setup_AWS_Managed_Microsoft_AD_for_Aviatrix Solutions/aviatrix_aws_meshVPC Solutions/build_zerotrust_cloud_network Solutions/aviatrix_aws_transitvpc Solutions/netapp_sap_floating_ip Solutions/egress_nat_pool HowTos/tgw_route_limit HowTos/tgw_pan_ecmp HowTos/tgw_egress_vpc HowTos/aws_transit_gateway_orchestrator HowTos/transit_snat_dnat HowTos/ipv6_peering HowTos/nextgentransit_for_azure HowTos/nat_only_outbound_traffic HowTos/activemesh_migration HowTos/openvpn_fqdn HowTos/HowTo_Setup_SAML_with_G_SUITE_ORG HowTos/transit_firenet_workflow_aws HowTos/transit_firenet_workflow_aws_gwlb HowTos/transit_firenet_workflow_azure HowTos/transit_subnet_inspection_azure HowTos/transit_firenet_workflow_gcp HowTos/transit_firenet_workflow_oci HowTos/cloud_wan_workflow_azure_vwan HowTos/using_VPC_Endpoints_w_AVX HowTos/transit_gateway_peering_with_private_network_workflow HowTos/transit_gateway_peering_over_public_network_workflow HowTos/aviatrix_aws_outposts HowTos/s2c_overlapping_cidrs_with_fast_convergence HowTos/transit_gateway_external_device_bgp_over_lan_with_aws_meraki_workflow HowTos/azure_bgpolan_multi_peer HowTos/azure_bgpolan_multi_peer_ARS HowTos/rescure_pki_agent_cert .. _Good To Know: .. toctree:: :maxdepth: 1 :caption: Good To Know HowTos/cloudformation_condition_howto HowTos/aws_network_limits HowTos/tgw_limits HowTos/opstools_survey HowTos/multi_cloud_region_affinity_and_latency HowTos/general_glossary HowTos/aviatrix_glossary HowTos/multi_cloud_rosetta_stone .. _Support Center: .. toctree:: :maxdepth: 1 :caption: Support Center Support/support_center_operations .. toctree:: :maxdepth: 1 :caption: Legal Notices legal_notices <file_sep> ================================================== Deploying Aviatrix Secure Edge 1.0 for VMware ESXi ================================================== Aviatrix Secure Edge has a virtual form factor that lets you deploy an Edge Gateway as a standard virtual machine (VM). This document provides step-by-step instructions for deploying Aviatrix Secure Edge in a private or public Cloud network. The instructions in this document show you how to set up an Edge Gateway in VMware ESXi. For deployment diagrams and additional information, refer to `Aviatrix Edge FAQ <http://docs.aviatrix.com/HowTos/edge-faq.html>`_. Prerequisites ------------- Aviatrix Secure Edge 1.0 requires the following: - Aviatrix Controller 6.7. For instructions on how to upgrade to Aviatrix Controller 6.7, refer to `Upgrading the Aviatrix Cloud Network Platform <http://docs.aviatrix.com/HowTos/selective_upgrade.html>`_. - VMware vCenter Server (optional) - VMware ESXi OVA file - VMware ESXi Versions: 6.7 or 7.0.1 The Aviatrix Edge can run on the VMware ESXi Hypervisor. VMware ESXi runs on x86-based CPU platforms. For more information about installing VMware vSphere products, refer to the VMware product documentation. Requesting a VMware ESXi OVA File ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Before you begin the deployment of the Edge Gateway, submit a request to Aviatrix Support for a link to the VMware ESXi OVA file. You will use the OVA file to deploy the Edge virtual machine in VMware ESXi. 1. Log in to the Aviatrix Support Portal: `<https://aviatrix.zendesk.com>`_. 2. Select **Submit a request**. 3. In the **Subject** field, enter **Requesting access to Edge image**. 4. In the **Description** field, enter the physical address of the location where you will install the Edge VM(s), such as a data center, headend, co-location site, or office. If you are installing Edge VMs at more than one location, provide the following information for each physical location: - Physical Address (Do not enter a P.O.Box.) - City - State or Locality - Zip Code or Postal Code - Country 5. Click **Submit**. Aviatrix Support will respond with a link you can use to download the OVA file. Access Requirements ------------------- The Aviatrix Controller requires access to the following ports for Edge Gateway deployment. You must allow access on these ports on your firewall. - MGMT: TCP 443 access to the Aviatrix Controller’s public IP address - MGMT: TCP 443 access to the Aviatrix Controller’s private IP address (only permit this access if you selected **Over Private Network** for management IP connectivity) - WAN: UPD 500/4500 Virtual Machine CPU and Memory Configurations --------------------------------------------- The following table provides CPU and memory configurations of the virtual machine instance supported for the Aviatrix Edge Gateway deployment. +-----------------+------------------+----------------------+ | Deployment Type | Hardware Profile | Storage Requirements | +=================+==================+======================+ | Small | 2CPU - 4GB | 64 GB | +-----------------+------------------+----------------------+ | Medium | 4CPU - 8GB | 64 GB | +-----------------+------------------+----------------------+ | Large | 8CPU - 16GB | 64 GB | +-----------------+------------------+----------------------+ | X-Large | 16CPU - 32GB | 64 GB | +-----------------+------------------+----------------------+ We recommend that you not change the Edge VM resource allocation after deploying it. Aviatrix support may not be able to assist with any issue that occurs on a system with customized resource allocation. Oversubscription of host resources can lead to a reduction of performance and your instance could become unstable. We recommend that you follow the guidelines and the best practices for your host hypervisor. Deploying an Edge Gateway in VMware ESXi ------------------------------------------ To deploy an Edge Gateway in VMware ESXi, follow these steps. 1. `Deploy the Edge virtual machine in VMware ESXi <http://docs.aviatrix.com/HowTos/secure_edge_workflow.html#deploying-an-edge-gateway-in-vmware-esxi>`_. 2. `Set up the Edge Gateway in Aviatrix Controller <http://docs.aviatrix.com/HowTos/secure_edge_workflow.html#setting-up-an-edge-gateway-in-aviatrix-controller>`_. 3. `Attach the ISO image to the Edge virtual machine <http://docs.aviatrix.com/HowTos/secure_edge_workflow.html#attaching-the-iso-image-to-the-edge-virtual-machine>`_. 4. `Attach the Edge Gateway to the Transit Gateway <http://docs.aviatrix.com/HowTos/secure_edge_workflow.html#attaching-an-edge-gateway-to-a-transit-gateway>`_. Deploying the Edge Virtual Machine in VMware ESXi ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To deploy the Edge virtual machine in VMware ESXi, follow these steps. 1. Download the ESXi OVA file by using the link provided to you by Aviatrix Support. Refer to `Requesting a VMware ESXi OVA File <http://docs.aviatrix.com/HowTos/secure_edge_workflow.html#requesting-a-vmware-esxi-ova-file>`_. 2. Log into VMware vSphere Web client to access the ESXi host. You can use vSphere Web client to manage ESXi host, launch a VM, mount ISO files, and start and stop the Aviatrix Edge Gateway. 3. To load the OVA file into the ESXi using vSphere, go to: **ESXI** > **Virtual Machines** > **Create/Register VM**. 4. Select **Deploy a virtual machine from an OVF or OVA file**. Click **Next**. 5. Enter a name for the Edge VM and drag the OVA file into the blue pane. Click **Next**. |edge_ova_load_file| 6. In the Select storage page, select the storage device for the instance you created (the OVA is installed in this instance). Click **Next**. 7. In the Deployment options window, enter the network interface mappings and select the Deployment type. (Refer to the pull-down menu or see `Virtual Machine CPU and Memory Configurations <http://docs.aviatrix.com/HowTos/secure_edge_workflow.html#virtual-machine-cpu-and-memory-configurations>`_.) |edge_ova_deploy_options| 8. Click **Next**. 9. In the Ready to complete page, click **Finish**. Setting Up an Edge Gateway in Aviatrix Controller ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. note:: You must have port 443 open to the IP address of the Aviatrix Controller. For the required access for Edge Gateway deployment, refer to `Access Requirements <http://docs.aviatrix.com/HowTos/secure_edge_workflow.html#access-requirements>`_. To set up an Edge Gateway in Aviatrix Controller, follow these steps. 1. Log in to Aviatrix Controller 6.7. 2. Go to **CLOUDN** > **Setup**. 3. In the Launch an Edge Gateway page, enter the following Edge name and IP information: a. Cloud Type is always set to **Aviatrix**. b. In **Gateway Name**, enter a name for the new Edge Gateway. c. For **ZTP File Type**, select **ISO**. .. note:: The ISO file is the equivalent of the Zero-Touch Provisioning (ZTP) token. ZTP allows network engineers to remotely deploy and provision network devices at remote locations. d. For **Management Connection Type**, select DHCP or Static, depending on your environment. .. note:: Steps (e-m) are applicable only for static IP configuration on the management interface. For IP and DNS settings, enter using the applicable format. For example, if the Edge Gateway's WAN IP is 10.1.1.151, enter 10.1.1.151/24 or what your netmask is. e. For **Management Interface IP/Mask**, enter the management interface IP/mask for the Edge VM. f. For **Default Gateway IP**, enter the IP address of the Default Gateway for the Management Subnet. g. For **Primary DNS Server**, enter the DNS server IP address. h. For **Secondary DNS server**, enter the DNS server IP address, this field is optional. i. For **Over Private Network**, check the box if the Edge management connection to Controller is over a private network. Leave it unchecked if the connection is over the public internet. j. For **Management Egress Gateway IP**, enter the IP address of the Edge VM visible to the Controller (this IP is optional and can be added later). This field adds a security bypass filter rule for the incoming traffic on TCP/443 to your Controller. k. For **WAN Interface IP/Mask**, enter the interface IP/mask for the Edge VM. l. For **WAN Default Gatewa**, enter the IP address of the Edge WAN interface. m. For **LAN Interface IP/Mask**, enter the interface IP/mask for the Edge VM. The image below shows the Launch an Edge Gateway configuration when you do not select **Over Private Network**. |secure_edge_launch_gateway_a| 4. Click **Create**. Aviatrix Controller prompts you to download the ISO file. Attaching the ISO Image to the Edge Virtual Machine ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. note:: * The ZTP ISO file can only be used for a single Edge VM instance, and only one time for that instance. * The ZTP token expires after 24 hours. If you wait too long to boot up the VM with the attached ISO image, it will not work. In that case, delete the Edge Gateway in the Controller UI and create a new Edge Gateway to receive a new ISO file. 1. Upload the ISO file you downloaded from Aviatrix Controller to your VMware datastore. 2. In vSphere, select the Edge VM you created and click **Edit settings**. 3. Select the **Virtual Hardware** tab. 4. Next to CD/DVD Drive 1, click the down arrow and select **Datastore ISO file** from the pull-down menu. 5. To load the ISO to the virtual CD drive, next to **Status**, check **Connect at power on**. 6. Next to the CD/DVD Media field, click **Browse**. Select the ISO file you downloaded. |edge_edit_settings| .. note:: **Connect at power on** (step 4) is required when you attach the ISO image to the VM for the first time. If the VM is powered on at the time you attach the ISO image, select the **Datastore ISO file** and save the configuration to make the ISO available to ZTP. 7. Click **Save**. Attaching an Edge Gateway to a Transit Gateway ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ After you deploy an Edge Gateway, you must attach it to a Transit Gateway. 1. In Aviatrix Controller, go to **CLOUDN** > **List**. 2. In Registered Devices, locate the Edge VM you created. Confirm that the Edge VM was successfully registered. If the registration was successful, the status in the **State** column will show registered. |secure_edge_registered_devices_a| If the VM was not successfully registered, follow these troubleshooting steps. a. Confirm you have network connectivity from the Edge Gateway to the Controller. b. Confirm any firewall and security rules (such as security groups) that allow traffic to and from the Controller. c. If steps a) and b) do not resolve the issue, reset the Edge Gateway configuration and try again. If these steps fail, contact Aviatrix Support at `Aviatrix Support Portal <https://support.aviatrix.com>`_. 3. To attach the Edge Gateway to the Transit Gateway, go to **Controller** > **CLOUDN** > **Attach**. 4. In step 2, **Attach Device to Cloud**, complete the following fields: .. note:: If you are connecting over a public network, WAN discovery is currently mandatory. a. For **Device Name**, select the registered Edge Gateway. b. For **Aviatrix Transit Gateway**, select the Transit Gateway you want the Edge Gateway to connect to. c. For **Connection Name**, enter a name for this connection. d. For **Aviatrix Transit Gateway BGP ASN**, enter the ASN for your Transit Gateway. e. For **Device’s BGP ASN**, enter the ASN for your Edge Gateway. f. For **Device’s LAN Interface Neighbor’s IP**, enter the Neighbor’s LAN interface IP. g. For **Device’s LAN Interface Neighbor’s BGP ASN**, enter the Neighbor’s LAN interface BGP ASN. h. For **Over Private Network**, leave the box unchecked if you are building the tunnel over the public internet. |secure_edge_attach_device_a| 5. Click **Attach**. 6. Navigate back to **CLOUDN** > **List**. Once the tunnel is successfully built, the Edge Gateway status in the **State** column changes from registered to attached. Editing or Viewing an Edge Gateway Configuration ------------------------------------------------ 1. To edit the Management Egress IP, select the Edge Gateway and click **EDIT**. |secure_edge_mgmt_egress_ip_a| 2. Update the Egress Management IP and click **SAVE**. |secure_edge_update_egress_ip_a| 3. To run and show diagnostics, upload Tracelog, download Syslog, and reset configuration, select the Edge Gateway and click **DIAG**. |secure_edge_run_diag_a| Deregistering and Reregistering an Edge Gateway ----------------------------------------------- An Edge Gateway can be deregistered from the Aviatrix Controller only when it is in the **registered** state. If the gateway is in any other state, its configuration needs to be reset first to remove it from the Aviatrix Controller. Deregistering an Edge Gateway from Aviatrix Controller ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To deregister an Edge Gateway from the Aviatrix Controller, the Edge Gateway must be in **registered** state. To reset Edge Gateway configuration, refer to `Resetting an Edge Gateway's Configuration from Aviatrix Controller <http://docs.aviatrix.com/HowTos/secure_edge_workflow.html#resetting-edge-gateway-configuration-from-aviatrix-controller>`_. To deregister an Edge Gateway: 1. Navigate to **CLOUDN** > **List**. 2. Select the Edge Gateway, and click **DEREGISTER**. |secure_edge_deregister_a| Resetting Edge Gateway Configuration from Aviatrix Controller ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To reset an Edge Gateway's configuration: 1. Navigate to **CLOUDN** > **List**. 2. Select the Edge Gateway. Click **DIAG**. In the drop-down list of options, select **Reset Configuration**. |secure_edge_reset_config_a| If you reset an Edge Gateway when it is in the **check** state, you also need to reset its configuration on the Edge virtual machine. To do this, log in to the Edge Gateway’s Clish command line interface and execute the **reset_config** command. This resets the Edge virtual machine to its factory settings. The Edge virtual machine can now be treated as a new Edge virtual machine. Reregistering an Edge Gateway with Aviatrix Controller ------------------------------------------------------ You can register an Edge virtual machine as a new Edge Gateway after it has been deregistered from the Aviatrix Controller or after you reset it to the factory settings. To reregister an Edge Gateway, do the following. 1. `Download and attach the ISO file to the Edge virtual machine <http://docs.aviatrix.com/HowTos/secure_edge_workflow.html#downloading-and-attaching-the-iso-file-to-the-edge-virtual-machine>`_. 2. `Register the Edge virtual machine with the Aviatrix Controller <http://docs.aviatrix.com/HowTos/secure_edge_workflow.html#registering-the-edge-virtual-machine-with-the-aviatrix-controller>`_. 3. `Attach the Edge Gateway to the Transit Gateway <http://docs.aviatrix.com/HowTos/secure_edge_workflow.html#attaching-a-reset-edge-gateway-to-a-transit-gateway>`_. Downloading and Attaching the ISO file to the Edge Virtual Machine ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To register an Edge Gateway after it has been deregistered from the Aviatrix Controller, do the following. 1. Download the ISO file for your new Edge Gateway by following the steps in `Setting up an Edge Gateway in Aviatrix Controller <http://docs.aviatrix.com/HowTos/secure_edge_workflow.html#setting-up-an-edge-gateway-in-aviatrix-controller>`_. 2. To Attach the new ISO file to your Edge virtual machine, upload the ISO file to your VMware datastore. 3. Power OFF the Edge virtual machine. 4. In vSphere, select the Edge VM and click **Edit**. 5. Select the Virtual Hardware tab. 6. Expand the CD/DVD Drive 1 section. 7. Next to **CD/DVD Drive 1**, click the down arrow and select **Datastore ISO file** from the pull-down menu. Check the **Connect** box next to Datastore ISO file. 8. Next to the **Status** field, check the **Connect at power on** box. 9. Next to the **CD/DVD Media** field, click **Browse**. Select the new ISO file that you uploaded to the datastore. |secure_edge_attach_iso| 10. Click **Save** to save this configuration and configure the Edge VM. 11. Power ON the Edge VM. 12. Ensure the new ISO file is connected to the CD/DVD Drive 1 of the Edge VM. |secure_edge_hardware_config| The Edge VM is ready to be registered with the Aviatrix Controller. Registering the Edge Virtual Machine with the Aviatrix Controller ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ If you are reusing an Edge VM, ZTP is not triggered automatically after you attach the new ISO file to the Edge VM. It must be triggered manually by using the Clish console. 1. Use the Edge VM’s vSphere serial console to log in to the Edge VM’s Clish command line interface. 2. Execute the **register** command and wait for the command to complete. 3. If the Edge Gateway registration is successful, you should see a success message. If the gateway registration fails, you will see a message with the next steps to troubleshoot the failure. The Edge Gateway can now be attached to the Transit Gateway. Attaching a Reset Edge Gateway to a Transit Gateway --------------------------------------------------- After you deploy an Edge Gateway that you reset, you attach it to a Transit Gateway. To attach the Edge Gateway to a Transit Gateway, follow the steps in `Attaching an Edge Gateway to a Transit Gateway <http://docs.aviatrix.com/HowTos/secure_edge_workflow.html#attaching-an-edge-gateway-to-a-transit-gateway>`_. Selective Gateway Upgrade for Secure Edge ----------------------------------------- The Aviatrix Secure Edge base OS is not upgradeable. To update the base OS to a newer version, you can only deploy a newer version of the Secure Edge image to a new VM to replace it. As Secure Edge base OS is not field upgradeable, Secure Edge does not support selective gateway image update and software rollback. Troubleshooting --------------- You can use the Clish commands below to troubleshoot the Edge Gateway. To run Clish on the Edge Gateway, log in with the username **admin**. +-----------------------------------+--------------------------------------------------------+ | Command | Description | +===================================+========================================================+ | change_console_password | Changes the password for the CLI login. | +-----------------------------------+--------------------------------------------------------+ | diagnostics | Show gateway diagnostics from | | | /home/ubuntu/cloudx-aws/avx_edge_status.json, which is | | | written by register process or reset_config process. | +-----------------------------------+--------------------------------------------------------+ | logout | Log out of the console. | +-----------------------------------+--------------------------------------------------------+ | ping [-c count] [dest] | Ping destination, optional parameter ping packet count.| | | The default is 5. | +-----------------------------------+--------------------------------------------------------+ | reboot | Reboot the system. | +-----------------------------------+--------------------------------------------------------+ | register | Register with the Controller. | +-----------------------------------+--------------------------------------------------------+ | reset_config | Deregister and reset to factory default. | +-----------------------------------+--------------------------------------------------------+ | set_controller_ip [controller_ip] | Set controller ip, usually performed after controller | | | migration when controller ip changed. | +-----------------------------------+--------------------------------------------------------+ | set_lan addr [lan_cidr] | Set LAN interface CIDR. | +-----------------------------------+--------------------------------------------------------+ | set_lan mtu [lan_mtu] | Set LAN interface MTU. | +-----------------------------------+--------------------------------------------------------+ | set_wan addr [wan_cidr] | Set WAN interface CIDR. | +-----------------------------------+--------------------------------------------------------+ | set_wan gateway [gateway_ip] | Set WAN gateway IP. | +-----------------------------------+--------------------------------------------------------+ | set_wan mtu [wan_mtu] | Set WAN interface MTU. | +-----------------------------------+--------------------------------------------------------+ | show_interfaces | Show output from the command “ifconfig -a | more”. | +-----------------------------------+--------------------------------------------------------+ | show_routes | Show output from the command “ip route show table all”.| +-----------------------------------+--------------------------------------------------------+ | test connect | Test TLS and port 443 connection to controller. | +-----------------------------------+--------------------------------------------------------+ | test dns [host_name] | Test DNS availability. | +-----------------------------------+--------------------------------------------------------+ | test port | Test controller port 443 reachability. | +-----------------------------------+--------------------------------------------------------+ | unlock | Unlock console and enter Linux shell. | +-----------------------------------+--------------------------------------------------------+ Tech Notes About BGP and Routing -------------------------------- If the connectivity to the Cloud Service Provider (CSP) is over a private network: - The edge (WAN) router runs a BGP session to VGW (AWS) where the edge router advertises an Edge Gateway WAN subnet network, and the VGW advertises the Transit VPC CIDR. - The Edge Gateway LAN interface runs a BGP session to the edge router where the edge router advertises the on-prem network address range to Edge Gateway LAN interface. - The Edge Gateway WAN interface runs a BGP session to the Transit Gateway in the Transit VPC where Transit Gateway advertises all Spoke VPC CIDRs to the Edge Gateway, and the Edge Gateway advertises on-prem network to the Transit Gateway. If the connectivity to the CSP is over a public network: - The Edge Gateway LAN and WAN interfaces do not use public IP addresses. The interfaces rely on the edge router or Firewall NAT function and Internet connectivity. - The Edge Gateway LAN interface runs a BGP session to the edge router where the edge router advertises the on-prem network address range to the Edge Gateway LAN interface. - The Edge Gateway WAN interface runs a BGP session to the Transit Gateway in the Transit VPC/VNET where the Transit Gateway advertises all Spoke VPC/VNET CIDRs to the Edge Gateway, and the Edge Gateway advertises the on-prem network to the Transit Gateway. .. |edge_ova_load_file| image:: CloudN_workflow_media/edge_ova_load_file.png :scale: 80% .. |edge_ova_deploy_options| image:: CloudN_workflow_media/edge_ova_deploy_options.png :scale: 80% .. |secure_edge_launch_gateway_a| image:: CloudN_workflow_media/secure_edge_launch_gateway_a.png :scale: 80% .. |edge_edit_settings| image:: CloudN_workflow_media/edge_edit_settings.png :scale: 50% .. |secure_edge_mgmt_egress_ip_a| image:: CloudN_workflow_media/secure_edge_mgmt_egress_ip_a.png :scale: 70% .. |secure_edge_update_egress_ip_a| image:: CloudN_workflow_media/secure_edge_update_egress_ip_a.png :scale: 70% .. |secure_edge_run_diag_a| image:: CloudN_workflow_media/secure_edge_run_diag_a.png :scale: 60% .. |secure_edge_reset_config_a| image:: CloudN_workflow_media/secure_edge_reset_config_a.png :scale: 60% .. |secure_edge_deregister_a| image:: CloudN_workflow_media/secure_edge_deregister_a.png :scale: 60% .. |secure_edge_attach_iso| image:: CloudN_workflow_media/secure_edge_attach_iso.png :scale: 40% .. |secure_edge_registered_devices_a| image:: CloudN_workflow_media/secure_edge_registered_devices_a.png :scale: 60% .. |secure_edge_attach_device_a| image:: CloudN_workflow_media/secure_edge_attach_device_a.png :scale: 70% .. |secure_edge_hardware_config| image:: CloudN_workflow_media/secure_edge_hardware_config.png :scale: 40% .. disqus:: <file_sep> ============================================= How to Launch Aviatrix ============================================= Aviatrix Secure Networking Platform consists of two components, Controller and gateway. The Controller is launched first. From the Controller browser console, gateways are launched using your cloud account credentials with cloud provider APIs. The Controller is launched and managed by you using AMI in your AWS account. The Controller AMI is available in `AWS Marketplace, <http://docs.aviatrix.com/StartUpGuides/aviatrix-cloud-controller-startup-guide.html>`_ `Azure Marketplace <http://docs.aviatrix.com/StartUpGuides/azure-aviatrix-cloud-controller-startup-guide.html>`_ and `GCloud <http://docs.aviatrix.com/StartUpGuides/google-aviatrix-cloud-controller-startup-guide.html>`_. .. add in the disqus tag .. disqus:: <file_sep>Aviatrix VPN Client Release Notes ------------------------------------------------- **2.16.42 - Feb 02 2023** - Prevent connection issues when the existing connection has not completely terminated - Update the About window with message to reach out to IT network admin for any issues with VPN client - Update OpenSSL version to 1.1.1o for Windows VPN clients - VPN client now supports Ubuntu 22.04 - Ubuntu 16.04 support has been deprecated **Issues Corrected in VPN Client 2.16.42** When you set your minimum version client to 2.16.42 under OpenVPN > Advanced > Global Config > Minimum Aviatrix VPN Client Version, Mac and Ubuntu users received an error: “the required minimum VPN client is 2.16.42.” Note that this issue did not affect Windows users. **2.14.14 - April 27 2021** - Support non-ASCII Windows user login account - Support non-ASCII VPN connection profile name on the client UI - Support opensource OS deb format installer - `Enhance the Windows client security <https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-31776>`_ **2.13.12 - Jan 28 2021** - Provide a MD5 checksum along with every single installer - Support MacOS Big Sur - Verify the settings before exiting the Settings UI **2.12.10 - September 3 2020** - Support opensource OS FIPS - A toggle to support Cisco Umbrella DNS servers or the VPC DNS servers on MacOS - Support multiple MacOS system login accounts - Allow override of manually set DNS flag to be enabled by default on MacOS **2.11.6 - July 22 2020** - OpenSSL lib of the MacOS client is updated to 1.1.11g - OpenSSL lib of the Windows client is updated to 1.1.11f - Enhance the security to prevent Man-in-the-middle attack - Boost the Windows client data throughput - Improve the connectivity of the MacOS client under the unstable WiFi connection - Improve the connectivity of the Windows client under the high data throughput **2.10.8 - May 14 2020** - Address client vulnerabilities of elevation in privilege and arbitrary file write. **2.9.6 - April 23 2020** - Support displaying system use notifications **2.8.2 - April 10 2020** - Boost VPN throughput **2.7.9 - March 4 2020** - UI enhancements for password-based authentication - Support the OVPN parameter: 'route' - Fixed issue where tray icon sometimes did not accurately reflect the VPN status - Fixed issue where VPN client becomes unresponsive if quit from the MacOS taskbar - VPN client will now no longer erroneously prompt for another authentication retry after previous fail - Fixed issue where the old VPN client will not quit, and crashes, if not uninstalled prior to the installation of a newer client **2.6.6 - Jan 29 2020** - Improve the user experience to add a new VPN profile - `Security fixes for the OpenVPN params <https://docs.aviatrix.com/HowTos/security_bulletin_article.html#article-avxsb-00001>`_ **2.5.7 - Nov 20 2019** - New UI - Detect missing VPN configuration file - Fixed password based authentication issues on Windows - Fixed the intermittent VPN disconnection issues **2.4.10 - Nov 2 2019** - Security fixes - Remove config caching causing issues on MacOS - Fixes an issue preventing connection after switching between auth types **2.3.10 - Oct 18 2019** - Support MacOS Catalina - Resolve fresh installation issues - Set version in PkgInfo in Mac - Nameserver wasn't being pushed correctly in Windows 10 **2.2.10 - Sep 26 2019** - FIPS 140-2 support for openvpn - Sorting and ordering profiles - Option to disable legacy port usage - Support non-ascii characters in the ovpn configuration file name **2.1.3 - Aug 1 2019** - Security fixes **2.0.3 - Jul 23 2019** - Fix for localhost cert being revoked - Backward compatible with older controller via self signed cert **1.10.16 - Jul 9 2019** - Security fix for backend communication - Fixed Windows log rotation errors - Added an option to hide connnection window - Added an option to hide notifications - Fixed Mac dnsResponder not restarting to remove cached DNS - Updated bundled tap driver **1.9 - Oct 18 2018** - Mac - Add an option to override manually set DNS - Mac - Fixed an issue that gave "cannot assign requested address" error while switching between Wifi networks on full tunnel - Mac - Upgraded openvpn to 2.4.3 - Prevent new connections while disconnecting - Windows - Fixed a log rotation error - Windows - Install tap driver on silent install - Alert if localhost.aviatrix.com does not resolve to 127.0.0.1 (Eg: DD-WRT) - Handle private DNS/Full tunnel disconnects better **1.8 - Jun 22 2018** - Windows VPN Service to run the client without Admin access - Graceful VPN exit on windows(8.0 and above) disconnect - Add platform, GUI version and peer info - Add resolvconf dependency for opensource OS. - Fix some connection issues on Mac **1.7 - Mar 7 2018** - Support for Profile as an attribute feature **1.6 - Dec 19 2017** - FreeBSD support - Configure reconnection behaviour on network disconnection - Disable TLSv1 for client browser communication - View log issue fix **1.5 - Oct 16 2017** - Mac does not require admin password to run - Mac icon fix - Removed cert warning - Bundled TAP driver for Windows - Improved linux support. Fixed system tray. App mode - Debian installation files - Fixed viewing logs in Linux **1.4 - Aug 8 2017** - Signed Mac application - Parallel windows execution fix **1.3 - Jun 15 2017** - Disconnection fixes - Timeout fixes - Connection profile is displayed - IE support for SAML - Signed Windows application **1.2 - Mar 15 2017** - HTTPS Version for SAML - Multiple Profiles - Linux version - Connection status detection - Unblock disconnection while connecting - Retry prompt for LDAP - Multi process feature for Mac/Linux. - Removed VPN Lockdown - Permissions fixes - Fixes in logging **1.1 - Jan 30 2017** - Settings window for troubleshooting - Mac default application behavior - Bug fixes for hangs - In built resources - Connection timeout issues fixed - Kill other OpenVPN® on start - Connection status fix - VPN lockdown feature **1.0 - Dec 15 2016** - Initial release - HTTP Version OpenVPN is a registered trademark of OpenVPN Inc. <file_sep> ========================================================= Firewall Network ========================================================= For enterprises that wish to deploy firewall in AWS, Aviatrix's FireNet deployment model provides the best performance and automation. Benefits of FireNet Deployment Model ---------------------------------------------------------------------------------------- - **Full Traffic Inspection** With FireNet, North South (on-prem and cloud), East West (VPC to VPC) and Internet bound egress traffic can be inspected by firewall instances. - **No IPSEC Tunnels** No IPSEC tunnels connecting to firewall instances as opposed to ECMP VPN deployment model, maximizing each firewall instance throughput. - **No SNAT** No SNAT function required to be performed by firewall instances for east west traffic inspection as opposed to the ECMP VPN deployment model, resulting in instances in Spoke VPCs having complete visibility of source traffic. - **Scale Out** Multiple firewall instances can be deployed as a group to meet the demand of increasing workload. - **Policy Driven** Policy driven workflow allows you to customize which VPCs traffic should be inspected. - **Vendor Integration** Launch Palo Alto Networks VM-Series from the Aviatrix Controller console to simplify deployment. - **Automation** The Aviatrix Controller automatically updates Palo Alto VM-Series route tables when on-prem route changes or VPC attachment changes. FireNet Deployment Model 1 - Transit VPC --------------------------------------------------- FireNet supports AWS Transit Gateway (TGW), as shown below. |firenet_transit| FireNet Deployment Model 2 - Insane Mode ---------------------------------------------- FireNet supports AWS Transit (TGW) with Insane Mode, |firenet_insane| FireNet Deployment Model 3 (Future release) ---------------------------------------------- In the future release, the hybrid deployment can be using native AWS Direct Connect Gateway. |firenet| What is the problem with deploying firewall instances with ECMP? ------------------------------------------------------------------ AWS Transit Gateway (TGW) supports VPN with ECMP load balancing. With its capability, you can launch multiple firewall instances in a load balanced fashion for Egress Inspection and VPC to VPC traffic inspection. The problem with this deployment is performance. The IPSEC tunnel limits each firewall instance to be capped at 1Gbps. When this architecture is deployed for VPC to VPC inspection, traffic goes through VGW (the other end of the IPSEC tunnel) twice, further reducing its throughput to 400Mbps. What this implies is that each firewall instance can only operate at 400Mpbs throughput. This is much lower than what firewall instances can do without IPSEC tunnel. .. |firenet| image:: firewall_network_media/firenet.png :scale: 30% .. |firenet_transit| image:: firewall_network_media/firenet_transit.png :scale: 30% .. |firenet_insane| image:: firewall_network_media/firenet_insane.png :scale: 30% .. |main_companion_gw| image:: transit_dmz_media/main_companion_gw.png :scale: 30% .. |main_companion_subnets| image:: transit_dmz_media/main_companion_subnets.png :scale: 30% .. disqus:: <file_sep> .. toctree:: :numbered: ============================================================================== OpenVPN® with SAML Authentication on AWS SSO IdP ============================================================================== Overview ------------ This guide provides an example on how to configure Aviatrix to authenticate against AWS SSO IdP. When SAML client is used, your Aviatrix Controller acts as the Identity Service Provider (ISP) that redirects browser traffic from client to IdP (e.g., AWS SSO) for authentication. Pre-Deployment Checklist ----------------------------------- Before configuring SAML integration between Aviatrix and AWS SSO, make sure the following is completed: #. The `Aviatrix Controller <#awsssosaml-aviatrix-controller>`__ is set up and running. #. You have a valid `AWS account <#awsssosaml-aws-account>`__ with `AWS SSO <https://aws.amazon.com/single-sign-on/>`_ enabled. #. You have downloaded and installed the `Aviatrix SAML VPN client <#awsssosaml-aviatrix-client>`__. .. _awsssosaml_aviatrix_controller: Aviatrix Controller #################### If you haven’t already deployed the Aviatrix Controller, follow `the Controller Startup Guide <https://docs.aviatrix.com/StartUpGuides/aviatrix-cloud-controller-startup-guide.html>`_ and start with a Metered AMI. .. _awsssosaml_aws_account: AWS Account with AWS SSO Enabled ################################ Enable AWS SSO on your AWS account before continuing with the configuration. .. tip:: If your AWS account is a consolidated account, you cannot set up SSO. SSO can only be enabled with a master account. .. _awsssosaml_aviatrix_client: Aviatrix VPN Client ################### All users must use the Aviatrix VPN client to connect to the system. Download the client for your OS `here <../Downloads/samlclient.html>`__. Configuration Steps ----------------------------- Follow these steps to configure Aviatrix to authenticate against your AWS SSO IDP: #. Create a `AWS SSO SAML Application <#awssso-saml-app>`__ for Aviatrix in the AWS Console. #. Create a `SAML Endpoint <#awssso-saml-endpoint>`__ in the Aviatrix Controller. .. _awssso_saml_app: AWS SSO Custom SAML Application (Part 1) ######################################## Before you start, pick a short name to be used for the SAML application name. In the notes below we will refer to this as **aviatrix_awssso**, but it can be any string. We will use the string you select for the SAML application name to generate a URL for AWS SSO to connect with Aviatrix. This URL is defined below as **SP_ACS_URL**. This URL should be constructed as: "https://<<<your Controller IP or host name>>>/flask/saml/sso/<<<aviatrix_awssso>>>" .. tip:: Replace **<<<your Controller IP or host name>>>** with the actual host name or IP address of your Controller and **<<<aviatrix_awssso>>>** with the string you chose to refer to the SAML application. #. Log in to your AWS console. #. Go to the AWS Single Sign-On service. #. Add a new Application (Applications > Add a new application). |imageAddAppsMenu| #. Click **Custom SAML 2.0 application**. |imageSelectCustom| #. Enter a Display Name. #. Copy the **AWS SSO SAML metadata file** URL. |imageCopyURL| .. _awssso_saml_endpoint: Aviatrix Controller SAML Endpoint ################################# #. Log in to your Aviatrix Controller. #. Enable SAML. Go to OpenVPN® > Edit Config > Modify Authentication. Select SAML. Skip this step if you have already done so. #. Select OpenVPN > Advanced on the left sidebar. #. Select the **SAML** tab. #. Click **+ Add New**. #. Follow the table below for details on the fields in the table: +----------------------------+-----------------------------------------+ | Field | Description | +----------------------------+-----------------------------------------+ | Endpoint Name | aviatrix_awssso | +----------------------------+-----------------------------------------+ | IPD Metadata Type | URL | +----------------------------+-----------------------------------------+ | IDP Metadata Text/URL | Paste in the | | | **AWS SSO SAML metadata file URL** | | | copied earlier from AWS SSO dashboard. | +----------------------------+-----------------------------------------+ | Entity ID | Select `Hostname` | +----------------------------+-----------------------------------------+ | Custom SAML Request | Mark this checkbox | | Template | | +----------------------------+-----------------------------------------+ |add_saml_endpoint| #. Remove the XML element "<samlp:NameIDPolicy>..</samlp:NameIDPolicy>." .. note:: This is required to connect with AWS SSO. If you don't do this, you will receive an error message when testing. #. Click **OK**. #. Right-click **SP Metadata** next to the SAML endpoint just created and save the file to your local machine. |imageSPMetadataURL| .. tip:: Save this XML file to your local machine. It will be used in the next step. AWS SSO Custom SAML Application (Part 2) ######################################## Return to the AWS SSO console. #. Scroll to **Application metadata**. #. **Browse...** to the **SP Metadata** file saved in the previous step. #. Leave the **Application start URL** blank. #. Click **Save changes**. |imageAppMetadata| Adding Attribute Mappings +++++++++++++++++++++++++ #. Select the **Attribute mappings** tab. #. Add the following attributes: +----------------------------+-----------------------------------------+ | User attribute in the | Maps to this string value or user | | application | attribute in the AWS SSO | +============================+=========================================+ | FirstName | ${user:givenName} | +----------------------------+-----------------------------------------+ | LastName | ${user:familyName} | +----------------------------+-----------------------------------------+ | Email | ${user:email} | +----------------------------+-----------------------------------------+ As shown below: |attribute_mapping| #. Click **Save changes**. Validating ---------------- .. tip:: Be sure to assign users to the new application in AWS Single Sign-on service prior to validating. You can use AWS SSO Directory service under AWS SSO page to assign users. If you do not assign your test user to the Aviatrix User VPN application, you will receive an error. You can quickly validate that the configuration is complete by clicking **Test** next to the SAML endpoint. |imageAvtxTestButton| .. |imageAddAppsMenu| image:: awssso_saml_media/add_new_application.png .. |imageSelectCustom| image:: awssso_saml_media/select_custom_application.png .. |imageCopyURL| image:: awssso_saml_media/copy_metadata_file_url.png .. |imageAvtxSAMLEndpoint| image:: awssso_saml_media/avx_controller_saml.png .. |imageSPMetadataURL| image:: awssso_saml_media/sp_metadata_button.png .. |imageAvtxTestButton| image:: awssso_saml_media/avtx_test_button.png .. |imageAppMetadata| image:: awssso_saml_media/application_metadata_save.png .. |add_saml_endpoint| image:: awssso_saml_media/add_saml_endpoint.png :scale: 30%% .. |attribute_mapping| image:: awssso_saml_media/attribute_mapping.png :scale: 30%% <file_sep> =========================== Aviatrix OpenVPN® Client FAQs =========================== My Public IP address did not change after connecting to the VPN. Is my VPN configured correctly? --------------------------------------------------------------------------------------------- You may be connecting to a split tunnel VPN. This ensures that only your connections are being forwarded through the tunnel. What user devices are VPN client software supported? ---------------------------------------------------------- Typical VPN client software on Windows, MAC, Linux, Chromebook, Android and iOS devices are supported. If you are using Aviatrix VPN Client for OpenVPN with SAML authentication, only Windows, MAC, Linux and FreeBSD are supported. I have a token generator for my Okta account. How do I use it? ------------------------------------------------------------- You can append the 6 digit token to your Okta password with to use it with the VPN during authentication Which client should I use? ------------------------------------------- Aviatrix's `VPN Client <../Downloads/samlclient.html>`__ supports SAML authentication from the VPN client itself. If you need the VPN client itself to authenticate against an IDP (for example, Okta or Duo), you will need to use the Aviatrix VPN client. Aviatrix VPN gateway can authenticate a VPN user against OKTA on behalf of a VPN user. In that case, you don’t need Aviatrix VPN client, any OpenVPN® clients software such as Tunnelblick can be supported. Are multiple profiles supported by the Aviatrix VPN client? ----------------------------------------------------------- Aviatrix's `VPN Client <../Downloads/samlclient.html>`__ allows you to load and switch between one or more VPN profiles. Load multiple configurations: #. Open the client #. Click on the `Advanced` button. #. Select the `Profile` tab. #. Click `Add` button. #. Enter a name for the new profile. #. Select the configuration file. Switch to a different configuration: #. Open the client. #. Click `Connect` button. A drop down will appear. #. Select the profile from the list. Which log files should I share when I open a support ticket? --------------------------------------------------------------- Please share the following log files with your support request. For MacOS, you can find them at "/Applications/Aviatrix VPN Client.app/Contents/Resources/logs" and for Windows, please look at “Program Files(x86)/Aviatrix VPN Client” * commandlog.log * server.log * openvpn1.log How to restart Aviatrix Windows client background service? --------------------------------------------------------------- #. Exit the Aviatrix VPN client from the tray #. Use the Task Manager to end all openvpn.exe processes #. Open a terminal and "Run as administrator" #. Run command "sc stop AVPNC_RP" in the terminal #. Run command "sc start AVPNC_RP" in the terminal #. Start Aviatrix VPN client again OpenVPN is a registered trademark of OpenVPN Inc. .. disqus:: <file_sep> ========================================================================================= Site2Cloud with Customized SNAT and DNAT to a virtual ip address ========================================================================================= This technical note provides a step-by-step configuration on Aviatrix controller that will address the following requirements: 1. An EC2 instance with private ip address 172.31.72.13 in VPC will need to reach a device in a customer on-premise network. 2. The EC2 instance will only use a virtual ip address 172.27.254.100 when it needs to access the remote on-premise device. 3. The remote on-premise device will see the EC2 instance traffic as coming from 10.123.51.100 instead of the actual 172.31.72.13. 4. The remote on-prem device will access the EC2 instance in the VPC using the 10.123.51.100 instead of the actual 172.31.72.13. 5. The EC2 instance will see the traffic from on-premise as coming from 172.27.254.100. In this example, we will use 2 Aviatrix gateways to simulate the cloud VPC and on-premise network. - Cloud VPC: 172.31.72.0/24 - Cloud-EC2: 172.31.72.13/32 - Onprem VPC:10.23.75.0/24 (simulating on-premise internal network) - Onprem-EC2: 10.23.75.7/32 (simulating on-premise device) In the diagram below, both Aviatrix gateways (demo1-ptp-cloud and demo1-ptp-onprem) will build a Site2Cloud to a VGW. |s2c_snat_dnat1_01| We will configure customized SNAT and DNAT at Aviatrix gateway demo1-ptp-cloud, which translates the source IP of traffic initiated from Cloud-EC2 172.31.72.13 to an user defined IP address (10.123.51.100 in this example). In this way, Onprem-EC2 will see all packets from Cloud-EC2 with the source IP address (10.123.51.100) when the Cloud-EC2 attempts to access the virtual ip address 172.27.254.100. We also need to configure the relevant SNAT and DNAT to meet the requirement in which traffic initiated from Onprem-EC2 will reach the Cloud-EC2 using the 10.123.51.100. Traffic from on-premise will be seen as coming from 172.27.254.100. Create Aviatrix gateways ------------------------ 1. Create Aviatrix gateway in Cloud VPC - Follow the instructions in this `document <http://docs.aviatrix.com/HowTos/gateway.html>`__ to create an Aviatrix gateway (we use demo1-ptp-cloud as the gateway name and us-east-2 region in this example) in the Cloud VPC (172.31.72.0/24) without selecting "Enable SNAT". 2. Create Aviatrix gateway in Onprem VPC - If you are building the actual Site2Site VPN from your remote onprem device (router/firewall) to the VGW, you may skip this step 2. Else, follow the instructions in this `document <http://docs.aviatrix.com/HowTos/gateway.html>`__ to create an Aviatrix gateway (we use demo1-ptp-onprem and us-east-2 region in this example) in the Onprem VPC (10.23.75.0/24) without selecting "Enable SNAT". Create a Site2Cloud connection between Aviatrix GW and VGW ---------------------------------------------------------- .. Note:: In the Aviatrix terminology, Site2Cloud is the name of the feature that enables connections from one site (or datacenter) to other sites (including cloud environments). .. 1. Go to AWS console in us-east-2 (Ohio) region. Click on Services and go to VPC Dashboard. 2. Click on Virtual Private Gateways at the left panel and create a Virtual Private Gateway. 3. Click on the Site-to-Site VPN Connections at the left panel and click "Create VPN Connection" to create an IPsec tunnel to demo1-ptp-cloud EIP with static route 10.123.51.0/24. 4. Select the VPN connection that you just created and click "Download Configuration" to download the "Generic" configuration. 5. At Aviatrix Controller UI, click Site2Cloud at the navigation panel. 6. Click "Add New" to configure the Site2Cloud connection. |s2c_snat_dnat1_02| 7. Click on Site2Cloud > Diagnostics page and verify that the IPsec tunnel is established between demo1-ptp-cloud and the VGW. Please note that it may take a few minutes for the tunnel status as UP at the Site2Cloud page. |s2c_snat_dnat1_03| 8. Since we are using another Aviatrix gateway demo1-ptp-onprem to simulate the on-premise device, click on the Site-to-Site VPN Connections at the left panel in AWS portal. Click "Create VPN Connection" to create an IPsec tunnel to demo1-ptp-onprem EIP with static route 10.23.75.0/24. If you are connecting the actual remote device to the VGW, you will create the VPN connection with the remote device public IP. 9. Repeat step 4 through 7 for the new VPN connection created in step 8. The following screenshots show Site2Cloud configuration that simulate the on-premise network. |s2c_snat_dnat1_04| |s2c_snat_dnat1_05| Configure Customized SNAT and DNAT at Aviatrix gateway ------------------------------------------------------ 1. Log into the Controller and go to "Gateway" page. 2. Select the Aviatrix gateway demo1-ptp-cloud previously created. 3. Click "Edit" button and go to "Source NAT" section. 4. Select "Customized SNAT". 5. Configure the following SNAT rule. |s2c_snat_dnat1_06| 6. Click "Save" and "Enable SNAT" buttons 7. Configure the following DNAT rule. |s2c_snat_dnat1_07| 8. Click "Save" and "Update" buttons Validate the connectivity ------------------------- 1. At Cloud-EC2 instance, ping to the virtual ip address 172.27.254.100. Turn on "tcpdump icmp -n" at Onprem-EC2 instance to verify the source IP of the icmp ping. |s2c_snat_dnat1_08| |s2c_snat_dnat1_09| 2. At Onprem-EC2 instance, ping to the virtual ip address 10.123.51.100. Turn on "tcpdump icmp -n" at Cloud-EC2 instance to verify the source IP of the icmp ping. |s2c_snat_dnat1_10| |s2c_snat_dnat1_11| .. |s2c_snat_dnat1_01| image:: s2c_snat_dnat1_media/s2c_snat_dnat1_01.png .. |s2c_snat_dnat1_02| image:: s2c_snat_dnat1_media/s2c_snat_dnat1_02.png .. |s2c_snat_dnat1_03| image:: s2c_snat_dnat1_media/s2c_snat_dnat1_03.png .. |s2c_snat_dnat1_04| image:: s2c_snat_dnat1_media/s2c_snat_dnat1_04.png .. |s2c_snat_dnat1_05| image:: s2c_snat_dnat1_media/s2c_snat_dnat1_05.png .. |s2c_snat_dnat1_06| image:: s2c_snat_dnat1_media/s2c_snat_dnat1_06.png .. |s2c_snat_dnat1_07| image:: s2c_snat_dnat1_media/s2c_snat_dnat1_07.png .. |s2c_snat_dnat1_08| image:: s2c_snat_dnat1_media/s2c_snat_dnat1_08.png .. |s2c_snat_dnat1_09| image:: s2c_snat_dnat1_media/s2c_snat_dnat1_09.png .. |s2c_snat_dnat1_10| image:: s2c_snat_dnat1_media/s2c_snat_dnat1_10.png .. |s2c_snat_dnat1_11| image:: s2c_snat_dnat1_media/s2c_snat_dnat1_11.png .. disqus:: <file_sep> ========================================================= Aviatrix Default Route Handling ========================================================= This document explains how Aviatrix handles the default route 0.0.0.0/0 starting from R6.2. Public Subnet vs. Private Subnet ================================================================ A public subnet is different from a private subnet in a VPC/VNet in each Cloud Service Provider (CSP) by way of how the default route is managed. In AWS, a public subnet is well-defined. If the subnet associated route table has a route entry 0.0.0.0/0 pointing to IGW, the subnet is a public subnet. On the other hand, if 0.0.0.0/0 does not point to IGW, this is a private subnet. In Azure, such distinction is less defined via explicit route entries. By default any VM in Azure is a public instance with direct Internet access and can be reached from the Internet as long as it has a public IP address. This is because Azure automatically programs a system route entry with 0.0.0.0/0 pointing to Internet, as shown in the screenshot below after a VM is launched. Azure's "system programmed default route" is displayed in Effective Routes. |system_default_route| Since Aviatrix Controller programs route table extensively and there are use cases that deal with egress control, it is important that the Controller follow well-defined rules when handling different types of subnets. Below are what Aviatrix Controller defines as public or private subnet. +--------------------------------------+--------------------------------------+---------------------------------------------+ | **Aviatrix definition table 1** | **AWS** | **Azure** | +--------------------------------------+--------------------------------------+---------------------------------------------+ | **Public** cloud subnet/route table | 0.0.0.0/0 to IGW | UDR does not exist | | | +---------------------------------------------+ | | | UDR is associated with a subnet: | | | +---------------------------------------------+ | | | - UDR: 0.0.0.0/0 entry doesn't exist | | | +---------------------------------------------+ | | | - UDR: 0.0.0.0/0 to Cloud Internet | +--------------------------------------+--------------------------------------+---------------------------------------------+ | **Private** cloud subnet/route table | 0.0.0.0/0 route entry does not exist | UDR is associated with a subnet: | | +--------------------------------------+---------------------------------------------+ | | 0.0.0.0/0 to non-Aviatrix NVA | - UDR: 0.0.0.0/0 to None | | +--------------------------------------+---------------------------------------------+ | | 0.0.0.0/0 to VGW | - UDR: 0.0.0.0/0 to non-Aviatrix NVA | | +--------------------------------------+---------------------------------------------+ | | 0.0.0.0/0 to TGW | - UDR: 0.0.0.0/0 to Virtual Network | | +--------------------------------------+---------------------------------------------+ | | 0.0.0.0/0 to AWS NAT gateway | - UDR: 0.0.0.0/0 to Virtual Network Gateway | | +--------------------------------------+---------------------------------------------+ | | overall: 0.0.0.0/0 to non-IGW | | +--------------------------------------+--------------------------------------+---------------------------------------------+ | Notes: | IGW: Internet gateways | UDR: User Defined Routing | | +--------------------------------------+---------------------------------------------+ | | NVA: Network Virtual Appliance | NVA: Network Virtual Appliance | | +--------------------------------------+---------------------------------------------+ | | VGW: Virtual private gateway | | | +--------------------------------------+---------------------------------------------+ | | TGW: AWS Transit Gateway | | +--------------------------------------+--------------------------------------+---------------------------------------------+ .. important:: In Azure, the rule of thumb of classifying a subnet as private is that the subnet's associated route table has a UDR (User Defined Routes) route entry of 0.0.0.0/0 pointing to None, an NVA appliance, Virtual Network or Virtual Network Gateway. Changes Made on **Azure** in R6.2 ========================================================================= Prior to 6.2, Aviatrix Controller blindly overwrites the default route to point to Aviatrix gateway in every route table whenever egress control is involved. This can cause outages if the deployment has public facing application or VMs. In 6.2, the rules for Aviatrix Controller to overwrite the default route becomes well defined. .. tip:: Use the Useful Tool "create a VPC tool" to create an Spoke and Transit Azure VNet. For Spoke VNet, the Controller will program a UDR default route 0.0.0.0 pointing to next hop type "None" to the route table associated with the private subnets. Check `Create a VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ for more info. If you created Azure VNet via `create a VPC tool` prior R6.2 or created Azure VNet via your own scrip, make sure you inject a UDR route 0.0.0.0 pointing to the next hop type "None" to signal to the Aviatrix Controller that this is a private subnet and its default route can be overwritten. If you have already deploy Transit FireNet with Egress Control, upgrading to 6.2 does not impact the existing traffic. However if you detach a Spoke VNet and re-attach it or disable Egress Inspection and re-enable it, the new rules will kick in. Testing =================== When testing egress control from a VM in Azure VNet, make sure this VM is on a private subnet as defined in this document. Since this VM is on a private subnet without a public IP address, you cannot directly SSH into the VM. You can use `Azure Bastion Service <https://docs.microsoft.com/en-us/azure/bastion/bastion-overview>`_ or `Aviatrix User VPN gateway <https://docs.aviatrix.com/HowTos/uservpn.html>`_ to connect to the private IP address of the VM via SSH. Use Case: Single SNAT or FQDN in a VPC/VNet ======================================================== Users can launch Aviatrix Gateways within the network, and enable Single SNAT or FQDN feature on the gateway. Aviatrix gateway will discover 'private' subnets/route tables, then program default route 0.0.0.0/0 pointing to Aviatrix gateway into it. Furthermore, to reduce friction and to shorten downtime when users remove default route in their cloud environment by themselves, Aviatrix performs overwriting default route logic by default. By doing this, private instances/VMs internet traffic will go through Aviatrix gateway, and inspected by FQDN (if enabled). Rule 4.1: Overwrite default route entry 0.0.0.0/0 in subnet/route table where Aviatrix defines it as “Private” when the below features are enabled: --------------------------------------------------------------------------------------------------------------------------------------------------- Features: ^^^^^^^^^ - Single SNAT - FQDN discovery - FQDN High-level logic: ^^^^^^^^^^^^^^^^^ - Utilize the definition in this document above to discover private subnet/route table  - Save customer's original route entry 0.0.0.0 configuration - Overwrite route entry 0.0.0.0 to Aviatrix - Restore back customer's original route entry 0.0.0.0 configuration if users disable the above features Rule 4.2: Load balance the route entry 0.0.0.0/0 between Aviatrix gateways when users attempt to enable the same type of feature such as Single SNAT/FQDN which is already deployed in the same network. -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - Refer to `NAT GW Load-balance with AZ affinity <https://docs.aviatrix.com/HowTos/nat_gw_LoadBalance_AZ.html>`_ for Aviatrix load balance detail Use Case: Aviatrix Centralized Egress or On-Prem Advertising Default Route 0.0.0.0/0 ======================================================================================== In the Aviatrix Transit Network solution, for private instances/VMS in spoke networks, users can choose centralized egress by using Aviatrix FireNet, or using on-prem egress. In either case, Aviatrix transit gateway propagates 0.0.0.0/0 route to Aviatrix spoke gateways, and program 0.0.0.0/0 route in spoke private subnets/route tables. Thus, all private instance/VM's internet traffic are forwarded to transit gateway, and then forwarded to FireNet or on-prem networks. How does Aviatrix Define a Public or Private Subnet/Route Table in Each Cloud, and What are the Rules/Scenarios for Use Case 2? ------------------------------------------------------------------------------------------------------------------------ Here, we only discuss AWS and Azure. .. _aviatrixdefinitiontable2: +--------------------------------------+--------------------------------------+---------------------------------------------+ | **Aviatrix definition table 2** | **AWS** | **Azure** | +--------------------------------------+--------------------------------------+---------------------------------------------+ | **Public** cloud subnet/route table | 0.0.0.0/0 to IGW | UDR does not exist | | | +---------------------------------------------+ | | | UDR is associated with a subnet: | | | +---------------------------------------------+ | | | - UDR: 0.0.0.0/0 entry doesn't exist | | | +---------------------------------------------+ | | | - UDR: 0.0.0.0/0 to Cloud Internet | +--------------------------------------+--------------------------------------+---------------------------------------------+ | **Private** cloud subnet/route table | 0.0.0.0/0 route entry does not exist | UDR is associated with a subnet: | | | +---------------------------------------------+ | | | - UDR: 0.0.0.0/0 to None | | | +---------------------------------------------+ | | | - UDR: 0.0.0.0/0 to Virtual Network | +--------------------------------------+--------------------------------------+---------------------------------------------+ Rule 5.1: Aviatrix Transit Gateway on route 0.0.0.0/0 ------------------------------------------------------------------------------ Scenarios: ^^^^^^^^^^ - Learning default route 0.0.0.0/0 from on-prem - Learning default route 0.0.0.0/0 from Aviatrix Transit peering - Enabling Central Egress feature High-level logic: ^^^^^^^^^^^^^^^^^ - Utilize the `Aviatrix definition table 2 <#aviatrixdefinitiontable2>`_ above to discover private subnet/route table  - Program '0.0.0.0/0 to Aviatrix Spoke Gateway' into private subnet/route table of Spoke network, but it has a slightly different implementation for each cloud as below table. - Program '0.0.0.0/0 to Aviatrix Transit Gateway' into private subnet/route table of Spoke network by following Azure implementation as below table if Azure ARM Spoke through Native Peering feature is deployed +--------------------------------------+--------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------+ | **Aviatrix definition** | **AWS** | **Azure** | +--------------------------------------+--------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------+ | **Private** cloud subnet/route table | Silently ignore if there is a route 0.0.0.0/0 existed. | Silently ignore most of the route 0.0.0.0/0 if it is existed, but Aviatrix overwrites the default route 0.0.0.0/0 as follows: | | +--------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------+ | | Aviatrix does NOT overwrite 0.0.0.0/0 in this case. | - UDR: 0.0.0.0/0 to None | | +--------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------+ | | | - UDR: 0.0.0.0/0 to Virtual Network | +--------------------------------------+--------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------+ Rule 5.2: Error out a warning message when users attempt to enable single SNAT/FQDN in a Spoke network where default route 0.0.0.0/0 is already programmed by Rule 3.1. --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Example: ^^^^^^^^ If there is a default route 0.0.0.0/0 learned from on-prem already existed in Aviatrix Transit solution, then Aviatrix will pop out a warning message when users attempt to enable single SNAT/FQDN features in Spoke network. .. |system_default_route| image:: default_route_faq_media/system_default_route.png :scale: 30% .. disqus:: <file_sep> ==================================== Developer’s Sandbox ==================================== Objective ========= As a gatekeeper, security must be one of your top concerns when managing a functional network for your production environment in the cloud. Keeping your environment secure while giving your developers the freedom to experiment and learn new services offered by AWS is a challenge. In this regard, we are here to help you. This reference design leverages the multi tenants’ capability of an Aviatrix Controller to build sandboxes for your developers. While the developer has full administrative authority to her sandbox, the sandbox itself is isolated from your main production environments. The network diagram is shown below, |image0| where the Aviatrix Controller instance can be in the same or a different VPC, and two developers' sandboxes are shown: John (10.10.0.0/16) and Sam (10.5.0.0/16). In this configuration, assume you want the VPN to be in split tunnel mode, that is, only traffic destined to the cloud goes through the SSL tunnel. If a user does general browsing to Internet or watches movies from Hulu, traffic should be routed via her device WI-FI to ISP to Internet. You do not wish to pay AWS for this type of compute and network cost. Solution ======== The solution is to give John and Sam each their own AWS accounts and link their accounts to your corporate root account, using the Consolidated Billing feature offered by AWS. http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/consolidated-billing.html With John’s own AWS account and API credentials, you can create a corresponding Cloud Account on the controller. Using this Cloud Account, you can create VPC for John. John may have more privileges in his VPC. Configuration Workflow ====================== Before you start, make sure you have the latest software by checking the Dashboard. If an alert message displays, click **Upgrade** to download the latest software. We assume here that you have created a management VPC 172.31.0.0/16, its corresponding VPN gateways and John has been added as a VPN user. For more information for this part of configuration, check out this `reference design <https://s3-us-west-2.amazonaws.com/aviatrix-download/Cloud-Controller/Cloud+Networking+Reference+Design.pdf>`__: The configuration workflow is as follows, with major steps highlighted. 1. Create a Cloud Account for John. Go to Accounts > Cloud Account > New Account, make sure: a. The Account Name is unique to the Controller, for example, JohnSmith. b. The Account Password can be used to log in in with Account Name. c. An email will be sent for this account created. d. Add AWS credentials for this account. 2. Create a VPC and Gateway for John. Go to Advanced Config > Create VPC Pool > Create: a. Account Name: JohnSmith b. Pool Name: John c. Number of VPCs: 1 d. VPC Size: the gateway size. A t2.micro may be all you need. A t2.micro Aviatrix Gateway performance is between 40mbps to 80mbps. e. Launch Gateway: mark this checkbox. f. Custom CloudFormation Script: a URL that points to your custom CloudFormation script in S3. Note that only VPC ID is taken as input parameter. After gateway is launched, a CloudFormation stack will be created. One use case for this script is security groups and policies. g. Public Subnets: check. This will create subnets whose default gateway is IGW. h. Enable NAT: check. If this is checked, NAT function is integrated on the gateway. 3. Build Encrypted Peering. Go to Peering > Encrypted Peering > New Peering. Note that each VPC is represented by one or more gateways. Make sure you want to peer between two gateways without VPN capability. In this example, the peering is between John and the peering gateway in the management VPC 172.31.0.0/16 (not the VPN gateway) 4. Repeat the above two steps for other developers or projects. 5. Add users. If you have not done so, add VPN user John to the cloud network. Go to OpenVPN®, Use Profile to control which user can access what cloud instance/application/ports. OpenVPN is a registered trademark of OpenVPN Inc. .. |image0| image:: DevSandbox_media/image1.png .. disqus:: <file_sep> =========================================================================================== Site2Cloud to a Public IP Address =========================================================================================== This document addresses the scenario where a customer on-prem firewall device needs to route encrypted traffic to a partner network in the cloud (AWS/Azure/GCP). However due to concerns for overlapping CIDR blocks to the customer network, the customer side enforces a policy that the destination IP address must be a public IP address regardless if the partner network is in the RFC 1918 range. For example, the VPC instance IP address that the on-prem machine should send data to is 172.16.31.10, but the on-prem machine must instead send data to a public IP address 172.16.31.10 (or even 192.168.3.11). The scenario is shown in the diagram below. |site2cloud-publicIP| This problem can be solved by combining `Site2Cloud <https://docs.aviatrix.com/HowTos/site2cloud.html>`_ feature and `DNAT <https://docs.aviatrix.com/HowTos/gateway.html#destination-nat>`_ feature. Below are the configuration steps. Step 1: Determine the public IP address ---------------------------------------- As this public IP address is what the on-prem host sees, it should not change. There are a couple of ways to determine it. You can allocate an EIP in the VPC for this public IP address. Make sure you don't associate this EIP to any instance. Alternatively, if the EC2 instance that on-prem hosts need to send data to has an EIP, you can use that EIP. You can also try a reserved public IP address range, for example, 100.100.x.x range, if the customer does not object. Step 2: Follow the Site2Cloud workflow to launch a gateway ----------------------------------------------------------- Login to the Controller console, go to Site2Cloud. Follow step 1 to launch a gateway in the VPC 172.16.31.10/16. In this example the gateway name is Spoke1. (You can follow the `gateway launch instructions in this <http://docs.aviatrix.com/HowTos/gateway.html>`_. Leave optional parameters unchecked.) Step 3: Follow the Site2Cloud workflow to Create a Site2Cloud tunnel ----------------------------------------------------------------------- Click "+Add New". Fill the form and click OK. Note the Local Subnet field is the real or fake public IP address. If there are multiple instances in VPC that needs to be addressed, enter multiple such IP addresses separate them by comma. |site2cloud-publicIP-config| Step 4: Download the Configuration Template --------------------------------------------- Click on the connection just created, the Edit page pops up. Select the Vendor (Generic) and click Download Configuration. This will download a text file with configuration information. Send the text file to your customer-X so they'll configure their end. Step 5: Configure DNAT ----------------------- This step is to configure the gateway to translate the destination IP address 172.16.31.10 to the real private IP address 192.168.127.12. At the main navigation bar, click Gateway. Highlight the gateway, in this case, Spoke1, and click Edit. Scroll down to Destination NAT. Follow the instructions `here <https://docs.aviatrix.com/HowTos/gateway.html#destination-nat>`_ to configure, as shown below. Note to use "Connection" field to specify the site2cloud connection name configured in Step 3. |dnat-config| Step 6. Test the Site2Cloud Connection and DNAT --------------------------------------------------------- Go to the "Site2Cloud" page and verify that the site2cloud connection status is "Up". Test connectivity from on-prem host to the EC2 instance. For example, ping 172.16.31.10 from an on-prem host machine. The ping should reach 172.16.31.10. .. |site2cloud-publicIP| image:: s2c_for_publicIP_media/site2cloud-publicIP.png :scale: 30% .. |site2cloud-publicIP-config| image:: s2c_for_publicIP_media/site2cloud-publicIP-config.png :scale: 30% .. |dnat-config| image:: s2c_for_publicIP_media/dnat-config.png :scale: 30% .. disqus:: <file_sep> ======================================================================= Transit Gateway ECMP for DMZ Deployment Limitation Test Validation ======================================================================= Introduction -------------- This document demonstrates that using AWS Transit Gateway ECMP functions to deploy multiple (or multi-AZ) firewalls for traffic inspection between on-prem and cloud does not work. AWS Transit Gateway VPN supports ECMP protocol that can load balance traffic across multiple VPN tunnels. The question is, can Transit Gateway ECMP be used to deploy a transit DMZ as shown in the diagram below? |dmz_with_ecmp| If the above deployment were feasible, customers could inspect traffic between on-prem and cloud and effectively build a scale out DMZ architecture. Test Validation ---------------- The test setup uses Palo Alto Networks (PAN) as the example firewall and is described in the following. VPC1 is a Spoke VPC attached to a Transit Gateway. An EC2 instance in VPC1 serves as the HTTP client. VPC3 is another Spoke VPC attached Transit Gateway. VPC3 simulates an on-prem data center with an EC2 instance serving as the HTTP server. TGW-2 simulates an on-prem router, which also runs ECMP with the two Palo Alto Network instances in VPC2. VPC2 is a Transit VPC and has two Available Zones (AZs). Each AZ has one Palo Alto Networks firewall to ensure HA. PAN1 is in AZ-a and PAN2 is in AZ-b. Both Palo Alto Network instances have three interfaces and all three interfaces have EIPs associated: - eth0: Management interface dedicated for remote access to Palo Alto Network's portal - eth1: Public IP used for creating Customer Gateway with TGW1 - eth2: Public IP used for creating Customer Gateway with TGW2 |tgw-pan-ecmp| Our configuration steps are as following: 1. Go to AWS Console and create two TGWs (TGW1 and TGW2). Both have "VPN ECMP Support" enabled. 2. Attach VPC1 to TGW1 and attach VPC3 to TGW2 at AWS console. 3. Update the route tables of VPC1 and VPC3: - VPC1: Traffic destinating to VPC3 CIDR -> TGW1-ID - VPC3: Traffic destinating to VPC1 CIDR -> TGW2-ID 4. Create two VPN Transit Gateway Attachments at TGW1. One attachment uses PAN1-eth1 as a Customer Gateway and the other attachment uses PAN2-eth1 as a Customer Gateway. Both attachments require BGP running between PANs and TGW1. BGP ASN numbers for both Customer Gateways are the same (64999 in this test). 5. Create two VPN Transit Gateway Attachments at TGW2. One attachment uses PAN1-eth2 as a Customer Gateway and the other attachment uses PAN2-eth2 as a Customer Gateway. Both attachments require BGP running between PANs and TGW2. BGP ASN numbers for both Customer Gateways are the same (64999 in this test). 6. Configure PAN1 and PAN2 to bring up IPSec tunnels with TGW1 and TGW2. There are two IPSec tunnels for each attachment between the PAN and its attached Transit Gateway. Both PANs advertise a default route (0.0.0.0/0) and VPC2 CIDR (10.201.0.0/16) through BGP to TGW1 and TGW2. 7. Verify that ECMP is running between Transit Gateway and Palo Alto Network instances. - At AWS Console, check Transit Gateway Route Tables for TGW1 and TGW2. For each route advertised by PANs (0.0.0.0/0 and 10.201.0.0/16), there are four attachments. These four attachments are the four IPSec tunnels from both PAN1 and PAN2. Transit Gateway will use ECMP to distribute traffic among these four IPSec tunnels. One sample Transit Gateway route table is as below: |tgw-pan-ecmp1| - At the Palo Alto Networks portal, check both Palo Alto Networks' route tables. Taking PAN1 as an example, traffic destinating to VPC1's CIDR (10.200.0.0/16) has two next hops. These two next hops are TGW1 IP addresses for terminating the two IPSec tunnels between PAN1 and TGW1. Same thing for traffic destinating to VPC3's CIDR (10.202.0.0.16). The image below is route table from PAN1. Please note that the highlighted "E" flag indicates ECMP is running among the two tunnels. |tgw-pan-ecmp2| - Run traffic monitor in the Palo Alto Networks portal. Send pings between VPC1 and VPC3 and verify that ICMP packets are flowing through PAN1/PAN2. After bringing up the setup, we run wget at VPC1 EC2 to browse the HTTP server running at VPC3 EC2 and observe the following behaviors: 1. Stop PAN2 at AWS Console and only keep PAN1 running. wget from VPC1 to VPC3 always succeeds. 2. Stop PAN1 at AWS Console and keep PAN2 running. wget from VPC1 to VPC3 always succeeds. 3. Keep both PAN1 and PAN2 running. wget from VPC1 to VPC3 sometimes succeeds. Sometimes, wget times out. When a timeout happens, TCP packets from VPC1 to VPC3 go through PAN1 or PAN2, but the returning packets from VPC3 to VPC1 are distributed to a different Palo Alto Network instances by the other ECMP interface. The other Palo Alto Network instance will drop the returning packets due to missing initiating a TCP connection. Summary --------- Running ECMP between Transit Gateway and multiple firewall instances cannot guarantee that the returning traffic will go through the same firewall instance as the initiating traffic. As such, the ECMP based solution cannot be used to load balance traffic between multiple firewall instances between on-prem and cloud. The technical reason behind it is that the two sets of ECMP running between firewall and Transit Gateway and between firewall and on-prem have no coordination among them. The ECMP decisions to determine the next hop are made independently, resulting in the situation when the return traffic does not always go through the same firewall instance as the initiating traffic. .. |dmz_with_ecmp| image:: tgw_pan_ecmp_media/dmz_with_ecmp.png :scale: 30% .. |tgw-pan-ecmp| image:: tgw_pan_ecmp_media/tgw-pan-ecmp.png :scale: 30% .. |tgw-pan-ecmp1| image:: tgw_pan_ecmp_media/tgw-pan-ecmp1.PNG :scale: 30% .. |tgw-pan-ecmp2| image:: tgw_pan_ecmp_media/tgw-pan-ecmp2.PNG :scale: 30% .. add in the disqus tag .. disqus:: <file_sep> .. raw:: html <style> /* override table no-wrap */ .wy-table-responsive table td, .wy-table-responsive table th { white-space: normal !important; } </style> ################################### Controller HA in AWS ################################### Overview -------- Aviatrix Controller HA in AWS leverages an auto scaling group and a Lambda function to perform monitoring the health of the current Controller, launching a new controller and restoring the configuration when the active controller instance become unreachable. When a new controller is launched, the existing controller is terminated, its EIP is associated to the newly launched controller, and the private IP is created in the new controller subnet. Existing configuration is restored, resulting in a seamless experience when failover happens. Prerequisites ------------- * Existing AVX Controller. If you have not yet launched an AVX Controller, please follow `this guide </StartUpGuides/aviatrix-cloud-controller-startup-guide.html>`__. * The Aviatrix version must be **>= 3.4**. If older than 3.4, please `upgrade <inline_upgrade.html#how-to-upgrade-software>`__. * Enable Controller `Backup <controller_backup.html>`__. * AMI **aviatrix_cloud_services_gateway_043018_YYYY-xxxxxx** or later. If you are on an older AMI, please refer `here <Migration_From_Marketplace.html>`__ to migrate to the latest controller AMI first. * The Controller's VPC should have one or more public subnets, preferably in different AZs for HA across multiple AZ. * To use Controller HA with an ELB, refer to `here <https://docs.aviatrix.com/HowTos/controller_ssl_using_elb.html>`_ * Controller has enabled backup function. Controller HA Details --------------------- Aviatrix Controller HA operates by relying on an AWS Auto Scaling Group. This ASG has a desired capacity of 1 (and minimum capacity = 0 and maximum capacity = 1). If the Controller EC2 instance is stopped or terminated, it will be automatically re-deployed by the ASG. An AWS Lambda script is notified via SNS when new instances are launched by the Auto Scaling Group. This script handles configuration using a recent Controller backup file. The Aviatrix Controller manages these backups once `enabled <controller_backup.html>`__. Restoring the Aviatrix Controller from a newly built instance requires access to the S3 bucket to retrieve the latest backup file. In order to do this, the newly built EC2 Controller instance must be granted permission to read files in the bucket. The simplest method of doing this is via an `IAM user with programmatic access to the S3 bucket <#create-iam-user>`__. The lambda script also requires access to the S3 bucket. It is recommended that the backup bucket is used in the same account that was used to launch the controller. Steps to Enable Controller HA ----------------------------- Launch CloudFormation Stack ########################### #. Log in to the AWS console and switch to the region where your existing AVX Controller is installed. #. Launch `this CloudFormation stack <https://console.aws.amazon.com/cloudformation/home#/stacks/new?stackName=AviatrixControllerHA&templateURL=https://s3-us-west-2.amazonaws.com/aviatrix-cloudformation-templates/aviatrix-aws-existing-controller-ha.json>`__ #. Click **Next** #. Populate the fields as follows: +-------------------------------+------------------------------------------+ | Field | Expected Value | +===============================+==========================================+ | Stack name | Any valid stack name. | +-------------------------------+------------------------------------------+ | Enter VPC of existing | Select the VPC in this region where the | | controller instance. | AVX Controller is installed. | +-------------------------------+------------------------------------------+ | Enter one or more subnets in | Select a PUBLIC subnet of the controller | | different Availability zones | VPC. Optionally one additional subnet for| | within that VPC. | redundancy. | +-------------------------------+------------------------------------------+ | Enter Name tag of the existing| Enter the **Name** tag for the existing | | Aviatrix Controller instance. | Controller EC2 instance. | +-------------------------------+------------------------------------------+ | Enter S3 Bucket which will be |Name of S3 bucket that stores the | | used to store backup files. |backup files from the AVX Controller. | | | | | | | | |**Note**: The S3 bucket you use or create | | |for Controller HA and Backups does not | | |need to have public access enabled and | | |should be configured to restrict general | | |public access. | +-------------------------------+------------------------------------------+ | Enter an email to receive | Enter an email address that will be | | notifications for autoscaling | notified whenever a new Controller is | | group events | provisioned. | +-------------------------------+------------------------------------------+ #. Click **Next** #. Populate any additional CloudFormation Options. #. Click **Next** #. Check "I acknowledge that AWS CloudFormation might create IAM resources with custom names." #. Click **Create** #. Refresh the Stacks page and wait for the status of this stack to change to **CREATE_COMPLETE** .. note:: If the stack fails (and ends with status of **ROLLBACK_COMPLETE**) check the log messages in the **Events** section. If you see an error that says "Failed to create resource. AMI is not latest. Cannot enable Controller HA. Please backup/restore to the latest AMI before enabling controller HA. ", then follow the steps outlined `here <Migration_From_Marketplace.html>`__. .. note:: This stack creates the following: * An Autoscaling group of size 1 (minimum capacity=0, maximum capacity=1, desired capacity=1) and associated security group * A SNS topic with same name as of existing controller instance * An email subscription to the SNS topic (optional) * A Lambda function for setting up HA and restoring configuration automatically * An AWS Role for Lambda and corresponding role policy with required permissions .. note:: Please note that if you change the Controller name or change the backup destination bucket on S3, your Controller HA will not work as expected. You would have to delete the Controller HA CloudFormation Stack and redeploy it. .. tip:: Additional instructions and code are available `here <https://github.com/AviatrixSystems/Controller-HA-for-AWS/>`__. .. note:: During spinning up the HA after the current active controller stops or being terminated by accident, you won't see a new controller for a few minutes on AWS console, it is expected. Steps to Disable Controller HA ------------------------------ You can disable Controller HA by deleting the Controller HA CloudFormation stack. * Please take a backup from the Controller first - Controller/Settings/Maintenance/Backup&Restore/BackupNow. Please check in your S3 bucket to make sure that there is new backup files were generated and saved * Check the ASG capacity first, it should be minimum capacity=0, maximum capacity=1, desired capacity=1. If these are changed, deleting the Controller HA Cloudformation stack could have an impact on your current Controller * Log in to AWS Console, go to CloudFormation Service, identify the CloudFormation stack you used to enable Controller HA and delete the stack * **Please be careful,** and delete the cloudformation stack associated with the controller HA - and do not delete your controller launch cloudformation stack FAQ --- * How can I know which version of HA script I am running? versions.py file found in the AWS Lambda function with the name <controller_name>-ha would show the information. You can also see the version in the cloudwatch logs. Only versions from 1.5 and above are visible. * How can I get notification for H/A events? Enter an email address to receive notifications for autoscaling group events while launching the CFT. You would receive an email to subscribe to SNS. Click on the link from the email to accept SNS event notifications * My H/A event failed. What can I do? You can manually restore the saved backup to a newly launched controller. Please ensure controller H/A is disabled and re-enabled by deleting and re-creating the CFT stack to ensure that lambda is pointing to the right backup * How do I ensure that lambda is pointing to the right backup? In the AWS Lambda, verify if the INST_ID environment variable is updated correctly to the current controller instance ID and the PRIV_IP environment variable is updated to the current controller private IP. * Where do I find logs related to controller H/A ? All logs related to H/A can be found in AWS Cloudwatch under the log group <controller_name>-ha * How do I make lambda talk to the controller privately within the VPC? Launch CFT with Private access set to True. Attach lambda to the VPC from the AWS console. Ensure that the VPC that you have attached the lambda to has internet access via NAT gateway or VPC endpoints. You can also ensure that lambda has internet access by attaching an EIP(Elastic IP) to the lambda ENI(Network Interface). Please ensure that everything is reverted before you destroy the stack. Otherwise the lambda will not have internet access to respond to the CFT(CFT may get stuck on destroy). * Can two controllers in two different regions be linked such that they can detect if one or the other is down? Is this possible? Our Controller HA script leverages EC2 auto scaling. EC2 auto scaling doesn’t support cross regions but it does support cross AZs. The script will automatically bring up a new Controller in case the existing Controller enters an unhealthy state. * Could a controller in a different region be used to restore a saved configuration in case of disaster recovery? Will the change in controller’s IP cause any issues? A controller can be manually launched from a different region and the backed up configuration can be restored on it. The controller’s new EIP shouldn’t cause any issue unless SAML VPN authentication is being used. (All peering tunnels will still work). In that case, SAML VPN client will need reach the controller IP address. If FQDN hostname is used for the controller for SAML, then it should work after changing the Route 53 to resolve to the correct EIP in the different region. * How do I manage the controller HA stack if the controller instance's disk is encrypted? If EBS Encryption using Customer managed key is enabled, the Autoscaling Group created may not have permissions to launch the instance. You will need to allow the service-linked role created for the Autoscaling group to have permissions to use this key for the cryptographic operation. To do so, go to AWS KMS->Customer managed keys->select the key and add the "AWSServiceRoleForAutoScaling" role to the list of Key Users. * What do I need to do after I change the controller name? Please delete the CFT stack and then create a new CFT stack using the new controller name. Changelog --------- The changes from various releases can be viewed from `here <https://github.com/AviatrixSystems/Controller-HA-for-AWS/releases>`_ .. disqus:: <file_sep> .. toctree:: :numbered: ============================================================================== AWS SSO IdP for SAML Integration ============================================================================== Overview ------------ This guide provides an example on how to configure Aviatrix to authenticate against AWS SSO IdP. When SAML client is used, your Aviatrix controller acts as the Identity Service Provider (ISP) that redirects browser traffic from client to IdP (e.g., AWS SSO) for authentication. Before configuring SAML integration between Aviatrix and AWS SSO, make sure you have a valid AWS account with administrator access. .. tip:: If your AWS account is a consolidated account, you cannot set up SSO. SSO can only be enabled with a master account. Configuration Steps ------------------- Follow these steps to configure Aviatrix to authenticate against your AWS SSO IdP: Step 1. Retrieve `Aviatrix SP Metadata <#awssso-saml-sp-metadata>`__ from the Aviatrix Controller Step 2. Create an `AWS SSO SAML Application <#awssso-saml-app1>`__ for Aviatrix Step 3. Retrieve `AWS SSO IdP metadata <#awssso-idp-metadata>`__ Step 4. Update `Aviatrix SP Endpoint <#awssso-update-saml-endpoint>`__ in the Aviatrix Controller Step 5. `Test the Integration <#awssso-test-integration>`__ is Set Up Correctly .. _awssso_saml_sp_metadata: Step 1. Retrieve Aviatrix SP Metadata from Aviatrix Controller ############################################################## Before creating the AWS SSO SAML Application, AWS SSO requires the Service Provider (SP) metadata file from the Aviatrix Controller. You can create a temporary SP SAML endpoint to retrieve the SP metadata for now. Later on in the guide, the SP SAML endpoint will be updated. Visit one of the following links based on your use case and follow step1 (Create temporary Aviatrix SP Endpoint for Aviatrix) from the link's Configuration section: #. If integrating AWS SSO IdP with `Controller Login SAML Config <https://docs.aviatrix.com/HowTos/Controller_Login_SAML_Config.html#config-31>`_ #. If integrating AWS SSO IdP with `OpenVPN with SAML Authentication <https://docs.aviatrix.com/HowTos/VPN_SAML.html#config-31>`_ For AWS SSO, right click the **SP Metadata** button next to the SAML endpoint and save the file. |imageSPMetadataURL| .. tip:: Save this XML file to your local machine. It will be uploaded to the AWS SSO IdP in the later steps. This step will ask you to pick a short name to be used for the SAML application name ``[Endpoint Name]``. In the notes below we will refer to this as **aviatrix_awssso**. It can be any string that will identify the SAML application you create in the IdP. We will use the string you select for the SAML application name to generate a URL for AWS SSO to connect with Aviatrix. This URL is defined below as **SP_ACS_URL**. This URL should be constructed as: ``https://<<<your controller ip or host name>>>/flask/saml/sso/<<<aviatrix_awssso>>>`` .. tip:: Replace **<<<your controller ip or host name>>>** with the actual host name or IP address of your controller and **<<<aviatrix_awssso>>>** with the ``[Endpoint Name]`` you chose to refer to the SAML application. .. _awssso_saml_app1: Step 2. Create an AWS SSO SAML Application ########################################### .. note:: This step is usually done by the AWS SSO Admin. #. Login to your AWS console #. Go to the AWS Single Sign-On service #. Add a new Application (**Applications** > **Add a new application**) |imageAddAppsMenu| #. Click **Custom SAML 2.0 application** |imageSelectCustom| #. Enter a Display Name #. Scroll to **Application metadata** #. **Browse...** to the **SP Metadata** file saved in the `previous step (Step 1) <#awssso-saml-app>`_ #. Leave the **Application start URL** blank #. Click **Save changes** |imageAppMetadata| Add Attribute Mappings ++++++++++++++++++++++ #. Click on the **Attribute mappings** tab #. Add the following attributes: +----------------------------+-----------------------------------------+ | User attribute in the | Maps to this string value or user | | application | attribute in the AWS SSO | +============================+=========================================+ | FirstName | ${user:givenName} | +----------------------------+-----------------------------------------+ | LastName | ${user:familyName} | +----------------------------+-----------------------------------------+ | Email | ${user:email} | +----------------------------+-----------------------------------------+ As shown below: |attribute_mapping| #. Click **Save changes** .. _awssso_idp_metadata: Step 3. Retrieve AWS SSO IdP metadata ##################################### Copy the **AWS SSO IdP metadata file** URL. This URL will be provided to the Aviatrix SP endpoint later on. |imageCopyURL| .. _awssso_saml_app2: .. _awssso_update_saml_endpoint: Step 4. Update Aviatrix SP Endpoint ################################### .. note:: This step is usually completed by the Aviatrix admin. AWS SSO IdP provides IdP Metadata through URL obtained in `Retrieve AWS SSO IdP metadata (Step 3) <#awssso-idp-metadata>`_. AWS SSO IdP requires a custom SAML request template. Continue with updating Aviatrix SAML Endpoint by visiting one of the following links based on your use case: #. If integrating AWS SSO IdP with `Controller Login SAML Config <https://docs.aviatrix.com/HowTos/Controller_Login_SAML_Config.html#config-34>`_ #. If integrating AWS SSO IdP with `OpenVPN with SAML Authentication <https://docs.aviatrix.com/HowTos/VPN_SAML.html#config-34>`_ +----------------------------+-----------------------------------------+ | Field | Description | +----------------------------+-----------------------------------------+ | Endpoint Name | ``[Endpoint Name]`` | +----------------------------+-----------------------------------------+ | IPD Metadata Type | URL | +----------------------------+-----------------------------------------+ | IdP Metadata Text/URL | Paste in the | | | **AWS SSO SAML metadata file URL** | | | copied earlier from `AWS SSO dashboard <#awssso-idp-metadata>`_. | +----------------------------+-----------------------------------------+ | Entity ID | Select `Hostname` | +----------------------------+-----------------------------------------+ | Access | Select admin or read-only access | +----------------------------+-----------------------------------------+ | Custom SAML Request | Checked | | Template | | +----------------------------+-----------------------------------------+ .. note:: Each endpoint only supports one type of access. If you need admin and read-only access, create two separate SAML apps. `Hostname` is the default for Entity ID, but if you have other apps using the same hostname, use a custom Entity ID. |add_saml_endpoint| #. Remove the XML element ``<samlp:NameIdPolicy>..</samlp:NameIdPolicy>`` .. note:: This is required to connect with AWS SSO. If you don't do this, you will receive an error message when testing. #. Click **OK** #. Right click on the **SP Metadata** button next to the SAML endpoint just created and save the file to your local machine. |imageSPMetadataURL| .. tip:: Save this XML file to your local machine. It will be used in the next step. .. _awssso_test_integration: 5. Test the Integration ######################## .. tip:: Be sure to assign users to the new application in AWS Single Sign-on service prior to validating. You can use AWS SSO Directory service under AWS SSO page to assign users. If you do not assign your test user to the Aviatrix SAML application, you will receive an error. Continue with testing the integration by visiting one of the following links based on your use case: 1. If integrating AWS SSO IdP with `Controller Login SAML Config <https://docs.aviatrix.com/HowTos/Controller_Login_SAML_Config.html#config-35>`__ #. Click `Settings` in the left navigation menu #. Select `Controller` #. Click on the `SAML Login` tab 2. If integrating AWS SSO IdP with `OpenVPN with SAML Authentication <https://docs.aviatrix.com/HowTos/VPN_SAML.html#config-35>`__ #. Expand `OpenVPN®` in the navigation menu and click `Advanced` #. Stay on the `SAML` tab You can quickly validate that the configuration is complete by clicking on the **Test** button next to the SAML endpoint. |imageAvtxTestButton| .. |imageAddAppsMenu| image:: awssso_saml_media/add_new_application.png .. |imageSelectCustom| image:: awssso_saml_media/select_custom_application.png .. |imageCopyURL| image:: awssso_saml_media/copy_metadata_file_url.png .. |imageAvtxSAMLEndpoint| image:: awssso_saml_media/avx_controller_saml.png .. |imageSPMetadataURL| image:: awssso_saml_media/sp_metadata_button.png .. |imageAvtxTestButton| image:: awssso_saml_media/avtx_test_button.png .. |imageAppMetadata| image:: awssso_saml_media/application_metadata_save.png .. |add_saml_endpoint| image:: awssso_saml_media/add_saml_endpoint.png :scale: 30%% .. |attribute_mapping| image:: awssso_saml_media/attribute_mapping.png :scale: 30%% <file_sep> ============================================================ TGW Approval ============================================================ TGW VPN and TGW DXGW dynamically learns BGP routes from remote peer, Aviatrix Controller periodically pulls the TGW route table and propagate these routes to Spoke VPCs route table that have connection policy to the VPN. There are scenarios where you require an approval process before these learned CIDRs propagation take place. For example, a specific TGW VPN may be connected to a partner network and you need to make sure undesirable routes, such as the default route (0.0.0.0/0) are not propagated into your own network and accidentally bring down the network. |tgw_approval| Approval is enabled on per TGW VPN and TGW DXGW bases. When Approval is enabled on a TGW VPN, dynamically learned routes trigger an email to the Controller admin. Controller admin logins into the Controller and go to TGW > Approval, the admin should see the routes, both unapproved and already approved. Moving the routes from Pending Learned CIDRs panel to Approved Learned CIDRs panel allows those routes to be propagated. To enable Approval, go to TGW > Approval. Select the TGW and VPN/DXGW, click Learned CIDRs Approval to enable. How does it work? --------------------- When Approval feature is enabled, TGW route table route propagation to connected Security Domain is turned off. That is, the TGW VPN/DXGW learned routes are statically programmed into the TGW route table of connected Security Domains after the routes are approved. This is illustrated in the following two examples. Example 1: Two TGW VPN/DXGW in the same domain ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |tgw_two_vpn_approval| In the example above, two identical VPN CIDRs 10.10.1.0/24 are advertised to two TGW VPNs but are in the same domain. Both have Approval enabled. Whichever VPN attachment learns the CIDR first and is approved, its attachment is programmed into Spoke associated TGW route table, in this case, VPN1 attachment is approved first and is programmed into the Spoke associated TGW route table. VPN2 CIDR should continue to remain in pending list. If VPN1 withdraw route 10.10.1.0/24, you can initiate approval by moving the VPN2 pending CIDR to the approved panel, and this time it should be programmed. Example 2: One TGW VPN requires approval and another one does not ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |tgw_vpn_different_domains| In the second example, TGW VPN2 link 10.10.9.0/24 is in a different domain and does not require approval. Its route is propagated to the Spoke TGW route table, while TGW VPN1 link 10.10.1.0/24 is statically programmed to Spoke TGW route table after approval is initiated by the customer. Note in the second example, if TGW VPN2 link advertises the same network CIDR 10.10.1.0/24, this CIDR will be propagated first and TGW VPN1 approval request will be rejected and the CIDR 10.10.1.0/24 from TGW VPN1 remains in the approval pending list. .. |tgw_approval| image:: tgw_overview_media/tgw_approval.png :scale: 30% .. |tgw_two_vpn_approval| image:: tgw_approval_media/tgw_two_vpn_approval.png :scale: 30% .. |tgw_vpn_different_domains| image:: tgw_approval_media/tgw_vpn_different_domains.png :scale: 30% .. disqus:: <file_sep> =================================================== VPN User Accelerator =================================================== The VPN User Accelerator leverages the `AWS Global Accelerator <https://aws.amazon.com/global-accelerator/>`_ to connect VPN users to the nearest AWS Edge location access point and traverse the AWS backbone to the VPN Gateway. .. Note:: When this feature is enabled, the VPN user source address is masked out by AWS. .. To configure, 1. First `launch a VPN Gateway <https://docs.aviatrix.com/HowTos/uservpn.html>`_ by following the instructions. #. After the VPN is setup, an AWS NLB should be displayed on the left side panel, highlight it and click **Add**. Then click **OK**, as shown below. |user_accelerator| 3. From this point on, you can add VPN users which will use the new User Accelerator. .. Note:: * The new User Accelerator will reflect on the ovpn file's remote field. * For pre-existing users, the ovpn file has to be re-downloaded in order for AWS Global Accelerator to be reflected as the new remote endpoint. .. *OVPN File with User Accelerator OFF* |ovpn_using_elb| *OVPN File with User Accelerator ON* |ovpn_using_user_accelerator| OpenVPN is a registered trademark of OpenVPN Inc. .. |user_accelerator| image:: user_accelerator_media/user_accelerator.png :scale: 30% .. |ovpn_using_elb| image:: user_accelerator_media/ovpn_using_elb.png :scale: 30% .. |ovpn_using_user_accelerator| image:: user_accelerator_media/ovpn_using_user_accelerator.png :scale: 30% .. |imageArchitecture| image:: GeoVPN_media/architecture_overview.png .. |imageWithoutGeoVPN| image:: GeoVPN_media/architecture_without_geovpn.png .. |imageWithGeoVPN| image:: GeoVPN_media/architecture_with_geovpn.png .. |imageEnable| image:: GeoVPN_media/enable_geovpn.png .. |imageEnablePopulate| image:: GeoVPN_media/enable_geovpn_populate.png .. |imageAddAdditionalELB| image:: GeoVPN_media/add_additional_elb.png .. |imageAddAdditionalELBComplete| image:: GeoVPN_media/add_additional_elb_complete.png .. |imageComplete| image:: GeoVPN_media/geovpn_complete.png .. |imageAddVPNUser| image:: GeoVPN_media/add_vpn_user.png .. disqus:: <file_sep> =============================== Metered AMI Pricing Book =============================== To review the latest metered pricing information, see the `Aviatrix AWS Marketplace listing <https://aws.amazon.com/marketplace/pp/prodview-qzvzwigqw72ek?sr=0-3&ref_=beagle&applicationId=AWSMPContessa>`_. For questions on pricing, please `contact us <https://aviatrix.com/contact/>`_ or reach out to your Aviatrix account team. .. disqus:: <file_sep> ================================= Role-Based Access Control FAQ ================================= What is Aviatrix Role-Based Access Control (RBAC)? ---------------------------------------------------------- The Aviatrix Controller is a multi-cloud and multi-tenant enterprise platform. As such, the Aviatrix Controller manages multiple cloud accounts by requiring access by multiple administrators. RBAC provides access controls to protect the security and integrity of the Controller while providing the ability to delegate and limit specific Aviatrix features to groups defined by the admin of the Controller. Aviatrix RBAC aims to achieve two objectives: - **Granular Access Control** A Controller administrator in a specific permission group can perform certain tasks for a subset of Aviatrix `Access Account <https://docs.aviatrix.com/HowTos/aviatrix_account.html>`_. For example, an Administrative user can be limited to perform on his own AWS account VPC attachment function. - **Self Service** A Controller administrator in a specific permission group can onboard its own cloud accounts on the Controller and perform tasks. For example, a Controller administrator can be allowed to onboard his own AWS account on the Controller and create a group of users for different tasks on this access account. Another use case is for developers to have a read_only login permission to troubleshoot network connectivity issues. How does RBAC work? ---------------------- RBAC allows you to create a hierarchy of administrators within the Aviatrix Controller. It has the flexibility to permutate based on your requirements. The best way to explain how RBAC works is through examples. Below are a few deployment examples. RBAC Deployment Example 1 ------------------------------------------ In this example, the Controller admin creates a user, Bob, who has full responsibility to access account account-A and account-B. The Controller admin also creates another user, Alice, who has full responsibility to access account-C and account-D. |rbac_example_1| Tasks carried out by an Admin ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1. The admin creates an account admin group by logging in and navigating to Accounts > Permission Groups > **+Add New**. The admin gives the group a name, such as "account-admins." .. note:: For every new Permission Group, the admin has two additional options: * Toggle Local Login (disabled by default) – This setting determines whether users log into the Controller with a local password vs. an LDAP password. The admin can enable this setting to let users log in with a local password, which will allow users who are not registered in the Active Directory to log into the Controller. * Toggle Concurrent Session (enabled by default) – This setting determines whether users can have concurrent sessions, or multiple login sessions per user on different browser sessions. The admin can disable this setting to ensure that a user can only have one login session at a time. 2. The admin gives this group permission to create Access Accounts by navigating to Accounts > Permission Groups. The admin selects the group in the table > **Manage Permission**> **+Add New**. 3. The admin selects **Accounts** in the list of functions and **OK** to confirm. 4. The admin creates user Bob to the account_admins group by navigating to Account Users > **+New User**. The admin enters Bob in the name field and completes the other fields. For the field RBAC Groups, the admin selects account-admins created in step 1. Tasks carried out by Bob ~~~~~~~~~~~~~~~~~~~~~~~~~ 4. Bob should receive an email to invite him to access the Controller. Bob logs in and creates a new permission group with full access by navigating to Accounts > Permission Groups > **+Add New**. He enters a permission group name, for example, "group-bob." 5. Bob associates himself with the group-bob by navigating to Accounts -> Permission Groups and selecting bob-group. He clicks **Manage users** and selects "Bob" to associate himself with the group. 6. Bob grants group-bob functional privilege. He navigates to Accounts > Permission Groups and selecting **group-bob**. He clicks **Manage permissions** and then **ALLWrite** to grant group-bob the functional privilege. 7. Bob creates a new Access Account account-A by logging in and navigating to Accounts > Access Accounts > **+Add New**. For the field Attach to RBAC Groups, he selects **group-bob**. This creates an access account that associates a cloud account that Bob manages. For the Account Name field, Bob enters "account-A." Bob can repeat **Step 7** to create account-B. Now Bob has full functional access to both account-A and account-B. Apply **Step 3** to **Step 7** for Alice to manage account-C and account-D. Can Bob assign a teammate with subset of functional privileges? --------------------------------------------------------------------------------------- Yes. The deployment is shown in the diagram below. |rbac_example_2| Bob should perform the following tasks to set it up. 1. Bob creates a new permission group, such as "Site2Cloud-ops." 2. Bob assigns himself to the Site2Cloud-ops group. 3. Bob clicks **Manage permission** for Site2Cloud-ops group to select Site2Cloud permission for the group. 4. Bob clicks **Manage access accounts** for Site2Cloud-ops group to select account-A. 5. Bob creates a new user such as "Adam" and associates Adam to Site2Cloud-ops group. After the above tasks, Adam will be able to log in and perform Site2Cloud tasks for account-A. However, Adam cannot perform Site2Cloud tasks for Alice's account. How do I add a read_only user? ---------------------------------------------- Read_only user has visibility to all pages on the Controller and can perform troubleshooting tasks. A read_only user cannot make modifications to any functions or accounts. |rbac_example_3| In this example, Alice creates a read_only user George. Alice performs the following steps. 1. Alice logs in and navigates to Accounts > Account Users > **+Add New**. #. Alice adds a user named George and adds a User Name, User Email, and Password. For RBAC Groups, she selects read_only. Can there be multiple admin users? ---------------------------------------------------------- Yes. Only an admin can add more admin users. An admin user has the same privilege as the login admin with full access to all pages and accounts. In this example, an admin creates a new admin user, Jennifer. The admin performs the following steps. |rbac_example_4| 1. The admin logs in and navigates to Accounts > Account Users > **+Add New**. 2. The admin adds a user with the User Name "Jennifer," User Email, Password. For RBAC Groups, the admin selects **admin**. Does RBAC support remote authentications? ---------------------------------------------------------- RBAC supports remote authentication against LDAP, Duo, and other SAML IDPs. For LDAP and Duo, RBAC supports authentication only. The permissions are still validated locally on the Controller. For other SAML IDPs, you can configure profile attribute associated with the SAML user for permissions and avoid having to add users on the Controller. How do I set up SAML login for RBAC? ------------------------------------------------- The Aviatrix Controller login supports `SAML login. <https://docs.aviatrix.com/HowTos/Controller_Login_SAML_Config.html>`_ You have the option of authorizing users by Controller configuration or through SAML IDP Attribute. Go to Settings > Controller > SAML Login > **+ Add New**. If you select **Set Access By** to be 'SAML IDP attribute', follow the instructions to setup SAML. In the SAML IDP Attribute Statements, add a new attribute, "Profile." For the Value field, add the Name of the Permission Groups you configured on the Controller. When a user authenticates against SAML IDP, the Controller retrieves the profile attribute and apply permission to the user. There is no need to configure account users on the Controller, but you still need to specify Permission Groups and their associated permissions. If you select **Set Access By** to be "Controller," you need to select an RBAC Group when creating an IDP endpoint. .. |rbac_example_1| image:: rbac_faq_media/rbac_example_1.png :scale: 50% .. |rbac_example_2| image:: rbac_faq_media/rbac_example_2.png :scale: 50% .. |rbac_example_3| image:: rbac_faq_media/rbac_example_3.png :scale: 50% .. |rbac_example_4| image:: rbac_faq_media/rbac_example_4.png :scale: 50% .. |account_structure| image:: adminusers_media/account_structure_2020.png :scale: 50% .. |access_account_35| image:: adminusers_media/access_account_35.png :scale: 50% .. disqus:: <file_sep> **A few important notes before we launch the instance:** 1. This document complements the existing deployment guide that was designed to help you to associate a Palo Alto VM-Series. We are going to assume that you have completed all the steps from 1 to 6 before launching this firewall instance. Step 7a is not necessary as it is Palo Alto VM-Series specific. 2. Currently we do not have a full integration between the Aviatrix dashboard and the CloudGuard, which means that you will not be able to update the firewall routing table via API, as it is currently possible with the Palo Alto VM-Series. 3. The Check Point CloudGuard has mainly two types of deployments – standalone or distributed – which basically means whether you are going to have both the Gateway and the Management Server on the same instance. Since we currently CANNOT configure the firewall policies without the management server, we need to configure a management server. Also, we need to consider that the Aviatrix gateways within the FireNet VPC will monitor whether the Check Point gateway instance is up or not. That being said, only versions R77.30 and R80.10 support standalone deployments, while another possibility is to have a single R80.20 Management Server inside the management subnet to control multiple CloudGuard instances (although this is not part of the scope. For more information, try this `link <https://supportcenter.checkpoint.com/supportcenter/portal/user/anon/page/default.psml/media-type/html?action=portlets.DCFileAction&eventSubmit_doGetdcdetails=&fileid=24831>`_. 4. For more information on the differences across the available models/versions we suggest the following `link <https://supportcenter.checkpoint.com/supportcenter/portal?eventSubmit_doGoviewsolutiondetails=&solutionid=sk95746>`_. Check Point has recommended the upgrade to R80 as part of their roadmap. For more information regarding such advisories, please check this `link <https://supportcenter.checkpoint.com/supportcenter/portal?eventSubmit_doGoviewsolutiondetails=&solutionid=sk110980>`_. 5. For the purpose of this installation guide, we are going to consider only version R80.10 in standalone mode using the latest CloudFormation template available at the time this document was written 6. You have access to a Windows client so you can run the SmartConsole, which is provided by Check Point and is specific per version of CloudGuard being installed. You can use this link: `R80.10 <https://supportcenter.checkpoint.com/supportcenter/portal?eventSubmit_doGoviewsolutiondetails=&solutionid=sk119612>`_. ========================================================= Setup Firewall Network(Firenet) ========================================================= Complete steps 1-6 of the Firewall Network Workflow in Aviatrix controller to prepare your Firewall VPC (FireNet VPC). This will also set up the subnets that you will need for launching your Checkpoint instance. ========================================================= Deploy Checkpoint instance From AWS marketplace ========================================================= a. Go to aws.amazon.com/marketplace and search for the chosen instance model/version in AWS Marketplace. Click “Continue to Subscribe” |image1| b. On the next screen, accept the terms and you should be able to continue. If you have chosen any of the R80 versions, you should be able to launch it using one of the CloudFormation `templates <https://supportcenter.checkpoint.com/supportcenter/portal?eventSubmit_doGoviewsolutiondetails=&solutionid=sk111013>`_.. For the purpose of this guide, we are going to use template 15 (standalone into existing VPC). If you a Management Server deployed already you should use template 2 instead. c. This template will configure the first interface (eth0) as “external” and the second (eth1) as “internal”. For consistency purposes we suggest keeping eth0 as egress and management and eth1 for LAN. d. The template should look like this (if you have selected existing VPC). Please make sure your interfaces are in the same AZ. |image2| e. For the next part of the template, please make sure you have created/downloaded your pem key, as well as selected the proper instance size.For information on the networking features of each instance type, we recommend the following `link <https://aws.amazon.com/ec2/instance-types/>`_. |image3| |image4| |image5| f. After you click on “Create stack” you should go to CloudFormation to monitor the stack creation. Once the status is set to “CREATE_COMPLETE” you should be able to move on. Any different warning can be troubleshooted by checking the details in the “Outputs” tab are they are usually self-explanatory. g. Now go to the EC2 instances to monitor the status check – once they are done, you should be able to SSH into the instance |image6| h. Now that the instance is up – open your preferred terminal and SSH into the instance using the proper keys and the user “admin”. It takes only two commands to set a new password |image7| |image8| i. Please open a browser and go to https://management_eip/ to log into the Gaia Portal. You should be prompted with a screen like the one below. Just enter the user name as admin and the password you have just configured on the previous step. |image9| j. Go to Network Management > Network Interfaces. You should simply double-check whether all interfaces are active and with a valid IP address; k. The next step is to update the route table. For the purpose of this guide, we suggest adding three return routes, each for a RFC1918 address pointing back to the VPC router of the subnet aviatrix*dmz-firewall (or aviatrix*hagw-dmz-firewall if you are attaching the instance to the backup gateway instead). Please go to the AWS console > VPC > Subnets and filter by “dmz-firewall” – that will allow you to determine the VPC router IP, which is the first host of each subnet |image10| l. Once you have determined the IP of the next hop, just go to IPv4 Static Routes and click on “Add”. Repeat this step for all three RF1918 subnets |image11| m. Great. Now please download and install the SmartConsole if you have not done it already please download using this link: `R80.10 <https://supportcenter.checkpoint.com/supportcenter/portal?eventSubmit_doGoviewsolutiondetails=&solutionid=sk119612>`_. On SmartConsole you need to define a security policy that will allow the traffic to be inspected/logged and update the topology. n. In the SmartConsole go to via Security Policies and then Policy and change the default policy to ‘accept’ traffic and to ‘Log’ it as well. This can (and SHOULD) be customized to comply with your project requirements. Finally, install the policy on the gateway(s) in question. Your basic policy should look like this |image12| o. As per the topology page, it can be reached via Gateways & Servers and a double-click on the gateway itself. Then click on Network Management > Get Interfaces. |image13| p. The final step is to monitor your traffic to confirm that the inspection is being performed as configured. Go to Logs & Monitor. |image14| q. You are now good to repeat this process to attach another CloudGuard instance to the backup Aviatrix gateway. The difference regarding the backup gateway attachment is that the subnets should be in a different AZ r. For more information on the Firewall network solution, please refer to this `link <https://docs.aviatrix.com/HowTos/firewall_network_faq.html>`_. .. |image1| image:: ./config_Checkpoint_media/image1.png :width: 100% .. |image2| image:: ./config_Checkpoint_media/image2.png :width: 100% .. |image3| image:: ./config_Checkpoint_media/image3.png :width: 100% .. |image4| image:: ./config_Checkpoint_media/image4.png :width: 100% .. |image5| image:: ./config_Checkpoint_media/image5.png :width: 100% .. |image6| image:: ./config_Checkpoint_media/image6.png :width: 100% .. |image7| image:: ./config_Checkpoint_media/image7.png :width: 100% .. |image8| image:: ./config_Checkpoint_media/image8.png :width: 100% .. |image9| image:: ./config_Checkpoint_media/image9.png :width: 100% .. |image10| image:: ./config_Checkpoint_media/image10.png :width: 100% .. |image11| image:: ./config_Checkpoint_media/image11.png :width: 100% .. |image12| image:: ./config_Checkpoint_media/image12.png :width: 100% .. |image13| image:: ./config_Checkpoint_media/image13.png :width: 100% .. |image14| image:: ./config_Checkpoint_media/image14.png :width: 100% <file_sep> ====================================== Aviatrix Companion Gateway in Azure ====================================== If you need to launch an Aviatrix Gateway in Azure, you must subscribe to **Aviatrix Companion Gateway** in **Azure Marketplace**. This model removes the requirement to download the Aviatrix Gateway image into your Azure account which typically takes more than 30 minutes, thus greatly reducing the deployment time. The Aviatrix Companion Gateway in the Azure marketplace is free of charge. The following steps describe how to subscribe to an Aviatrix Companion Gateway in Azure marketplace. 1. To select an Aviatrix Companion Gateway, go to the `Azure Marketplace <https://azuremarketplace.microsoft.com/en-us/marketplace/apps/aviatrix-systems.aviatrix-companion-gateway-v5?tab=Overview>`_ and subscribe to Companion Gateway V8. |companion_gw| 2. Click **Want to deploy programmatically? Get started ->**. |get_started| 3. To enable the subscription, select **[Enable]** and click **[Save]**. |enable_program| For support, please go to `Aviatrix Support <https://support.aviatrix.com>`_ and open a ticket. .. |image0| image:: CompanionGateway_media/img_01.PNG .. |image1| image:: CompanionGateway_media/img_02.PNG .. |image2| image:: CompanionGateway_media/img_03_enable_and_save.PNG .. |companion_gw| image:: CompanionGateway_media/companion_gw.png :scale: 30% .. |get_started| image:: CompanionGateway_media/get_started.png :scale: 30% .. |enable_program| image:: CompanionGateway_media/enable_program.png :scale: 30% .. disqus:: <file_sep> .. raw:: html <style> /* override table no-wrap */ .wy-table-responsive table td, .wy-table-responsive table th { white-space: normal !important; } </style> =============================================================== LDAP Configuration for Authenticating VPN Users =============================================================== Overview -------------------- Aviatrix provides integration with an LDAP/AD server for the authentication of users logging into the VPN services. This guide walks you through the configuration steps. Configuration Details -------------------------------- .. note:: This step must be done by an existing Aviatrix Controller admin user. .. tip:: This configuration before or after a gateway is created. These steps assume it is done after creation. #. Log in to your Controller. #. Select **OpenVPN** on the left sidebar. #. Select **Edit Config**. #. In the **Modify Authentication** section, click on the **LDAP** below the Authentication label. |imageLDAPForm| #. Enter the values as described in the table below. +-------------------------+-------------------------------------------------+ | Field | Description | +=========================+=================================================+ | LDAP Server | Enter the public IP or hostname for the LDAP | | | / AD server. | +-------------------------+-------------------------------------------------+ | Use TLS to connect to | When this checkbox is marked, STARTTLS is used | | LDAP server | to connect with the LDAP server. NOTE: LDAP Over| | | SSL is not supported (port 636). | +-------------------------+-------------------------------------------------+ | Client Certificate | Only visible if the **Use TLS to connect ...** | | | checkbox is marked. | | | This file must be in PEM format and contain a | | | public and private key pair. | +-------------------------+-------------------------------------------------+ | CA Certificate | Only visible if the **Use TLS to connect ...** | | | checkbox is marked. | +-------------------------+-------------------------------------------------+ | Bind DN | DN of the user that the Gateway will use to | | | authenticate with the LDAP server to handle | | | user authentication. | +-------------------------+-------------------------------------------------+ | Password | The password of the Bind DN user. | +-------------------------+-------------------------------------------------+ | Base DN for User Entries| Starting point in the directory for searching | | | for matching usernames. | +-------------------------+-------------------------------------------------+ | Username Attribute | User attribute name for username to match. | +-------------------------+-------------------------------------------------+ | Group Membership DN | LDAP | | (Optional) | `search <https://ldap.com/ldap-filters/>`__ | | | filter. This value must be entered in the | | | form of a query. For example:\ | | | | | | *for Linux OpenLDAP:\ | | | ``memberOf=cn=vpn_users,DC=example,DC=com``\ | | | | | | *for Windows Active Directory:\ | | | ``cn=vpn_users,DC=example,DC=com``\ | +-------------------------+-------------------------------------------------+ | LDAP User (Optional) | This field is only used when you click | | | **Test LDAP Configuration**. It will use | | | this value to search and respond if it was | | | able to connect and find the user. | +-------------------------+-------------------------------------------------+ | LDAP User (Optional) | This field is only used when you click | | | **Test LDAP Configuration**. It will use | | | this value to search and respond if it was | | | able to connect and find the user. | +-------------------------+-------------------------------------------------+ #. Enter a value for **LDAP User** and click **Test LDAP Configuration** to test the configuration. #. Click **Modify** to save this configuration. .. |imageLDAPForm| image:: vpnusers_ldap_media/ldapform.png :scale: 50% <file_sep> ========================================================= Vendor Integration ========================================================= Aviatrix Transit DMZ works with any firewall instances. However, API level integration allows the DMZ solution to provide significantly improved automation. Launch Palo Alto Networks VM-Series Instance ---------------------------------------------- You can launch a Palo Alto Networks VM-Series from the Aviatrix Controller. Make sure you have subscribed to the the AMI. Enter the fields below and click Launch. ========================================== ========== **Setting** **Value** ========================================== ========== Cloud Type Select AWS. Instance Name Give the VM-Series instance a name. Account Name The account name for the transit VPC. Region One of the AWS region. VPC ID The VPC to launch the firewall instance. Firewall Image Select one of the Palo Alto VM-Series AMI to launch. Management Subnet VM-Series management interface, must be a public subnet with EIP. Egress Subnet VM-Series instance for Internet, must be a public subnet with EIP. Main Interface Subnet VM-Series instance interface for Aviatrix Main gateway. Companion Interface Subnet VM-Series instance interface for Aviatrix Companion gateway. ========================================== ========== .. Tip:: After the instance is launched, it will be listed in the same page. Wait for 15 minutes after you launch the VM-Series instance before you login to instance to setup the password. To login to the instance, click the skewer button to download the pem file for the instance. Note eth1 is management interface, eth0 is egress interface, eth2 and eth3 are north and south interfaces. |download_pem_file| Palo Alto Networks VM-Series Configuration -------------------------------------------- In the release 4.1, the supported firewall vendor is Palo Alto Networks VM-Series Firewall in AWS. For how to configure Palo Alto Networks, refer to `this guide. <https://docs.paloaltonetworks.com/vm-series/8-1/vm-series-deployment/set-up-the-vm-series-firewall-on-aws/deploy-the-vm-series-firewall-on-aws/launch-the-vm-series-firewall-on-aws.html#ide07b93a2-ccb3-4c69-95fe-96e3328b8514>`_ Follow the following steps to enable Palo Alto Networks API programming. 1. Enable Ping ~~~~~~~~~~~~~~~~~~ Make sure that the Palo Alto Networks management interface has ping enabled and the instance's security group has ICMP policy open to the Aviatrix Controller's public IP address. |pan_ping| 2. Create API Administrator Role Profile ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Create a new role profile and name it Aviatrix-API-Role. Edit the profile to enable Report, Configuration, Operation Requests and Commit for the tab XML API. This allows the Aviatrix Controller to update the relevant route entries the Palo Alto Network interfaces. Go to Device -> Setup -> Management Interface Settings, as shown below. |pan_role_profile| 3. Add an Administrator for API ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ At the Palo Alto Networks Console, go to Device -> Administrators -> +Add, to add an administrator for Role Based access as shown below. Use the profile created in previous step. |pan_admin| 5. Configure on the Aviatrix Controller ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Login to the Aviatrix Controller, go to Transit DMZ -> Vendor Integration. Configure the following parameters. ========================================== ========== **Setting** **Value** ========================================== ========== Transit VPC ID The Transit VPC ID for the Transit DMZ deployment. . Firewall instance ID The firewall EC2 instance ID. Aviatrix Controller monitors the health of this instance and determines fail over when it becomes unreachable. Firewall Name (Optional) A name to remember. Firewall Vendor Type Select PAN Firewall Login User Name firewall login name for API calls from the Controller. Firewall Login Password firewall login password for API calls. Firewall Management IP Address The public IP address of the firewall management interface for API calls from the Aviatrix Controller Firewall Virtual Router name (Optional) Specify the firewall virtual Router name you wish the Controller to program. If left unspecified, the Controller programs the firewall's default router. ========================================== ========== 4. API calls ~~~~~~~~~~~~~~~~ The integrated functions by the Controller are the following: - The Controller monitors the health of Palo Alto Network software by using the VM-series API and performs switch over based on the API return status. - The Controller dynamically programs Palo Alto Network route tables for any new propagated new routes discovered both from new Spoke VPCs and new on-premise routes. Example of Palo Alto Networks API used: 1. get key: :: https://172.16.58.3/api/?password=<PASSWORD>&type=keygen&user=apiadmin 2. get route tables: :: https://172.16.58.3/api/?type=config&xpath=/config/devices/entry[@<EMAIL>']/network/virtual-router/entry[@name='default']&key=<KEY>=&action=get 3. show interfaces: :: https://172.16.58.3/api/?key=<KEY>=&type=op&cmd=<show><interface>ethernet1/2</interface></show> 4. add route: :: https://172.16.31.10/api/?type=config&xpath=/config/devices/entry[@<EMAIL>']/network/virtual-router/entry[@name='default']/routing-table/ip/static-route/entry[@name='test2']&key=<KEY>1NXEzeDBnST0=&action=set&element=<nexthop><ip-address>10.201.1.1</ip-address></nexthop><bfd><profile>None</profile></bfd><path-monitor><enable>no</enable><failure-condition>any</failure-condition><hold-time>2</hold-time></path-monitor><metric>10</metric><destination>10.40.0.0/24</destination><route-table><unicast/></route-table> 5. delete route: :: https://172.16.31.10/api/?type=config&xpath=/config/devices/entry[@<EMAIL>']/network/virtual-router/entry[@name='default']/routing-table/ip/static-route/entry[@name='test2']&key=<KEY>=&action=delete 6. commit :: https://172.16.31.10/api/?type=commit&key=<KEY>=&cmd=<commit></commit> .. |main_companion_gw| image:: transit_dmz_workflow_media/main_companion_gw.png :scale: 30% .. |pan_admin| image:: transit_dmz_vendors_media/pan_admin.png :scale: 30% .. |download_pem_file| image:: transit_dmz_vendors_media/download_pem_file.png :scale: 30% .. |pan_role_profile| image:: transit_dmz_vendors_media/pan_role_profile.png :scale: 30% .. |pan_ping| image:: transit_dmz_vendors_media/pan_ping.png :scale: 30% .. disqus:: <file_sep>$(function() { $('.wy-breadcrumbs-aside').append('<br /><a href="https://aviatrix.com/schedule-demo/">&raquo; Request Product Demo</a>'); $('.wy-menu-vertical > ul.current').prev().addClass('active'); $('.wy-menu-vertical > p.caption').on('click', function(e){ e.preventDefault(); $(this).toggleClass('active'); }); });<file_sep> Peering =========== Encrypted Peering ^^^^^^^^^^^^^^^^^^^^ Aviatrix provides a point-and-click solution to create an encrypted tunnel between two VPC/VNets. The two VPC/VNets could be in the same region, in different regions (inter region), and in different clouds (inter cloud). This guide helps you configure an encrypted peering. For cluster peering, refer to `this doc. <http://docs.aviatrix.com/HowTos/Cluster_Peering_Ref_Design.html>`__ 1. At the Gateway menu, create a gateway in an existing VPC/VNet. 2. Repeat the step 1 for a different VPC/VNet. 3. To enable Peering HA, go to Peering > Encrypted Peering > New peering, select the two gateways launched in the previous two steps. * Select **Enable HA** if you wish to build a backup encrypted tunnel for HA. * Note that you must first create two respective backup gateways prior to this step. To launch backup gateways, go to the Gateway page, select the gateway, click **Edit**, at the Gateway for High Availability Peering field, select one subnet (public in AWS, GCP, and OCI), and click **Create**. 4. Go to Peering > Encrypted Peering and click **New Peering** to peer the two gateways. .. Note:: If the two gateways have `Insane Mode Encryption <https://docs.aviatrix.com/HowTos/gateway.html#insane-mode-encryption>`_ enabled, the Controller automatically creates an AWS VPC Peering (PCX)/Azure VNet Peering and establishes high performance encrypted peering between the two gateways. AWS VPC Peering ^^^^^^^^^^^^^^^^^^^ The Aviatrix Controller integrates native AWS `VPC Peering <https://www.aviatrix.com/learning/cloud-routing-networking/aws-vpc-peering/>`_ for both intra region peering and inter region peering, where it is available. Cross account peering is also supported. We have made it simple for AWS VPC Peering by integrating route table programming and integrating requester and acceptor into one step. You can also decide which route table to participate in the AWS VPC Peering. To configure: :: 1. Go to Peering > AWS Peering > New Peering. 2. Select the account, region, and VPC. 3. You can choose to build the peering for the entire VPC or select individual route tables. 4. Click **OK**. Azure VNET Peering ^^^^^^^^^^^^^^^^^^^^^^^ The Aviatrix Controller integrates native Azure `VNET Peering <https://docs.microsoft.com/en-us/azure/virtual-network/virtual-network-peering-overview/>`_ for both intra region peering and inter region peering. Cross subscription peering is also supported as long as both subscriptions are onboarded to the controller. To configure: :: 1. Go to Peering > Azure Peering > New Peering. 2. Select the subscription, region, and VNET. 3. Click **OK**. Azure VNET Peering ^^^^^^^^^^^^^^^^^^^^^^^^^ The Aviatrix Controller integrates native Azure `VNET Peering <https://docs.microsoft.com/en-us/azure/virtual-network/virtual-network-peering-overview>`_ for both intra region peering and inter region peering. Cross subscription peering is also supported as long as both subscriptions are onboarded into the controller. To Configure: :: 1. Go to Peering > Azure Peering > New Peering. 2. Select the subscription, region and VNET. 3. Click **OK**. MultiCloud Peering ^^^^^^^^^^^^^^^^^^^^^^^^^^ MultiCloud Peering configuration is the same way as Encrypted Peering. You launch two gateways in a VPC or VNet, follow the `Encrypted Peering <http://docs.aviatrix.com/HowTos/peering.html#encrypted-peering>`_ to complete. .. disqus:: <file_sep> ================================================================================ Configuring Azure Multi-Peer BGP over LAN with Azure Route Server Integration ================================================================================ Introduction ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The Aviatrix Controller allows Azure Route Server (ARS) integration for on-premises connectivity using Azure ExpressRoute with no overlay. Azure Route Server is a managed service that is highly available. It provides a mechanism for exchanging routes between Azure Software Defined Networking (SDN) and Network Virtual Appliances (NVAs) dynamically through Border Gateway Protocol (BGP). You can achieve full-mesh high availability by running two BGP peering endpoints. Aviatrix integrates with Azure Route Server by treating the Azure Route Server as a BGP over LAN peer and exchanging routes using BGP. This enables Azure cloud networks to connect to on-prem or branch locations and provides connectivity across hybrid environments. Customers who use high-speed Azure ExpressRoute connectivity with no encryption for hybrid environments can exchange routes between the Aviatrix Transit Gateways and the on-prem network connected via ExpressRoute. This solution provides you with an enterprise-grade transit network. The diagram below shows Azure Route Server integration with Aviatrix Transit Gateways. Full mesh is enabled so that both Transit Gateways peer with the two Azure Route Server IP endpoints in the Azure Route Server. |ARS_High_Level| Related Topics ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ * `Azure Multi-Cloud Transit BGP over LAN Workflow <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_azure_workflow.html>`_ * `Azure Multi-Peer BGP over LAN Workflow <https://docs.aviatrix.com/HowTos/azure_bgpolan_multi_peer.html>`_ * `AWS Multi-Cloud Transit BGP over LAN Workflow <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_workflow.html>`_ * `GCP Multi-Peer BGP over LAN Workflow <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_gcp_workflow.html>`_ Prerequisites ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ * Aviatrix Controller is updated to software version 6.8 or above. * Aviatrix Transit Gateways are deployed with Insane Mode (mandatory) and with BGP over LAN enabled. You only need to configure one BGP over LAN interface to peer with both Azure Route Server instances. |prereq_insane_mode_bgpolan| * A BGP ASN is assigned to the Transit Gateways (configured on the Aviatrix Controller in Multi-Cloud Transit > Advanced Config > Local AS Number). Complete the following tasks in Azure: * Create a VNet to deploy the Azure Route Server. * Deploy the Azure Route Server in this VNet by referring to the applicable Azure documentation. * Go to your Route Server > Overview and record the ASN and the private IP addresses of the Azure Route Server endpoints you created. You will use these later in the Aviatrix Controller configuration. |prereq_ASN_private_IP| Configuring Azure BGP over LAN with Azure Route Server Integration ----------------------------------------------------------------------------------------- Configure VNet Peering Between Transit VNet and Azure Route Server ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ You need to configure the VNet peering between the VNet that is hosting the Azure Route Server and the Aviatrix Transit VNet. Follow these steps to configure the peering parameters from the Azure Route Server VNet to the Aviatrix Transit VNet. .. important:: If you are using Terraform, make sure to explicitly set the argument “allow_forwarded_traffic” to “True” for both VNet peerings. 1. Launch the Azure Portal. 2. Go to Virtual networks and select your Route Server VNet. * Under Settings, click **Peerings**. * On the Peerings page, click **Add**. * On the Add peering page, select the following options: +------------------------------------------------+--------------------------------------------+ | **Setting** | **Value** | +------------------------------------------------+--------------------------------------------+ | Traffic to remote virtual network | Allow | +------------------------------------------------+--------------------------------------------+ | Traffic forwarded from remote virtual network | Allow | +------------------------------------------------+--------------------------------------------+ | Virtual network gateway or Route Server | Select the appropriate Azure account | +------------------------------------------------+--------------------------------------------+ |add_peering| 3. Go to Virtual networks and select your peered Transit Server VNet. * Under Settings, click **Peerings**. * On the Peerings page, click **Add**. * On the Add peering page, select the following options: +--------------------------------------------------+--------------------------------------+ | **Setting** | **Value** | +--------------------------------------------------+--------------------------------------+ | Traffic to remote virtual network | Allow | +--------------------------------------------------+--------------------------------------+ | Traffic forwarded from remote virtual network | Allow | +--------------------------------------------------+--------------------------------------+ | Virtual network gateway or Route Server |Select **Use the remote virtual | | |network’s gateway or Route Server** | +--------------------------------------------------+--------------------------------------+ |use_remote_virtual_network| Click **Add**. Configure BGP peering Between Azure Route Server and Transit Gateways ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1. In your Aviatrix Controller, go to Multi-cloud Transit > List, select your primary Transit gateway and click **Details/Diag**. Then, click on Gateway Interface Info and record the IP address assigned to the BGP over LAN interface of both the primary and HA Transit gateways. |gateway_interface_info| 2. In your Azure portal, go to Route Servers > select your Azure Route Server > Peers. Click **Add** and configure the Azure Route Server peering to both remote Aviatrix Transit Gateways in the Transit VNet by specifying the ASN you configured for your Aviatrix Transit Gateways and the IP address of the BGP over LAN network interface on each Transit Gateway. See the Prerequisites section to find the ASN number. |ars_peers| 3. Go to Route Servers > select your Azure Route Server > Configuration. 4. Next to Branch-to-branch, select **Enabled**. This option allows the Azure Virtual Network Gateways to propagate the routes the Azure Route Server has learned from the Aviatrix Transit Gateways. It is disabled by default. |enable_branch-to-branch| Configure External Connection in Controller ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1. Open the Aviatrix Controller. 2. Go to Multi-Cloud Transit > Setup > External Connection. 3. In Connect to VGW / External Device / Azure VNG, select the following options: * External Device * BGP * LAN 4. Use the VPC Name / Site ID drop-down menu to select the Transit Gateway. 5. Mark the checkbox for **Enable Remote Gateway HA**. 6. Mark the checkbox to enable **BGP Activemesh**. .. note:: The BGP Activemesh option is only available when you select a Transit Gateway in VPC Name / Site ID. When you select BGP Activemesh, Aviatrix Controller creates two peers from each Transit Gateway to both instances of Azure Route Server. This is required for the correct operation of Azure Route Server. 7. In the remaining fields, enter the ARS IP addresses. Use the IP addresses for each Azure Route Server instance as reported in the Azure portal. .. note:: Azure Route Server always resides in ASN 65515 and cannot be changed. +--------------------------------+------------------------------------------------------------+ | **Setting** | **Value** | +--------------------------------+------------------------------------------------------------+ | Remote BGP AS number |65515 | +--------------------------------+------------------------------------------------------------+ | Remote vnet:rg:sub |ARS VNET | +--------------------------------+------------------------------------------------------------+ | Remote LAN IP |ARS instance 0 IP address | | | | | |**Note**: the Prerequisites section above shows where to | | |find the Azure Route Server IP addresses. | +--------------------------------+------------------------------------------------------------+ |Local LAN IP |Primary Transit Gateway BGPoLAN IP address | | | | | |**Note**: The BGPoLAN IP address of the gateway is | | |automatically suggested here. | +--------------------------------+------------------------------------------------------------+ | Remote BGP AS number (Backup) |65515 | +--------------------------------+------------------------------------------------------------+ | Remote LAN IP (Backup) |ARS instance 1 IP address | +--------------------------------+------------------------------------------------------------+ | Local LAN IP (Backup) | HA Transit Gateway BGPoLAN interface IP address | +--------------------------------+------------------------------------------------------------+ .. note:: To confirm that the Aviatrix Controller set up the Azure Network Virtual Appliance (NVA) peering in Steps 5 and 6, go to Multi-Cloud Transit > BGP > Connections. You may need to use the sorting tool in the Remote AS Num column to identify the pairs of Route Servers. In the HA Status column, confirm that Activemesh is the status for the Route Servers and confirm that Neighbor Status is established. You can also use CoPilot to check the status of the BGP peerings to the Azure Route Server and the BGP routes learned/advertised. In CoPilot, go to Cloud Routes > BGP Info and click on the BGP Map, Learned Routes, or Advertised Routes button to get more details. |check_status| |copilot_bgp_info| .. |ARS_High_Level| image:: azure_bgpolan_multi_peer_ars_media/ARS_High_Level.png :scale: 20% .. |prereq_insane_mode_bgpolan| image:: azure_bgpolan_multi_peer_ars_media/prereq_insane_mode_bgpolan.png :scale: 60% .. |prereq_ASN_private_IP| image:: azure_bgpolan_multi_peer_ars_media/prereq_ASN_private_IP.png :scale: 60% .. |add_peering| image:: azure_bgpolan_multi_peer_ars_media/add_peering.png :scale: 60% .. |use_remote_virtual_network| image:: azure_bgpolan_multi_peer_ars_media/use_remote_virtual_network.png :scale: 60% .. |gateway_interface_info| image:: azure_bgpolan_multi_peer_ars_media/gateway_interface_info.png :scale: 20% .. |ars_peers| image:: azure_bgpolan_multi_peer_ars_media/ars_peers.png :scale: 60% .. |enable_branch-to-branch| image:: azure_bgpolan_multi_peer_ars_media/enable_branch-to-branch.png :scale: 60% .. |check_status| image:: azure_bgpolan_multi_peer_ars_media/check_status.png :scale: 60% .. |copilot_bgp_info| image:: azure_bgpolan_multi_peer_ars_media/copilot_bgp_info.png :scale: 60% .. disqus:: <file_sep> .. raw:: html <style> /* override table no-wrap */ .wy-table-responsive table td, .wy-table-responsive table th { white-space: normal !important; } </style> =============================================================== Controller LDAP Login Configuration =============================================================== Overview -------- Aviatrix allows you to configure LDAP authentication for users logging into the Controller. At the login prompt for the Controller, the user will enter their username and LDAP/AD password to authenticate. Configuration Details --------------------- .. note:: This step must be done by an existing Aviatrix Controller admin user. #. Login to your Controller #. Go to the **Settings** navigation menu item #. Select **Controller** #. Click on the **LDAP Login** tab |imageLDAPForm| #. Enter the values as described in the table below +-------------------------+-------------------------------------------------+ | Field | Description | +=========================+=================================================+ | Status | Select `Enabled` to enable LDAP login on the | | | Controller. | +-------------------------+-------------------------------------------------+ | LDAP Server | Enter the IP or hostname of the LDAP | | | / AD server. | +-------------------------+-------------------------------------------------+ | LDAP Port | UDP Port 389 is the standard port for both | | | encrypted LDAP (using STARTTLS) and non- | | | encrypted connections. | +-------------------------+-------------------------------------------------+ | Bind DN | DN of the user that the Controller will use to | | | authenticate with the LDAP server to handle | | | user authentication. | +-------------------------+-------------------------------------------------+ | Password | The <PASSWORD> of the `Bind DN` user. | +-------------------------+-------------------------------------------------+ | Base DN | Starting point in the directory for searching | | | for matching usernames. | +-------------------------+-------------------------------------------------+ | Username Attribute | User attribute name for username to match. | +-------------------------+-------------------------------------------------+ | LDAP User | This field is only used when clicking on the | | | `Test LDAP Configuration` button. It will use | | | this value to search and respond if it was | | | able to connect and find the user. | +-------------------------+-------------------------------------------------+ | Use TLS to connect to | When checked, STARTTLS is used to connect with | | LDAP server | the LDAP server. NOTE: LDAP Over SSL is not | | | supported (port 636). You'd have to provide a | | | FQDN for the LDAP server if TLS is turned on. | +-------------------------+-------------------------------------------------+ | Client Certificate | Only visible if `Use TLS to connect ...` is | | | checked. | +-------------------------+-------------------------------------------------+ | CA Certificate | Only visible if `Use TLS to connect ...` is | | | checked. | +-------------------------+-------------------------------------------------+ #. Enter a value for `LDAP User` and click **Test LDAP Configuration** to test the configuration #. Click **Save** to save this configuration Considerations --------------- * LDAP authentication requires that local user accounts be created on the Controller. The username configured in the `Account Users` must match the username in LDAP/AD. * Once enabled, local user accounts will no longer be active. That is, if there is a user created in the Controller that does not match a user in LDAP, they will no longer be able to login to the Controller. .. note:: The local `admin` account is active when ldap is used for controller login authentication as descrived above. Please note that if the `admin` account is disabled via "Settings/Controller/LoginCustomization" and if your ldap authentication is not working as expected for any reason(for eexamp, server is down or not reachable), you will get locked out of the controller till your ldap authentication process is back up. .. |imageLDAPForm| image:: AdminUsers_LDAP_media/controller_settings_ldap.png :scale: 50% <file_sep> ###################################################### Encryption over Direct Connect/ExpressRoute ###################################################### The Problem --------------------------- AWS Direct Connect and Azure ExpressRoute provide a private routed circuit to an AWS VPC and an Azure VNet. The Aviatrix Site2Cloud feature provides encryption over Direct Connect or ExpressRoute (named "Over Private Network" when configuring a Site2Cloud connection). This document describes how to implement the feature over Express Route. The same method applies to AWS. The VNet VPN gateway that terminates the ExpressRoute connects VNet virtual machines with the on-prem servers in a traditional routing domain. While Azure ExpressRoute provides a private link between a customer’s on-prem network and an Azure VNet without going through the Internet, packets between on-prem edge and VNet travel through exchange points and third party provider networks and are not encrypted. If encryption is a requirement for security and compliance reasons, this is a problem. Aviatrix Solution for Encryption over ExpressRoute --------------------------------------------------- The Aviatrix Site2Cloud solution can be applied to encrypt traffic over ExpressRoute, as shown below. |image1| In the diagram above, an encrypted IPsec tunnel is established between an Aviatrix Gateway and the customer’s edge router. An Aviatrix Gateway is deployed in a separate subnet from the subnets where the user virtual machines are launched. (The Controller is not drawn.) This is necessary as the Aviatrix Gateway is the router for user subnets to reach the enterprise data center. An Aviatrix Gateway can be deployed in a 1:1 redundancy fashion where a backup gateway is ready to take over should the primary IPsec tunnel go down due to gateway VM hardware/software failure. Configuration Workflow ----------------------------------- Before you start, make sure you have the latest software by checking the Dashboard. If an alert message displays, click **!New** to download the latest software. For the network design, you must decide if you want to enable HA for the gateway. The configuration workflow is as follows, with major steps highlighted. | 1. Create a gateway in a VNet where you want to connect to the enterprise datacenter. | Go to Gateway > Create and make sure: - The gateway is launched in a different subnet from the user subnets. In this example, the gateway is deployed on Subnet1. - The gateway may have VPN access disabled. | 2. (Optional) If HA is enabled, create a backup gateway in the same VNet. | Go to Gateway > Create, and make sure: - The gateway is launched in a different subnet from the user subnets. In this example, the gateway is deployed on Subnet1. - The gateway may have VPN access disabled. | 3. Create a connection to the Enterprise data center. | Go to Site2Cloud > Add New and: | | a. Select the VPC/VNet Name where the Aviatrix Gateway for encryption is launched. | b. If HA is not enabled: | i. In the Gateway field, select a gateway that was launched with encryption enabled. | c. If HA is enabled: | i. In the Primary Cloud Gateway field, select a gateway launched earlier as primary gateway. | ii. In the Backup Gateway field, select a gateway launched earlier as backup gateway. | d. Input the connection with a unique name (for example, FirstExpressRoute). | e. In the Remote Gateway IP Address field, enter the private IP address of the edge router for Enterprise data center. | f. In the Remote Subnet (Real) field, enter the network CIDR of the Enterprise datacenter. If there are multiple subnets, enter each one separated with a comma. | g. Select the Over Private Network check box. | h. In the Route Table To Modify field, select the route table(s) associated with subnet2 and subnet3. i. Enter the Remote Gateway Latitude/Longitude. Click `here <https://www.iplocation.net>`_ for information on how to obtain these values. | | 4. Download the configuration template: | | a. Select the Site2Cloud connection. | b. Click Download Configuration. | c. If your remote edge device is not listed in the dropdown menu, select an available one in the menu. | d. Click **Download Configuration** to download a template file that contains the gateway public IP address, VPC/VNet CIDR, and pre-shared secret and encryption algorithm or CA certificate. Incorporate the information to your remote router/firewall configuration. | | 5. At the enterprise data center or remote site, configure encryption on the edge device. | Make sure your peer network is Subnet2 and Subnet3, as shown in this example. | .. |image0| image:: EncOverExpRoute_media/image1.png :width: 5.55625in :height: 3.26548in .. add in the disqus tag .. disqus:: <file_sep> =========================================================================================== Overlapping Network Connectivity Solutions =========================================================================================== This document describes a few scenarios of overlapping networking CIDRs and their solutions. The solution uses the Mapped option of Aviatrix `Site2Cloud <https://docs.aviatrix.com/HowTos/site2cloud.html>`_ feature when building IPsec tunnels. Using Mapped Site2Cloud provides the advantage of not having to configure individual SNAT/DNAT rules, as all virtual and physical network addresses are 1-1 translated. This document does not go into specifics of the actual configurations. For such information, check out `this example document <https://docs.aviatrix.com/HowTos/connect_overlap_cidrs_routebasedipsec.html>`_. Scenario 1: On-prem Overlaps with Spoke VPC/VNet in TGW Deployment ------------------------------------------------------------------------------------------ In this scenario, on-prem site-1 overlaps with Spoke-1 VPC/VNet CIDR, they both are 172.16.17.32/16 and wish to communicate with each other. The solution is to deploy an Aviatrix Gateway in Spoke-2 VPC/VNet and build IPsec tunnel between Spoke-2 gateway and the on-prem. In the deployment, both Spoke-1 and Spoke-2 are attached to TGW and are in the same Security Domain. The diagram is shown below. Note one can launch an Aviatrix Gateway in Spoke-1 directly and build the IPsec tunnel. This example demonstrates how to use `Spoke VPC Advertised Routes <https://docs.aviatrix.com/HowTos/tgw_list.html#edit-spoke-vpc-advertised-routes>`_ to build a more complex network. .. Tip:: VPC Spoke-1 is for illustration purposes. The destination network that overlaps with the on-prem site may be on on-prem network that connects with AWS TGW via DXGW or VPN. Similarly, the on-prem network could be a VPC/VNet in the cloud. |overlap_onprem_tgw| Following are the steps to setup the above networks. 1. Attach VPC/VNet Spoke-2 to TGW. Go to TGW Orchestrator > Build to attach. #. Launch Aviatrix gateway in Spoke-2. Go to Gateway > Add New to launch. #. (Optional) Enable HA. Go to Gateway > Gateway for High Availability Peering to enable HA. #. Configure Site2Cloud to site-1 with Mapped Option on Spoke-2. Go to Site2Cloud > Add New. Key parameters on Site2Cloud IPsec configuration: :: Spoke-2 gateway Site2Cloud key parameters: Connection Type: Mapped Enable HA: Selected (Optional) Local Subnet (real): 172.16.17.32/16 local Subnet (virtual): 192.168.0.0/16 Remote Subnet (real): 172.16.17.32/16 Remote Subnet (virtual): 172.16.17.32/16 #. Configure the on-prem site-1 IPsec. Key parameters :: on-prem site-1 IPsec key parameters: Local Subnet: 172.16.17.32/16 Remote Subnet: 192.168.0.0/16 #. Make sure the tunnel come up. #. **Important** Advertise 172.16.17.32/16 to TGW from Spoke-2 VPC/VNet. Go to TGW Orchestrator > List. Click Spoke-2, click Actions > Edit Spoke Advertised Routes. Enter `192.168.3.11/100, 172.16.17.32/16`, where 192.168.3.11/16 is Spoke-2 VPC/VNet CIDR and 172.16.17.32/16 is the virtual network CIDR of on-prem site-1. #. Test connectivity. From on-prem site-1 to ping an instance in Spoke-1 using the Spoke-1 virtual network CIDR with the real host portion of its IP address. For example, if the instance in Spoke-1 is 172.16.58.3, then site-1 should ping 192.168.10.15. #. Done. Scenario 2: Multi-Sites Overlap in TGW Deployment ----------------------------------------------------------------- Scenario 1 can be extended to on-prem multi sites that have overlapping or identical network addresses, as shown in the diagram below. |overlap_multi_onprem_tgw| 1. Attach VPC/VNet Spoke-2 to TGW. Go to TGW Orchestrator > Build to attach. #. Launch Aviatrix gateway in Spoke-2. Go to Gateway > Add New to launch. #. (Optional) Enable HA. Go to Gateway > Gateway for High Availability Peering to enable HA. #. Create a Site2Cloud connection to site-1 with Mapped Option on Spoke-2. Key parameters on Site2Cloud IPsec configuration: :: Spoke-2 gateway Site2Cloud to site-1 key parameters: Connection Type: Mapped Enable HA: Selected (Optional) Local Subnet (real): 172.16.17.32/16 local Subnet (virtual): 192.168.0.0/16 Remote Subnet (real): 172.16.17.32/16 Remote Subnet (virtual): 172.16.17.32/16 #. Create an on-prem site-1 to Spoke-2 Gateway IPsec connection with an on-prem router or firewall. Key parameters :: on-prem site-1 IPsec key parameters: Route Based VPN. Local Subnet: 172.16.17.32/16 Remote Subnet: 192.168.0.0/16 #. Make sure the tunnel come up. #. Configure a Site2Cloud to site-2 connection with Mapped Option on Spoke-2. Key parameters on Site2Cloud IPsec configuration: :: Spoke-2 Gateway Site2Cloud to site-2 key parameters: Connection Type: Mapped Enable HA: Selected (Optional) Local Subnet (real): 172.16.17.32/16 local Subnet (virtual): 192.168.0.0/16 Remote Subnet (real): 172.16.17.32/16 Remote Subnet (virtual): 192.168.3.11/16 #. Create an on-prem site-2 to Spoke-2 gateway IPsec connection with an on-prem router or firewall. Key parameters :: on-prem site-2 IPsec key parameters: Route Based VPN. Local Subnet: 172.16.17.32/16 Remote Subnet: 192.168.0.0/16 #. **Important** Advertise 172.16.17.32/16 192.168.3.11/16 to TGW from Spoke-2 VPC/VNet. Go to TGW Orchestrator > List. Click Spoke-2, click Actions > Edit Spoke Advertised Routes. Enter `192.168.3.11/100, 172.16.17.32/16, 192.168.3.11/16`, where 192.168.3.11/16 is Spoke-2 VPC/VNet CIDR and 172.16.17.32/16 is the virtual network CIDR of on-prem site-1 and 192.168.3.11/16 is the virtual network CIDR of on-prem site-2. #. Test connectivity. From on-prem site-1 to ping an instance in Spoke-1 using the Spoke-1 virtual network CIDR with the real host portion of its IP address. For example, if the instance in Spoke-1 is 172.16.58.3, then site-1 should ping 192.168.10.15. #. Test connectivity. From on-prem site-2 to ping an instance in Spoke-1 using the Spoke-1 virtual network CIDR with the real host portion of its IP address. For example, if the instance in Spoke-1 is 172.16.58.3, then site-2 should ping 192.168.10.15. #. Done. Scenario 3: On-prem Overlaps with Spoke in Aviatrix Transit Deployment ---------------------------------------------------------------------------------------------- In this scenario, Aviatrix Transit solution is deployed and similarly on-prem site overlaps with a Spoke CIDR where it needs to communicate with, as shown in the diagram below. |overlap_onprem_aviatrix_transit| This scenario is made possible by the **Forward Traffic to Transit Gateway** option that you can enable after configuring your Site2Cloud connection. See `here <https://docs.aviatrix.com/HowTos/site2cloud.html#forward-traffic-to-transit-gateway>`_ for more information. Scenario 4: Multi-Sites Overlap in Aviatrix Transit Deployment ---------------------------------------------------------------------------- This scenario extends the previous solution to include multi sites, as shown in the diagram below. |overlap_multi_onprem_aviatrix_transit| This scenario is made possible by the **Forward Traffic to Transit Gateway** option that you can enable after configuring your Site2Cloud connection. See `here <https://docs.aviatrix.com/HowTos/site2cloud.html#forward-traffic-to-transit-gateway>`_ for more information. Spoke 2 in this scenario is a landing Spoke. When the Site2Cloud Forwarding option referenced above is enabled, NAT occurs on the landing Spoke and ensures that bi-directional traffic flow is possible between on-prem routers and local Spoke and Transit gateways. Either side can now initiate traffic (locally or remotely), as per what you configured in your Site2Cloud connection. If you select only one of these, you cannot initiate from the other direction and NAT translation will not occur. Enabling the **Auto Advertise Spoke Site2Cloud CIDRs** option (configured at Multi-Cloud Transit > List > Spoke; select a Spoke gateway and select this option from the Actions list) in this scenario ensures that the other Spokes in the scenario are aware of the virtual CIDRs on which the landing Spoke is going to perform NAT (Spoke 2). If you select this Auto Advertise option ensure that you do not advertise more than the CSP-allowed limit of routes per route table. For example, for AWS the routes per route table limit is described `here <https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html>`_. .. |overlap_onprem_tgw| image:: overlapping_network_solutions_media/overlap_onprem_tgw.png :scale: 30% .. |overlap_multi_onprem_tgw| image:: overlapping_network_solutions_media/overlap_multi_onprem_tgw.png :scale: 30% .. |overlap_onprem_aviatrix_transit| image:: overlapping_network_solutions_media/overlap_onprem_aviatrix_transit.png :scale: 30% .. |overlap_multi_onprem_aviatrix_transit| image:: overlapping_network_solutions_media/overlap_multi_onprem_aviatrix_transit.png :scale: 30% .. disqus:: <file_sep> ================================================================== AWS Startup Guide ================================================================== .. raw:: html <script> /** * Function that captures a click on an outbound link in Analytics. * This function takes a valid URL string as an argument, and uses that URL string * as the event label. Setting the transport method to 'beacon' lets the hit be sent * using 'navigator.sendBeacon' in browser that support it. */ var captureOutboundLink = function(url) { ga('send', 'event', 'outbound', 'click', url, { 'transport': 'beacon', 'hitCallback': function(){document.location = url;} }); } </script> .. raw:: html <script> /** * Function that registers a click on an outbound link in Analytics. * This function takes a valid URL string as an argument, and uses that URL string * as the event label. Setting the transport method to 'beacon' lets the hit be sent * using 'navigator.sendBeacon' in browser that support it. */ var getOutboundLink = function(url) { gtag('event', 'click', { 'event_category': 'outbound', 'event_label': url, 'transport_type': 'beacon', 'event_callback': function() {window.open(url, '_blank');} }); } </script> .. raw:: html <script> /** * Function that registers a click on an outbound link in Analytics. * This function takes a valid URL string as an argument, and uses that URL string * as the event label. Setting the transport method to 'beacon' lets the hit be sent * using 'navigator.sendBeacon' in browser that support it. */ var getOutboundLinkAndOpen = function(url) { gtag('event', 'click', { 'event_category': 'outbound', 'event_label': url, 'transport_type': 'beacon', 'event_callback': function() {} }); } </script> Welcome to getting started on AWS! This guide takes you through the 3 steps to launch your Aviatrix Controller instance: #. `Subscribing to the AMI (Amazon Machine Image) <https://docs.aviatrix.com/StartUpGuides/aviatrix-cloud-controller-startup-guide.html#subscribing-to-an-aviatrix-ami>`_. #. `Launching the Controller with CloudFormation <https://docs.aviatrix.com/StartUpGuides/aviatrix-cloud-controller-startup-guide.html#id1>`_. #. `Onboarding your AWS account in your Aviatrix Controller <https://docs.aviatrix.com/StartUpGuides/aviatrix-cloud-controller-startup-guide.html#id2>`_. When complete, you'll be ready to deploy use cases. |3-step| .. important:: The Aviatrix Controller must be launched by a Cloudformation script provided by Aviatrix. Follow the instructions in this document to launch the Controller. Do not launch the Controller instance from the AWS Console. Subscribing to an Aviatrix AMI ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ If you have already subscribed the Metered AMI on AWS Marketplace, skip this step and proceed to the Launch the Controller with CloudFormation section. 1. To subscribe to the AMI, click the AMI link below to take you to the AWS Marketplace. .. |marketplace_metered_link2| raw:: html <a href="https://aws.amazon.com/marketplace/pp/B08NTSDHKG?qid=1616801289672&sr=0-2" target="_blank" onclick="getOutboundLinkAndOpen('https://aws.amazon.com/marketplace/pp/B08NTSDHKG?qid=1616801289672&sr=0-2');">Aviatrix Secure Networking Platform Metered with Copilot</a> |marketplace_metered_link2| .. `Aviatrix Secure Networking Platform Metered - Copilot & 24x7 Support <https://aws.amazon.com/marketplace/pp/B08NTSDHKG?qid=1616801289672&sr=0-2&ref=_ptnr_docs_startup_metered_copilot24x7>`_ 2. Click **Continue to Subscribe**. Subscribing means that you can begin deploying the software in later steps via the CloudFormation template. |AMI_24x7_copilot| 3. Click **Accept Terms**. Then, **return to this guide and continue**. Do not proceed to Continue to Configuration. Launching the Controller with CloudFormation ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1. Click the link below to take you to the CloudFormation page on the AWS Console with the pre-loaded template. Follow the instructions in the next steps to run the Cloudformation script. .. |CFT_link| raw:: html <a href="https://us-west-2.console.aws.amazon.com/cloudformation/home?region=us-west-2#/stacks/new?stackName=AviatrixController&templateURL=https://aviatrix-cloudformation-templates.s3-us-west-2.amazonaws.com/aws-cloudformation-aviatrix-metered-controller-copilot-24x7-support.template" target="_blank" onclick="getOutboundLinkAndOpen('CFT_launch');">CloudFormation for Aviatrix Secure Networking Platform Metered with Copilot</a> |CFT_link| .. `CloudFormation for Aviatrix Secure Networking Platform Metered - Copilot & 24x7 Support <https://us-west-2.console.aws.amazon.com/cloudformation/home?region=us-west-2#/stacks/new?stackName=AviatrixController&templateURL=https://aviatrix-cloudformation-templates.s3-us-west-2.amazonaws.com/aws-cloudformation-aviatrix-metered-controller-copilot-24x7-support.template>`_ **Other Aviatrix Products** CloudFormation for Aviatrix Secure Networking Platform Metered with Copilot * `Aviatrix Secure Networking Platform - BYOL <https://us-west-2.console.aws.amazon.com/cloudformation/home?region=us-west-2#/stacks/new?stackName=AviatrixController&templateURL=https://aviatrix-cloudformation-templates.s3-us-west-2.amazonaws.com/avx-awsmp-BYOL.template>`_ * `Aviatrix Secure Networking Platform - Enterprise Subscription <https://us-west-2.console.aws.amazon.com/cloudformation/home?region=us-west-2#/stacks/new?stackName=AviatrixController&templateURL=avx-awsmp-5tunnel.template>`_ * `Aviatrix Secure Networking Platform Metered - Copilot & 24x7 Support <https://us-west-2.console.aws.amazon.com/cloudformation/home?region=us-west-2#/stacks/new?stackName=AviatrixController&templateURL=https://aviatrix-cloudformation-templates.s3-us-west-2.amazonaws.com/aws-cloudformation-aviatrix-metered-controller-copilot-24x7-support.template>`_ 2. If you have not logged in, you will be prompted to log in to the AWS console. 3. Change to the region where you would like to install the Aviatrix Controller on the CloudFormation page. Note the CloudFormation is already loaded. 4. Click **Next**. |cft-next| 5. Fill in the following fields: * The Stack name, * Select a VPC in the dropdown menu, * Select a **public subnet in that VPC** (Go to AWS VPC console to make sure the public subnet is indeed in your selected VPC. A public subnet must have a default route point to IGW in its associated VPC route table. Read `this link <https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_Subnets.html>`__ if you do not know what public subnet is.) * And a keypair (Read `how to create a keypair <https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html>`_ to create a keypair in AWS EC2 console if this field is blank.) |imageCFSpecifyDetails| .. note:: The Aviatrix Controller must be launched on a public subnet. If this is the first time you launch an Aviatrix Controller, select the default setting **New** for IAM Role Creation. If an Aviatrix IAM role has been created before, select **aviatrix-role-ec2** for IAM Role Creation. The Aviatrix Controller instance is termination protected. .. 6. Select instance size. Set the Controller Size to t3.large and keep the IAM role creation at New unless you have already created the Aviatrix IAM roles. 7. Click **Next**. 8. Click **Acknowledge**. 9. Mark the checkbox next to "I acknowledge that AWS CloudFormation ..." and then click **Create**. |imageCFCreateFinal| 10. When the stack creation completes (the status changes to CREATE_COMPLETE), click on the **Outputs** tab. You will need to use the values displayed when you onboard a primary access account for AWS in your Aviatrix Controller. (You might have to refresh your browser window and/or AWS console to see your Stack show up and the Status to be updated). |imageCFComplete| Onboarding your AWS account in your Aviatrix Controller ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Now that Aviatrix Controller instance has been launched, log in to your Controller and go through the onboarding process. 1. To access the Controller, open a browser window to https://AviatrixControllerEIP, where AviatrixControllerEIP can be found in the Stack Outputs. You can also find the Controller instance EIP by going to AWS EC2 console, click the Controller instance, and locate its public IP address. .. tip:: You may receive a warning that the connection may not be secure. This is because the certificate is self-signed by the Controller. It is safe to continue to the page. .. |imageControllerBrowserWarning| 2. Log in to the Controller: * Username - admin * Password - the <PASSWORD> from your AWS account. You can find this IP address in the Outputs section of the CloudFormation stack or by going to AWS EC2 console, clicking the Controller instance, and locating its private IP address. 3. Enter your email address. This email will be used for alerts as well as password recovery if needed. 4. When prompted, change your password. Make sure this password is secure. 5. Click Run. The Controller will upgrade itself to the latest software version. Wait for a few minutes for the process to finish. .. tip:: The Controller upgrade takes about 3-5 minutes. Once complete, the login prompt will appear. Use the username "admin" and your new password to login. .. If you wish to run a custom version, consult the Aviatrix Support team before attempting it. 6. When you log into the Controller, the Onboarding page should open. On the Onboarding page, select AWS. |imageOnboardAws| 7. Set up a primary access account for AWS using the following information: * The Controller instance's AWS 12-digit account ID. Check out `this link <http://docs.aviatrix.com/HowTos/onboarding_faq.html#what-is-an-aviatrix-access-account-on-the-controller>`__ if you have questions regarding Aviatrix access account. Fill out the fields as follows: (The AWS Account Number can be found at the Stack Outputs section or get from `this link. <https://docs.aws.amazon.com/IAM/latest/UserGuide/console_account-alias.html>`__) +-------------------------------+--------------------------------------------+ | Field | Expected Value | +===============================+============================================+ | Account Name | Enter a name that is unique on the | | | Controller. | | | Example name: `AWSOpsTeam`. | +-------------------------------+--------------------------------------------+ | AWS Account Number | The Controller instance's 12-digit | | | AWS account number. It can be found in the | | | Stack Outputs section `AccoundId`. | +-------------------------------+--------------------------------------------+ | IAM role-based | Check this box. | +-------------------------------+--------------------------------------------+ 8. Once complete, click **Create** at the bottom of the form. Occasionally, you may need to update your IAM policy. See `this document <https://docs.aviatrix.com/HowTos/iam_policies.html>`_ to audit your policy to check for updates and update it if necessary. Next: Start a Use Case ^^^^^^^^^^^^^^^^^^^^^^^^^ Congratulations! You are now ready to deploy use cases. Here are some of the things you can do: - `Build Net-Gen Transit Network for AWS <https://docs.aviatrix.com/HowTos/tgw_plan.html>`__ - `Build Egress Security <../HowTos/FQDN_Whitelists_Ref_Design.html>`__ - `Build User SSL VPN <../HowTos/uservpn.html>`__ - `Build Site to Cloud VPN <http://docs.aviatrix.com/HowTos/site2cloud_faq.html>`_ - `Build Multicloud Peering <http://docs.aviatrix.com/HowTos/GettingStartedAzureToAWSAndGCP.html>`_ - `Build Encrypted Peering <http://docs.aviatrix.com/HowTos/peering.html>`_ - `Build Firewall Network <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html>`_ - `Build PrivateS3 <https://docs.aviatrix.com/HowTos/privateS3_workflow.html>`_ - `Aviatrix Overview. <http://docs.aviatrix.com/StartUpGuides/aviatrix_overview.html>`_ .. Important:: Any resources created by the Controller, such as Aviatrix gateways, route entries, ELB, SQS queues, etc, must be deleted from the Controller console. If you delete them directly on an AWS console, the Controller's view of resources will be incorrect which will lead to features not working properly. For technical support, please open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_. Enjoy! Additional Information for Controller ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - **Controller backup and restore** `Controller backup instructions info <https://docs.aviatrix.com/HowTos/controller_backup.html>`_. - **Controller high availability** Controller HA instructions can be found `here <https://docs.aviatrix.com/HowTos/controller_ha.html>`_. - **Software upgrade** `Software upgrade procedure info <https://docs.aviatrix.com/HowTos/inline_upgrade.html>`_. .. add in the disqus tag .. disqus:: .. |subscribe| image:: ZeroToConnectivityInAWS_media/subscribe.png :scale: 30% .. |subscribe_24x7| image:: ZeroToConnectivityInAWS_media/subscribe_24x7.png :scale: 30% .. |AMI_24x7_copilot| image:: ZeroToConnectivityInAWS_media/AMI_24x7_copilot.png :scale: 40% .. |3-step| image:: ZeroToConnectivityInAWS_media/3-step.png :scale: 30% .. |4-steps| image:: ZeroToConnectivityInAWS_media/4-steps.png :scale: 30% .. |imageAwsMarketplacePage1| image:: ZeroToConnectivityInAWS_media/aws_marketplace_page1.png .. |imageAwsMarketplaceContinuetoSubscribe| image:: ZeroToConnectivityInAWS_media/aws_marketplace_step1.png .. |imageAwsMarketplaceContinuetoSubscribe5tunnel| image:: ZeroToConnectivityInAWS_media/aws_marketplace_step1_5tunnel.png .. |imageAwsMarketplaceAccept| image:: ZeroToConnectivityInAWS_media/aws_marketplace_step2.png .. |imageAwsMarketplaceAcceptTerms| image:: ZeroToConnectivityInAWS_media/aws_marketplace_select_region_and_accept.png .. |imageCFCreate| image:: ZeroToConnectivityInAWS_media/cf_create.png .. |imageCFOptions| image:: ZeroToConnectivityInAWS_media/cf_options.png .. |imageCFCreateFinal| image:: ZeroToConnectivityInAWS_media/cf_create_final.png .. |imageCFComplete| image:: ZeroToConnectivityInAWS_media/cf_complete_outputs.png .. |imageCFOutputsWithPassword| image:: ZeroToConnectivityInAWS_media/cf_complete_outputs_private_ip_highlight.png .. |imageControllerBrowserWarning| image:: ZeroToConnectivityInAWS_media/controller_browser_warning.png :scale: 30% .. |imageControllerEnterEmail| image:: ZeroToConnectivityInAWS_media/controller_enter_email.png :scale: 50% .. |imageControllerChangePassword| image:: ZeroToConnectivityInAWS_media/controller_change_password.png :scale: 50% .. |imageproxy-config| image:: ZeroToConnectivityInAWS_media/proxy_config.png :scale: 50% .. |imageControllerUpgrade| image:: ZeroToConnectivityInAWS_media/controller_upgrade.png :scale: 50% .. |imageCFSelectTemplate| image:: ZeroToConnectivityInAWS_media/cf_select_template.png .. |imageCFSelectTemplate-S3| image:: ZeroToConnectivityInAWS_media/imageCFSelectTemplate-S3.png .. |imageCFSpecifyDetails| image:: ZeroToConnectivityInAWS_media/cf_specify_details_new.png .. |imageCFEnableTermProtection| image:: ZeroToConnectivityInAWS_media/cf_termination_protection.png :scale: 30% .. |imageAviatrixOnboardNav| image:: ZeroToConnectivityInAWS_media/aviatrix_onboard_nav.png :scale: 50% .. |imageOnboardAws| image:: ZeroToConnectivityInAWS_media/onboard_aws.png :scale: 50% .. |imageEnterCustomerID| image:: ZeroToConnectivityInAWS_media/customerid_enter.png :scale: 50% .. |cft-next| image:: ZeroToConnectivityInAWS_media/cft-next.png :scale: 25% .. |imageCreateAccount| image:: ZeroToConnectivityInAWS_media/create_account.png <file_sep> ======================================= Azure Startup Guide ======================================= The Aviatrix cloud network solution consists of two components, the Controller and Gateways, both of which are Azure VMs (Virtual Machines). Gateways are launched from the Controller console to specific VNets. This guide helps you to launch the Controller VM in Azure. Follow the instructions to also subscribe to the Aviatrix Companion Gateway described in this guide: * `Subscribing to the Aviatrix Metered Offer <https://docs.aviatrix.com/StartUpGuides/azure-aviatrix-cloud-controller-startup-guide.html#id1>`_ * `Subscribing to the Aviatrix Controller BYOL Offer <https://docs.aviatrix.com/StartUpGuides/azure-aviatrix-cloud-controller-startup-guide.html#id2>`_ * `Launching the Controller VM from the Azure Marketplace Portal <https://docs.aviatrix.com/StartUpGuides/azure-aviatrix-cloud-controller-startup-guide.html#id4>`_ * `Onboarding your Azure Account in the Aviatrix Controller <https://docs.aviatrix.com/StartUpGuides/azure-aviatrix-cloud-controller-startup-guide.html#id5>`_ .. note:: These instructions apply generally to both Azure commercial and Azure Government clouds for deploying an Aviatrix Controller. Note that some screenshots may show regions that are only available for commercial Azure accounts. Commercial Azure offers multiple regions worldwide while Azure Government offers four US regions: (US) USGov Virginia, (US) UsGov Arizona, (US) UsGov Iowa, and (US) UsGov. For more information about Azure regions, click `here <https://azure.microsoft.com/en-us/global-infrastructure/geographies/#overview>`_. Subscribing to the Aviatrix Metered Offer ============================================= .. note:: Launching a new Controller, or migrating Controller images, requires two offers from the Azure Marketplace: 1) Aviatrix Secure Networking Platform Metered 2208-Universal 24x7 Support 2) Aviatrix Secure Network Platform BYOL (Bring Your Own License) Both offers are required. Subscribe to the metered offer to receive your Customer ID, and then subscribe to the BYOL offer to deploy your Controller using that Customer ID. You will only be billed for the metered offer. 1. Go to the `Azure Marketplace <https://azuremarketplace.microsoft.com/en-us/marketplace/apps/aviatrix-systems.aviatrix-controller-abu-saas?tab=Overview>`_ to subscribe to the Aviatrix Secure Networking Platform Metered 2208-Universal 24x7 Support offer. 2. Click **Get it Now** on the left side of the page. 3. Mark the permissions checkbox and click **Continue**. 4. Click **Subscribe**. 5. Enter your Subscription name, Resource group, Name, and Recurring billing preference. Then, click **Review + subscribe**. 6. Click **Subscribe**. 7. After the configuration completes, click **Configure account now**. 8. Enter your email address in the Email field and click **Submit**. 9. You receive a new email from <EMAIL> with the subject line "License key for Aviatrix Metered Controller and CoPilot." This email contains your Controller customer ID, Copilot customer ID, and offer subscription ID. Save these values in a secure place to use later for onboarding. Note with the Aviatrix Metered License, you are billed monthly. No upfront cost and pay as you go. (Optional) Subscribing to an Aviatrix Companion Gateway =========================================================== This step is not required for most of deployment scenarios as Aviatrix Controller automatically subscribes to the Aviatrix Companion Gateway when it is launched. There are exceptional cases, such as if you provide Managed Service on Azure, the Aviatrix Companion Gateway requires manual subscription. To subscribe manually, follow the steps in `this doc <http://docs.aviatrix.com/HowTos/CompanionGateway.html>`__. Launching the Controller ============================== After subscribing to the metered offer and receiving your license key, click the link in the "License key for Aviatrix Metered Controller and Copilot" email you received. This link opens the Azure marketplace to the Aviatrix Secure Networking Platform BYOL (Bring Your Own License) page. .. note:: As explained above, this BYOL offer activates the metered subscription. Launching the Controller VM from the Azure Marketplace Portal ------------------------------------------------------------------------------- #. On the Aviatrix Secure Network Platform BYOL page, click **Get it Now**. |aviatrix_byol_offer_azure_marketplace| #. Under Create this app in Azure, click **Continue**. #. Under Aviatrix Secure Networking Platform BYOL, click **Create**. #. Create a new Resource Group titled "aviatrix." The virtual machine name can be "aviatrixController." For the instance size, at least 8GB of RAM is recommended; the B2ms instance size should be sufficient. #. Next, enter a username, password, and Resource group. Please do **not** use "ubuntu" as username if you use password as the authentication type. |Azure_Basics| #. Click **Review + create**. #. Click **Create**. #. Under Generate new key pair, click **Download private key and create resources** to download your secret key. #. When you receive the message that your deployment is compete, click **Go to resource**. #. At the networking header, this will be preconfigured with a default subnet and security group. You should not need to change anything here. For Public IP, click **Create New**. #. At Assignment, select **Static** and click **OK**. |static_ip| #. The management, advanced, and tag headers should not need any configuration changes. #. Click **Create** to finish launching the VM. #. Find the VM’s public IP address, as shown below: |VM| #. Use a browser to access the controller VM. In this example, it is https://172.16.58.3 #. At the login page, enter "admin" as the username. The initial password is the internal IP address of the VM, as shown below. |login| #. Log into your new Controller. #. After logging in, click on the Onboarding tab. .. Warning:: Any resources created by the Controller, such as Aviatrix gateways, Azure routing entries, subnets, etc, must be deleted from the Controller. If you delete them directly on Azure console, The Controller's view of the resources will be incorrect, which will lead to features not working properly. Onboarding your Azure Account in the Aviatrix Controller ===================================================== The purpose of onboarding is to help you setup an account on the Aviatrix Controller that corresponds to an Azure account with policies so that the Controller can launch gateways using Azure APIs. Follow the `instructions <http://docs.aviatrix.com/HowTos/Aviatrix_Account_Azure.html>`_ here to create an Aviatrix account that corresponds to your Azure account credential. Note: you can create a single Aviatrix account that corresponds to AWS, Azure, and GCloud account credentials. This is a multi-cloud platform. Gateway Troubleshooting ======================== If the Controller fails to launch an Aviatrix gateway in Azure RM, check out `this troubleshooting guide. <http://docs.aviatrix.com/HowTos/azuregwlaunch.html>`_ Enjoy! .. |image0| image:: AzureAviatrixCloudControllerStartupGuide_media/image001.png :scale: 50% .. |marketplace| image:: AzureAviatrixCloudControllerStartupGuide_media/marketplace.png :scale: 60% .. |dropdown| image:: AzureAviatrixCloudControllerStartupGuide_media/dropdown.png :scale: 70% .. |Azure_Basics| image:: AzureAviatrixCloudControllerStartupGuide_media/Azure_Basics.png :scale: 70% .. |image3| image:: AzureAviatrixCloudControllerStartupGuide_media/image04___2017_08_14.PNG :scale: 70% .. |VM| image:: AzureAviatrixCloudControllerStartupGuide_media/VM.png :scale: 60% .. |login| image:: AzureAviatrixCloudControllerStartupGuide_media/login.png :scale: 70% .. |Networking| image:: AzureAviatrixCloudControllerStartupGuide_media/Networking.png :scale: 70% .. |subscribe_to_meter| image:: AzureAviatrixCloudControllerStartupGuide_media/subscribe_to_meter.png :scale: 90% .. |license_key| image:: AzureAviatrixCloudControllerStartupGuide_media/license_key.png :scale: 90% .. |aviatrix_byol_offer_azure_marketplace| image:: AzureAviatrixCloudControllerStartupGuide_media/aviatrix_byol_offer_azure_marketplace.png :scale: 70% .. |static_ip| image:: AzureAviatrixCloudControllerStartupGuide_media/static_ip.png :scale: 30% .. add in the disqus tag .. disqus:: <file_sep> .. raw:: html <style> /* override table no-wrap */ .wy-table-responsive table td, .wy-table-responsive table th { white-space: normal !important; } </style> ======================================== Public Subnet Filtering Gateway FAQ (AWS) ======================================== What does Public Subnet Filtering gateway do? =============================================== Public Subnet Filtering gateway, PSF gateway, provides both Ingress and Egress security for AWS public subnets where instances have public IP addresses. It includes two parts: Ingress filtering via GuardDuty enforcement and Egress FQDN. Public Subnet Filtering function is described in the diagram below. |public_subnet_filter| Ingress protection via GuardDuty enforcement is a feature where Aviatrix Controller periodically polls the AWS GuardDuty findings and blocks the malicious source IP addresses from attacking the public subnet instances by programming stateful firewall rules in the filtering gateway. Egress FQDN is an existing `FQDN feature <https://docs.aviatrix.com/HowTos/fqdn_faq.html>`_ applied to the public subnets. Previously, this feature was only available to filter egress traffic initiated from instances in the private subnets. How do I deploy a Public Subnet Filtering gateway? --------------------------------------------------------------- Follow the workflow below. Launching a Public Subnet Filtering Gateway ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Go to Security > Public Subnet > Add New. =================== ================= Setting Value =================== ================= Cloud Type AWS Gateway Name Input a unique gateway name Account Name Select the Access Account Region Select the AWS region VPC ID Select the VPC in the chosen AWS region Unused Subnet Aviatrix Controller creates a public subnet and creates a route table associated with the subnet to launch the filtering gateway Gateway Size Select an instance type Route Table Select a route table whose associated public subnets are protected. =================== ================= After the PSF gateway is launched, Ingress traffic from IGW is routed to the gateway in a pass through manner. Egress traffic from instances in the protected public subnets is routed to the gateway in a pass through manner. Enabling GuardDuty Enforcement ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Go to Security > AWS GuardDuty, select an Access Account and AWS Region > click **Enable**. Once GuardDuty is enabled, malicious source IP addresses attacking instances in the public subnets in the region will be polled by the Controller. The Controller then programs rules into the filtering gateway to drop these packets. .. Note:: if you enable AWS GuardDuty without launching the PSF gateway, GuardDuty does not have enforcement functionality. Enabling Egress FQDN ^^^^^^^^^^^^^^^^^^^^^^^^ Once the PSF gateway is launched, you can configure the FQDN feature. Go to Security > Egress Control, follow the instructions in `FQDN workflow <https://docs.aviatrix.com/HowTos/FQDN_Whitelists_Ref_Design.html>`_. How do I view blocked malicious IPs? ----------------------------------------------- After the filtering gateway is launched and AWS GuardDuty is enabled from the previous steps, view blocked malicious IPs by going to Security > Public Subnet. Highlight the PSF gateway, click the 3 dots skewer, and click **Show Details**. Scroll down to Blocked Malicious IPs. Do the public subnet instances keep their public IP addresses with FQDN function? ------------------------------------------------------------------------------------------------------ Yes. When you enable FQDN filtering for public subnets, packets initiated from the instances on the public subnet do not get NATed when going through FQDN filtering gateway, and the source public IP address of a public subnet instance is preserved. .. |public_subnet_filter| image:: public_subnet_filtering_faq_media/public_subnet_filter.png :scale: 30% .. add in the disqus tag .. disqus:: <file_sep> ======================================================================== Migrating an Aviatrix Transit Network to AWS Transit Gateway (TGW) ======================================================================== This document assumes that you have deployed an `Aviatrix Global Transit Network solution <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ with Aviatrix Transit Gateway and VGW. The following steps provide instructions to migrate a live Aviatrix Global Transit deployment to AWS Transit Gateway using Aviatrix TGW Orchestrator. The objectives here are: - No change to any on-prem network. - No change to the connectivity between AWS VGW and on-prem. (either over DX or over Internet or both) - Re-use AWS VGW deployed in Aviatrix Global Transit solution if possible. - No change to existing VPC infrastructure. - Minimum operation downtime. Prior to migration, you may plan on the `security domains <https://docs.aviatrix.com/HowTos/tgw_plan.html#create-a-new-security-domain>`_ and their `connection policy <https://docs.aviatrix.com/HowTos/tgw_plan.html#build-your-domain-connection-policies>`_. If you are not sure and is in need to transition, you can add or modify the security domains at any time later. 1. **Create AWS Transit Gateway** Follow `Step 1 <https://docs.aviatrix.com/HowTos/tgw_plan.html#create-aws-tgw>`_ in TGW Orchestrator > Plan page. 2. **Create Security Domains** If you have plans for custom security domains, follow `Step 2 <https://docs.aviatrix.com/HowTos/tgw_plan.html#optional-create-a-new-security-domain>`_ to create them. If you do not intend to build custom security domains, skip this step. 3. **Add/modify connection policies** Follow `Step 3 <https://docs.aviatrix.com/HowTos/tgw_plan.html#optional-build-your-domain-connection-policies>`_ to build connection policies. 4. **Prepare Aviatrix Transit GW for TGW Attachment** Follow `Step 5 <https://docs.aviatrix.com/HowTos/tgw_plan.html#prepare-aviatrix-transit-gw-for-tgw-attachment>`_. 5. **Attach Aviatrix Transit Gateway to TGW** `Follow Step 6. <https://docs.aviatrix.com/HowTos/tgw_plan.html#attach-aviatrix-transit-gw-to-tgw>`_ to complete the hybrid connection between your existing VGW and the TGW. At this point, VGW starts to advertise to Aviatrix Transit GW. Make sure you specify a different "AS" number for the BGP session of Aviatrix Transit GW connection to VGW. Also note that if Transit GW and VGW are in the same account and same VPC, VGW must be detached from the VPC. 6. **Detach Spoke GW** Follow `Step 7 <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#remove-a-spoke-gw-from-a-transit-gw-group>`_ to detach a Spoke GW from the existing Aviatrix Global Transit Network. 7. **Delete Spoke GW** Go to Gateway on the main navigation tab, select the Spoke gateway and click Delete. If you have HA gateway, you will need to delete it first before the primary Spoke gateway. 8. **Attach Spoke VPC to Transit Gateway** Follow `Step 1 <https://docs.aviatrix.com/HowTos/tgw_build.html#attach-vpc-to-tgw>`_ to attach a VPC to the corresponding security domain. 9. Repeat the above step 6-8 for the remaining Spoke gateways. The effective operation downtime for each Spoke VPC is the time between step 6-8 above. A quick summary of the migration is shown in the following diagram. |avx_tgw_migration01| .. |avx_tgw_migration01| image:: avx_tgw_migration_media/avx_tgw_migration01.png :scale: 30% .. disqus:: <file_sep> ================================================== Oracle Cloud Infrastructure (OCI) Onboarding Guide ================================================== Onboarding helps you set up an account on the Aviatrix Controller that corresponds to an Oracle Cloud Infrastructure (OCI) account with compartment policies so that the Controller can launch gateways using OCI APIs. To onboard the OCI account in the Aviatrix Controller, you need the following four pieces of information. #. User OCID #. Tenancy OCID #. Compartment OCID #. API Private Key File This document explains where you can find these four pieces of information and how to use them to onboard your OCI account to your Aviatrix Controller. Accessing Your User OCID ----------------------------------- 1. Log in to your OCI console and open the Navigation menu in the top left > Identity > Users. 2. Identify the IAM User who will be making the API calls and copy the User OCID. |oci_user| Accessing Your Tenancy OCID ------------------------------------- 1. Log in to your OCI console and open the Navigation menu in the top left > Tenancy Details. 2. Copy the Tenancy OCID. |oci_tenancy| Accessing Your Compartment OCID ----------------------------------------------- 1. Log in to your OCI console and open the Navigation menu in the top left > Identity > Compartments. 2. Choose the compartment and copy the Compartment OCID. |oci_compartment| Please note that if you have multiple compartments, choose one that has right set of policies which are required for Aviatrix to work. The best practice is to create a separate compartment for your operations and assign right policies to it. Accessing Your API Key -------------------------------- If you already have an existing RSA key pair in .pem format, you can use that as well. However, please note that this key pair is not the SSH key that is used to access compute instances. Both the private key and public key must be in PEM format (not SSH-RSA format). If you do not have an existing RSA key pair, you can follow the aforementioned steps from the terminal in your laptop to generate the API key. Generate an API Signing Key ^^^^^^^^^^^^^^^^^^^^^^^^^^^ If you're using Windows, you'll need to install “Git Bash for Windows” and run the following commands with that tool. Mac and Linux users can run the following commands on their terminal 1. Create a. oci directory to store the credentials: mkdir ~/ .oci 2. Generate the private key without passphrase: openssl genrsa -out ~/.oci/oci_api_key.pem 2048 3. Change the key settings, so that only you can read the file: chmod go-rwx ~/.oci/oci_api_key.pem 4. Generate the Public Key: openssl rsa -pubout -in ~/.oci/oci_api_key.pem -out ~/.oci/oci_api_key_public.pem 5. Copy the contents of the public key in clipboard locally in your computer: cat ~/.oci/oci_api_key_public.pem | pbcopy. Note: You may have to install pbcopy, if it is not already installed on your system. Alternatively, you can also open the public key file on the terminal and copy the file from there Uploading the Public Key in the Console ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1. Log in to your OCI console and open the Navigation Menu in the top left > Identity > Users. 2. Select the user who will be making the API call. 3. Click **Add Public Key**. 4. Paste the contents of the PEM public key and click **Add**. Once you complete this, you will see the Key’s fingerprint. |oci_api_key| For more details, please see `Required Keys and OCIDs <https://docs.cloud.oracle.com/iaas/Content/API/Concepts/apisigningkey.htm>`_ Onboarding Your OCI Account in Your Aviatrix Controller -------------------------------------------------------------------------- Once you have your User OCID, Tenancy OCID, Compartment OCID, and API Private Key File, please go to Aviatrix Controller > Accounts > Access Accounts > New Account and fill the required information. Please note that you should upload the Private Key file in the Aviatrix controller (which is different than the one you put in the OCI console). You can find that key in the folder where you generated the key in the above steps (.oci folder in above example) |oci_account| OCI Gov (oc2) Support ^^^^^^^^^^^^^^^^^^^^^^^^^^ Aviatrix provides support in OCI Gov (oc2) for customers interested in running workloads in this environment. See `Oracle Cloud Infrastructure US Government Cloud with FedRAMP Authorization <https://docs.oracle.com/en-us/iaas/Content/General/Concepts/govfedramp.htm>`_. OCI Gov (oc2) is a separate operating realm comprised of two regions: * us-langley-1 (Ashburn) * us-luke-1 (Phoenix) Initial OCI Gov support is tailored for customers interested in multi-cloud transit patterns. In future releases, if there is demand, Aviatrix will evaluate adding additional functionality. FireNet is not supported in initial release. Onboarding OCI Gov Accounts ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ You need to subscribe to the Aviatrix image from OCI Marketplace in the same region and compartment used to onboard the OCI Gov account in the OCI Gov tenancy to your Aviatrix Controller. .. Note:: If you have an OCI Gov tenancy, the workflow for onboarding OCI Gov accounts is identical to commercial OCI. .. Important:: There are some limitations to using OCI Commercial (oc1) and OCI Gov (oc2) gateways in the same network. * OCI Gov and OCI Commercial have different regions, separate accounts, and separate compartments; they are completely isolated from each other. Therefore, you should treat them as two separate clouds. * HPE peering between OCI Commercial and OCI Gov gateways is not supported because oc2 and oc1 are two completely different environments and there is no native private connectivity between oc2 and oc1. To create a VCN with all the dependencies, please navigate to the Useful Tools menu at the main menu on the left sidebar and select Create a VPC > **+Create**. For more info, please see the Aviatrix product documentation at `https://docs.aviatrix.com/ <https://docs.aviatrix.com/>`_. For more info, please see the Aviatrix product documentation at `https://docs.aviatrix.com/ <https://docs.aviatrix.com/>`_. .. |oci_user| image:: OCIAviatrixCloudControllerOnboard_media/oci_user.png .. |oci_tenancy| image:: OCIAviatrixCloudControllerOnboard_media/oci_tenancy.png .. |oci_compartment| image:: OCIAviatrixCloudControllerOnboard_media/oci_compartment.png .. |oci_api_key| image:: OCIAviatrixCloudControllerOnboard_media/oci_api_key.png .. |oci_account| image:: OCIAviatrixCloudControllerOnboard_media/oci_account.png .. disqus:: <file_sep> =================================================== Migrating Gateway Images =================================================== Introduction ^^^^^^^^^^^^^^^^^^^^^^^^^^^ A gateway image is a virtual resource or template that contains all the information required to launch, backup, or restore a gateway in your cloud network. Aviatrix periodically releases new gateway images that include updates, enhancements, and security improvements. A best practice is to plan to upgrade your gateways at least once a quarter. You may need to upgrade your gateway image outside of a periodic upgrade in the following situations: * Aviatrix has released a new gateway image as part of a security update or product enhancement. * A gateway requires significant repair. This document shows you how to upgrade an Aviatrix Gateway to a new image. .. note:: A gateway image upgrade is also known as a gateway replacement. .. important:: For major security issues or software issues, Aviatrix sends out a field notice to notify you to upgrade to the newest image. You can review past `Field Notices <https://docs.aviatrix.com/HowTos/field_notices.html>`_ and `Aviatrix Controller and Gateway Image Release Notes <https://docs.aviatrix.com/HowTos/image_release_notes.html>`_. Prerequisites ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - Check the `current software version <https://docs.aviatrix.com/documentation/latest/platform-administration/controller-migration.html>`_ of your Controller. You cannot upgrade your gateways to a newer version than your Controller. - (Cloud gateways) An image upgrade to 6.7.1574 and later versions will fail if the Cloud Gateway is based on IKE-type Racoon**. You must perform an image upgrade of Cloud gateways running IKE-type Racoon before performing the software upgrade. An image upgrade will upgrade the gateway image version and thereby change the IKE-type on the gateways from Racoon to Strongswan. Cloud gateways running older images will not be able to upgrade from 6.6 to 6.7.1574 without performing an image upgrade of gateways to switch to IKE-type Strongswan. All Cloud gateways must run Strongswan prior to upgrading to version 6.1574. ** If your account uses Racoon-based Cloud, contact Aviatrix Support to replace your Cloud hardware to Strongswan before upgrading to version 6.7.1574. ** Note that CloudN Gateways, as opposed to Cloud gateways, can run Racoon-based gateways up to release 6.8.1148. - Every quarter, or if you receive a field notice about a new image, schedule this gateway image upgrade for an off-peak time on your network, during a maintenance window. These upgrades do require some downtime, but they have minimal impact. - Consider enabling HA (High Availability) on the Transit and Spoke Gateways that require an image upgrade if you have not done so. HA helps minimize downtime. * If you do not have HA configured, a gateway image upgrade requires downtime. * If you have HA configured, when you perform a gateway image upgrade, your Controller routes all traffic to the gateway that is not being replaced. Performance during the upgrade depends on the size of the gateway and the amount of traffic. .. tip:: Before upgrading, consider `upsizing <https://docs.aviatrix.com/HowTos/gateway.html?highlight=resize#gateway-resize>`_, that is, increasing the size of your gateway, if the traffic load is high. .. warning:: Even with HA configured, if you have high traffic during a gateway image upgrade, the gateway that remains up could receive too much traffic. Schedule gateway image upgrades during a low-traffic period. * Before upgrading any gateway images, `upgrade <https://docs.aviatrix.com/HowTos/selective_upgrade.html#upgrading-the-platform-software>`_ your Controller to the latest software version. This software upgrade ensures that you can update to the latest gateway image and reduce downtime for gateway image upgrades. Image Upgrades by Gateway Type ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The process and best practices for upgrading a gateway image can differ based on the type of gateway. Review this list to decide how to structure and schedule your gateway image upgrades. +----------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Gateway Type | Image Upgrade Notes | +========================================+====================================================================================================================================================================================+ | OpenVPN Gateway | * When you have an Open VPN Gateway deployed behind a load balancer, you can upgrade images in batches without causing an outage, depending on the number of users you have. | | | * For OpenVPN Gateways that are not deployed with a load balancer, you should expect an outage. | | | * If any users are already on an OpenVPN gateway, they will be bumped when the gateway goes through an image upgrade. If you have more than one OpenVPN gateway, the end user can | | | connect immediately to another gateway. | +----------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | FQDN Gateways with HA | The Controller does not reroute all traffic for these gateways. | +----------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Public Subnet Filtering (PSF) Gateway | This gateway type does not have HA. | +----------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Transit and Spoke Gateways | If your network has many Spoke Gateways, replacing the transit primary or HA Gateways takes more time. Wait for one group of image upgrades to complete before beginning another. | +----------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Site2Cloud Gateways | A best practice is to upgrade one gateway at a time. | | | | | | | | | | | | | +----------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ Upgrade Gateway Image ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1. In your Controller, go to Settings > Maintenance. 2. In the Selective Gateway Upgrade window, select the gateways that require an upgrade. The system automatically selects the platform controller current software version and the compatible gateway image version for that software version. .. tip:: * Your Controller can replace up to 15 gateways in parallel. Try to group your image upgrades in groups of no more than 15. * For greater simplicity and efficiency, combine all your HA gateways, which have “hagw” in their names, and all primary gateways in separate operations. * To organize multiple image upgrades, considering spreading out groups of upgrades in separate windows on your browser. 3. Click **Image Upgrade**. You can follow the status in the progress window. Replacing a gateway can take 5-7 minutes. After the gateway is up, it takes more time for the tunnels to come up. The total length of time required varies depending on the number of tunnels. .. note:: Upgrading gateway images for gateways with many tunnels can take some time. For example, depending on the software version of the Controller, it may take up to one hour to upgrade 4,000 tunnels. Migrating Unmanaged Disk to Managed Disk (Azure) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ If you have a gateway deployed on Azure and you intend to migrate your unmanaged disk to a managed disk, it is recommended to follow the process of `gateway image upgrade <https://docs.aviatrix.com/HowTos/gateway-image-migration.html#upgrade-gateway-image>`_. This gateway image upgrade will automatically migrate the unmanaged disk to a managed disk after the gateway image upgrade. .. important:: It is highly recommended to migrate your unmanaged disk to a managed disk as soon as possible, as Azure will be `retiring <https://azure.microsoft.com/en-gb/updates/azure-unmanaged-disks-will-be-retired-on-30-september-2025>`_ unmanaged disks soon. Verify ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Verify the gateway upgrade by reviewing the gateway information in the Current Image Version column. For information about migrating your Controller to a new image, please see `this document <https://docs.aviatrix.com/HowTos/Migration_From_Marketplace.html>`_ for AWS Controllers and `this document <https://docs.aviatrix.com/HowTos/controller_migration.html>`_ for Azure, GCP, or OCI Controllers. .. disqus:: <file_sep> ================================================================== Multi-Cloud Transit Integration with Azure VNG ================================================================== Introduction ============ Currently, Aviatrix Multi-cloud Transit solution requires encryption over Azure ExpressRoute or External Device to on-prem directly. There are times where encryption is not required and native network connectivity on ExpressRoute is highly desirable. In such scenarios, Aviatrix Transit solution including Transit FireNet can only forward traffic between Spoke VNets or inspect east-west traffic only, as shown `here <https://docs.aviatrix.com/HowTos/azure_transit_designs.html#aviatrix-transit-gateway-for-azure-spoke-to-spoke-connectivity>`_. This feature allows Aviatrix Multi-cloud Transit solution to integrate with native Azure Virtual Network Gateway (VNG) and enables Aviatrix Transit Gateway to inspect traffic from on-prem to cloud in addition to east-west and egress traffic inspection. Both native Spoke VNet and Aviatrix Spoke Gateway based Spoke VNets are supported. The key ideas for this solution are: ------------------------------------- - The edge (WAN) router runs a BGP session to Azure VNG via Azure ExpressRoute or VPN where the edge router advertises to the Azure VNG the on-prem routes and the VNG advertises the Spoke VNet CIDRs. - Aviatrix Controller periodically retrieves route entries from the Transit VNet VNG route table advertised from on-prem. The Controller then distributes these routes to Spoke VNet and Aviatrix Transit Gateway. - Azure native VNet Peering is configured between each Spoke VNet and Transit VNet VNG with `Allow Remote Gateway` attribute configured on the Spoke VNet to automatically advertise routes from Spoke VNet to VNG and to On-prem. - Traffic coming from on-prem to VNG is routed to the Azure Load Balancer which then forwards traffic to both Aviatrix Transit Gateways for Active-mesh deployment. The same Load Balancer is also used to distribute traffic to firewalls for inspection. - Traffic coming from Spoke VNet is routed to Aviatrix Transit Gateway directly which then forwards the traffic to the Azure Load Balancer. Future release will support ActiveMesh in this direction of traffic. This document describes the configuration workflow for the following network diagram. |topology_expressroute| where there are two Spoke VNets, one with Aviatrix Spoke Gateway (172.16.17.32/16) and one native Spoke VNet (192.168.3.11/16). Prerequisite ==================== `Upgrade <https://docs.aviatrix.com/HowTos/inline_upgrade.html>`_ Aviatrix Controller to at least version 6.3. .. tip:: We highly recommend creating a Azure Transit VNET by using the Aviatrix feature `Create a VNet <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ with Aviatrix FireNet VNet option enabled. Create a VNG in this Transit VNet. Connecting VNG on On-Prem ======================================================================================================= If you have already created VNG in Transit VNet, skip this section. Building Azure ExpressRoute is customer's responsibility. For more information about Azure ExpressRoute, please check out the below documents: - Refer to `Azure ExpressRoute <https://azure.microsoft.com/en-us/services/expressroute/>`_. - Refer to `ExpressRoute documentation <https://docs.microsoft.com/en-us/azure/expressroute/>`_ for more info. - Refer to `Equinix ECX Fabric Microsoft Azure ExpressRoute <https://docs.equinix.com/en-us/Content/Interconnection/ECXF/connections/ECXF-ms-azure.htm>`_ if users select Equinix solution. This is just an example here. Adjust the topology depending on your requirements. Follow the steps below to set up this configuration workflow. 1. Create an ExpressRoute circuit. See `Tutorial: Create and modify an ExpressRoute circuit <https://docs.microsoft.com/en-us/azure/expressroute/expressroute-howto-circuit-portal-resource-manager>`_. 2. Create Azure private network for an ExpressRoute circuit. See the `private peering section in Create and modify peering for an ExpressRoute circuit <https://docs.microsoft.com/en-us/azure/expressroute/expressroute-howto-routing-portal-resource-manager>`_. 3. Create a VNG in Transit VNet. We highly recommend creating Azure Transit VNET by utilizing `Create a VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ with Aviatrix FireNet VNet option enabled. Note that this step may take up to 45 minutes to complete. See `Configure a virtual network gateway for ExpressRoute using the Azure portal <https://docs.microsoft.com/en-us/azure/expressroute/expressroute-howto-add-gateway-portal-resource-manager>`_ 4. Connect a virtual network to an ExpressRoute circuit. See `Connect a virtual network to an ExpressRoute circuit using the portal <https://docs.microsoft.com/en-us/azure/expressroute/expressroute-howto-linkvnet-portal-resource-manager>`_. 5. Check ExpressRoute Circuits - List Routes Table on the Azure portal. Checking ExpressRoute Circuits Routes Table in Azure ----------------------------------------------------------------------- 1. Log in to the Azure portal and search for "ExpressRoute circuits" on the search bar. #. Select the ExpressRoute circuits that you created. #. Select the Azure private peering row #. Select **Get route table** to verify routes learned from on-prem. Connect Aviatrix Transit Gateway with VNG ============================================================================ Refer to `Global Transit Network Workflow Instructions <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ for the below steps. Please adjust the topology depending on your requirements. Deploying an Aviatrix Multi-Cloud Transit Gateway and HA in Azure -------------------------------------------------------------------------------------- - Follow this step `Deploy the Transit Aviatrix Gateway <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html#step-2-deploy-the-transit-aviatrix-gateway>`_ to launch Aviatrix Transit Gateway and enable HA with insane mode enabled in Azure Transit VNET. Insane mode is not required but an optional feature to increase throughput. - Instance size of at least Standard_D5_v2 will be required for `Insane Mode Encryptions <https://docs.aviatrix.com/HowTos/gateway.html#insane-mode-encryption>`_ for higher throughput. Please refer to this `doc <https://docs.aviatrix.com/HowTos/insane_mode_perf.html>`_ for performance details. - Enable `Transit FireNet Function <https://docs.aviatrix.com/HowTos/transit_firenet_workflow.html#enable-transit-firenet-function>`_. Connecting Transit FireNet Gateway to VNG ------------------------------------------------------------------------------ This step assumes VNG is already deployed in the Transit VNet. 1. Go to Multi-Cloud Transit > External Device tab. 2. Select **Azure VNG** radio button. 3. Select **Primary Aviatrix Transit Gateway** in the dropdown menu. Note if VNG has not been deployed in the Transit VNet, this step cannot complete. 4. VNG Name will populate automatically. Click **Connect**. |vng_step| Checking Effective Routes Info on Azure Portal ------------------------------------------------------------ 1. Log in to the Azure portal and search for "Network interfaces" on the search bar. 3. Select Aviatrix Transit Gateway's interface. 4. Navigate to the "Effective routes" page by selecting **Effective routes** under the Support + troubleshooting section. 5. Check route entry for On-prem pointing Next Hop Type **Virtual network gateway**. |azure_effective_routes_routing_entry| Attach Spoke VNet to Aviatrix Transit Gateway ========================================= 1. Deploy Aviatrix Spoke Gateway in Spoke VNet. Create an Azure VNET for Aviatrix Spoke Gateway by using the Aviatrix feature `Create a VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ or manually deploy it in cloud portal or feel free to use existing virtual network. 2. Follow this step `Deploy Spoke Gateways <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_azure.html#step-3-deploy-spoke-gateways>`_ to launch Aviatrix Spoke Gateway and enable HA with insane mode enabled in Azure Spoke VNET. Insane mode is optional. An instance size of at least Standard_D5_v2 will be required for `Insane Mode Encryptions <https://docs.aviatrix.com/HowTos/gateway.html#insane-mode-encryption>`_ for higher throughput. Please refer to this `doc <https://docs.aviatrix.com/HowTos/insane_mode_perf.html>`_ for performance details. 3. (Optional) Create Spoke VNet. If you do not have any Spoke VNet, create one by using Aviatrix feature `Create a VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ or manually do so in Azure portal. 4. Attach Spoke Gateways to Transit Network. * Follow this step `Attach Spoke Gateways to Transit Network <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_azure.html#step-4-attach-spoke-gateways-to-transit-network>`_ to attach Aviatrix Spoke Gateways to Aviatrix Transit Gateways in Azure * Follow step `Attach Native Azure VNET to Transit Network <https://docs.aviatrix.com/HowTos/transit_firenet_azure_native_spokes_workflow.html?highlight=Transit%20Firenet%20Native%20Azure%20Spoke%20workflow#step-3-attach-native-spoke-vnets-to-transit-network>`_ to attach Azure Native VNET Spoke to Aviatrix Transit Gateway. Ready to Go ============ Now you should be able to send traffic from cloud to on-prem as well as on-prem to cloud over Azure Express Route. For an end-to-end example configuration workflow, follow the `Multi-cloud transit with Azure VNG VPN example <https://docs.aviatrix.com/HowTos/transit_gateway_integration_with_vng_IOSexample.html>`_. For FireNet deployment, follow the `Transit FireNet workflow <https://docs.aviatrix.com/HowTos/transit_firenet_workflow.html>`_. Limitations =========== By design routes advertised to VNG to onprem are limited only to native spoke VNET peering, it does not advertise non-native spoke/transit-to-transit peerings. .. |topology_expressroute| image:: transit_gateway_integration_with_expressroute_media/topology_expressroute.png :scale: 60% .. |traffic_onprem_to_cloud_disable_inspection| image:: transit_gateway_integration_with_expressroute_media/traffic_onprem_to_cloud_disable_inspection.png :scale: 60% .. |azure_effective_routes_routing_entry| image:: transit_gateway_integration_with_expressroute_media/azure_effective_routes_routing_entry.png :scale: 40% .. |vng_step| image:: transit_gateway_integration_with_expressroute_media/vng_step.png :scale: 40% .. disqus:: <file_sep> ############################ Encrypt EBS Volume ############################ .. note:: Aviatrix starts to support enabling EBS encryption by default when users launch gateway since release 6.0. Description ------------ This feature is used to encrypt your gateway EBS volume. Note that you will need to disable the `Gateway Single AZ HA <https://docs.aviatrix.com/HowTos/gateway.html#gateway-single-az-ha>`_ on your gateway prior if you are running a release prior to 5.2 before encrypting its EBS volume. On 5.2 release and later you do not need to disable the Single AZ HA before encrypting. Prerequisite -------------- You need to add below rules into your IAM role policies ("aviatrix-app-policy"). :: { "Effect": "Allow", "Action": [ "ec2:DescribeInstances", "ec2:DescribeVolumes", "ec2:DescribeSnapshots", "ec2:StopInstances", "ec2:StartInstances", "ec2:CopySnapshot", "ec2:CreateSnapshot", "ec2:CreateVolume", "ec2:DeleteVolume", "ec2:DeleteSnapshot", "ec2:AttachVolume", "ec2:DetachVolume" ], "Resource": "*" } | How to add IAM rules? ^^^^^^^^^^^^^^^^^^^^^^ **Step1: Go to your AWS account and select IAM service.** |image_1_IAMRolesClickAviatrixroleapp| **Step2: Select "Roles", then double click the role name "aviatrix-role-app."** |image_2_selectAviatrixAppPolicyEnditPolicy| **Step3: Click "JSON", then put the rules into the JSON file. Then click "Review policy".** |image_3_selectJSONAddRulesClickReviewPolicy| **Step4: Click “Save changes” to finish editing aviatrix-app-policy** |image_4_saveChanges| | How to encrypt gateway EBS volume via Aviatrix controller? ----------------------------------------------------------- **Step1: Go to your Aviatrix controller page, and select "Gateway" page.** **Step2: Select the gateway which you want to encrypt, then click "Edit" button.** |image_11_selectGwEdit| **Step3: Check the current status of Gateway EBS volume.** |image_12_checkStatus| **Step4: Scroll down to "Encrypt Volume" and Click "Encrypt" button to encrypt the EBS. Please wait for the encryption process to complete.** |image_13_scrollDownToEncryptVolume| .. note:: The controller will use Default **"AWS Managed Keys"** to encrypt your EBS volume. Otherwise, you can use your* **"Customer Managed Key ID"** to encrypt the gateway EBS volume. `How to create AWS Customer Managed Key ID? <http://docs.aws.amazon.com/kms/latest/developerguide/create-keys.html#create-keys-api>`_ | **Step5: Check the encrypted volume. You may need to refresh the controller "Gateway" page to check the status of Gateway’s EBS volume.** |image_14_checkEncryptResult| **Step6: You can check the result on your AWS console. It's on EC2 -> Volume page.** |image_15_checkEncryptResultOnAws| .. note:: You can see that the gateway EBS volume was encrypted. Also, the previous unencrypted volume will be kept. Please make sure to add "aviatrix-role-app" to the CMK as Key users in KMS when you want to replace or resize the gateway later. | .. |image_1_IAMRolesClickAviatrixroleapp| image:: Encrypt_Volume_media/image_1_IAMRolesClickAviatrixroleapp.PNG .. |image_2_selectAviatrixAppPolicyEnditPolicy| image:: Encrypt_Volume_media/image_2_selectAviatrixAppPolicyEnditPolicy.PNG .. |image_3_selectJSONAddRulesClickReviewPolicy| image:: Encrypt_Volume_media/image_3_selectJSONAddRulesClickReviewPolicy.PNG .. |image_4_saveChanges| image:: Encrypt_Volume_media/image_4_saveChanges.PNG .. |image_11_selectGwEdit| image:: Encrypt_Volume_media/image_11_selectGwEdit.PNG .. |image_12_checkStatus| image:: Encrypt_Volume_media/image_12_checkStatus.PNG .. |image_13_scrollDownToEncryptVolume| image:: Encrypt_Volume_media/image_13_scrollDownToEncryptVolume.PNG .. |image_14_checkEncryptResult| image:: Encrypt_Volume_media/image_14_checkEncryptResult.PNG .. |image_15_checkEncryptResultOnAws| image:: Encrypt_Volume_media/image_15_checkEncryptResultOnAws.PNG .. disqus:: <file_sep> ============================================================ Aviatrix CoPilot FAQs ============================================================ .. important:: This content has moved. Please see the monitoring and troubleshooting guide in `Aviatrix CoPilot Product Documentation <https://docs.aviatrix.com/copilot/latest/index.html>`_ for CoPilot FAQ information. <file_sep> .. toctree:: :numbered: ============================================================================== OneLogin IdP for SAML Integration ============================================================================== Overview ------------ This guide provides an example on how to configure OneLogin as an IdP for an Aviatrix SAML SP (endpoint). When SAML client is used, your Aviatrix controller acts as the Identity Service Provider (ISP) that redirects browser traffic from client to IdP (e.g., OneLogin) for authentication. Before configuring SAML integration between Aviatrix and OneLogin, make sure you have a valid OneLogin account with administrator access. Configuration Steps ------------------- Follow these steps to configure Aviatrix to authenticate against your OneLogin IdP: Step 1. Create a `temporary Aviatrix SP Endpoint <#aviatrix-endpoint>`__ in the Aviatrix Controller Step 2. Create a `OneLogin SAML App <#onelogin-saml-app>`__ for Aviatrix in OneLogin's Portal Step 3. Retrieve `OneLogin IdP metadata <#onelogin-idp-metadata>`__ Step 4. Update `Aviatrix SP Endpoint <#onelogin-update-saml-endpoint>`__ in the Aviatrix Controller Step 5. `Test the Integration <#onelogin-test-integration>`__ is Set Up Correctly .. _aviatrix_endpoint: Step 1. Create an Aviatrix SP Endpoint ######################################## Visit one of the following links based on your use case and follow step1 (Create temporary Aviatrix SP Endpoint for Aviatrix) from the link's Configuration section: If integrating OneLogin IdP with `Controller Login SAML Config <https://docs.aviatrix.com/HowTos/Controller_Login_SAML_Config.html#config-31>`_ If integrating OneLogin IdP with `OpenVPN with SAML Authentication <https://docs.aviatrix.com/HowTos/VPN_SAML.html#config-31>`_ This step will ask you to pick a short name to be used for the SAML application name ``[Endpoint Name]``. In the notes below we will refer to this as **aviatrix_onelogin**. It can be any string that will identify the SAML application you create in the IdP. We will use the string you select for the SAML application name to generate a URL for OneLogin to connect with Aviatrix. This URL is defined below as **SP_ACS_URL**. This URL should be constructed as: ``https://<your controller ip or host name>/flask/saml/sso/<aviatrix_onelogin>`` .. tip:: Replace **<your controller ip or host name>** with the actual host name or IP address of your controller and **<aviatrix_onelogin>** with the ``[Endpoint Name]`` you chose to refer to the SAML application. .. _onelogin_saml_app: Step 2. Create a OneLogin SAML App for Aviatrix ################################################ .. note:: This step is usually done by the OneLogin Admin. #. Login to OneLogin as an administrator #. To add a new app go to **Applications** > **Applications** > click **Add Apps** |imageOLAddAppsMenu| #. Search for `SAML Test Connector` |imageOLNewAppSearch| #. Select **SAML Test Connector (Advanced)** #. Enter the Configuration values and click **Save** |imageOLNewAppStep1| You can download the rectangular image from `here <./onelogin_saml_media/aviatrix-logo-rect.png>`__ and the square image from `here <./onelogin_saml_media/aviatrix-logo-square.png>`__. #. Click on **Configuration** tab #. Enter the values +--------------------+------------------------------------------------------+ | Field | Value | +====================+======================================================+ | RelayState | Blank | +--------------------+------------------------------------------------------+ | Audience(Entity ID)| **SP Entity ID** | +--------------------+------------------------------------------------------+ | Recipient | **SP_ACS_URL** | +--------------------+------------------------------------------------------+ | ACS (Consumer) | **SP_ACS_URL** | | URL Validator | | +--------------------+------------------------------------------------------+ | ACS (Consumer) URL | **SP_ACS_URL** | +--------------------+------------------------------------------------------+ | Single Logout URL | Blank | +--------------------+------------------------------------------------------+ | Login URL | **SP Login(Test) URL** | +--------------------+------------------------------------------------------+ | SAML not valid | 3 (default) | | before | | +--------------------+------------------------------------------------------+ | SAML not valid | 3 (default) | | on or after | | +--------------------+------------------------------------------------------+ | SAML initiator | Service Provider | +--------------------+------------------------------------------------------+ | SAML nameID format | Transient | +--------------------+------------------------------------------------------+ | SAML issuer type | Specific (default) | +--------------------+------------------------------------------------------+ | SAML signature | Assertion | | element | | +--------------------+------------------------------------------------------+ | Encrypt assertion | Unchecked (default) | +--------------------+------------------------------------------------------+ | SAML encryption | TRIPLEDES-CBC (default) | | method | | +--------------------+------------------------------------------------------+ | Sign SLO Response | Unchecked (default) | +--------------------+------------------------------------------------------+ | SAML | 1440 (default) | | sessionNotOnOrAfter| | +--------------------+------------------------------------------------------+ | Generate | Unchecked (default) | | AttributeValue tag | | | for empty values | | +--------------------+------------------------------------------------------+ | Sign SLO Request | Unchecked (default) | +--------------------+------------------------------------------------------+ |imageConfiguration| #. Click **Save** #. Click on the **Parameters** tab #. Add the following custom parameters (case sensitive) +--------------------+------------+-----------------------------------------+ | Field | Value | Flags | +====================+============+=========================================+ | Email | Email | Include in SAML assertion | +--------------------+------------+-----------------------------------------+ | FirstName | First Name | Include in SAML assertion | +--------------------+------------+-----------------------------------------+ | LastName | Last Name | Include in SAML assertion | +--------------------+------------+-----------------------------------------+ |imageOLNewAppParams| #. Optionally, add a field to map to the profile in Aviatrix +--------------------+----------------+-------------------------------------+ | Field | Value | Flags | +====================+================+=====================================+ | Profile | (User Defined) | Include in SAML assertion | +--------------------+----------------+-------------------------------------+ #. Click **Save** .. _onelogin_idp_metadata: Step 3. Retrieve OneLogin IdP metadata ###################################### #. Click on **More actions** dropdown #. Copy the URL from the **SAML Metadata** for the next step. This URL will be provided to the Aviatrix SP Endpoint. |imageOLSSOTab| .. _onelogin_update_saml_endpoint: Step 4. Update Aviatrix SP Endpoint ################################### .. note:: This step is usually completed by the Aviatrix admin. OneLogin IdP provides IdP Metadata through URL obtained in `Retrieve OneLogin IdP metadata (Step 3) <#onelogin-idp-metadata>`_. Continue with updating Aviatrix SAML Endpoint by visiting one of the following links based on your use case: #. If integrating OneLogin IdP with `Controller Login SAML Config <https://docs.aviatrix.com/HowTos/Controller_Login_SAML_Config.html#config-34>`_ #. If integrating OneLogin IdP with `OpenVPN with SAML Authentication <https://docs.aviatrix.com/HowTos/VPN_SAML.html#config-34>`_ +----------------------------+-----------------------------------------+ | Field | Description | +----------------------------+-----------------------------------------+ | Endpoint Name | ``[Endpoint Name]`` | +----------------------------+-----------------------------------------+ | IPD Metadata Type | URL | +----------------------------+-----------------------------------------+ | IdP Metadata Text/URL | Paste in the **Issuer URL** obtained | | | from the `OneLogin app | | | <#onelogin-idpimetadata>`_. | +----------------------------+-----------------------------------------+ | Entity ID | Select `Hostname` | +----------------------------+-----------------------------------------+ | Access | Select admin or read-only access | +----------------------------+-----------------------------------------+ | Custom SAML Request | Unchecked | | Template | | +----------------------------+-----------------------------------------+ .. note:: Each endpoint only supports one type of access. If you need admin and read-only access, create two separate SAML apps. `Hostname` is the default for Entity ID, but if you have other apps using the same hostname, use a custom Entity ID. .. _onelogin_test_integration: Step 5. Test the Integration ############################# .. tip:: Be sure to assign users to the new application in OneLogin prior to validating. If you do not assign your test user to the Aviatrix SAML application, you will receive an error. Continue with testing the integration by visiting one of the following links based on your use case: 1. If integrating OneLogin IdP with `Controller Login SAML Configuration <https://docs.aviatrix.com/HowTos/Controller_Login_SAML_Config.html#config-35>`_ #. Click `Settings` in the left navigation menu #. Select `Controller` #. Click on the `SAML Login` tab 2. If integrating OneLogin IdP with `OpenVPN with SAML Auth <https://docs.aviatrix.com/HowTos/VPN_SAML.html#config-35>`_ #. Expand `OpenVPN®` in the navigation menu and click `Advanced` #. Stay on the `SAML` tab You can quickly validate that the configuration is complete by clicking on the **Test** button next to the SAML endpoint. |imageAvtxTestSAML| .. |imageOLNewAppSearch| image:: onelogin_saml_media/onelogin_new_app_search.png .. |imageOLNewAppStep1| image:: onelogin_saml_media/onelogin_new_app_step1.png .. |imageOLNewAppParams| image:: onelogin_saml_media/onelogin_parameters.png .. |imageAvtxTestSAML| image:: onelogin_saml_media/avtx_saml_endpoint_test.png .. |imageAvtxSAMLEndpoint| image:: onelogin_saml_media/avtx_saml_endpoint.png .. |imageOLAddAppsMenu| image:: onelogin_saml_media/onelogin_select_add_apps.png .. |imageOLSSOTab| image:: onelogin_saml_media/onelogin_issuer_url.png\ .. |imageConfiguration| image:: onelogin_saml_media/onelogin_configuration.png <file_sep> ============================================================ AWS TGW Orchestrator FAQ ============================================================ What is the AWS TGW Orchestrator? ------------------------------------------------------ .. note:: The AWS TGW Orchestrator is for AWS users only. 1. Orchestrates VPC to VPC and on-prem to VPC connectivity via AWS Transit Gateway. #. Automates AWS Resource Access Manager (RAM) for multi-account support. #. Creates security boundaries between groups of VPCs to achieve network segmentation. #. Out-of-the-box integration of AWS Transit Gateway and Direct Connect and Internet to re-use what has been built. #. Provides `Insane Mode high performance <https://docs.aviatrix.com/HowTos/insane_mode.html>`_ and features rich hybrid network for connecting to on-prem. #. Supports Bring Your Own Firewall to TGW deployment for inline traffic inspection (`Firewall Network <https://docs.aviatrix.com/HowTos/firewall_network_faq.html>`_) #. Orchestrate AWS TGW Inter Region Peering and expand the Security Domains to be global. #. Advanced mode for end-to-end encryption where Aviatrix Gateways are deployed in the AWS Spoke VPCs and Azure Spoke VNets. The AWS Transit Gateway Orchestrator is illustrated in the diagram below. |tgw_overview| In the above diagram, AWS VPCs are grouped into four domains: Dev domain, Prod domain, Shared Service domain and Aviatrix Edge domain. Each VPC in the same domain can communicate with each other via AWS Transit Gateway. VPCs in Prod domain cannot communicate with VPCs in Dev Domain, while all VPCs in Dev domain and Prod domain can communicate with Shared service domain and Aviatrix Edge domain. Through the Aviatrix Transit GW in the Aviatrix Edge domain, Spoke VPCs can communicate with on-prem over Direct Connect. In the deployment, the VPC in the Aviatrix Edge domain is a Spoke VPC from the Transit Gateway point of view. However, it serves as Transit VPC from the Aviatrix Transit Network point of view. No Aviatrix gateways are deployed in Spoke VPCs except in the Transit VPC. Aviatrix Transit GW serves as hub connecting to Azure and GCP networks. What is the Aviatrix TGW Orchestrator? ------------------------------------------------------------- Aviatrix TGW Orchestrator builds the Transit Network that includes TGW attached Spoke VPCs. Why should I use Transit Gateway Orchestrator? ------------------------------------------------- AWS Transit Gateway Orchestrator simplifies, abstracts, and extends the latest AWS Transit Gateway service. Aviatrix Controller makes Transit Gateway-based Transit architecture deployable by overcoming `Transit Gateway limitations <https://docs.aviatrix.com/HowTos/aws_network_limits.html>`_. - **Functional Completeness** Aviatrix makes AWS Transit Gateway functionally deployable. The Orchestrator programs and updates both VPC route tables and TGW route tables so the routes are dynamically propagated to the Spoke VPCs. Read `this answer <https://docs.aviatrix.com/HowTos/tgw_faq.html#why-should-i-use-aviatrix-tgw-orchestrator-to-build-a-transit-network-architecture>`_ for more details. - **Segmentation** The Orchestrator abstracts the route domain and route propagation concepts in Transit Gateway that allows you to create network segmentation by policy and intent. - **Multi-Account** The Orchestrator automates the AWS Resource Access Manager (RAM) to allow you to manage multi account VPC attachments to TGW. - **Scaling** Aviatrix solution overcomes Transit Gateway route limits to scale the hybrid deployment to hundreds/thousands of VPCs. - **Hybrid** The Orchestrator extends the Transit Gateway capability to include Direct Connect support for connecting to on-prem data center. - **Multi Cloud Architecture** Aviatrix Controller creates and manages a multi-cloud global transit architecture with a single pane of glass. How does Transit Gateway (TGW) Orchestrator compliment AWS Transit Gateway service? ----------------------------------------------------------------------------------------------------------------- - **Dynamic Route Propagation** Using Aviatrix Orchestrator is the only guaranteed way to ensure your on-prem routes are properly propagated to Spoke VPCs. AWS Transit Gateway propagates VPC CIDR and IPsec VPN routes to the Transit Gateway route table. But the routes are not propagated to the VPC route table. It is the account owner's responsibility to program VPC route tables. Aviatrix Transit Gateway Orchestrator dynamically updates route entries in the VPC route tables. - **Policy Abstraction** An AWS Transit Gateway provides the capability to allow two Transit Gateway route tables to propagate routes to each other, but the actual route entry programming is left to the owner. Transit Gateway Orchestrator builds on that and allows customers to define policies that form a security boundary. - **Multi-Account Support** Automate the RAM resource sharing process to seamlessly manage multi-account VPC attachment. - **Troubleshooting** FlightPath allows a single pane of glass for troubleshooting connectivity with expert diagnostics capabilities. - **Hybrid and Multi-Cloud Support** Native AWS Transit Gateway VPN and Direct Connect support. Furthermore, Aviatrix allows customers to bridge multiple Transit Gateways together in different and public clouds. - **Traffic Visibility** Netflow log support for traffic between on-prem and all VPCs. - **Stateful Firewall** Enforce security policy for all traffic between on-prem and all VPCs. - **10Gbps Transit** Support 10Gbps Transit network throughput. How does Transit Gateway Orchestrator work with Transit VPC? ------------------------------------------------------------- The Transit Gateway Orchestrator leverages the Aviatrix Transit Network workflow for the hybrid connectivity function to an on-prem data center and branches. It enables the Transit Gateway Orchestrator to connect with on-prem over Direct Connect or Internet. The Transit Gateway Orchestrator can also be used as a stand-alone function for orchestrating VPC to VPC connections. When using the Transit Gateway Orchestrator for hybrid connectivity, no gateways are deployed in the Spoke VPCs for hybrid function. How does the TGW Transit compare with Aviatrix VPC? ---------------------------------------------------------------- Transit VPC refers to the transit deployment model where an Aviatrix Gateway is deployed in a Spoke VPC. This is now called "advanced mode" in the AVX Transit. The Transit Gateway Orchestrator can be deployed with some Spoke VPCs run Aviatrix gateways. When is the right use case to run Aviatrix Spoke gateway? 1. If you need a packet in flight to be encrypted, launch an Aviatrix gateway in the Spoke VPC. #. If you need various NAT functions between Spoke and Transit VPC, use an Aviatrix gateway in the Spoke VPC. #. If you need to obtain Netflow and log information from the Spoke and Transit, use Aviatrix gateway. #. If you want to build a fully isolated Transit network where there is no inter-VPC connectivity by default. There is AWS CloudFormation and Terraform support for Transit Gateway. Why should I use Aviatrix Orchestrator? -------------------------------------------------------------------------------------------------------------------------------------------- AWS CloudFormation for `Transit Gateway <https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-transitgateway.html>`_ is a resource construct for Transit Gateway. So is the `Terraform example<https://www.terraform.io/docs/providers/aws/r/ec2_transit_gateway_route_table.html>`_. They are all useful solutions, but these constructs may not be sufficient to run your network. For example, a Transit Gateway does not propagate routes from on-prem to the VPC route table, meaning there is no guarantee that your VPC instances can reach a specific on-prem server or host. Even if you hard coded the list of CIDRs to shuffle them down to Transit Gateway, what happens when a new VLAN or Subnet is stood up on-prem. Who is going to notify you? A modern distributed network either requires BGP to dynamically propagate the routes or a controller that dynamically updates the routes. No matter what approach you use, it is the only way to guarantee the network actually functions. At Aviatrix, we choose a software defined approach with our Controller. Unless you plan to develop a Controller like ours, you should consider using our product. Learn more about Transit Gateway limitations from `this link <https://docs.aviatrix.com/HowTos/aws_network_limits.html>`_. What is a Security Domain? ------------------------------------- A Security Domain is an Aviatrix enforced network of VPC members, where VPCs in the Security Domain can communicate with each other, and VPCs not in the security domain cannot communicate with VPCs in the Security Domain. An Aviatrix Security Domain is an abstraction that builds upon the AWS Transit Gateway route table concept. One or more Spoke VPCs are members in a security domain. |security_domain| VPCs in a security domain can communicate with each other via a Transit Gateway. Each security domain has a corresponding route table on Transit Gateway. The Aviatrix Controller dynamically programs and updates both VPC route tables so that instances in different Spoke VPCs in the same domain can communicate with each other. Two security domains are not connected, i.e., a Spoke VPC in one domain has no connectivity to another Spoke VPC in a different domain. Connection policy must be specified to connect the two domains so that VPCs in each domain can communicate with each other. What is a Connection Policy? ------------------------------------- A connection policy is an Aviatrix enforced cross Security Domain connectivity rule. A connection policy builds upon the Transit Gateway route table propagation concept, it specifies the connection relationship of one Security Domain to others. If there are two Security Domains connected by policy, instances in Spoke VPCs attached to each domain can communicate with each other via Transit Gateway. In the example below, both Dev_Domain and Prod_Domain have connection policy to Shared_Service_Domain. Dev_Domain and Prod_Domain are not connected. Instances of a VPC in Dev_Domain can communicate with instances of a VPC in Shared_Service_Domain. But instances of a VPC in Dev_Domain cannot communicate with instances of a VPC in Prod_Domain. |domain_policy_diagram| Aviatrix Controller programs all VPC route tables and Transit Gateway route tables so that two Security Domains with a connection policy can communicate with each other automatically. What are the benefits of using Security Domains and Connection Policies? -------------------------------------------------------------------------------------------- The key use case for building Security Domains is to segment traffic between VPCs, sometimes also called east west traffic. The benefits are: - Native Service. It leverages AWS Transit Gateway route domains and route domain propagation constructs. - Zero performance impact. Compared to deploying a firewall instance, this approach has zero network performance impact. Using Security Domains and Connection Policies allow you to identify groups of VPCs with the same requirements from a networking point of view and then apply connection policies at the group level. This avoids having to individually specify connections at the VPC level. The Aviatrix Controller takes care of route programming of all route tables. One analogy to think of a Security Domain is datacenter VLAN/Subnets and hosts connecting to the VLAN/Subnet. In the Aviatrix Security Domain concept, a security domain is a VLAN, a host is VPC plugging in to the VLAN. Hosts in the same VLAN can communicate with each other. If two VLANs are defined by policy to be connected, the hosts in different VLAN can communicate with each other. What is the Default_Domain? -------------------------------------------- When a Transit Gateway is created by the Aviatrix Controller, the Default_Domain is created and a route table corresponding to the Default_Domain is created on the Transit Gateway. If you do not plan on building any network segmentation, you can use Default_Domain for inter Spoke VPC and hybrid communications. What is the Shared_Service_Domain? -------------------------------------------------- When a Transit Gateway is created by the Aviatrix Controller, the Shared_Service_Domain is created and a route table corresponding to the Shared_Service_Domain is created on Transit Gateway. You can attach a Spoke VPC to this domain and host your shared service instances such as your DevOps tools. Shared_Service_Domain is always connected to Default_Domain and Aviatrix_Edge_Domain. What is the Aviatrix_Edge_Domain? ---------------------------------- When a Transit Gateway is created by the Aviatrix Controller, the Aviatrix_Edge_Domain is created and a route table corresponding to the Aviatrix_Edge_Domain is created on the Transit Gateway. Aviatrix_Edge_Domain is designated for connecting VPCs managed by the Transit Gateway Orchestrator to on-prem network. There must be one VPC attached to this domain. In the VPC, an Aviatrix Transit GW is deployed and used for data traffic forwarding between Spoke VPCs and on-prem network. Aviatrix_Edge_Domain is always connected to the Shared_Service Domain and the Default_Domain. How do I deploy the Transit Gateway Orchestrator? --------------------------------------------------------------- The Transit Gateway Orchestrator is deployed in two stages. - `Orchestrator Plan <https://docs.aviatrix.com/HowTos/tgw_plan.html>`_: Define and setup Security Domains and Connection Policies. - `Orchestrator Build <https://docs.aviatrix.com/HowTos/tgw_build.html>`_: Attach a VPC to Transit Gateway and Security Domain. In addition, you can Orchestrator List/Edit ^^^^^^^^^^^^^^^^^^^^^^^^^ - **Show Details** on what is programmed in the VPC route tables and Transit Gateway route table for a given VPC. - **Audit Routes** to discover incorrectness in VPC route tables and Transit Gateway route tables for a given VPC. - **Update VPC CIDR** to update propagated routes to TGW when a new VPC CIDR is added to VPC. - **Edit Spoke VPC Customized Routes** allows you to edit Spoke VPC route table entries that target to TGW. To configure, go to TGW Orchestrator > List, select the Spoke VPC, click the 3 dots skewer and select Edit Spoke VPC Customized Routes. - **Edit Spoke VPC Advertised Routes** allows you to advertise to TGW via Controller a different set of routes other than the default VPC CIDR. To configure, go to TGW Orchestrator > List, select the Spoke VPC, click the 3 dots skewer and select **Edit Spoke VPC** Advertised Routes** to edit. - **Update DXGW Allowed Prefix** if you like to change the summarized prefix after the DXGW has been attached to TGW. Orchestrator View ^^^^^^^^^^^^^^^^^^^^^^^^^^ View what VPC members are attached to Security Domains and Connection Policies. Orchestrator Test ^^^^^^^^^^^^^^^^^^^^^^^^ Instance to instance end-to-end troubleshoot. For more information, refer to `FlightPath <https://docs.aviatrix.com/HowTos/flightpath.html>`_. **TGW Audit** ^^^^^^^^^^^^^^^^^ Audit the correctness of route entries of all attached VPC route tables and its associated TGW route tables including connection policy introduced route propagation. **TGW Approval** ^^^^^^^^^^^^^^^^^^^ Refer to this `link <https://docs.aviatrix.com/HowTos/tgw_approval.html>`_. What can be displayed at the View page? -------------------------------------------------------- View page provides the following information: - ALL Transit Gateways created by the Controller. - All Security Domains under a Transit Gateway. - All VPC members in a Security Domain. - For a given Security Domain, what other domains it connects to. - All VPC attachments to a Transit Gateway. - For a given VPC, what other VPCs in other domains it connects to. |tgw_view| What are the Transit Gateway Orchestrator deployment scenarios? ----------------------------------------------------------------- Check out some `design patterns <https://docs.aviatrix.com/HowTos/tgw_design_patterns.html>`_ that address your requirements. Can I change my plan or VPC attachment on Transit Gateway Orchestrator? -------------------------------------------------------------------------- Yes, all stages (Plan, Build, List, View and Test) are modular. You can change your design any time. I already have a Transit Gateway and some VPCs attached to it. How do I migrate? ----------------------------------------------------------------------------------------------------- Unlike a VPC, where once you have created it and launched instances in the VPC you cannot delete the VPC or move the instances easily, a Transit Gateway and its attachments can all be changed without making changes to the instances and VPC CIDRs. Simply detach the VPCs from the current Transit Gateway, launch a new Transit Gateway, and build it out again. The Aviatrix Transit Gateway Orchestrator manages the entire life cycle of the network, including Security Domains, all Transit Gateway and attachments should be created and managed by the Orchestrator. I plan to isolate a Dev Domain and Prod Domain, but there is one VPC in Dev that needs to connect to Prod. What should I do? ----------------------------------------------------------------------------------------------------------------------------- Since you can create as many security domains as you need, you can create one domain and connect this domain to your Prod domain, and if needed, also to the Dev domain. Simply attach the special VPC to this domain, it will have connectivity to Prod domain. How does the CSR based Transit VPC solution compare with the Transit Gateway? --------------------------------------------------------------------------------- Transit Gateway significantly simplifies building VPC connections. But the Transit Gateway itself is functionally incomplete for hybrid connection. For example, the Transit Gateway does not propagate routes to Spoke VPCs, which means using a Transit Gateway alone does not offer a functional hybrid solution. The example below illustrates how CSR based Transit VPC provides an end-to-end solution while a Transit Gateway alone leaves Spoke VPC route table all empty. |tgw_transit_vpc_compare| The missing function of Transit Gateway is listed as below: - Not able to propagate routes from on-prem to the Spoke VPCs. - Not able to connect with Direct Connect. - The Transit Gateway VPN has 100 route limits. - The Transit Gateway route table cannot summarize routes to advertise to Transit Gateway VPN. While you may think you can gather the on-prem routes and program the Spoke VPC tables, it is in reality not so simple. The on-prem routes change from time to time as new networks are added or removed, which means you need a reliable way to monitor the route changes, handle exceptions and deal with errors and duplicate routes -- essentially a function carried by BGP or an orchestrator. Why should I use Aviatrix Transit Gateway Orchestrator to build a transit network architecture? -------------------------------------------------------------------------------------------------------------------------- Aviatrix Transit Gateway Orchestrator fulfills the need to propagate on-prem routes to the Spoke VPCs. This function is either carried by BGP or is software defined. In the Aviatrix case, it is software defined and performed by the Controller. The diagram below shows how the CSR Transit VPC, the Transit Gateway and the Aviatrix Orchestrator compare for route propagation function. As can be seen, in the CSR Transit VPC case, CSR propagates on-prem routes to Spoke VPC via BGP to VGW; the Transit Gateway has no route propagation to Spoke VPC. Aviatrix Controller propagates routes to Spoke VPC through a software-defined mechanism. |tgw_transit_orchestrator_compare| What value does an Aviatrix Gateway provide in the Transit Gateway Orchestrator? ----------------------------------------------------------------------------------- An Aviatrix Gateway deployed at the edge/transit VPC provides the following values: - Ensure the correctness of connectivity by monitoring and dynamically programming on-prem network address ranges to Spoke VPCs' route tables. - Avoid network outages by detecting and alerting overlapping and conflicting network address ranges between on-prem and all VPCs. - Avoids AWS VGW or Transit Gateway VPN 100 route limits by summarizing Spoke VPC CIDRs advertisements to on-prem network. - Provides traffic visibility by supporting Netflow logs between on-prem network and all VPCs. - Provides stateful firewall to enforce policy between on-prem network and all VPCs. - Out-of-the-box integration to support Direct Connect. - Connects multi-region Transit Gateway deployment. - Supports Transit DMZ architecture by inserting third party firewalls at the edge/transit VPC. - Supports 10Gbps Transit network throughput. When a VPC is attached to a TGW, why can't I simply program the default route in the VPC route table to point to the TGW? ------------------------------------------------------------------------------------------------------------------------------------------------------- In some cases, you absolutely can. For example, if you have a group of VPCs that need to be connected to each other, you can attach each VPC to the same TGW route table with propagation enabled. Then program each VPC route table with the default route (0.0.0.0/0) to point to TGW. But in other cases you may not. Using the above example, if there is public subnet in a Spoke VPC, then you cannot simply program each route table with the default route pointing to TGW, as a public subnet already must have its default route pointing to the IGW. Even a Spoke VPC route table for private subnet may already have the default route point to an AWS NAT gateway. This is quite a common situation and as it happens, you cannot program the default route to the TGW. However, in the example scenarios above, you maybe able to program RFC 1918 (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16) routes of the Spoke VPCs to point to TGW. This is a viable solution you can use to address the issues mentioned above and one that works in a lot of situations. Can the Aviatrix Controller orchestrate VPN attachment to AWS Transit Gateway? ---------------------------------------------------------------------------------------------------------------------- Yes. The Aviatrix Controller allows you setup a VPN attachment from the Controller directly. Can the Aviatrix Controller orchestrate Direct Connect Gateway to AWS Transit Gateway? ---------------------------------------------------------------------------------------------------------------------- Yes. If you would like to connect your Direct Connect directly into Transit Gateway, the Aviatrix Controller allows you to configure an association between the Direct Connect Gateway and AWS Transit Gateway on the Controller. How do I migrate from Aviatrix Transit Gateway to on-prem to TGW + DXGW? ----------------------------------------------------------------------------------------------- 1. Prepare. Create a DXGW on AWS Console, figure out the cloud VPCs summary prefixes. i.e., prepare for TGW Orchestrator > Plan > Step 7. #. Disconnect Aviatrix Transit Gateway from VGW. Transit Network > Setup > Step 8 (Disconnect VGW). #. Connect. Connect to DXGW. TGW Orchestrator > Plan > Step 7 How does Aviatrix TGW Orchestrator compare with AWS Serverless TGW Orchestrator? ------------------------------------------------------------------------------------------------------------- AWS Serverless TGW Orchestrator is a solution published by AWS. It orchestrates VPC attachment to a TGW by programming both the TGW route table and VPC route table. The deployment is a Cloudformation Template that contains many AWS services such as Amazon DynamoDB, Amazon EventBridge, Amazon Simple Notification, AWS Lambda function. ========================================= ============================= ============================= Feature Aviatrix TGW Orchestrator Serverless TGW Orchestrator ========================================= ============================= ============================= Single pane of glass for orchestration Yes No. Orchestration is done by VPC tag Single pane of glass for visualization Yes (View, List) No. Each region must have its own deployment Inter region peering Yes No Orchestration consistency checking Yes (Audit) No Configuration for TGW DXGW Yes No Configuration for TGW VPN Yes No Troubleshooting connectivity Yes (Test) No Onboard secondary account Automated Manual Connection Policies between Domains Flexible Connection Policies 4 Policies defined (Flat, Isolated, Infrastructure & On-premises) Integrate Firewall deployment Yes No ========================================= ============================= ============================= What is Edge Segmentation? --------------------------------------------------- Edge Segmentation allows you to further specify on each edge connection which domain it can communicate with. At `Setup Aviatrix Transit GW <https://docs.aviatrix.com/HowTos/tgw_plan.html#setup-aviatrix-transit-gw>`_, you can select Edge Segmentation for each connection. When this option is selected, you can then use `Build Your Domain Connection Policies <https://docs.aviatrix.com/HowTos/tgw_plan.html#build-your-domain-connection-policies>`_ to specify which Security Domain this edge connection can communicate with, as shown in the diagram below. |edge_segmentation| In the above diagram, Site 1 can communicate with Prod domain but not with Dev domain and Shared Service domain. Site 2 can communicate with Dev domain but not with Prod domain and Shared Service domain. Site 3 can communicate with Shared Service domain but not with Dev domain and Prod domain. Edge Segmentation works across Connection Policies for `AWS TGW Peered <https://docs.aviatrix.com/HowTos/tgw_plan.html#tgw-inter-region-peering>`_ Security Domains. .. note:: The Edge Segmentation is only applicable to TGW Orchestrator deployed Spoke VPCs. It does not apply to Aviatrix Encrypted Transit. It also does not apply to Aviatrix Transit Gateway peering. To enable Edge Segmentation, go to Multi-Cloud Transit Network > Advanced Config, select the Edit Transit tab, scroll down to AWS TGW Segmentation, and click to set it to **Enabled**. How do I enable multicast capability function on TGW? ------------------------------------------------------------------------- Multicast capability function is able to be turned on when users launch AWS TGW. This is API support only. .. |tgw_overview| image:: tgw_overview_media/tgw_overview.png :scale: 30% .. |security_domain| image:: tgw_overview_media/security_domain.png :scale: 30% .. |domain_policy_diagram| image:: tgw_overview_media/domain_policy_diagram.png :scale: 30% .. |tgw_view| image:: tgw_overview_media/tgw_view.png :scale: 30% .. |tgw_transit_vpc_compare| image:: tgw_overview_media/tgw_transit_vpc_compare.png :scale: 30% .. |tgw_transit_orchestrator_compare| image:: tgw_overview_media/tgw_transit_orchestrator_compare.png :scale: 30% .. |edge_segmentation| image:: tgw_overview_media/edge_segmentation.png :scale: 30% .. |tgw_approval| image:: tgw_overview_media/tgw_approval.png :scale: 30% .. disqus:: <file_sep> ================================================================= Egress NAT to a Pool of IP Addresses ================================================================= This document describes the configuration steps for a specific scenario. The scenario is described as follows. - When a packet enters the gateway, the packet's TCP destination port needs to be changed to a different port number. (Destination port translation.) - Based on the original destination port, the packet's source address needs to be changed to a specific source address. (Source address translation.) Follow the steps below to setup for the scenario. Step 1. Launch a gateway ------------------------- Go to the Gateway page and click New Gateway to launch a gateway. Do not check "Enable SNAT". Make sure you select a gateway size that supports multiple secondary IPs. Click `here <https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html#AvailableIpPerENI>`_ for more information. Step 2. Add Multiple IP addresses ------------------------------------- This action creates secondary IP addresses on the selected gateway instance. Note that these IP addresses must be in one consecutive list. This secondary IP address should not include the primary IP address of the gateway. Go to Gateway page and click on the gateway launched in Step 1. Click Edit. Scroll down to "Edit Multiple IPs", enter one or more secondary IP addresses to the gateway. You must enter them in a segment format. Example 1: 192.168.3.11-192.168.3.11 Example 2: 192.168.8.10-192.168.8.16 |edit-secondary-ip| Note the number of secondary IP addresses are `limited <https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html#AvailableIpPerENI>`_ to the gateway instance size. For example, if the gateway instance size is t2.micro, it can support only one secondary IP address. Step 3. Mark and Map Destination Port ----------------------------------------- This action instructs the gateway to translate the destination port and also mark the associated TCP session. Go to Gateway page and click on the gateway you wish to configure. Click Edit. Scroll down to "Destination NAT", click Add/Edit DNAT 1. Click Add/Edit DNAT #. Click Add New #. Enter fields for Destination port, protocol, Mark (a unique number for the purpose of tracking the TCP session identified by the Destination port) and DNAT port. #. Click Save #. Repeat step 1 for multiple entries. #. Click Update to commit. |dnat-port-mapping| Step 4. Configure SNAT ----------------------- This action changes the packet's source IP address based on the "Mark" configured in Step 1. Continue on the Edit page, scroll to SNAT. Select `Customized SNAT`. 1. Select Customized SNAT #. Click Add New #. Enter Mark configured in Step 3; enter one SNAT IP or an IP segment format like Step 2 #. Click Save #. Repeat the above steps for more entries. #. Click Enable SNAT to commit. As shown below, |SNAT-customiz| Step 5. Associate EIPs ----------------------- Go to AWS Console, Services -> EC2 -> Elastic IPs -> Allocate new address. Select the new EIP, Actions -> Associate address -> Instance (for Resource type) -> select the gateway instance that has been allocated secondary IPs -> select one private IP. Repeat the above steps for all secondary IP addresses. Done. Limitations ------------ HA is not supported for Customized SNAT and DNAT in release 3.4. They will be supported in the future release. .. |edit-secondary-ip| image:: egress_nat_pool_media/edit-secondary-ip.png :scale: 30% .. |edit-dnat| image:: egress_nat_pool_media/edit-dnat.png :scale: 30% .. |dnat-port-mapping| image:: egress_nat_pool_media/dnat-port-mapping.png :scale: 30% .. |SNAT-customiz| image:: egress_nat_pool_media/SNAT-customiz.png :scale: 30% .. disqus:: <file_sep> Controller Configuration =========================== This document describes the configurations on the Controller under Settings tab. DNS Server ------------ When "Use VPC/VNET DNS Server" is enabled, the Controller's DNS server is provided by the DHCP option of the VPC where it is launched. The DHCP option contains DNS server which could be on-prem, thus if there is DNS reachability issue, there is network outage issue. When "Use VPC/VNET DNS Server" is disabled, the controller uses Google public DNS server, therefore making the controller's DNS reachability independent of customer's configuration. This is recommended configuration. Login Customization ---------------------- Enable/Disable Admin Login ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The “admin” account login can be disabled to instead use account user. To disable admin login to the Controller, go to Settings -> Controller -> Login Customization. Click Disable. Note that you need a local user with admin privileges to be created first, before you can disable the “admin” account. Login Banner ~~~~~~~~~~~~~~ Customize banner text for first time login for compliance. Any user who login for the first time must acknowledge the text before proceeding to Controller. To configure, go to Settings -> Controller -> Login Customization -> Login Banner. Enter the desired login banner text. Click Status to Enable and Click Save. The next time when a user login to the Controller, the user will be prompted with the banner text. Once the user clicks OK, the banner text does not show in the following logins. .. |imageGrid| image:: advanced_config_media/grid.png .. disqus:: <file_sep> .. raw:: html <style> /* override table no-wrap */ .wy-table-responsive table td, .wy-table-responsive table th { white-space: normal !important; } </style> =========================================================================================== AWS Transit Gateway Limits =========================================================================================== AWS recently announced the Transit Gateway (TGW), a service that significantly simplifies VPC connections and consolidates the edge. It is good to know TGW limits and functional limitations both for planning and operation. For example, while a TGW route table can carry thousands of routes, a TGW VPN has the same hard limit of 100 BGP routes as the classic VGW VPN. When the BGP prefixes exceed 100, the TGW VPN randomly resets the BGP session, leading to unpredictable network outages. The TGW VPN makes the route limit a more serious problem as a TGW route table does not summarize Spoke VPC CIDRs when propagating them to on-prem. This is unlike the Transit VPC CSR solution or Aviatrix solution where the instance based gateway can summarize the Spoke VPC CIDRs. As you migrate Transit VPC to TGW, you should be aware of the new route budget. For example, if you have 50 Spoke VPCs, your on-prem BGP prefixes should be less than 50. If you are already using Cisco CSR to summarize Spoke VPC CIDRs to avoid the route limit, migrating to native TGW will not work. AWS publishes Transit Gateway limits at `this link. <https://docs.aws.amazon.com/vpc/latest/tgw/transit-gateway-limits.html>`_ Below is a list of commonly asked limits and limitations by network engineers. =================================================== =============== ===================== Functions Limits Comments =================================================== =============== ===================== Propagating on-prem routes to Spoke VPC route table not supported VPC owner's responsibility. Learn more `here <https://docs.aviatrix.com/HowTos/tgw_faq.html#why-should-i-use-aviatrix-tgw-orchestrator-to-build-a-transit-network-architecture>`_ Direct Connect support on TGW supported Inter region TGW connectivity supported TGW VPN Static manual In addition to updating Spoke VPC route table, you need to update the TGW route table for on-prem routes. TGW VPN BGP prefix total 100 TGW does not summarize Spoke VPC CIDRs routes. The total route limit is aggregated routes from both on-prem and Spoke VPCs. Spoke VPC Route entries in a route table 100 Default is 50. Performance is impacted when more than 100 routes present. =================================================== =============== ===================== Check out how the Transit Gateway Orchestrator solves `these issues. <https://docs.aviatrix.com/HowTos/tgw_faq.html>`_ .. |survey| image:: opstools_survey_media/survey.png :scale: 30% .. disqus:: <file_sep> ================================================================== Migrating TGW Orchestrator to Multi-Cloud Transit ================================================================== This document helps you migrate from an Aviatrix-deployed `TGW Orchestrator <https://docs.aviatrix.com/HowTos/tgw_faq.html>`_ to an Aviatrix `Multi-Cloud Transit <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ deployment. The objectives here are: - Minimum downtime during migration. - No change to existing VPC infrastructure. - Minimum change to on-prem connectivity. - Transferring Security Domains and Connection Policies in TGW to Multi-Cloud Transit. The Solution ^^^^^^^^^^^^^^^^ The migration architecture is shown as the diagram below. We assume the current TGW Orchestrator deployment deploys Aviatrix Transit Gateway to connect to on-prem. |tgw_to_multi-cloud_transit| Migrating to ActiveMesh 2.0 ------------------------------------------ If the Aviatrix Transit Gateways was deployed prior to Release 6.0. A migration step to ActiveMesh 2.0 is necessary before migrating to Multi-Cloud Transit. 1. Upgrade to Release 6.0. Go to Settings > Maintenance > Upgrade to the Latest. #. After upgrading to 6.0 is complete and successful, go to Settings > Maintenance > Migration > ActiveMesh 2.0 Migration. Click **Migrate**. It should take a few minutes. (Optional) Creating Multi-Cloud Security Domains -------------------------------------------------------------------- If TGW Orchestrator configured Security Domains and Connection policies other than the default domains, create the corresponding security domains and connection policies. Otherwise skip this step and proceed. (You can always setup security domains for Multi-Cloud Transit later.) Follow the `Multi-Cloud Transit Segmentation workflow <https://docs.aviatrix.com/HowTos/transit_segmentation_workflow.html#aviatrix-transit-network-segmentation-workflow>`_ to plan. Migrating --------------- 1. Enable `Connected Transit <https://docs.aviatrix.com/HowTos/transit_advanced.html#connected-transit>`_ on the Aviatrix Transit Gateway if it is not already configured. This configuration mode ensures that migrated Spoke VPCs can communicate with Spoke VPCs that are still attached to TGW. #. Launch an Aviatrix Spoke Gateway in Spoke-1 VPC. Enable HA if required. #. Detach Spoke-1 from TGW. Go to TGW Orchestrator > Build > Detach. #. Attach Aviatrix Spoke-1 gateway to Aviatrix Transit Gateway. Go to Multi-Cloud Transit -> Attach (Step 6a) #. Repeat the steps above for all remaining Spoke VPCs during the migration process. #. (Optional) After all Spoke VPCs have been migrated, set up Multi-Cloud Connection policies. Go to Multi-Cloud Transit > Segmentation > Build to associate each Aviatrix Spoke gateway with a security domain. Other Components ----------------------- Hybrid Connectivity ~~~~~~~~~~~~~~~~~~~~~~~~~ If Hybrid connectivity is accomplished via TGW DXGW or TGW VPN, these connections can continue to serve the new deployment after migration to not to change the connectivity to on-prem. FireNet ~~~~~~~~~~~~ If TGW FireNet has been deployed with TGW Orchestrator, migrate that to `Transit FireNet <https://docs.aviatrix.com/HowTos/transit_firenet_faq.html>`_ where firewall instances can be attached to the Aviatrix Transit Gateway. Disassociate the firewall instances from FireNet and launch and associate to Aviatrix Transit Gateway after the Spoke migration is complete. .. |tgw_to_multi-cloud_transit| image:: migrate_tgw_orchestrator_to_aviatrix_transit_media/tgw_to_multi-cloud_transit.png :scale: 30% .. |migration_architecture| image:: diy_tgw_migrate_to_aviatrix_tgw_media/migration_architecture.png :scale: 30% .. |migrate_tgw_config_vpn| image:: diy_tgw_migrate_to_aviatrix_tgw_media/migrate_tgw_config_vpn.png :scale: 30% .. disqus:: <file_sep> ========================================================= Example Config for Palo Alto Network VM-Series in AWS ========================================================= In this document, we provide an example to set up the VM-Series for you to validate that packets are indeed sent to the VM-Series for VPC-to-VPC and from VPC to internet traffic inspection. For using bootstrap method to setup the VM-Series, follow `this document <https://docs.aviatrix.com/HowTos/bootstrap_example.html>`_. VM-Series in Azure can be set up using the guide `Palo Alto Networks VM-Series Azure Example <https://docs.aviatrix.com/HowTos/config_PaloAltoAzure.html#example-config-for-palo-alto-networks-vm-series-in-azure>`_. The Aviatrix Firewall Network (FireNet) workflow launches a VM-Series at `this step <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#launching-and-associating-firewall-instance>`_ in the process. After the launch is complete, the console displays the VM-Series instance with its public IP address of management interface and allows you to download the .pem file for SSH access to the instance. Below are the steps for initial setup. Downloading VM-Series Access Key -------------------------------------------- After `this step <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#launching-and-associating-firewall-instance>`_ is completed, click **Download** to download the .pem file. If you get a download error, usually it means the VM-Series is not ready. Wait until it is ready, refresh the browser, and then try again. |access_key| Resetting VM-Series Password ------------------------------------------ For Metered AMI, open a terminal and run the following command. .. tip :: Once you download the .pem file, change the file permission to 600. If you are asked to enter a password during the login, the VM-Series is still not ready. Wait and try again. It usually takes up to 15 minutes for the VM-Series to be ready. When the VM-Series is ready, you will not be asked for a password anymore. :: ssh -i <private_key.pem> admin@<public-ip_address> configure set mgt-config users admin password commit For BYOL, open a terminal and run the following command. :: ssh -i <private_key.pem> admin@<public-ip_address> configure set mgt-config users admin password set deviceconfig system dns-setting servers primary <ip_address> commit Terminate the SSH session. Logging in to VM-Series --------------------------------- Go back to the Aviatrix Controller. Go to `this step <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#launching-and-associating-firewall-instance>`_ of the Firewall Network workflow. Click **Management UI**. It takes you the VM-Series you just launched. Login with Username "admin". The password is the password you set at the previous step. Activating VM license ----------------------------- Dynamic updates ----------------------------- From Device > Dynamic Updates > Click **Check Now** > download and then install latest versions of a. Applications and Threats b. Wildfire updates > Click **Check Now** again > download and then install latest version of Antivirus. Configuring VM-Series ethernet1/1 with WAN Zone ------------------------------------------------------------------- Once logged in, click on the Network tab and you should see a list of ethernet interfaces. Click **ethernet1/1** and configure as the following screenshot. 1. Select the **Network** tab. 2. Click **ethernet1/1**. 3. Select **layer3** for Interface Type. 4. Select the **Config** tab in the popup Ethernet Interface window. 5. Select **default** for Virtual Router at the Config tab. 6. Click **New Zone for Security Zone** to create a WAN zone. 7. At the next popup screen, name the new zone **WAN** and click **OK**. |new_zone| Continue: 8. Select the **IPV4** tab in the popup Ethernet Interface window. 9. Select **DHCP Client**. 10. Unmark the **Automatically create default route pointing to default gateway provided by server** checkbox as shown below. |ipv4| 11. Click **Commit**. Once Commit is complete, you should see the Link State turn green at the Network page for ethernet1/1. Configuring VM-Series ethernet1/2 with LAN Zone ------------------------------------------------------------------ Repeat the steps in the "Configuring VM-Series ethernet1/1 with WAN Zone" section above for ethernet1/2. Name the new zone LAN. Click **Commit**. Once Commit is complete, you should see the Link State turn green at the Network page for ethernet1/2. .. tip :: If Keepalive via Firewall LAN Interface is enabled in Firewall Network > Advanced, ensure that ping is allowed in the Firewall LAN interface configuration: https://docs.aviatrix.com/HowTos/firewall_advanced.html?#keep-alive-via-firewall-lan-interface :: Configuring Allow Outbound Policies ------------------------------------------------ 1. Navigate to Policies > Security > Click **Add**. 2. Name the policy "Outbound," then select the **Source** tab. 3. Select LAN zone > Destination tab. 4. Select WAN zone > Click **OK**. Configuring NAT for Egress ------------------------------------- If you would also like to enable NAT to test egress, use the following steps: 1. Navigate to Policies > NAT > Click **Add**. 2. Select the General tab, give it a name, and click **Original Packet**. 3. At Source Zone, click **Add**, and select **LAN**. 4. At Destination Zone, select **WAN**. 5. At Destination Interface, select **Ethernet1/1**, as shown below. |nat_original_packet| 6. Click **Translated Packet**. At Translation Type, select **Dynamic IP And Port**. 7. At Address Type, select **Interface Address**. 8. At Interface, select **ethernet1/1**, as shown below. |nat_translated_packet| Setting up API Access ---------------------------- In order for the Aviatrix Controller to automatically update firewall instance route tables, monitor the firewall instance health and manage instance failover, you need to set up API access permissions. Follow `the instructions here <https://docs.aviatrix.com/HowTos/paloalto_API_setup.html>`_ to enable API access. Ready to Go ------------------- Now your firewall instance is ready to receive packets! The next step is to specify which Security Domain needs packet inspection by defining a connection policy that connects to the firewall domain. This is done by Configuring Allow Outbound Policies (see the section above) in the Firewall Network workflow. For example, deploy Spoke-1 VPC in Security_Domain_1 and Spoke-2 VPC in Security_Domain_2. Build a connection policy between the two domains. Build a connection between Security_Domain_2 to Firewall Domain. Launch one instance in Spoke-1 VPC and Spoke-2 VPC. From one instance, ping the other instance. The ping should go through. View Traffic Log ---------------------- You can view if traffic is forwarded to the firewall instance by logging in to the VM-Series console. 1. Click **Monitor**. 2. Start ping packets from one Spoke VPC to another Spoke VPC where one or both of Security Domains are connected to Firewall Network Security Domain. .. |access_key| image:: config_paloaltoVM_media/access_key.png :scale: 30% .. |new_zone| image:: config_paloaltoVM_media/new_zone.png :scale: 30% .. |ipv4| image:: config_paloaltoVM_media/ipv4.png :scale: 30% .. |nat_original_packet| image:: config_paloaltoVM_media/nat_original_packet.png :scale: 30% .. |nat_translated_packet| image:: config_paloaltoVM_media/nat_translated_packet.png :scale: 30% .. disqus:: <file_sep> =========================================== Docker Swarm Cluster Installation =========================================== Introduction ============ This document describes how to spin up a multi-host Docker swarm cluster built on a VXLAN overlay network in AWS, where a host is a AWS instance and multiple hosts may reside in the same VPC or different VPCs. If there is underlying network connectivity to connect VPCs securely (such as using Aviatrix encrypted peering), a swarm cluster can span across multiple VPCs and to Azure and Google. For a reference design on how to use Aviatrix OpenVPN® capability to remotely access containers in a swarm cluster in the same manner as accessing instances from your laptop, for example, being able to use “curl” to a container running a web service, check out `this link. <https://s3-us-west-2.amazonaws.com/aviatrix-download/Cloud-Controller/Container+Access+Reference+Design.pdf>`__ To build a Swarm cluster, there needs to be a manager instance, a consul instance, and a few hosting instances. To simplify the topology, manager and consul are combined into one instance. There are many How to resources online on creating a swarm cluster with a VXLAN overlay network, the guide below is intended to be a reference. Installation Steps ================== 1. Create one manager/consul instance and few container hosting instances. -------------------------------------------------------------------------- At AWS console, launch instances by using Amazon Linux AMI with Docker package, as shown below: |image0| 2. Install docker daemon --------------------------- | For each of the above instances, do the following: | a. ssh into each instance | b. *sudo yum update* | c. *curl -sSL https://get.docker.com/ \| sh* | d. *sudo service docker start* | e. *sudo service docker stop* | f. *sudo docker daemon -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock&* | g. *sudo usermod -aG docker ec2-user* | h. *logout* 3. Start manager/consul ----------------------- | On the manager/consul instance: | a. ssh into the manager/consul instance | b. *ifconfig eth0 (to get the consul’s eth0 IP address, for example, 172.31.12.28)* | c. *sudo docker run -d -p 8500:8500 --name=consul progrium/consul -server -bootstrap* | d. *docker run -d -p 4000:4000 swarm manage -H :4000 --replication --advertise 172.31.12.28:4000 consul://172.31.12.28:8500* 4. Setup Docker configuration file ------------------------------------ | On each container hosting instance: | a. ssh into each instance | b. Follow the same procedures as described in Step 2 to install docker daemon | c. *sudo vi /etc/sysconfig/docker* and add the following line: | OPTIONS="--default-ulimit nofile=1024:4096 -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock --cluster-advertise eth0:2375 --cluster-store consul://172.31.12.28:8500" | d. *sudo service docker restart* 5. Join swarm cluster ---------------------- | On each container hosting instance: | a. ssh into each instance | b. Use “\ *ifconfig eth0*\ ” to get container hosting instance’s own IP address, e.g. 172.31.14.64 | Tell consul my IP address and to join the swarm cluster: | *sudo docker run -d swarm join --advertise=172.31.14.64:2375 consul://172.31.12.28:8500* 6. Create a VXLAN overlay network ------------------------------------ On the manager/counsul instance: | a. ssh into each instance | b. Create an overlay network “my-overlay-network” with network CIDR “10.0.0.0/24”: *docker -H :4000 network create - -subnet=10.0.0.0/24 my-overlay-network* | c. To list the network and you will see the newly created “my-overlay-network” on each hosting instance joined the swarm cluster | *docker network ls* 7. Launch a container ---------------------------- On each container hosting instance: | a. ssh into the host | b. Launch a container “test01” within the overlay network “my-overlay-network: | *sudo docker run -itd --net my-overlay-network --name test01 ubuntu /bin/bash* | c. Find out the overlay IP address for container “test01” assigned by consul. There are at least three ways: 1. type command on the instance: *sudo docker inspect test01* The above command returns a json output, look for “IPAddress” under my-overlay-network. 2. Type command on the instance: *docker network inspect my-overlay-network,* where my-overlay-network is the overlay network name. 3. Alternatively, use the following command to find out overlay IP address: *docker inspect -f '{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' test01* where test01 is the container name. 8. Install Optional Tools (just for fun) -------------------------------------------- a. Access into the container and install some network tools if you like: | *sudo docker exec -ti test01 /bin/bash* | *apt-get update --yes* | *apt-get install net-tools --yes* | *apt-get install iputils-ping –yes* b. If you like to have ssh access to your container, follow these steps: | *apt-get install openssh-server* | *apt-get install vim* | *sudo vi /etc/ssh/sshd\_config* | and modify the following 2 lines to: | *PermitRootLogin yes* | *#StrictModes yes* | Setup root password by typing command “passwd” | *Sudo service ssh restart* | *ifconfig eth0* to get the IP address c. In the container, do “\ *ping 10.0.0.x*\ ” to other containers you created. 9. To add more container hosting instances, repeat steps 1, 2, 4, 5 and 7. ---------------------------------------------------------------------------- Note: You may need to modify “Security Group” of each instance and manager to allow the access to their ports. OpenVPN is a registered trademark of OpenVPN Inc. .. |image0| image:: Docker_media/image1.png :width: 6.05140in :height: 1.45854in .. add in the disqus tag .. disqus:: <file_sep> #################################################### How to Troubleshoot Azure RM Gateway Launch Failure #################################################### Before you launch an Aviatrix gateway in Azure RM, you must first subscribe to the Aviatrix Companion Gateway in Azure marketplace. To check if you have done so, follow these steps. 1. Log in to Azure Portal. #. Click More Services. #. Click Subscriptions. #. Click the subscription in which you wish to launch an Aviatrix gateway. #. Under Settings, click Programmatic deployment. #. You should see that the Aviatrix companion gateway is in the "Enable" state. #. If the Aviatrix companion gateway is in a Disabled state, click to enable. #. If you do not see an Aviatrix companion gateway at all, follow `these instructions <http://docs.aviatrix.com/HowTos/CompanionGateway.html>`_ When the Aviatrix Controller fails to launch a gateway, there is a toaster error message on the Controller console. If this message does not help you understand the root cause, take the following steps to further troubleshoot. 1. Disable Rollback Function ----------------------------- Typically, when a gateway launch fails, the Controller rolls back all resources including the ones allocated from Azure. In this case, disable the rollback function. Go to Troubleshoot -> Diagnostics -> KEEP GATEWAY ON ERROR. Enable it to make it True. Note this rollback only applies to the next gateway launch. Each time when you need to disable the rollback of gateway creation, you need to turn on this option. 2. Launch the Gateway and Observe Failure ------------------------------------------ From the Controller console, launch the gateway again and observe the failure. 3. Check on Azure Portal Activity Log --------------------------------------- 1. Login in to Azure Portal. #. Click More Services. #. Click Resource Groups. #. Click the resource group created by Aviatrix Controller. The resource group should have a prefix "av-". Click Activity Log. #. Click the error message in red color. #. The specific error message should have a Summary tab and a JSON tab. #. Click the JSON tab to examine the detailed error message, as shown below: |image0| 4. Get Help from Aviatrix Support --------------------------------- If you still cannot figure out the problem, please open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_ to get help. .. |image0| image:: azuregwlaunch_media/azuregwlaunch.png .. disqus:: <file_sep> .. toctree:: :numbered: ============================================================================== Okta IdP for SAML Integration ============================================================================== Overview ------------ This guide provides an example on how to configure Okta as an IdP for an Aviatrix SAML SP (endpoint). When SAML client is used, your Aviatrix controller acts as the Identity Service Provider (ISP) that redirects browser traffic from client to IdP (e.g., Okta) for authentication. Before configuring SAML integration between Aviatrix and Okta, make sure you have a valid Okta account with administrator access. Configuration Steps ------------------- Follow these steps to configure Aviatrix to authenticate against your Okta IdP: Step 1. Create a `temporary Aviatrix SP Endpoint <#aviatrix-endpoint>`__ in the Aviatrix Controller Step 2. Create an `Okta SAML App <#okta-saml-app>`__ for Aviatrix in the Okta Portal Step 3. Retrieve `Okta IdP metadata <#okta-idp-metadata>`__ Step 4. Update `Aviatrix SP Endpoint <#okta-update-saml-endpoint>`__ in the Aviatrix Controller Step 5. `Test the Integration <#okta-test-integration>`__ is Set Up Correctly .. _aviatrix_endpoint: Step 1. Create an Aviatrix SP Endpoint ######################################## Visit one of the following links based on your use case and follow step1 (Create temporary Aviatrix SP Endpoint for Aviatrix) from the link's Configuration section: If integrating Okta IdP with `Controller Login SAML Config <https://docs.aviatrix.com/HowTos/Controller_Login_SAML_Config.html#config-31>`_ If integrating Okta IdP with `OpenVPN with SAML Authentication <https://docs.aviatrix.com/HowTos/VPN_SAML.html#config-31>`_ .. _okta_saml_app: Step 2. Create an Okta SAML App for Aviatrix ############################################ .. note:: This step is usually done by the Okta Admin. #. Login to the Okta Admin portal #. Follow `Okta documentation <https://developer.okta.com/standards/SAML/setting_up_a_saml_application_in_okta>`__ to create a new application. (Use Okta Classic UI to create the app) +----------------+----------------+ | Field | Value | +================+================+ | Platform | Web | +----------------+----------------+ | Sign on method | SAML 2.0 | +----------------+----------------+ |image0| #. General Settings +----------------+-----------------+----------------------------------------+ | Field | Value | Description | +================+=================+========================================+ | App name | Aviatrix | This can be any value. It will be | | | | displayed in Okta only. | +----------------+-----------------+----------------------------------------+ | | Aviatrix logo: | Aviatrix logo (optional) | | | | | | App logo | | |logoAlias1|_ | | | | | |logoAlias2|_ | | +----------------+-----------------+----------------------------------------+ | App visibility | N/A | Leave both options unchecked | +----------------+-----------------+----------------------------------------+ |image1| #. SAML Settings * General +----------------------+----------------------------------------------------+ | Field | Value | +======================+====================================================+ | Single sign on URL | ``https://[host]/flask/saml/sso/[Endpoint Name]`` | +----------------------+----------------------------------------------------+ | Audience URI | ``https://[host]/`` | | (SP Entity ID) | | +----------------------+----------------------------------------------------+ | Default RelayState | ``https://[host]/#/dashboard`` | +----------------------+----------------------------------------------------+ | Name ID format | Unspecified | +----------------------+----------------------------------------------------+ | Application username | Okta username | +----------------------+----------------------------------------------------+ ``[host]`` is the hostname or IP of your Aviatrix controller. ``[Endpoint Name]`` is an arbitrary identifier. This same value should be used when configuring SAML in the Aviatrix controller. The example uses ``aviatrix_saml_controller`` for ``[Endpoint Name]`` ``https://[host]/#/dashboard`` must be set as the Default RelayState so that after SAML authenticates, user will be redirected to dashboard. * Attribute Statements +----------------+-----------------+--------------------------------------+ | Name | Name format | Value | +================+=================+======================================+ | FirstName | Unspecified | user.firstName | +----------------+-----------------+--------------------------------------+ | LastName | Unspecified | user.lastName | +----------------+-----------------+--------------------------------------+ | Email | Unspecified | user.email | +----------------+-----------------+--------------------------------------+ |image2| .. _okta_idp_metadata: Step 3. Retrieve Okta IdP metadata ################################## .. note:: This step is usually completed by the Okta admin. #. After the application is created in Okta, go to the `Sign On` tab for the application. #. Copy the URL from the *Identity Provider metadata* link. This value will be used to configure the Aviatrix SP Endpoint. |image4| 3. Assign the application to your account |image8| .. _okta_update_saml_endpoint: Step 4. Update Aviatrix SP Endpoint ################################### .. note:: This step is usually completed by the Aviatrix admin. Okta IdP provides IdP Metadata through text or URL obtained in `Retrieve Okta IdP metadata (Step 3) <#okta-idp-metadata>`_. Continue with updating Aviatrix SAML Endpoint by visiting one of the following links based on your use case: #. If integrating Okta IdP with `Controller Login SAML Config <https://docs.aviatrix.com/HowTos/Controller_Login_SAML_Config.html#config-34>`_ #. If integrating Okta IdP with `OpenVPN with SAML Authentication <https://docs.aviatrix.com/HowTos/VPN_SAML.html#config-34>`_ +-------------------------+-------------------------------------------------+ | Field | Value | +=========================+=================================================+ | Endpoint Name | ``[Endpoint Name]`` (Use the same name you entered | | | in the Okta Application previously) | +-------------------------+-------------------------------------------------+ | IdP Metadata Type | Text | +-------------------------+-------------------------------------------------+ | IdP Metadata Text/URL | ``URL copied from Okta`` (IdP metadata URL) | +-------------------------+-------------------------------------------------+ | Entity ID | Select `Hostname` | +-------------------------+-------------------------------------------------+ | Access | Select admin or read-only access | +-------------------------+-------------------------------------------------+ | Custom SAML Request | Unchecked | | Template | | +-------------------------+-------------------------------------------------+ .. note:: Each endpoint only supports one type of access. If you need admin and read-only access, create two separate SAML apps. `Hostname` is the default for Entity ID, but if you have other apps using the same hostname, use a custom Entity ID. .. _okta_test_integration: Step 5. Test the Integration ############################# .. tip:: Be sure to assign users to the new application in Okta prior to validating. If you do not assign your test user to the Aviatrix SAML application, you will receive an error. Continue with testing the integration by visiting one of the following links based on your use case: 1. If integrating Okta IdP with `Controller Login SAML Config <https://docs.aviatrix.com/HowTos/Controller_Login_SAML_Config.html#config-35>`_ #. Click `Settings` in the left navigation menu #. Select `Controller` #. Click on the `SAML Login` tab 2. If integrating Okta IdP with `OpenVPN with SAML Authentication <https://docs.aviatrix.com/HowTos/VPN_SAML.html#config-35>`_ #. Expand `OpenVPN®` in the navigation menu and click `Advanced` #. Stay on the `SAML` tab You can quickly validate that the configuration is complete by clicking on the **Test** button next to the SAML endpoint. Configure Okta for Multifactor Authentication (OPTIONAL) ######################################################## Once you have successfully configured Okta IdP with Aviatrix SP, you can configure Okta for Multifactor Authentication. Please read this `article <https://support.okta.com/help/Documentation/Knowledge_Article/Multifactor-Authentication-1320134400>`__ from Okta on Multifactor setup. See this `article <https://support.okta.com/help/Documentation/Knowledge_Article/Configuring-Duo-Security-734413457>`__ if you're interested in using DUO in particular. OpenVPN is a registered trademark of OpenVPN Inc. .. |logoAlias1| replace:: Aviatrix logo with red background .. _logoAlias1: https://a.aviatrix.com/news/press-kit/logo-aviatrix-reverse.zip .. |logoAlias2| replace:: Aviatrix logo with transparent background .. _logoAlias2: https://a.aviatrix.com/news/press-kit/logo-aviatrix.zip .. |image0| image:: SSL_VPN_Okta_SAML_media/image0.png .. |image1| image:: Controller_Login_Okta_SAML_media/image1.png .. |image2| image:: Controller_Login_Okta_SAML_media/image2.png .. |image3| image:: SSL_VPN_Okta_SAML_media/image3.png .. |image4| image:: SSL_VPN_Okta_SAML_media/image4.png .. |image5| image:: SSL_VPN_Okta_SAML_media/image5.png .. |image6| image:: SSL_VPN_Okta_SAML_media/image6.png .. |image7| image:: SSL_VPN_Okta_SAML_media/image7.png .. |image8| image:: Controller_Login_Okta_SAML_media/image5.png .. |imageControllerNavOpenVPNAdvanced| image:: SSL_VPN_Okta_SAML_media/OpenVPN_Advanced_SAML_AddNew.png :scale: 50% .. disqus:: <file_sep> ================================================= Aviatrix Gateway to Cisco IOS Router ================================================= This document describes how to build an IPsec tunnel based Site2Cloud connection between an Aviatrix Gateway and a Cisco IOS router. The network setup is as follows: **VPC/VNet-AVX (with Aviatrix Gateway)** *VPC/VNet CIDR: 10.100.0.0/24* **On-Prem (with Cisco IOS Router)** *On-Prem Network CIDR: 10.10.2.0/24* Creating a Site2Cloud Connection at the Aviatrix Controller ====================================================== 1. Go to Gateway > New Gateway to launch an Aviatrix Gateway at the subnet (public subnet for AWS, GCP, or OCI) of VPC/VNet-AVX. Collect the Gateway's public IP addresses (172.16.31.10 in this example). 2. Go to the Site2Cloud page and click **Add New** to create a Site2Cloud connection. =============================== ================================================================= **Field** **Value** =============================== ================================================================= VPC ID/VNet Name Choose VPC/VNet ID of VPC/VNet-AVX Connection Type Unmapped Connection Name Arbitrary (e.g. avx-ios-s2c) Remote Gateway Type Generic Tunnel Type UDP Algorithms Unmark this checkbox Encryption over Direct Connect Unmark this checkbox Enable HA Unmark this checkbox Primary Cloud Gateway Select the Aviatrix Gateway created above Remote Gateway IP Address Public IP of IOS Router WAN port (172.16.31.10 in this example) Pre-shared Key Optional (auto-generated if not entered) Remote Subnet 10.10.2.0/24 (On-Prem Network CIDR) Local Subnet 10.100.0.0/24 (VPC/VNet-AVX CIDR) =============================== ================================================================= 3. Go to the Site2Cloud page. From the Site2Cloud connection table, select the connection created above (e.g. avx-ios-s2c). - Select **Generic** from the **Vendor** dropdown menu. - Click **Download Configuration** to download the **Generic** Site2Cloud configuration. - Save the configuration file as a reference for configuring your Cisco IOS router. The following is a sample configuration based on the Site2Cloud configuration above. |image0| Configuring Cisco IOS Router =============================== 1. Either ssh into the Cisco router or connect to it directly through its console port. 2. Apply the following IOS configuration to your router: Please note that from version 5.0, we use the gateway's public IP address as the identifier, so the "match identity address" should use the public ip instead of the private ip as pointed in the picture below. |image1| Troubleshooting and Verifying at the Aviatrix Controller ======================================================== 1. At the Aviatrix Controller, go to the Site2Cloud page. Verify that the status of the Site2Cloud connection is up. |image2| 2. At the **Site2Cloud - Diagnostics** page, run various diagnostics commands. =============================== ================================================================= **Field** **Value** =============================== ================================================================= VPC ID/VNet Name VPC/VNet-AVX (Aviatrix Gateway VPC/VNet) ID Connection Name of the Site2Cloud connection created above Gateway Name of the Aviatrix Gateway Action One of the supported diagnostics commands =============================== ================================================================= For support, please open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_ .. |image0| image:: s2c_gw_ios_media/s2c_sample_config.png :width: 5.55625in :height: 3.26548in .. |image1| image:: s2c_gw_ios_media/s2c_ios.png :width: 5.55625in :height: 3.26548in .. |image2| image:: s2c_gw_ios_media/s2c_page.PNG :width: 5.55625in :height: 3.26548in .. disqus:: <file_sep># Technical Contributor Guide This repository contains documentation for Aviatrix written using the [reStructuredText](http://docutils.sourceforge.net/rst.html) format. # Publishing HTML documentation is generated using [Sphinx](http://www.sphinx-doc.org/). Shortly after a commit is pushed to this repository, the latest source is turned into HTML files and published to [docs.aviatrix.com](https://docs.aviatrix.com). ## How To Generate If you'd like to generate the documentation yourself, follow the steps outlined below. ### Install Sphinx 1. Install the latest version of [Sphinx](http://www.sphinx-doc.org/en/stable/install.html) 2. Install [sphinx-rtd-theme](https://github.com/rtfd/sphinx_rtd_theme) ```pip install sphinx-rtd-theme``` 3. Install [sphinxcontrib-disqus](https://pypi.python.org/pypi/sphinxcontrib-disqus) ```pip install sphinxcontrib-disqus``` ### Build output with Sphinx To generate the output, use the `sphinx-build` command. It has a lot of options; but, the simple case of generating HTML output looks like: ```sphinx-build -b html . ./output``` <file_sep> document.addEventListener("DOMContentLoaded", (event) => { const h1Element = document.querySelector("h1"); if (h1Element) { var newDiv = document.createElement("div"); newDiv.classList.add("admonition", "important"); var firstP = document.createElement("p"); firstP.classList.add("first", "admonition-title"); var newSpan = document.createElement("span"); newSpan.classList.add("highlighted"); newSpan.innerHTML = "Important"; firstP.appendChild(newSpan); var secondP = document.createElement("p"); secondP.classList.add("last"); secondP.innerHTML = "This documentation site is for Controller version 6.9 and earlier. For the latest documentation, please visit: <a href=\"https://docs.aviatrix.com\">docs.aviatrix.com</a>." newDiv.appendChild(firstP) newDiv.appendChild(secondP) h1Element.parentNode.insertBefore(newDiv, h1Element); } else { console.error("No <h1> elements found on the page."); } }); <file_sep> .. raw:: html <style> /* override table no-wrap */ .wy-table-responsive table td, .wy-table-responsive table th { white-space: normal !important; } </style> ===================================================================== Aviatrix Gateway to Oracle DRG ===================================================================== Overview ------------------- This document describes how to configure an IPsec tunnel between an Aviatrix Gateway and an Oracle Dynamic Routing Gateway (DRG). |gw2drg| Deployment Guide ---------------------------------- For this use case, we will create an IPsec connection from DRG first and then configure a Site2Cloud connection at the Aviatrix Controller. Creating an IPsec Connection from DRG ++++++++++++++++++++++++++++++++++++ .. note:: **Prerequisites** #. You have a DRG created and attached to a VCN. #. You have an Aviatrix Gateway provisioned in a VPC/VNet. You will need this gateway's public IP address and its VPC/VNet CIDR for the steps below. #. Log in to your Oracle Cloud Console and create a route rule for the DRG. We need to modify the desired route table and create a route rule to take any traffic destined for the Aviatrix Gateway's VPC/VNet CIDR and route it to the DRG. #. Under **Core Infrastructure**, go to **Networking** and click **Virtual Cloud Networks**. #. Click your VCN. #. Select the desired route table(s) for your VCN. #. Click **Edit Route Rules**. #. Create a new route rule as following and save it. +--------------------------------+--------------------------------------------------------+ | Field | Description | +================================+========================================================+ | Target Type | Dynamic Route Gateway | +--------------------------------+--------------------------------------------------------+ | Destination CIDR Block | Aviatrix GW's VPC/VNet CIDR (172.19.0.0/16 in this | | | example) | +--------------------------------+--------------------------------------------------------+ | Target Dynamic Routing Gateway | Select the desired existing DRG | +--------------------------------+--------------------------------------------------------+ |vcn_route_table| #. Log in to your Oracle Cloud Console and create security rules. We will edit the security list associated with your VCN subnets. We need to add two new rules: one ingress rule for traffic coming from the Aviatrix Gateway's VPC/VNet and one egress rule for traffic destinating to the Aviatrix Gateway's VPC/VNet. #. Under **Core Infrastructure**, go to **Networking** and click **Virtual Cloud Networks**. #. Click your VCN. #. Select the desired security list(s) associated with your subnets. #. Click **Edit All Rules**. #. In **Allowed Rule for Ingress** section, enter the following values to create a rule to allow incoming traffic from Aviatrix Gateway's VPC/VNet. +--------------------------------+--------------------------------------------------------+ | Field | Description | +================================+========================================================+ | Source Type | CIDR | +--------------------------------+--------------------------------------------------------+ | Source CIDR | Aviatrix GW's VPC/VNet CIDR (172.19.0.0/16 in this | | | example) | +--------------------------------+--------------------------------------------------------+ | IP Protocols | All Protocols | +--------------------------------+--------------------------------------------------------+ |vcn_security_rule_ingress| #. In **Allowed Rule for Egress** section, enter the following values to create a rule to allow outgoing traffic to the Aviatrix Gateway's VPC/VNet. +--------------------------------+--------------------------------------------------------+ | Field | Description | +================================+========================================================+ | Destination Type | CIDR | +--------------------------------+--------------------------------------------------------+ | Destination CIDR | Aviatrix GW's VPC/VNet CIDR (172.19.0.0/16 in this | | | example) | +--------------------------------+--------------------------------------------------------+ | IP Protocols | All Protocols | +--------------------------------+--------------------------------------------------------+ |vcn_security_rule_egress| #. Create a CPE object. In this task, we create the CPE object, which is a logical representation of the Aviatrix Gateway. #. Under **Core Infrastructure**, go to **Networking** and click **Customer-Premises Equipment**. #. Click **Create Customer-Premises Equipment**. #. Enter the following values and click **Create**. +------------------------------+---------------------------------------------+ | Field | Description | +==============================+=============================================+ | Create in Compartment | Leave as is (the VCN's compartment) | +------------------------------+---------------------------------------------+ | Name | A descriptive name for the CPE object | +------------------------------+---------------------------------------------+ | IP Address | Public IP address of Aviatrix Gateway | +------------------------------+---------------------------------------------+ | Tags | Optional | +------------------------------+---------------------------------------------+ |cpe| #. From the DRG, create an IPsec connection to the CPE object. #. Under **Core Infrastructure**, go to **Networking** and click **Dynamic Routing Gateways**. #. Click the DRG created earlier. #. Click **Create IPsec Connection**. #. Enter the following values and click **Create IPsec Connection**. +-----------------------------------------+--------------------------------------------------------+ | Field | Description | +=========================================+========================================================+ | Create in Compartment | Leave as is (the VCN's compartment) | +-----------------------------------------+--------------------------------------------------------+ | Name | A descriptive name for the IPsec connection | +-----------------------------------------+--------------------------------------------------------+ | Customer-Premises Equipment Compartment | Leave as is (the VCN's compartment) | +-----------------------------------------+--------------------------------------------------------+ | Customer-Premises Equipment | Select the CPE object created earlier | +-----------------------------------------+--------------------------------------------------------+ | Static Route CIDR | Aviatrix GW's VPC/VNet CIDR (172.19.0.0/16 in this | | | example) | +-----------------------------------------+--------------------------------------------------------+ | Tags | Optional | +-----------------------------------------+--------------------------------------------------------+ |ipsec_connection| #. Once the IPsec connection enters the **Available** state, click the **Action** icon (three dots), and then click **Tunnel Information**. Please copy the **IP Address** of the VPN headend and the **Shared Secret** for configuring a Site2Cloud connection at the Aviatrix Controller. |ipsec_info| #. Log in to the Aviatrix Controller. #. Follow the steps in `this </HowTos/site2cloud.html>`__ guide. Use this table for specific field values. +-------------------------------+-----------------------------------------------------------------+ | Field | Description | +===============================+=================================================================+ | VPC ID/VNet Name | Select the Aviatrix Gateway's VPC/VNet | +-------------------------------+-----------------------------------------------------------------+ | Connection Type | Unmapped | +-------------------------------+-----------------------------------------------------------------+ | Connection Name | A descriptive name for the Site2Cloud connection | +-------------------------------+-----------------------------------------------------------------+ | Remote Gateway Type | Oracle | +-------------------------------+-----------------------------------------------------------------+ | Tunnel Type | UDP | +-------------------------------+-----------------------------------------------------------------+ | Encryption over ExpressRoute/ | Unchecked | | Direct Connect | | +-------------------------------+-----------------------------------------------------------------+ | Enable HA | Unchecked | +-------------------------------+-----------------------------------------------------------------+ | Primary Cloud Gateway | Select the desired Aviatrix Gateway | +-------------------------------+-----------------------------------------------------------------+ | Remote Gateway IP Address | Enter the **IP Address** copied from Oracle IPsec connection | +-------------------------------+-----------------------------------------------------------------+ | Pre-shared Key | Enter the **Shared Secret** copied from Oracle IPsec connection | +-------------------------------+-----------------------------------------------------------------+ | Remote Subnet | Enter Oracle VCN's CIDR (10.1.1.0/24 in this example) | +-------------------------------+-----------------------------------------------------------------+ | Local Subnet | Enter Aviatrix Gateway's VPC/VNet CIDR (Or leave it blank) | +-------------------------------+-----------------------------------------------------------------+ |s2c_config| Test -------- Once complete, test the communication using the tunnel by sending traffic between instances in the Aviatrix Gateway's VPC/VNet and Oracle VCN. Log in to the Aviatrix Controller and go to the **Site2Cloud** page. Verify that the Site2Cloud connection created above is "Up" in Status. |s2c_status| Troubleshooting ---------------------- Wait 2-3 minutes for the tunnel to come up. If it does not come up within that time, check the IP addresses to confirm they are accurate. Additional troubleshooting is available in the **Diagnostics** tab. Appendix: Enable HA ------------------------------ You can enable HA for an Aviatrix Site2Cloud connection to Oracle DRG. Please add following extra steps to the configuration. |gw2drg-ha| Creating an Aviatrix HA Gateway +++++++++++++++++++++++++++ Before creating a Site2Cloud connection, follow `this <https://docs.aviatrix.com/Solutions/gateway_ha.html>`__ guide's **Backup Gateway and Tunnel HA** section to create Aviatrix HA gateway in the same VPC/VNet. Creating a Second IPsec Connection Between the Same DRG and Aviatrix HA Gateway ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ From the Oracle Cloud console, create a second IPsec connection between the same DRG and Aviatrix HA Gateway. #. Create a new CPE at Oracle Cloud Console for the Aviatrix HA Gateway: +------------------------------+----------------------------------------------------+ | Field | Description | +==============================+====================================================+ | Create in Compartment | Leave as is (the VCN's compartment) | +------------------------------+----------------------------------------------------+ | Name | A descriptive name for the second CPE object | +------------------------------+----------------------------------------------------+ | IP Address | Public IP address of Aviatrix HA Gateway | +------------------------------+----------------------------------------------------+ | Tags | Optional | +------------------------------+----------------------------------------------------+ #. Create a new IPsec connection at Oracle Cloud Console for the Aviatrix HA Gateway: +-----------------------------------------+--------------------------------------------------------+ | Field | Description | +=========================================+========================================================+ | Create in Compartment | Leave as is (the VCN's compartment) | +-----------------------------------------+--------------------------------------------------------+ | Name | A descriptive name for the second IPsec connection | +-----------------------------------------+--------------------------------------------------------+ | Customer-Premises Equipment Compartment | Leave as is (the VCN's compartment) | +-----------------------------------------+--------------------------------------------------------+ | Customer-Premises Equipment | Select the second CPE object created earlier | +-----------------------------------------+--------------------------------------------------------+ | Static Route CIDR | Aviatrix GW's VPC/VNet CIDR (172.19.0.0/16 in this | | | example) | +-----------------------------------------+--------------------------------------------------------+ | Tags | Optional | +-----------------------------------------+--------------------------------------------------------+ #. Once the second IPsec connection enters the **Available** state, click the **Action** icon (three dots), and then click **Tunnel Information**. Please copy the **IP Address** of the VPN headend and the **Shared Secret**. Create Aviatrix Site2Cloud Connection with HA +++++++++++++++++++++++++++++++++++++++++++++ From the Aviatrix Controller > Site2Cloud page, click **+ Add New**. Under **Add a New Connection**, make sure the **Enable HA** checkbox is marked. Additional fields are displayed when checked. All other fields should have the same values as corresponding ones **without HA**. +-----------------------------------+-----------------------------------------------------------------+ | Field | Description | +===================================+=================================================================+ | Backup Gateway | Select the Aviatrix HA Gateway just created | +-----------------------------------+-----------------------------------------------------------------+ | Remote Gateway IP Address(Backup) | Enter the IP Address copied from the second IPsec connection | +-----------------------------------+-----------------------------------------------------------------+ | Pre-shared Key(Backup) | Enter the Shared Secret copied from the second IPsec connection | +-----------------------------------+-----------------------------------------------------------------+ .. |gw2drg| image:: s2c_drg_media/gw2drg.png .. |vcn_route_table| image:: s2c_drg_media/vcn_route_table.PNG .. |vcn_security_rule_ingress| image:: s2c_drg_media/vcn_security_rule_ingress.PNG .. |vcn_security_rule_egress| image:: s2c_drg_media/vcn_security_rule_egress.PNG .. |cpe| image:: s2c_drg_media/cpe.PNG .. |ipsec_connection| image:: s2c_drg_media/ipsec_connection.PNG .. |ipsec_info| image:: s2c_drg_media/ipsec_info.PNG .. |s2c_config| image:: s2c_drg_media/s2c_config.PNG .. |s2c_status| image:: s2c_drg_media/s2c_status.PNG .. |gw2drg-ha| image:: s2c_drg_media/gw2drg-ha.png .. disqus:: <file_sep>========================================================= Aviatrix Gateway to Azure VPN Gateway ========================================================= This guide helps you to configure Site2Cloud IPsec tunnels between an Aviatrix Gateway and an Azure Virtual Network Gateway (VNG). Configuration Workflow ====================== Before you start, make sure you have the latest software by checking the Dashboard. If an alert message displays, click **Upgrade** to download the latest software. The Site2Cloud on CloudN configuration workflow is very simple. 1. In Aviatrix Controller, go to Gateway page to create one non-VPN gateway. #. At the Azure portal, go to the Virtual network gateways page. Fill in the following information to create a new Virtual Network Gateway: +--------+-----------------------------------------------------+ | Name | Enter an Azure VPN gateway name (e.g. Azure-VPN-GW) | +--------+-----------------------------------------------------+ |Gateway | type: VPN | +--------+-----------------------------------------------------+ |VPN type| Policy-based | +--------+-----------------------------------------------------+ |SKU | Basic | +--------+-----------------------------------------------------+ |Location| Select a desired location | +--------+-----------------------------------------------------+ |Virtual | Select a desired VNet | |network | | +--------+-----------------------------------------------------+ #. Once the virtual network gateway is provisioned, record its public IP address. #. In Aviatrix Controller, go to the Site2Cloud page. Fill in the following information to create a Site2Cloud connection: +-------------------+----------------------------------------------------------------------------+ | VPC ID/VNet Name | Select the VPC/VNet where your Aviatrix gateway is created at Step 1 | +-------------------+----------------------------------------------------------------------------+ | Connection Type | Unmapped | +-------------------+----------------------------------------------------------------------------+ | Connection Name | Enter a Site2Cloud connection name | +-------------------+----------------------------------------------------------------------------+ | Remote Gateway | Select **Azure VPN** | | Type | | +-------------------+----------------------------------------------------------------------------+ | Algorithms | Unmark this checkbox | +-------------------+----------------------------------------------------------------------------+ | Encryption over | Unmark this checkbox | | ExpressRoute/ | | | Direct Connect | | +-------------------+----------------------------------------------------------------------------+ | Enabled HA | Unmark this checkbox | +-------------------+----------------------------------------------------------------------------+ | Primary Cloud | Select the gateway created at Step 1 | | Gateway | | +-------------------+----------------------------------------------------------------------------+ | Remote Gateway | Enter the public IP of your virtual network gateway (collected at | | IP Address | Step 3) | +-------------------+----------------------------------------------------------------------------+ | Pre-shared Key | Enter your own pre-shared key or leave it blank so that Controller will | | | generate one | +-------------------+----------------------------------------------------------------------------+ | Remote Subnet | Enter the CIDR of the VNet in which your Virtual Network Gateway is | | | created at Step 2 | +-------------------+----------------------------------------------------------------------------+ | Local Subnet | Enter the CIDR of the VPC/VNet in which your Aviatrix Gateway is | | | created at Step 1 | +-------------------+----------------------------------------------------------------------------+ #. Once the Site2Cloud connection is created, select the same connection at the Site2Cloud page. Select the following values for each specific field and click **Download Configuration**. +----------+---------------------+ | Vendor | Generic | +----------+---------------------+ | Platform | Generic | +----------+---------------------+ | Software | Vendor Independent | +----------+---------------------+ #. Collect the following information from the downloaded configuration template: +------------------------+-------------------------------------+ | Pre-Shared Key from #1 | Internet Key Exchange Configuration | +------------------------+-------------------------------------+ | Aviatrix Gateway Public| Tunnel Interface Configuration | | IP from #3 | | +------------------------+-------------------------------------+ | Cloud Network(s) from | Tunnel Interface Configuration | | the Subnets section | | | of #3 | | +------------------------+-------------------------------------+ #. At the Azure portal, go to the Local network gateways page. Enter the following information to create a local network gateway: +---------------+--------------------------------------------------------------+ | Name | Enter a local gateway name (e.g. AVX-GW) | +---------------+--------------------------------------------------------------+ | IP address | Enter the Aviatrix Gateway's public IP collected at Step 6 | +---------------+--------------------------------------------------------------+ | Address space | Enter the "Cloud Network" CIDR collected at Step 6 | +---------------+--------------------------------------------------------------+ | Configure | Unmark this checkbox | +---------------+--------------------------------------------------------------+ | BGP settings | | +---------------+--------------------------------------------------------------+ #. At Azure portal, go to Virtual network gateways page and select the gateway created at Step 2. #. Select "Connections" from "Settings". Enter the following information to create a connection: +------------------------------+-------------------------------------------------------+ | Name | Enter a VPN connection name (e.g. Azure-AVX-S2C) | +------------------------------+-------------------------------------------------------+ | Connection type | Select **Site-to-site (IPsec)** | +------------------------------+-------------------------------------------------------+ | Virtual network gateway | Select the VPN gateway created at Step 2 | +------------------------------+-------------------------------------------------------+ | Local network gateway | Select the local gateway created at Step 7 | +------------------------------+-------------------------------------------------------+ | Shared key (PSK) | Enter the pre-shared key collected at Step 6 | +------------------------------+-------------------------------------------------------+ Troubleshooting =============== To check a tunnel state, go to Site2Cloud. The tunnel status will be displayed in a popup window. To troubleshoot a tunnel state, go to Site2Cloud > Diagnostics. .. disqus:: <file_sep> =========================================== Site2Cloud Certificate-Based Authentication =========================================== If you want to use certificate-based authentication when establishing a Site2Cloud connection between your Aviatrix gateways, or between an Aviatrix gateway and an external device, you use the CA Certificate tab to: - Add external device CA certificates - Download the Aviatrix gateway CA certificate so that you can provide it to the external device The external device CA certificates must be available before you `configure the Site2Cloud connection <https://docs.aviatrix.com/HowTos/site2cloud.html>`_. On the external device side, you: - obtain the IPsec VPN gateway device certificate - export the Trusted Root CA certificate for use in the Site2Cloud configuration - import the Aviatrix CA certificate (downloaded from the CA Certificate tab) - use the information in the downloaded Site2Cloud configuration file to configure your tunnels/interfaces On the Aviatrix side, you: - configure the Site2Cloud connection - select the remote certificate (generated from the external device) when prompted - enter the remote identifier when prompted (depends on the external device; typically the Remote Identifier is the value of the common name or subject field in the VPN gateway device certificate) - export the Aviatrix CA certificate - download the Site2Cloud configuration you just created, to use when configuring tunnels/interfaces on your external device Currently only the Palo Alto VM-Series firewall is supported as an external device. See `here <https://docs.aviatrix.com/HowTos/S2C_GW_PAN.html>`_ for more information on certificate-based authentication using this firewall. For information on using certificate-based authentication between two Aviatrix gateways, see `here <https://docs.aviatrix.com/HowTos/site2cloud_aviatrix.html>`_. |ca-cert| Adding a CA Certificate ----------------------- After you obtain the CA certificate from your external device, you must upload it on the CA Certificate tab before creating your Site2Cloud connection. 1. In the Aviatrix Controller, navigate to Site2Cloud > CA Certificate. #. On the CA Certificate tab, click **Add**. #. Under Add Certificate, in the Tag Name field, enter a unique name for the certificate. #. Select the CA certificate to upload. #. Click **OK**. If you have received an email notification that a CA certificate is about to expire, or one of the certificates is showing as Invalid on the CA Certificate list, you use the above procedure to add the new certificate. You must then delete the expired certificate. .. important:: You cannot switch to another certificate after the Site2Cloud connection has been created. Downloading the Aviatrix CA Certificate ---------------------------------------- You must download the Aviatrix CA certificate and upload it to your external device (or Aviatrix gateway) for the Site2Cloud connection to work. Navigate to Site2Cloud > CA Certificate > Aviatrix CA Certificate to download the cloud gateway CA certificate. Deleting a Certificate ---------------------- You must delete a certificate if it has expired. These certificates show as 'invalid' in the CA Certificate table. .. important:: You should not delete the certificate while it is in use; this will bring down the Site2Cloud connection. Only admin users can delete certificates. 1. In the Aviatrix Controller, navigate to Site2Cloud > CA Certificate. #. On the CA Certificate tab, select the certificate and click **Delete**. #. (optional) On the Site2Cloud > Diagnostics tab, select the appropriate gateway and then select **Restart service** from the Action list. This removes the deleted certificate from the gateway cache. Limitations ----------- - Only the Palo Alto VM-Series firewall is supported in this version of Site2Cloud cert-based authentication. - Only the Elliptic Curve DSA algorithm (256-bit) is supported in this version. - Only the PEM certificate file type is supported in this version. - You can only use one certificate group (all the certificates with the same tag name) per Site2Cloud connection. - You can only roll back the platform version if the previous version supports certificate-based authentication (not supported prior to 6.8). .. |site2cloud| image:: site2cloud_cacert_media/ca-cert.png :scale: 50% .. disqus:: <file_sep> ========================================================================================= Use IPv6 for User VPN Access ========================================================================================= The Problem --------------------- If you need to give user VPN access to VPC/VNets but the VPC/VNets have overlapping CIDRs, currently there are two common solutions. One is to run a User VPN gateway in each VPC/VNet and have users to connect individually to a VPC/VNet. This approach makes managing user VPN certificates difficult for both users and administrators if the number of VPC/VNets are large. Another approach is to use NAT functions to translate the addresses between the overlapping CIDRs. This document describes how to use IPv6 to support user VPN access to multi-VPC/VNets where the VPC/VNet CIDRs may overlap, as shown in the diagram below. |ipv6_uservpn| Prerequisite -------------- Follow the instructions `here <https://docs.aviatrix.com/HowTos/ipv6_peering.html>`_ to created encrypted peering that tunnels IPv6 addresses. Launching an Aviatrix Gateway ---------------------------------------------- #. Log in to the Controller. #. Go to Gateways > Add New to launch a gateway in one central VPC/VNet. #. Make sure you mark the **VPN Access** checkbox to enable user VPN function. Adding VPN Networks for Split Tunnel ------------------------------------------------ This step adds the VPC/VNet CIDRs of the peered VPC/VNet so that the VPN gateway can push routes to the VPN endpoint. #. Log in to the Controller. #. Go to OpenVPN > Edit Config> Modify Split Tunnel. #. Add a list of VPC/VNet IPv6 CIDRs in a comma-separated format, as shown below. |ipv6_vpncidr| Adding a VPN User ----------------------------------- #, Log in to the Controller. #. Go to OpenVPN > VPN Users > Add New. #. Select the VPN gateway you launched above. Create a new user with email address. An email will be sent to the VPN user with instructions on how to download the VPN client and connect to VPN. Run the VPN client and you should be able to access virtual machine (EC2/GCE) instances using its IPv6 address. Scaling out VPN Gateways ---------------------------------- You can repeat the steps under "Launching an Aviatrix Gateway" section above to launch more VPN gateways to scale out the performance. To learn more about user VPN, see `User VPN FAQ <https://docs.aviatrix.com/HowTos/openvpn_faq.html>`_. Adding More VPC/VNets -------------------------------- If you need to connect more VPC/VNets, make sure you build encrypted tunnel and repeat Step2 to add the new IPv6 network CIDRs to the VPN Network list. Troubleshooting Tips --------------------------- If you experience VPN client connectivity issue, check the following: - Encrypted tunnel is up. - Instance Security Group is configured with the correct inbound port open. - If you have User Profile enabled, the profile has the correct policies. For support, please open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_. .. |ipv6_uservpn| image:: ipv6_multivpc_vpn_media/ipv6_uservpn.png :scale: 30% .. |ipv6_vpncidr| image:: ipv6_multivpc_vpn_media/ipv6_vpncidr.png :scale: 30% .. disqus:: <file_sep> ========================================================= Transit FireNet Workflow for Azure Native Spoke VNets ========================================================= Aviatrix Transit FireNet allows you to deploy firewalls functions for the Aviatrix Multi-Cloud Transit architecture. With Transit FireNet feature, the Firewall Network (FireNet) function is integrated into the Aviatrix Transit gateway. Aviatrix Transit FireNet supports different hashing algorithms available in Azure cloud to load balance the traffic across different firewalls which includes `Hash-based distribution mode (five-tuple hash) <https://docs.microsoft.com/en-us/azure/load-balancer/load-balancer-distribution-mode#hash-based-distribution-mode>`_ and `Source IP affinity mode (three-tuple or two-tuple hash) <https://docs.microsoft.com/en-us/azure/load-balancer/load-balancer-distribution-mode#source-ip-affinity-mode>`_. To learn more about Hashing Algorithm and Transit FireNet, check out `Transit FireNet FAQ. <https://docs.aviatrix.com/HowTos/transit_firenet_faq.html>`_ In this example, Transit VNet with Aviatrix Gateways will be deployed, and two Native Spoke VNets will be attached to it. The transit VNet will have a firewall of supported vendors (Check Point, Palo Alto Networks and Fortinet etc.) deployed in it. Please see the diagram below for more details. Once the infra is in-place then the policy will be created to inspect the east-west and north-south traffic. |avx_tr_firenet_topology_az_native| Step 1 : Create Transit VNet ******************************* VNets can be created manually on Azure or directly from Aviatrix Controller. Aviatrix controller has set of useful tools available for users and in this example, VNets are created following the Useful Tools `Create a VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ guidelines. 1. Login to the Aviatrix Controller with username and password #. Navigate to **Useful Tools -> Create A VPC** #. Add one VNet for Transit FireNet Gateway and select **Aviatrix FireNet VPC** option as shown below. #. Create two more VNets with **no option/checkbox** selected for Spoke Gateways. |create_vpc_native_case| Step 2: Deploy the Transit Aviatrix Gateway *************************************************** Transit Aviatrix Gateway can be deployed using the `Transit Gateway Workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-a-transit-gateway>`_ Prerequisite for Azure ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Transit FireNet builds on the Aviatrix Transit Network solution where Aviatrix gateways are deployed in Transit VNet and/or in Spoke VNet in Azure. Make sure the deployment meets the following specifications: 1. ActiveMesh must be enabled when launching the Aviatrix Transit Gateway. 2. Select the option “Enable Transit FireNet” when launching the Aviatrix Transit Gateway. 3. Aviatrix Transit Network must be in Connected mode. Go to Transit Network -> Advanced Config -> Connected Transit. Click Enable. .. important:: Controller version 6.0 and prior, the minimum size of the Aviatrix Transit Gateway virtual machine is Standard_B2ms. Starting 6.1, minimum Transit Gateway instance size requirement is removed. Procedure ~~~~~~~~~~~~~~~~~~~~~ 1. Navigate to **MULTI-CLOUD TRANSIT -> Setup -> #1 Launch an Aviatrix Transit Gateway** #. Choose virtual machine size **Standard_B2ms** #. Enable **ActiveMesh Mode (Mandatory)** #. Enable InsaneMode for higher throughputs (optional) #. Enable Transit Gateway HA by navigating to **MULTI-CLOUD TRANSIT -> Setup -> #2 (Optional) Enable HA to an Aviatrix Transit Gateway** Please see an example below for Transit FireNet GW: |tr_firenet_gw_native| .. note:: Insane Mode Encryption for higher throughput requires a virtual machine size as shown below. |insane_mode_tp| Step 3: Attach Native Spoke VNETs to Transit Network ******************************************************* Transit and spoke gateways are deployed, next step is to connect them. 1. Navigate to **MULTI-CLOUD TRANSIT -> Setup -> #6b Attach Azure ARM Spoke through Native Peering** #. Select one VNET at a time and attach to the Transit Gateway. |attach_native_vnet| .. note:: Transit Gateway is attached to Azure Native Spokes but by default, Transit Gateway will not route traffic between Native Spokes. Step 4: Enable Connected Transit ************************************** By default, spoke VNETs are in isolated mode where the Transit will not route traffic between them. To allow the Spoke VNETs to communicate with each other, we need to enable Connected Transit 1. Navigate to **MULTI-CLOUD TRANSIT -> Advanced Config**, select the right Transit Gateway and enable **“Connected Transit”** |connected_transit_native_vnet| Step 5: Configure Transit Firewall Network ************************************************** Transit and Native VNET Spokes have now been deployed, next step is to deploy and enable the Firewall for traffic inspection. Let’s start with enabling the firewall function and configure the FireNet policy. 1. Navigate to **MULTI-CLOUD TRANSIT -> Transit FireNet -> #1 Enable Transit FireNet on Aviatrix Transit Gateway** #. Choose the Aviatrix Transit Gateway and Click **“Enable”** |en_tr_firenet_native_case| 3. Navigate to **MULTI-CLOUD TRANSIT -> Transit FireNet -> #2 Manage FireNet Policy** #. Add spokes to the Inspected box for traffic inspection .. note:: By default, FireNet inspects ingress (Internet to VNET) and east-west traffic (VNET to VNET) only. |tr_firenet_policy_native_case| Step 6a: Launch and Associate Firewall Instance ***************************************************************** This step launches a Firewall instance and associates it with one of the FireNet gateways. To attach the existing firewall instance to one of the gateway, please follow Step 6b. .. note:: By default, Aviatrix Transit FireNet uses 5 tuple forwarding algorithm but that can be changed from Firewall Network -> Advanced settings. 6a.1 Launch and Attach ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Go to Aviatrix Controller's console and navigate to **Firewall Network -> Setup -> Step 7a** and provide all the required input as shown in a table and click **"Launch"** button. .. important:: Vendor's firewall may take some time after launch to be available. ========================================== ========== **Setting** **Value** ========================================== ========== VPC ID The Security VNET created in Step 1. Gateway Name The primary FireNet gateway. Firewall Instance Name The name that will be displayed on Azure Console. Firewall Image The Azure AMI that you have subscribed. Firewall Image Version Firewall supported software versions. Firewall Instance Size Firewall virtual machine size. Management Interface Subnet. Select the subnet whose name contains "gateway and firewall management" Egress Interface Subnet Select the subnet whose name contains "FW-ingress-egress". Username Applicable to Azure deployment only. "admin" as a username is not accepted. Authentication Method Password or SSH Public Key Password Applicable to Azure deployment only. Key Pair Name (Optional) The .pem file name for SSH access to the firewall instance. Attach (Optional) By selecting this option, the firewall instance is inserted in the data path to receive packet. If this is the second firewall instance for the same gateway and you have an operational FireNet deployment, you should not select this option as the firewall is not configured yet. You can attach the firewall instance later at Firewall Network -> Advanced page. Advanced (Optional) Click this selection to allow Palo Alto firewall bootstrap files to be specified. ========================================== ========== 1. Check Point Specification ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Check Point Security Gateway has 2 interfaces as described below. ======================================================== =============================== ================================ **Check Point VM interfaces** **Description** **Inbound Security Group Rule** ======================================================== =============================== ================================ eth0 (on subnet -Public-FW-ingress-egress) Egress or Untrusted interface Allow ALL eth1 (on subnet -dmz-firewall_lan) LAN or Trusted interface Allow ALL (Do not change) ======================================================== =============================== ================================ Note that security gateway eth1 is on the same subnet as Firenet gateway eth2 interface. Check Point Security Gateway launch from the Aviatrix Controller automatically initiates the on-boarding process, configure security gateway interfaces and program RFC 1918 routes. After completing this step, user should be able to login to the Check Point Gaia console with username **admin** and provided password during launch. .. note:: Repeat Step 7a to launch the second security gateway to associate with the HA FireNet gateway. Or repeat this step to launch more security gateways to associate with the same Firenet gateway. Follow `Check Point Example <https://docs.aviatrix.com/HowTos/config_CheckPointAzure.html#launch-check-point-firewall-from-aviatrix-controller>`_ to see how to launch Check Point Security Gateway in Azure, and for more details. 2. Palo Alto VM-Series Specifications ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Palo instance has 3 interfaces as described below. ======================================================== =============================== ================================ **Palo Alto VM interfaces** **Description** **Inbound Security Group Rule** ======================================================== =============================== ================================ eth0 (on subnet -Public-gateway-and-firewall-mgmt) Management interface Allow SSH, HTTPS, ICMP, TCP 3978 eth1 (on subnet -Public-FW-ingress-egress) Egress or Untrusted interface Allow ALL eth2 (on subnet -dmz-firewall_lan) LAN or Trusted interface Allow ALL (Do not change) ======================================================== =============================== ================================ Note that firewall instance eth2 is on the same subnet as FireNet gateway eth2 interface. Launch VM Series from Aviatrix Controller automatically set it up the Palo Alto Network VM-Series firewall. User should be able to login to the VM-Series console with given username and password during launch. Please follow `Palo Alto Networks VM-Series Azure Example <https://docs.aviatrix.com/HowTos/config_PaloAltoAzure.html#example-config-for-palo-alto-networks-vm-series-in-azure>`_ to see how to launch VM-Series in Azure, and for more details. .. important:: For Panorama managed firewalls, you need to prepare Panorama first and then launch a firewall. Check out `Setup Panorama <https://docs.aviatrix.com/HowTos/paloalto_API_setup.html#managing-vm-series-by-panorama>`_. When a VM-Series instance is launched and connected with Panorama, you need to apply a one time "commit and push" from the Panorama console to sync the firewall instance and Panorama. .. Tip:: If VM-Series are individually managed and integrated with the Controller, you can still use Bootstrap to save initial configuration time. Export the first firewall's configuration to bootstrap.xml, create an IAM role and Bootstrap bucket structure as indicated above, then launch additional firewalls with IAM role and the S3 bucket name to save the time of the firewall manual initial configuration. 3. Fortinet Specifications ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FortiGate Next Generation Firewall instance has 2 interfaces as described below. ======================================================== =============================== ================================ **FortiGate VM interfaces** **Description** **Inbound Security Group Rule** ======================================================== =============================== ================================ eth0 (on subnet -Public-FW-ingress-egress) Egress or Untrusted interface Allow ALL eth1 (on subnet -dmz-firewall_lan) LAN or Trusted interface Allow ALL (Do not change) ======================================================== =============================== ================================ .. tip:: Starting from Release 6.2, FortiGate bootstrap configuration is supported. Please refer to `FortiGate Azure Configuration Example <https://docs.aviatrix.com/HowTos/config_FortiGateAzure.html#example-config-for-fortigate-vm-in-azure>`_ for more details. Step 6b: Associate an Existing Firewall Instance ******************************************************* This step is the alternative step to Step 7a. If you already launched the firewall (Check Point, Palo Alto Network or Fortinet) instance from Azure Console, you can still associate it with the FireNet gateway. Go to Aviatrix Controller's console and navigate to **Firewall Network -> Setup -> Step 7b** and associate a firewall with right FireNet Gateway. Step 7: Vendor Firewall Integration ***************************************************** Vendor integration dynamically updates firewall route tables. The use case is for networks with RFC 1918 and non-RFC 1918 routes that require specific route table programming on the firewall appliance 1. Go to Firewall Network -> Vendor Integration -> Select Firewall, fill in the details of your Firewall instance. 2. Click Save, Show and Sync. .. important:: Aviatrix Controller automatically programs RFC 1918 in Check Point Security Gateway at a time of launch. This step can be skipped for Check Point if non-RFC 1918 routes programming is not required in Security Gateway. .. note:: Vendor integration is not supported for FortiGate. User needs to configure RFC 1918 static routes manually in FortiGate firewall. Step 8: Enable Health Check Policy in Firewall *************************************************** Aviatrix Controller uses HTTPS (TCP 443) to check the health of firewall every 5 seconds. User needs to enable this port in firewall as per given instruction. Check Point ~~~~~~~~~~~~~~ By default, HTTPS or TCP 443 is allowed in Security Gateway. No action is required. Palo Alto Network (PAN) ~~~~~~~~~~~~~~~~~~~~~~~~~ By default, VM-Series do not allow HTTPS or TCP 443 port. Pleas follow the given steps to enable it: 1. Login to VM-Series with username and password. #. Go to Network -> Interface Mgmt under Network Profiles and click "Add". #. Give any name in "Interface Management Profile", check HTTPS checkbox under Administrative Management Service and click "OK". #. Attach Profile with LAN interface. Network -> Interfaces -> Select LAN Ethernet Interface -> Advanced -> Management Profile -> Select appropiate profile. |PAN-health-check| See an example screenshot below how to attach profile to an interface. |pan_hcheck_attach| Firewall health check probes can be verified in Monitor -> Traffic. |pan-health-probe| Fortinet ~~~~~~~~~~~~~~~ User needs to allow HTTPS or TCP 443 port in FortiGate firewall to monitor the health of firewall. Please follow the steps to allow HTTPS in FortiGate: 1. Login to FortiGate's console using username and password #. Go to Network -> Interfaces, select **port 2** and click "Edit". #. Check HTTPS checkbox under Administrative access -> IPv4 and click "OK". |health-check| The health check probes can be verified in FortiGate by navigating to Log & Report -> Local Traffic. |health-probe-logs| Step 9: Example Setup for "Allow All" Policy *************************************************** After a firewall instance is launched, wait for 5 to 15 minutes for it to come up. Time varies for each firewall vendor. In addition, please follow example configuration guides as below to build a simple policy on the firewall instance for a test validation that traffic is indeed being routed to firewall instance. Palo Alto Network (PAN) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For basic configuration, please refer to `example Palo Alto Network configuration guide <https://docs.aviatrix.com/HowTos/config_PaloAltoAzure.html>`_. For implementation details on using Bootstrap to launch and initiate VM-Series, refer to `Bootstrap Configuration Example <https://docs.aviatrix.com/HowTos/bootstrap_example.html>`_. FortiGate (Fortinet) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For basic policy configuration, please refer to `example Fortinet configuration guide <https://docs.aviatrix.com/HowTos/config_FortiGateAzure.html#configure-basic-traffic-policy-to-allow-traffic-vpc-to-vpc>`_. Check Point ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For basic policy configuration, please refer to `example Check Point configuration guide <https://docs.aviatrix.com/HowTos/config_CheckPointAzure.html#configure-basic-traffic-policy-to-allow-traffic-vnet-to-vnet>`_. Step 10: Verification *************************** There are multiple ways to verify if Transit FireNet is configured properly: 1. Aviatrix Flightpath - Control-plane Test #. Ping/Traceroute Test between Spoke VNETs (East-West) - Data-plane Test Flight Path Test for FireNet Control-Plane Verification: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Flight Path is a very powerful troubleshooting Aviatrix tool which allows users to validate the control-plane and gives visibility of end to end packet flow. 1. Navigate to **Troubleshoot-> Flight Path** #. Provide the Source and Destination Region and VNET information #. Select ICMP and Private subnet, and Run the test .. note:: VM instance will be required in Azure, and ICMP should be allowed in security group. Ping/Traceroute Test for FireNet Data-Plane Verification: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Once control-plane is established and no problem found in security and routing polices. Data-plane validation needs to be verified to make sure traffic is flowing and not blocking anywhere. There are multiple ways to check data-plane: 1. One way to SSH to Spoke EC2 instance and ping other Spoke EC2 to instance to make sure no traffic loss in the path. 2. Ping/traceroute capture can also be performed from Aviatrix Controller. Go to **TROUBLESHOOT -> Diagnostics** and perform the test. .. |avx_tr_firenet_topology_az_native| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/avx_tr_firenet_topology_az_native.png :scale: 20% .. |insane_mode_tp| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/insane_mode_tp.png :scale: 30% .. |create_vpc_native_case| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/create_vpc_native_case.png :scale: 40% .. |tr_firenet_gw_native| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/tr_firenet_gw.png :scale: 35% .. |attach_native_vnet| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/attach_native_vnet.png :scale: 35% .. |en_tr_firenet_native_case| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/en_tr_firenet_native_case.png :scale: 35% .. |tr_firenet_policy_native_case| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/tr_firenet_policy_native_case.png :scale: 35% .. |avx_tr_firenet_topology| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/avx_tr_firenet_topology.png :scale: 35% .. |connected_transit_native_vnet| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/connected_transit_native_vnet.png :scale: 40% .. |health-check| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/health-check.png :scale: 35% .. |PAN-health-check| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/PAN-health-check.png :scale: 35% .. |health-probe-logs| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/health-probe-logs.png :scale: 40% .. |pan-health-probe| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/pan-health-probe.png :scale: 40% .. |pan_hcheck_attach| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/pan_hcheck_attach.png :scale: 40% .. disqus:: <file_sep> ===================================================================== Aviatrix Gateway to FortiGate ===================================================================== Overview -------- This document describes how to configure an IPsec tunnel between an Aviatrix Gateway and a FortiGate firewall using Aviatrix Site2Cloud. This task is divided into two parts: #. Configure a `Site2Cloud tunnel <#fg-s2c-avtx-start>`__ in the Aviatrix Controller. #. Configure a `VPN tunnel <#fg-s2c-fg-start>`__ and related components in the FortiGate Firewall. .. _fg_s2c_avtx_start: Aviatrix Configuration ----------------------------- Adding a Site2Cloud tunnel in the Aviatrix Controller ++++++++++++++++++++++++++++++++++++++++++++++ Follow the steps in `this </HowTos/site2cloud.html>`__ guide. .. tip:: Download the configuration to aid in the creation of the tunnel in FortiGate. The configuration can be downloaded from the **Aviatrix Controller > Site2Cloud > Select the connection created earlier > Download Configuration**. Select **Generic** for Vendor and Platform and **Vendor independent** for Software. .. _fg_s2c_fg_start: |imagedownloadconfiguration| FortiGate Configuration ----------------------------------- The configuration and screenshots below make the following three assumptions: * There are 2 interfaces on the FortiGate: * Interface port1 is an externally facing interface. * Interface port2 is an internally facing interface. * You have a subnet in AWS, Azure, or GCP in a VPC/VNet that has an Aviatrix Gateway. This subnet is defined as "10.0.0.0/16" for the examples below but it can be any valid CIDR range. .. note:: In the examples below we refer to this range as **AWS_Cloud**. * You have a subnet behind your FortiGate firewall that will be accessible in the cloud. This subnet is defined as "172.16.0.0/20" in the examples below but it can be any valid CIDR range. .. note:: In the examples below, we refer to this range as **Shared_With_AWS**. Configuring Named Address Ranges in FortiGate +++++++++++++++++++++++++++++++++++++++++++ Access the FortiGate Dashboard, then, under **Policy & Objects** > **Addresses**, create two new addresses: **AWS_Cloud** +-------------------------------+------------------------------------------+ | Field | Expected Value | +===============================+==========================================+ | Name | AWS_Cloud | +-------------------------------+------------------------------------------+ | Type | Subnet | +-------------------------------+------------------------------------------+ | Subnet / IP Range | CIDR matching the range specified in | | | tunnel configuration (remote to FortiGate) | +-------------------------------+------------------------------------------+ | Interface | Any | +-------------------------------+------------------------------------------+ | Show in Address List | Enabled | +-------------------------------+------------------------------------------+ | Static Route Configuration | Enabled | +-------------------------------+------------------------------------------+ |imageawscloudconfig| **Shared_With_AWS** +-------------------------------+------------------------------------------+ | Field | Expected Value | +===============================+==========================================+ | Name | Shared_With_AWS | +-------------------------------+------------------------------------------+ | Type | Subnet | +-------------------------------+------------------------------------------+ | Subnet / IP Range | CIDR matching the range specified in | | | tunnel configuration (local to FortiGate) | +-------------------------------+------------------------------------------+ | Interface | Any | +-------------------------------+------------------------------------------+ | Show in Address List | Enabled | +-------------------------------+------------------------------------------+ | Static Route Configuration | Enabled | +-------------------------------+------------------------------------------+ |imagesharedwithawsconfig| Creating an IPsec Tunnel on FortiGate +++++++++++++++++++++++++++++++++++ #. Log in to the FortiGate and access the Dashboard. #. In the VPN menu, select **IPsec Wizard**. #. Change the Template Type to "Custom." #. Enter any value as the Name. For this example, we are using "ToAviatrixGW." #. Click **Next >**. #. Fill out the Network fields as recommended below: **VPN Setup** +-------------------------------+------------------------------------------+ | Field | Expected Value | +===============================+==========================================+ | Name | Any Value | +-------------------------------+------------------------------------------+ | Template Type | Custom | +-------------------------------+------------------------------------------+ |imagevpnwizard| **Network** +-------------------------------+------------------------------------------+ | Field | Expected Value | +===============================+==========================================+ | IP Version | IPv4 | +-------------------------------+------------------------------------------+ | Remote Gateway | Static IP Address | +-------------------------------+------------------------------------------+ | IP Address | Public IP address of Aviatrix Gateway | +-------------------------------+------------------------------------------+ | Interface | Select the Appropriate Port/Interface | +-------------------------------+------------------------------------------+ | Local Gateway | Disabled | +-------------------------------+------------------------------------------+ | Mode Config | Unmark this checkbox | +-------------------------------+------------------------------------------+ | NAT Traversal | Enable | +-------------------------------+------------------------------------------+ | Keepalive Frequency | Any value | +-------------------------------+------------------------------------------+ | Dead Peer Detection | On Demand | +-------------------------------+------------------------------------------+ | Forward Error Correction | Unmark this checkbox | +-------------------------------+------------------------------------------+ | Advanced Options | Disabled | +-------------------------------+------------------------------------------+ |imagenetworkconfig| **Authentication** +-------------------------------+------------------------------------------+ | Field | Expected Value | +===============================+==========================================+ | Method | Pre-shared Key | +-------------------------------+------------------------------------------+ | Pre-shared Key | Enter the value from the downloaded | | | configuration or the value typed in | | | to the field in Aviatrix Site2Cloud | +-------------------------------+------------------------------------------+ | IKE Version | 1 | +-------------------------------+------------------------------------------+ | IKE Mode | Main (ID protection) | +-------------------------------+------------------------------------------+ |imageauthentication| **Phase 1 Proposal** .. important:: The following values from the Aviatrix Site2Cloud configuration are needed below: #. In the Aviatrix Controller, select the Site2Cloud configuration created earlier. #. Click |imageThreeLines| next to Connect Detail. |imageconnectiondetails| +-------------------------------+------------------------------------------+ | Field | Expected Value | +===============================+==========================================+ | Encryption | Match value specified in Aviatrix S2C | | | configuration (Phase 1 Encryption) | +-------------------------------+------------------------------------------+ | Authentication | Match value specified in Aviatrix S2C | | | configuration (Phase 1 Authentication) | +-------------------------------+------------------------------------------+ | Diffie-Hellman Group | Match value specified in Aviatrix S2C | | | configuration (Phase 1 DH Groups) | +-------------------------------+------------------------------------------+ | Key Lifetime (seconds) | 28800 | +-------------------------------+------------------------------------------+ | Local ID | Leave Blank | +-------------------------------+------------------------------------------+ |imagephase1proposal| **XAUTH** +-------------------------------+------------------------------------------+ | Field | Expected Value | +===============================+==========================================+ | Type | Disabled | +-------------------------------+------------------------------------------+ |imagexauth| **Phase 2 Selectors** *New Phase 2* +-------------------------------+------------------------------------------+ | Field | Expected Value | +===============================+==========================================+ | Name | Any String Value | +-------------------------------+------------------------------------------+ | Comments | Any String Value | +-------------------------------+------------------------------------------+ | Local Address | Named Address - **Shared_With_AWS** | +-------------------------------+------------------------------------------+ | Remote Address | Named Address - **AWS_Cloud** | +-------------------------------+------------------------------------------+ |imagephase2selector| *Advanced* .. important:: The following values from the Aviatrix Site2Cloud configuration are needed below: #. In the Aviatrix Controller, select the Site2Cloud configuration created earlier. #. Click |imageThreeLines| next to Connection Detail. |imageconnectiondetails2| +-------------------------------+------------------------------------------+ | Field | Expected Value | +===============================+==========================================+ | Encryption | Match value specified in Aviatrix S2C | | | configuration (Phase 2 Encryption) | +-------------------------------+------------------------------------------+ | Authentication | Match value specified in Aviatrix S2C | | | configuration (Phase 2 Authentication) | +-------------------------------+------------------------------------------+ | Diffie-Hellman Group | Match value specified in Aviatrix S2C | | | configuration (Phase 2 DH Groups) | +-------------------------------+------------------------------------------+ | Key Lifetime | Seconds | +-------------------------------+------------------------------------------+ | Seconds | 3600 | +-------------------------------+------------------------------------------+ |imagephase2advanced| #. Click **OK**. Configuring IPv4 Policy +++++++++++++++++++++ In **Policy & Objects**, select **IPv4 Policy**. Create two new IPv4 policies: * Outbound traffic from FortiGate (Shared_With_AWS) to Aviatrix (AWS_Cloud) |imageip4outboundpolicy| * Inbound traffic from Aviatrix (AWS_Cloud) to FortiGate (Shared_With_AWS) |imageip4inboundpolicy| .. note:: The reference to port2 in the screenshots should be replaced with your own interface name that represents the internal facing interface. .. note:: Be sure to select **accept** for "action" and select **all** for "service." Adding a Static Route ++++++++++++++++++ From the FortiGate UI: navigate to Network > Static Routes , add a new static route for traffic destined to "AWS_Cloud" to use the VPN tunnel. |imagestaticroute| .. note:: If Named Address is disabled, be sure that you enabled Static Route Configuration on the Address configuration. |imageaddressstaticconfig| Bringing Up IPsec Monitor ++++++++++++++++++++++++++ From the FortiGate UI: In **Monitor** > **IPsec Monitor**, select the Aviatrix tunnel and click **Bring Up**. Test ---- Once complete, test the communication using the tunnel. Troubleshooting --------------- **Error Message** ``failed to get valid proposal`` ``no suitable proposal found`` **Solution** Check that the Phase 1 authentication, encryption, and Diffie-Hellman groups match on both sides. :: If you are experiencing low IPsec throughput, you may want to configure two commands on the Fortigate. config system global set ipsec-asic-offload disable end configure system global set ipsec-hmac-offload disable end .. |imagedownloadconfiguration| image:: site2cloud_fortigate_media/downloadconfiguration.png .. |imagevpnwizard| image:: site2cloud_fortigate_media/vpnwizard.png .. |imagenetworkconfig| image:: site2cloud_fortigate_media/networkconfig.png .. |imageauthentication| image:: site2cloud_fortigate_media/authentication.png .. |imagephase1proposal| image:: site2cloud_fortigate_media/phase1proposal.png .. |imagexauth| image:: site2cloud_fortigate_media/xauth.png .. |imagephase2selector| image:: site2cloud_fortigate_media/phase2selector.png .. |imagephase2advanced| image:: site2cloud_fortigate_media/phase2advanced.png .. |imagestaticroute| image:: site2cloud_fortigate_media/staticroute.png .. |imageip4outboundpolicy| image:: site2cloud_fortigate_media/ip4outboundpolicy.png .. |imageip4inboundpolicy| image:: site2cloud_fortigate_media/ip4inboundpolicy.png .. |imageThreeLines| image:: site2cloud_fortigate_media/three_lines.png .. |imageconnectiondetails| image:: site2cloud_fortigate_media/connectiondetails.png .. |imageconnectiondetails2| image:: site2cloud_fortigate_media/connectiondetails2.png .. |imageaddressstaticconfig| image:: site2cloud_fortigate_media/addressstaticconfig.png .. |imageawscloudconfig| image:: site2cloud_fortigate_media/aws_cloud_config.png .. |imagesharedwithawsconfig| image:: site2cloud_fortigate_media/shared_with_aws_config.png <file_sep> ========================================================= AWS Transit Gateway Route Limit Test Validation ========================================================= Introduction --------------- While an AWS Transit Gateway (TGW) carries thousands of routes in the TGW route table, a TGW VPN has the same 100 route limit as the VGW VPN. Test Validation ---------------- In the following setup, we launch a Cisco CSR 1000v as the Customer Gateway and use it to attach a VPN connection to the TGW. The TGW and the CSR also run BGP between themselves. The detailed steps are `here <https://docs.aws.amazon.com/vpc/latest/tgw/tgw-vpn-attachments.html>`_. |tgw_route_limit| After the VPN tunnel is created between TGW and CSR, run the following command at CSR to verify the BGP peer connection, where 169.254.11.233 is the TGW's BGP ID: :: ip-10-10-0-106#show ip bgp neighbors 169.254.11.233 | include BGP state BGP state = Established Turn on BGP debug on CSR and then configure CSR to advertise 101 routes to TGW through BGP. CSR shows the following BGP debug messages: :: *Dec 18 00:29:28.213: %BGP-3-NOTIFICATION: received from neighbor 169.254.11.233 6/1 (Maximum Number of Prefixes Reached) 7 bytes 00010100 000064 *Dec 18 00:29:28.213: BGP: ses global 169.254.11.233 (0x7F36A1AF6C60:1) Receive NOTIFICATION 6/1 (Maximum Number of Prefixes Reached) 7 bytes 00010100 000064 *Dec 18 00:29:28.213: %BGP-5-NBR_RESET: Neighbor 169.254.11.233 reset (BGP Notification received) *Dec 18 00:29:28.213: BGP: ses global 169.254.11.233 (0x7F36A1AF6C60:1) Reset (BGP Notification received). *Dec 18 00:29:28.213: BGP: 169.254.11.233 went from Established to Closing The above messages show that when the TGW exceeds its route limit (100), it sends a BGP reset message to CSR. The BGP connection becomes idle after these messages. :: ip-10-10-0-106#show ip bgp neighbors 169.254.11.233 | include BGP state BGP state = Idle This test indicates that TGW has the same BGP total prefix limitation (100) as a VGW. Summary ---------- TGW VPN has a total 100 BGP prefix. In addition, a TGW cannot summarize Spoke VPC routes. .. |tgw_route_limit| image:: tgw_route_limit_media/tgw_route_limit.png :scale: 70% .. add in the disqus tag .. disqus:: <file_sep> ========================================================== Managing Aviatrix Resources in CloudFormation ========================================================== .. note:: This functionality is not officially supported by Aviatrix. This is a community supported effort. And this document is our contribution to this community supported effort. Overview -------- Automating Aviatrix components is managed by APIs on the Aviatrix Controller. However, many AWS customers use CloudFormation to automate their infrastructure within AWS. In order to call Aviatrix APIs from CloudFormation templates, a `Custom Resource <https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources.html>`__ is required. Aviatrix has developed a Custom Resource to facilitate automation of Aviatrix components from CloudFormation templates. This Custom Resource is backed by an AWS Lambda function. Use this guide to set up your AWS account with the necessary components to automate Aviatrix from your CloudFormation templates. Deployment Guide ---------------- #. `Install an Aviatrix Controller <../StartUpGuides/aviatrix-cloud-controller-startup-guide.html>`__ if you don't already have one #. `Prepare your AWS account <#cfr-prepare-aws>`__ with components necessary to connect to your Aviatrix Controller from CloudFormation templates #. Use the Aviatrix Custom Resources in a `CloudFormation template <#cfr-use>`__ .. _cfr_prepare_aws: Prepare AWS Account ------------------- The Aviatrix Lambda script and related AWS resources need to be added to your AWS account to use the Custom Resources for CloudFormation. Follow these steps to set up your AWS account: #. `Add <#cfr-secret-manager>`__ your Aviatrix Controller password to AWS Secrets Manager #. `Upload <#cfr-upload-code>`__ the Lambda code to S3 #. `Add <#cfr-add-aws-resources>`__ AWS resources .. _cfr_secret_manager_: Add Controller Password to AWS Secret Manager ############################################# You will need to manually add your Aviatrix Controller password to the `AWS Secrets Manager <https://console.aws.amazon.com/secretsmanager>`__. At the time of this writing, the AWS Secrets Manager is not available in CloudFormation and cannot be automatically added. Follow these steps to add your Aviatrix Controller admin password to AWS Secrets Manager: #. Login to the `AWS Secrets Manager Console <https://console.aws.amazon.com/secretsmanager>`__ .. important:: Be sure you are storing this secret in the correct AWS region #. Click on the `Store a new secret` button |imageStoreNewSecret| #. Select `Other type of secrets` for `Secret type` #. Enter `<PASSWORD>password` in the first (key) text field #. Enter your Aviatrix password in the second (value) text field #. Click `Next` |imageSecretType| #. Enter a name and description for this secret. You can use any values here. #. Click `Next` |imageSecretName| #. Disable automatic rotation #. Click `Next` #. Click `Store` .. note:: Copy the ARN for the secret just created. You will need these when you run the CloudFormation stack. |imageSecretARN| .. _cfr_upload_code: Upload code for Lambda Function ############################### CloudFormation's Lambda resource requires that the `code` be obtained from a .zip file stored in an S3 bucket in the same region as the CloudFormation template. #. Download the handler code `here <https://s3.amazonaws.com/aviatrix-custom-resources/aviatrix_custom_resources.zip>`__. #. Upload this .zip file to an S3 bucket of your choice. .. note:: Remember the S3 bucket and path (key) to this uploaded file. You will need it later when you run the CloudFormation stack. .. _cfr_aws_resources: Add Required AWS Resources ########################## Once you have your Aviatrix Controller password `stored <#cfr-secret-manager>`__ in the AWS Secrets Manager and the `Lambda code uploaded to S3 <#cfr-upload-code>`__, you are ready to run a CloudFormation template to build the rest of the required components. #. From the CloudFormation console, create a `new stack <https://console.aws.amazon.com/cloudformation/home#/stacks/new?stackName=AviatrixCloudFormationCustomResources&templateURL=https://s3.amazonaws.com/aviatrix-custom-resources/aviatrix-custom-resource-install.json>`__ #. Click `Next` #. Enter the parameters: +-----------------------------+---------------------------------------------+ | Parameter | Description | +=============================+=============================================+ | ControllerHost | The hostname or IP of the Aviatrix | | | Controller. Example: demo.aviatrix.com | +-----------------------------+---------------------------------------------+ | ControllerUser | The username to login to the Controller. | | | You will most likely use the ``admin`` user | +-----------------------------+---------------------------------------------+ | ControllerPasswordSecretARN | The ARN of the secret storing your Aviatrix | | | Controller password that was created | | | earlier. | | | | | | |imageARNSecret| | +-----------------------------+---------------------------------------------+ | AviatrixAppPolicyARN | ARN of the aviatrix-app-policy IAM policy | | | | | | |imageARNAviatrixAppPolicy| | +-----------------------------+---------------------------------------------+ | CodeS3Bucket | S3 bucket name where you uploaded the | | | Labmda code | +-----------------------------+---------------------------------------------+ | CodeS3Key | S3 file key where you uploaded the code | +-----------------------------+---------------------------------------------+ |imageCFStackParameters| #. Create the stack Once the stack is created successfully, you are ready to use the Aviatrix Custom Resources in your CloudFormation templates. .. _cfr_use: Use Aviatrix Custom Resource in a CloudFormation Template --------------------------------------------------------- Overview ######## In order to manage Aviatrix resources in your AWS CloudFormation templates, add a new resource of type ``AWS::CloudFormation::CustomResource`` or ``Custom::YourString``. See additional details `here <https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cfn-customresource.html>`__. The ``AWS::CloudFormation::CustomResource`` requires that a ``ServiceToken`` property be provided. The value of this property should be the ARN of the Lambda function. This ARN is output by the CloudFormation stack created earlier. |imageARNLambda| How to Use this Custom Resource ############################### Arguments to the resource should be provided in the CFT resource `Properties` object. There are 3 required properties to allow the Lambda script to access the Controller at the top level: +---------------------------------------+--------------------------------------+ | Field | Description | +=======================================+======================================+ | AviatrixControllerPasswordSecretKeyId | Enter the `Secret Key` that you used | | | to store the password in AWS Secrets | | | Manager. | | | | | | |imageASMKey| | +---------------------------------------+--------------------------------------+ | AviatrixControllerHost | The host name (or IP address) of | | | your Aviatrix Controller. | +---------------------------------------+--------------------------------------+ | AviatrixControllerUser | The username of the Aviatrix | | | Controller. | +---------------------------------------+--------------------------------------+ |imageCFTExample| Reference ########## * `Aviatrix Gateway <#cfcr-ref-gw>`__ * `Attach/Detach FQDN Filter to Gateway <#cfcr-ref-fqdn-gw>`__ * `FQDN Filter Tag <#cfcr-ref-fqdn>`__ .. _cfcr_ref_gw: Aviatrix Gateway ++++++++++++++++ This resource allows you to create Aviatrix Gateways. **Properties** .. note:: These properties must be in an **args** object inside the resource's `Properties` object. +------------------+----------+------------------------------------------------+ | Name | Required | Description | +==================+==========+================================================+ | account_name | Yes | Friendly name for account from Aviatrix | | | | Controller. | +------------------+----------+------------------------------------------------+ | account_type | Yes | 1 = AWS, 4 = GCP, 8 = Azure ARM | +------------------+----------+------------------------------------------------+ | gw_name | Yes | Name of this gateway | +------------------+----------+------------------------------------------------+ | vpc_vnet_id | Yes | VPC or VNet ID | +------------------+----------+------------------------------------------------+ | region | Yes | Region name (AWS or Azure region) | +------------------+----------+------------------------------------------------+ | gw_size | Yes | Gateway instance size | +------------------+----------+------------------------------------------------+ | public_subnet | Yes | CIDR for the public subnet in the | | | | ``vpc_vnet_id`` | +------------------+----------+------------------------------------------------+ | additional_args | Yes | Dictionary with additional arguments for this | | | | gateway. | +------------------+----------+------------------------------------------------+ **Example** This sample shows how to create a User SSL VPN gateway. .. code-block:: json { "AWSTemplateFormatVersion": "2010-09-09", "Resources": { "AviatrixGateway": { "Type": "Custom::AviatrixGateway", "Properties": { "AviatrixControllerPasswordSecretKeyId": "aviatrix_controller_admin_password", "AviatrixControllerHost": "controller.aviatrix.demo", "AviatrixControllerUser": "admin", "args": { "account_name": "my_aws_account", "account_type": 1, "gw_name": "vpn-test", "vpc_vnet_id": "vpc-00000000", "region": "us-east-1", "gw_size": "t2.micro", "public_subnet": "172.16.1.0/28", "additional_args": { "vpn_access": "yes", "enable_elb": "yes", "cidr": "192.168.43.0/24", "max_conn": 100, "split_tunnel": "yes", "enable_ldap": "no" } }, "ServiceToken": "arn:aws:lambda:ca-central-1:000000000000:function:AviatrixGatewayHandler" } } } } .. _cfcr_ref_fqdn_gw: Attach/Detach FQDN Filter to Gateway ++++++++++++++++++++++++++++++++++++ This resource allows you to attach FQDN filter tags to an Aviatrix Gateway. **Properties** .. note:: These properties must be in an **args** object inside the resource's `Properties` object. +------------------+----------+------------------------------------------------+ | Name | Required | Description | +==================+==========+================================================+ | gw_name | Yes | Name of the gateway this tag will be attached | +------------------+----------+------------------------------------------------+ | tag_name | Yes | The name of the existing FQDN filter tag to | | | | attach to the given gateway. | +------------------+----------+------------------------------------------------+ .. _cfcr_ref_fqdn: FQDN Filter Tag ++++++++++++++++ This resource allows you to create FQDN filter tags. **Properties** .. note:: These properties must be in an **args** object inside the resource's `Properties` object. +------------------+----------+------------------------------------------------+ | Name | Required | Description | +==================+==========+================================================+ | tag_name | Yes | The name of the existing FQDN filter tag to | | | | attach to the given gateway. | +------------------+----------+------------------------------------------------+ | domains | Yes | An array of domain definitions for this fitler | | | | For example: [ "*.google.com", | | | | "*.aviatrix.com" ] | +------------------+----------+------------------------------------------------+ | enable | No | Enable the FQDN filter? Default is disabled | | | | Value can be 1 or true to enable. | +------------------+----------+------------------------------------------------+ **Example** This sample shows how to create a new FQDN filter called `production` that is enabled and filters for domains `"*.ubuntu.com", "ubuntu.com", "aviatrix.com", "*.aviatrix.com", "*.example.com"`. .. code-block:: json { "AWSTemplateFormatVersion": "2010-09-09", "Resources": { "AviatrixFQDNFilter": { "Type": "Custom::AviatrixFQDNFilter", "Properties": { "AviatrixControllerPasswordSecretKeyId": "aviatrix_controller_admin_password", "AviatrixControllerHost": "controller.aviatrix.demo", "AviatrixControllerUser": "admin", "args": { "tag_name": "production", "domains": [ "*.ubuntu.com", "ubuntu.com", "aviatrix.com", "*.aviatrix.com", "*.example.com" ], "enable": true }, "ServiceToken": "arn:aws:lambda:us-east-1:00000000000:function:AviatrixFQDNFilterHandler", "Await": true } } } } .. |imageStoreNewSecret| image:: CloudFormationResources_media/aws_asm_store_new.png .. |imageSecretType| image:: CloudFormationResources_media/aws_asm_select_secret_type.png .. |imageSecretName| image:: CloudFormationResources_media/aws_asm_name.png .. |imageSecretARN| image:: CloudFormationResources_media/aws_asm_copy_arn.png .. |imageCFStackParameters| image:: CloudFormationResources_media/aws_cf_stack_parameters.png .. |imageARNAviatrixAppPolicy| image:: CloudFormationResources_media/aws_aviatrix_app_policy.png :width: 400px .. |imageARNSecret| image:: CloudFormationResources_media/aws_copy_secret_arn.png :width: 400px .. |imageARNLambda| image:: CloudFormationResources_media/aws_lambda_copy_arn.png :width: 600px .. |imageCFTExample| image:: CloudFormationResources_media/code_example.png :width: 600px .. |imageASMKey| image:: CloudFormationResources_media/asm_secret_key_name.png :width: 300px <file_sep> ======================================================== OpenVPN + FQDN Filter Solution ======================================================== 1. Solution Overview ====================== This solution provides how to deploy a network topology to filter OpenVPN user traffic by fully qualified domain name (FQDN). 2. Configuration Workflow ========================== 2.1 Pre Configuration Checklist ------------------------------- Before configuring this solution, users need to make sure the following prerequisites are completed. **Pre Configuration Check List** 1. Deploy the Aviatrix Controller 2. Create AWS VPC with two public subnets in a same AZ for Aviatrix OpenVPN gateway and Aviatrix Egress gateway. These prerequisites are explained in detail below. 2.1.a Deploy the Aviatrix Controller ------------------------------------- The Aviatrix Controller must be deployed and setup prior to deploy Aviatrix Gateways. Please refer to "Aviatrix Controller Getting Started Guide for AWS" on how to deploy the Aviatrix Controller. `Aviatrix Controller Getting Started Guide <https://s3-us-west-2.amazonaws.com/aviatrix-download/docs/aviatrix_aws_controller_gsg.pdf>`_ Check and make sure you can access the Aviatrix Controller dashboard and login with an administrator account. The default URL for the Aviatrix Controller is: https://<public ip of Aviatrix Controller> 2.1.b Create AWS VPC with two public subnets in a same AZ for Aviatrix OpenVPN gateway and Aviatrix Egress gateway. ----------------------------------------- - Create 1 VPC with CIDR such as 10.1.0.0/16 - In the VPC, create 2 public subnets in a same Availability Zone such as 10.1.0.0/24 and 10.1.1.0/24. The public subnet means that it must be associated with a route table whose default route 0.0.0.0 points to IGW. - In the VPC, create multiple private subnets if needed. 2.2 Configuration Steps ----------------------- Make sure the pre-configuration steps in the previous section are completed before proceeding. The instructions in this section will use the following architecture. The CIDR and subnets may vary depending on your VPC setup; however, the general principals will be the same. |image0| 2.2.a Deploy Aviatrix Egress Gateway ------------------------------ The first step is to deploy Aviatrix Egress Gateway in the Public Subnet2 10.1.1.0/24 **Instructions:** a.1. Login to the Aviatrix Controller Console a.2. Create Aviatrix Egress Gateway in Public Subnet2 of VPC a.3. Click on Gateway -> "New Gateway" =============================== ================================================================================ **Setting** **Value** =============================== ================================================================================ Cloud Type Choose AWS Gateway Name This name is arbitrary (e.g. egress-gw) Account Name Choose the account name Region Choose the region of VPC VPC ID Choose the VPC ID of VPC Public Subnet Select a public subnet where the gateway will be deployed (e.g. 10.1.1.0/24) Gateway Size t2.micro is fine for testing Enable SNAT Check this box (IMPORTANT) VPN Access Uncheck this box Designated Gateway Uncheck this box Allocate New EIP Check this box Save Template Uncheck this box =============================== ================================================================================ a.4. Click “OK”. It will take a few minutes for the gateway to deploy. Do not proceed until the gateway is deployed. a.5. Refer Aviatrix FQDN documents to set up Egress Filter rules and enable Egress Control function `Egress FQDN FAQ <https://docs.aviatrix.com/HowTos/fqdn_faq.html>`_ `Egress Control Filter <https://docs.aviatrix.com/HowTos/FQDN_Whitelists_Ref_Design.html>`_ `Egress FQDN Discovery <https://docs.aviatrix.com/HowTos/fqdn_discovery.html>`_ `Egress FQDN View Log <https://docs.aviatrix.com/HowTos/fqdn_viewlog.html>`_ .. note:: For HA topology, please refer `Aviatrix Single AZ HA <https://docs.aviatrix.com/Solutions/gateway_ha.html#deployment-guide>`_ 2.2.b Deploy Aviatrix OpenVPN Gateway ------------------------------ The second step is to deploy Aviatrix OpenVPN Gateway in the Public Subnet1 10.1.0.0/24 **Instructions:** b.1. Create Aviatrix VPN Gateway in Public Subnet1 of VPC (note that OpenVPN Gateway is in a different subnet of Egress Gateway but both are in the same AZ) b.2. Click on Gateway -> "New Gateway" =============================== =================================================== **Setting** **Value** =============================== =================================================== Cloud Type Choose AWS Gateway Name This name is arbitrary (e.g. openvpn-gw) Account Name Choose the account name Region Choose the region of VPC VPC ID Choose the VPC ID of VPC Public Subnet Select the public subnet where the OpenVPN gateway will be deployed (e.g. 10.1.0.0/24) Gateway Size t2.micro is fine for testing. Enable SNAT Uncheck this box (IMPORTANT) Designated Gateway Uncheck this box Allocate New EIP Check this box VPN Access Check this box Advanced Options Check this box Enable SAML Uncheck this box VPN CIDR Block (e.g. 192.168.43.0/24) MFA Authentication Optional (Disable is fine for testing) Max Connections 100 is fine for testing Split Tunnel Mode No (IMPORTANT) Enable ELB Yes ELB Name Leave blank is fine for testing Enable Client Cert. Sharing No Enable PBR Check this box PBR Subnet Select the subnet where Aviatrix Egress Gateway is located (e.g. 10.1.1.0/24) PBR Default Gateway Select the private IP of Aviatrix Egress Gateway (e.g. 10.1.1.185) NAT Translation Logging Uncheck this box Enable LDAP Optional (Uncheck this box is fine for testing) Save Template Uncheck this box =============================== =================================================== b.3. Click “OK”. It will take a few minutes for the gateway to deploy. Do not proceed until the gateway is deployed. .. note:: 1. This solution needs the function "Full Tunnel Mode" be enabled on Aviatrix OpenVPN Gateway. 2. For Aviatrix OpenVPN GW scalability topology, any new Aviatrix OpenVPN gateways need to be added in the same AZ. 3. PBR function and other OpenVPN functions can be modified on the page "OpenVPN® -> Edit Config" after Aviatrix OpenVPN GW is launced. `Aviatrix OpenVPN® FAQs <https://docs.aviatrix.com/HowTos/openvpn_faq.html>`_ 2.2.c Create an OpenVPN® user ------------------------------------------------------------ This step explains how to create a OpenVPN® user. **Instructions:** c.1. From the Aviatrix Controller Console c.2. Click OpenVPN® -> VPN Users c.3. Click button "+Add New" =============================== =================================================== **Setting** **Value** =============================== =================================================== VPC ID Choose the VPC ID of VPC LB/Gateway Name Choose the ELB in VPC User Name This name is arbitrary (ex. vpn-user) User Email Email address Profile Uncheck this box is fine for the testing =============================== =================================================== c.4. Click button "OK" c.5. Check your email to receive an ovpn file c.6. Done 3. OpenVPN FQDN solution POC ============================ This step proofs how this solution works. **Instructions:** 1. Set up a whitelist rule with Domain Name "*.google.com", Protocol "tcp", and Port "443" in `Egress FQDN Filter <https://docs.aviatrix.com/HowTos/FQDN_Whitelists_Ref_Design.html>`_ 2. Enable Egress filter function on Aviatrix Egress gateway 3. Enable an OpenVPN® client tool 4. Establish an OpenVPN® connection with the ovpn file which has received in email 5. Confirm that the access to www.google.com via port 443/80 works properly 5.1. Issue CLI #wget www.google.com on your host machine where you established the OpenVPN session 5.2. It should access www.google.com and download the index.html to your host machine 6. Confirm that the access to www.yahoo.com via port 443/80 does not work 6.1. Issue CLI #wget www.yahoo.com on your host machine where you established the OpenVPN session 6.2. It should not able to access www.yahoo.com OpenVPN is a registered trademark of OpenVPN Inc. .. |image0| image:: OpenVPN_FQDN_Filter_Solution_media/OpenVPN_FQDN_Filter_Solution.png :width: 5.03147in :height: 2.57917in .. disqus:: <file_sep> Peering Over Route Limit ======================== This document explains how to set up Aviatrix `encrypted peering <http://docs.aviatrix.com/HowTos/peering.html#encrypted-peering>`_ that overcomes CSP route limits. Click `here <http://docs.aviatrix.com/HowTos/gateway.html#designated-gateway>`_ to learn about Designated Gateway feature. 1. At the Gateway menu, create a gateway in an existing VPC/VNet and make sure the option Designated Gateway is selected. 2. (Optional) If your VPC/VNet CIDR is outside RFC 1918 range (10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16), you should expand the Designated Gateway coverage by editing the Designated Gateway. Highlight the gateway you just created and click **Edit**. Scroll down to find Edit Designated Gateway section, follow the instructions to add additional CIDR ranges. 3. Repeat the step 1 and step 2 for a different VPC/VNet. 4. (Optional) To enable Peering HA, go to Peering > Encrypted Peering > New peering, select the two gateways launched in the previous two steps. Select **Enable HA** if you wish to build a backup encrypted tunnel for HA. Note that you must first create two respective backup gateways prior to this step. To launch backup gateways, go to the Gateway page, select the gateway, click **Edit**, At the Gateway for High Availability Peering field, select one subnet (public subnet for AWS, GCP, or OCI) and click **Create**. 4. Go to Peering > Encrypted Peering, and click **New Peering** to peer the two gateways. .. .. disqus:: <file_sep> ===================== Launching a Gateway ====================== .. raw:: html <style> /* override table no-wrap */ .wy-table-responsive table td, .wy-table-responsive table th { white-space: normal !important; } </style> This document explains how to launch an Aviatrix Gateway from the Aviatrix Controller. .. note:: **(AWS users)** When you launch a gateway, the gateway will use the Default encryption key set in your AWS account > EC2 > Settings > EBS encryption. * Make sure you are viewing the correct region, as encryption keys are region-specific. * Make sure the Default encryption key displayed here is the encryption key you want to use for this gateway. If not, click **Manage** to select a new encryption key. Launching a Gateway ^^^^^^^^^^^^^^^^^^^^^^^ To launch a new gateway in your Controller, click **Gateway** > **New** on the left sidebar. To launch a gateway with OpenVPN® capability, refer to `this link. <http://docs.aviatrix.com/HowTos/uservpn.html>`__ Subnet Information ^^^^^^^^^^^^^^^^^^^^^^^ Aviatrix Gateways are launched in a public subnet in AWS, GCP, and OCI. A public subnet in AWS VPC is defined as a subnet whose associated route table has a default route entry that points to IGW. To learn more about VPC and subnets, open `this link. <https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_Subnets.html>`_ If you do not have a VPC/VCN with public subnet in AWS, GCP, or OCI, you can use our `"Create a VPC" <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ tool to create a VPC with fully populated public and private subnet in each AZ. Select Gateway Size ^^^^^^^^^^^^^^^^^^^^ When selecting the gateway size, note the following guidelines of IPsec performance based on IPERF tests conducted between two gateways of the same size: AWS Performance Numbers: +----------------------------+-------------------------------------------------+ | AWS Instance Size | Expected Throughput | +============================+=================================================+ | T2 series | Not guaranteed; it can burst up to 130Mbps | +----------------------------+-------------------------------------------------+ | c5.2xlarge, c5.4xlarge | 2Gbps - 2.5Gbps | +----------------------------+-------------------------------------------------+ | c5n.4xlarge | 25Gbps (with InsaneMode) | +----------------------------+-------------------------------------------------+ | c5n.9xlarge | 70Gbps (with InsaneMode) | +----------------------------+-------------------------------------------------+ | c5n.18xlarge | 70Gbps (with InsaneMode) | +----------------------------+-------------------------------------------------+ Azure Performance Numbers (without Insane mode): +----------------------------+-------------------------------------------------+ | Azure Instance Size | Expected Throughput | +============================+=================================================+ | B series | Not guaranteed; it can burst up to 260Mbps | +----------------------------+-------------------------------------------------+ | D/Ds series | 480Mbps - 1.2Gbps | +----------------------------+-------------------------------------------------+ | F Series | approximately 450Mbps - 1.2Gbps | +----------------------------+-------------------------------------------------+ .. note:: SSD-based Virtual Machines are recommended. The names of SSD-based VMs have an “s” before the version number: for example, “Standard_D1**s**_v2,” “Standard_D2**s**_v3,” etc. GCP Performance Numbers (without Insane mode): +--------------------------------------------+-----------------------+ | GCP Instance Size | Expected Throughput | +============================================+=======================+ | n1-standard-1, n1-standard-2, n1-highcpu-2 | 1.0 - 1.2 Gbps | +--------------------------------------------+-----------------------+ | n1-standard-4, n1-highcpu-2 | 2.3 - 2.5 Gbps | +--------------------------------------------+-----------------------+ OCI Expected Throughput Numbers: +----------------------------+--------------------------------------+------------------------------------------+ | OCI Instance Shape | Throughput with Active Mesh | Throughput without Active Mesh | +============================+======================================+==========================================+ | VM.Standard2.2 or larger | 1.8G | 900 Mbps | +----------------------------+--------------------------------------+------------------------------------------+ With OCI you can choose a flexible shape to modify the Oracle CPU (OCPU) and memory configurations of your shape after it is deployed. +-----------------------+--------------------+ | OCI Flex Shape | OCPU and RAM | +=======================+====================+ | FLEX4.16 | E3 4 OCPU 8G RAM | +-----------------------+--------------------+ | FLEX8.32 | E3 8 OCPU 32G RAM | +-----------------------+--------------------+ | FLEX16.32 | E3 16 OCPU 32G RAM | +-----------------------+--------------------+ .. note:: If you need IPsec performance beyond 2Gbps, refer to `Aviatrix Insane Mode. <https://docs.aviatrix.com/HowTos/insane_mode.html>`_ Specifying a Reachable DNS Server IP Address ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Aviatrix gateways are launched with a default public DNS server IP address 8.8.8.8 to ensure the gateway has access to Cloud Service Provider public resources such as SQS for Controller and gateway communication. If you want to change to a different DNS server, mark the **Specify a Reachable DNS Server IP Address** checkbox to enter an alternative DNS IP address. Enabling NAT ^^^^^^^^^^^^^^^^^^^^ The Aviatrix Gateway performs Source NAT (SNAT) function when this option is selected. All VPC/VCN routing tables for private subnets in AWS, GCP, and OCI are automatically programmed with 0.0.0.0/0 points to the gateway. The function can be enabled at gateway launch time, or any time afterwards. For example, you may already have a NAT gateway configured for the VPC in AWS. To minimize downtime, follow the steps below: 1. Launch a gateway without the SNAT option selected. #. Go to your AWS console to remove the existing 0.0.0.0/0 route entry from the route table. #. Go to the Gateway page, highlight the desired gateway, click **Edit** > scroll down to SNAT > click **Enable**. Enabling BGP ^^^^^^^^^^^^^^^^^^^^ Select this option to enable the Aviatrix Spoke Gateway with BGP. In the current release (6.6), BGP must be enabled at the creation of the Spoke gateway. Spoke Gateways created pre-6.6 cannot be enabled with BGP. A Spoke Gateway enabled with BGP has a few restrictions compared to a non-BGP Spoke. See `Aviatrix Spoke Gateway to External Devices (BGP-Enabled Spoke) <https://docs.aviatrix.com/HowTos/spokegw_external.html>`_for information about restrictions. Allocating a New EIP in AWS ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Select this option to have the Aviatrix Gateway allocate a new EIP for the gateway from AWS. When the Aviatrix Gateway is deleted, the Controller will release this EIP. If this option is unchecked, the gateway will be allocated an unassociated EIP from the AWS account from which the gateway is launched. When the Aviatrix Gateway is deleted, the Controller will return this EIP to your AWS account without releasing it. VPN Access -------------------- When this option is selected, the Aviatrix Gateway will used for SSL VPN termination. It supports OpenVPN® client and Aviatrix SAML client. For more details, check out `this link. <http://docs.aviatrix.com/HowTos/openvpn_features.html>`_ Enabling SAML ^^^^^^^^^^^^^^^^^^^^ When SAML is enabled, a VPN client/user authenticates to an identity provider (IDP) directly, instead of the gateway doing it on behalf of the user. In this case, you must use Aviatrix VPN Clients. Check out the `details <http://docs.aviatrix.com/HowTos/VPN_SAML.html>`_ on how to configure and use Aviatrix VPN Clients for SAML. VPN CIDR Block ^^^^^^^^^^^^^^^^^ When a VPN user connects to the VPN gateway, the user will be assigned a virtual IP address from a pool of IP addresses. This pool of IP addresses is defined as the `VPN <https://www.aviatrix.com/learning/glossary/cidr.php>`_ CIDR Block. The default IP address pool is 192.168.43.0/24. The only reason you would want to change this address pool is if 192.168.43.0/24 overlaps with your desktop or laptop network address range. For example, if you are on a LAN with a network CIDR 10.0.0.0/24, your desktop IP address will never conflict with your VPN virtual IP address. On the other hand, if your desktop is on a LAN with a network CIDR 192.168.20.0/16, your VPN virtual IP address might conflict with your LAN address. In this case, change the VPN CIDR Block to a different address range, for example, 10.10.0.0/24. Note a /24 VPN CIDR block supports about 64 simultaneous VPN clients. This is because for each connected VPN client, VPN gateways reserves 3 virtual addresses. For larger number of clients per VPN gateway, consider making the VPN CIDR block to a /22 or /20 network. MFA Authentication ^^^^^^^^^^^^^^^^^^^^^^ You can select either Duo or Okta for the VPN gateway to authenticate to these two services on behalf of a VPN user. When either option is selected, you can use native OpenVPN® client software such as Tunnelblick for iOS and OpenVPN for Windows. To configure Duo, see `How to configure Duo. <http://docs.aviatrix.com/HowTos/duo_auth.html>`_ To configure Okta, see `How to configure Okta. <http://docs.aviatrix.com/HowTos/HowTo_Setup_Okta_for_Aviatrix.html>`_ Max Connections ^^^^^^^^^^^^^^^ Maximum number of active VPN users allowed to be connected to this gateway. The default is 100. When you change this address, make sure the number is smaller than the VPN CIDR block. The OpenVPN® VPN CIDR Block allocates 4 IP addresses for each connected VPN user; when the VPN CIDR Block is a /24 network, it supports about 60 users. Split Tunnel Mode ^^^^^^^^^^^^^^^^^ Split Tunnel Mode is enabled by default. When Split Tunnel mode is enabled, only traffic that is destined to the VPC/VNet CIDR where the VPN gateway is deployed is going into the VPN tunnel when a user is connected to the VPN gateway. When Split Tunnel Mode is disabled (Full Tunnel Mode), all laptop traffic, including Internet traffic (such as a visit to www.google.com), is going through the VPN tunnel when a user is connected to the VPN gateway. Disabling Split Tunnel Mode should be a deliberate decision. You will be charged for all Internet traffic as they are considered egress traffic by the Cloud Service Provider (AWS/Azure/GCP/OCI). Additional CIDRs ^^^^^^^^^^^^^^^^ This is an optional parameter. The VPC/VNet CIDR where the VPN gateway is deployed is the default CIDR that VPN gateway pushes to the VPN client. Leave it blank if you do not need it. When Split Tunnel Mode is enabled, the Additional CIDRs specifies a list of destination CIDR ranges that will also go through the VPN tunnel. This is a useful field when you have `multiple VPC/VNets <http://docs.aviatrix.com/HowTos/Cloud_Networking_Ref_Des.html>`_ that the VPN user needs to access. Enter all network ranges in CIDR blocks separated by commas, as shown below: |additional_cidr| Nameservers (Optional) ^^^^^^^^^^^^^^^^^^^^^^ This is an optional parameter. Leave it blank if you do not need it. When Split Tunnel Mode is enabled, you can instruct the VPN gateway to push down a list of DNS servers to your desktop, so that a VPN user is connected, it will use these DNS servers to resolve domain names. Search Domains (Optional) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This is an optional parameter. Leave it blank if you do not need it. When Split Tunnel Mode is enabled, Search Domains let you specify a list of domain names that will use the Nameserver when a specific name is not in the destination. Windows VPN clients support a maximum of **10** search-domain entries (the OpenVPN service supports only up to 10 on the Windows OS). Enable ELB ^^^^^^^^^^^^^^^^^^^^^ "Enable ELB" is turned on by default. When ELB is enabled, the domain name of the CSP's load balancer (ELB/ALB/CLB), will be the connection IP address when a VPN user connects to the VPN gateway. This connection IP address is part of the .ovpn cert file the Controller sends to the VPN client. Even when you delete all VPN gateways, you can re-launch them without having to reissue a new .ovpn cert file. This helps reduce friction to VPN users. When the ELB option is enabled, you can launch multiple VPN gateways behind ELB, thus achieving a scale out VPN solution. .. note:: AWS classic Load Balancers are not supported with UserVPN gateways. Instead, `migrate <https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/migrate-classic-load-balancer.html>`_ to Network Load Balancers in your AWS account. ELB Name ^^^^^^^^^^^^^^^^^^ The ELB Name is generated automatically if it is left blank. If it is left blank and there is already a load balancer in the specified VPC/VNet, the system uses that load balancer's name. You can set the ELB name if there is no existing ELB in the specified VPC/VNet. VPN Protocol ^^^^^^^^^^^^^^^^^^^^ When the TCP checkbox is marked, the VPN gateway will accept the VPN TCP connection only. If the UDP checkbox is marked, only the VPN UDP connection is allowed. These options are only available on the AWS. For all cloud types, the VPN protocol is TCP by default if ELB is enabled. If the ELB is disabled, the VPN protocol is always UDP. Enable Client Certificate Sharing ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This setting is disabled by default. By enabling the client certificate sharing, all VPN users share one .ovpn file. You must have MFA (such as SAML, DUO + LDAP) configured to make VPN access secure. Enable Duplicate Connections ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This option was introduced in Controller version 4.3. This setting controls whether users sharing the same common name can connect at the same time to the VPN Gateway. If this is disabled, when a user attempts to connect to the gateway through a different device, his existing VPN connection from the current device gets disconnected. Note that the users can still land on different VPN Gateways under a load balancer, even though the feature is enabled. Prior to 4.3, this setting was coupled with Client Certificate Sharing. VPN NAT ^^^^^^^^^^^^^^^^ This feature was introduced in Controller version 4.6 . This controls whether the VPN connection uses NAT (Network Address Translation) while the VPN traffic leaves the Aviatrix VPN Gateway. VPN NAT is enabled by default. If you want to disable it, you can do so from OpenVPN > Edit Config > VPN NAT. If NAT is disabled, the traffic would appear to originate from the virtual IP of the VPN user rather than the VPN Gateway itself. Note that you would need to open up the security groups of the target instance to the VPN CIDR for the traffic to flow through. Any peering connection to this VPN gateway would additionally require traffic for the VPN CIDR to be forwarded to the gateway as well. If you have multiple gateways under the load balancer, you would also need to ensure that the VPN CIDR of the gateways do not overlap, so that the traffic can be routed back to the respective gateway. Enable Policy Based Routing (PBR) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ PBR enables you to route VPN traffic to a different subnet with its default gateway. By default, all VPN traffic is NATed and sent to VPN gateway's eth0 interface. If you want to force the VPN traffic to go out on a different subnet other than VPN gateway eth0 subnet, you can specify a PBR Subnet in the VPC and the PBR Default gateway. One use case for this feature is `Anonymous Internet Surfing <http://docs.aviatrix.com/HowTos/Anonymous_Browsing.html>`_. Enable LDAP ^^^^^^^^^^^^^^^^ When LDAP authentication is enabled, the VPN gateway will act as a LDAP client on behalf of the VPN user to authenticate the VPN user to the LDAP server. Minimum VPN Client Version ============================ Set a minimum Aviatrix VPN client software version that is allowed to connect successfully. To configure, go to OpenVPN > Edit Config > MINIMUM VPN CLIENT VERSION to set the Aviatrix VPN client version. Available for Aviatrix VPN client only. Add/Edit Tags --------------------- The Aviatrix Gateway is launched with a default tag name avx-gateway@private-ip-address-of-the-gateway. This option allows you to add additional AWS/Azure tags at gateway launch time that you can use for automation scripts. Designated Gateway -------------------- If a gateway is launched with the **Designated Gateway** feature enabled, the Aviatrix Controller will insert an entry for each address space defined by RFC1918: * 10.0.0.0/8, * 192.168.0.0/16, and * 172.16.0.0/12 The target of each of these entries will point to the Aviatrix Gateway instance. Once enabled, Transit VPC, Site2Cloud, and Encrypted Peering connections will no longer add additional route entries to the route table if the destination range is within one of these RFC1918 ranges. Instead, the Aviatrix Gateway will maintain the route table internally and will handle routing for these ranges. .. note:: The Designated Gateway feature is automatically enabled on Spoke Gateways created by the `Transit Network workflow <./transitvpc_workflow.html>`__. Starting with `release 3.3 <./UCC_Release_Notes.html#r3-3-6-10-2018>`__, you can configure the CIDR range(s) inserted by the Aviatrix Controller when the Designated Gateway feature is enabled. To do this, follow these steps: #. Log in to your Aviatrix Controller. #. Go to the **Gateway** page. #. Select the designated gateway to modify from the list and click **Edit**. .. note:: You must enable the Designated Gateway feature at the gateway creation time. #. Scroll down to the section labeled **Edit Designated Gateway**. #. Enter the list of CIDR range(s) (separate multiple values with a comma) in the **Additional CIDRs** field. #. Click **Save**. |edit-designated-gateway| Once complete, your route table(s) will be updated with the CIDR range(s) provided. Security Policy -------------------- Starting Release 3.0, gateway security policy page has been moved Security > Stateful Firewall. See `this guide. <http://docs.aviatrix.com/HowTos/tag_firewall.html>`_ High Availability ------------------------------ There are 3 types of high availability on Aviatrix: "Gateway for High Availability," "Gateway for High Availability Peering," and Single AZ HA. Gateway for High Availability ------------------------------------------ :: This feature has been deprecated. It is listed here for backward compatibility reasons. When this option is selected, a backup gateway instance will be deployed in a different AZ if available. This backup gateway keeps its configuration in sync with the primary gateway, but the configuration does not take effect until the primary gateway fails over to the backup gateway. :: When using Terraform, this option is described by parameter "ha_subnet" by resource gateway. Gateway for High Availability Peering -------------------------------------- When this option is selected, a backup gateway instance will be deployed in a different AZ if available. If you have built `Aviatrix Encrypted Peering <http://docs.aviatrix.com/HowTos/peering.html>`_ and need HA function for tunnel down fail over, you can select this option. This backup gateway keeps backup VPN tunnels up, ready for fail over. If you use Aviatrix Gateway for `Egress Control function <http://docs.aviatrix.com/HowTos/FQDN_Whitelists_Ref_Design.html>`_ and need HA function, you should select this option. This option will try to load balance the traffic from different route tables to primary and backup gateways. If you consider deploying `Aviatrix Transit Network <http://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_, high availability is built into the workflow. You do not need to come to this page. :: When using Terraform, this option is described by parameter "peering_ha_subnet" by resource gateway. Gateway Single AZ HA -------------------------------- When enabled, the Controller monitors the health of the gateway and restart the gateway if it becomes unreachable. No secondary gateway is launched in this case. :: When using Terraform, this option is described by parameter "single_az_ha" by resource gateway. Gateway Resize ----------------------- You can change Gateway Size if needed to change gateway throughput. The gateway will restart with a different instance size. To configure, click Gateway on the left navigation panel, select the desired gateway, and click **Edit**. Scroll down to Gateway Resize and in the dropdown menu, select the new gateway instance size. Click **Change**. The gateway instance will be stopped and restarted again with the new instance size. o :: If you use Availability Set when launching Azure gateways, different classes of VM sizes can be resized interchangeably. Source NAT ----------------- You can enable and disable NAT function after a gateway is launched. NAT function enables instances on private subnets in AWS, GCP, or OCI to access the Internet. When NAT is enabled, all route tables for private subnets in the VPC/VNet are programmed with a route entry that points the gateway as the target for route entry 0.0.0.0/0. Three modes of Source NAT are supported: 1. Single IP ============== When **Single IP** is selected, the gateway's primary IP address is used as source address for source NAT function. This is the simplest and default mode when you enable NAT at gateway launch time. 2. Multiple IPs ================= When **Multiple IPs** is selected, the gateway translates the source address to the pool of the multiple IPs in a round robin fashion. The multiple IPs are the secondary IP addresses of the gateway that you need to `setup <https://docs.aviatrix.com/HowTos/gateway.html#edit-secondary-ips>`_ first. 3. Customized SNAT ==================== When **Customized SNAT** is selected, the gateway can translate source IP address ranges to different SNAT address and ports, as shown below. Check out `this link <https://docs.aviatrix.com/Solutions/egress_nat_pool.html#step-4-configure-snat>`_ for an example configuration. |SNAT-customize| Sync to HA Gateway feature is an option to help users automatically duplicating NAT rules to HA peer gateway. By default, this function is disabled on Customized SNAT meaning users need to configure NAT rules manually on HA peer gateway even NAT rules are same. ================================ ======================= **Field** Value ================================ ======================= SRC CIDR This is a qualifier condition that specifies a source IP address range where the rule applies. When left blank, this field is not used. SRC PORT This is a qualifier condition that specifies a source port that the rule applies. When left blank, this field is not used. DST CIDR This is a qualifier condition that specifies a destination IP address range where the rule applies. When left blank, this field is not used and a default route 0.0.0.0/0 pointing to Aviatrix Gateway will be programmed into Cloud platform routing table. DST PORT This is a qualifier condition that specifies a destination port where the rule applies. When left blank, this field is not used. PROTOCOL This is a qualifier condition that specifies a destination port protocol where the rule applies. When left blank, this field is not used. INTERFACE This is a qualifier condition that specifies output interface where the rule applies. When left blank, this field is not used. CONNECTION This is a qualifier condition that specifies output connection where the rule applies. When left blank, this field is not used. MARK This is a qualifier condition that specifies a tag or mark of a TCP session where the rule applies. When left blank, this field is not used. SNAT IPS This is a rule field that specifies the changed source IP address when all specified qualifier conditions meet. When left blank, this field is not used. One of the rule fields must be specified for this rule to take effect. Multiple translated source IP addresses are supported, they are specified as a range, for example, 172.16.58.3 - 192.168.3.11 SNAT PORT This is a rule field that specifies the changed source port when all specified qualifier conditions meet.. When left blank, this field is not used. One of the rule fields must be specified for this rule to take effect. APPLY ROUTE ENTRY This is an option to program the route entry "DST CIDR pointing to Aviatrix Gateway" into Cloud platform routing table. EXCLUDE ROUTE TABLE This field specifies which VPC private route table will not be programmed with the default route entry. Users can combine this with APPLY ROUTE ENTRY enabled. ================================ ======================= Destination NAT --------------------- Destination NAT (DNAT) allow you to change the destination to a virtual address range. There are multiple optional parameters you can configure to meet your requirement. Follow `this example <https://docs.aviatrix.com/Solutions/egress_nat_pool.html#step-3-mark-and-map-destination-port>`_ to see how DNAT can be used, as shown below: |dnat-port-mapping| Sync to HA Gateway feature is an option to help users automatically duplicating NAT rules to HA peer gateway. By default, this function is enabled on DNAT. ================================ ======================= **Field** Value ================================ ======================= SRC CIDR This is a qualifier condition that specifies a source IP address range where the rule applies. When left blank, this field is not used. SRC PORT This is a qualifier condition that specifies a source port that the rule applies. When left blank, this field is not used. DST CIDR This is a qualifier condition that specifies a destination IP address range where the rule applies. When left blank, this field is not used and a default route 0.0.0.0/0 pointing to Aviatrix Gateway will be programmed into Cloud platform routing table. DST PORT This is a qualifier condition that specifies a destination port where the rule applies. When left blank, this field is not used. PROTOCOL This is a qualifier condition that specifies a destination port protocol where the rule applies. When left blank, this field is not used. INTERFACE This is a qualifier condition that specifies output interface where the rule applies. When left blank, this field is not used. CONNECTION This is a qualifier condition that specifies output connection where the rule applies. When left blank, this field is not used. MARK This is a rule field that specifies a tag or mark of a TCP session when all qualifier conditions meet. When left blank, this field is not used. DNAT IPS This is a rule field that specifies the translated destination IP address when all specified qualifier conditions meet. When left blank, this field is not used. One of the rule field must be specified for this rule to take effect. Multiple translated source IP addresses are supported, they are specified as a range, for example, 172.16.58.3 - 192.168.3.11 DNAT PORT This is a rule field that specifies the translated destination port when all specified qualifier conditions meet. When left blank, this field is not used. One of the rule field must be specified for this rule to take effect. APPLY ROUTE ENTRY This is an option to program the route entry "DST CIDR pointing to Aviatrix Gateway" into Cloud platform routing table. EXCLUDE ROUTE TABLE This field specifies which VPC private route table will not be programmed with the default route entry. Users can combine this with APPLY ROUTE ENTRY enabled. ================================ ======================= Monitor Gateway Subnet --------------------------------------- This feature allows you to enforce that no unauthorized virtual machine (EC2/VM/GCE) instances are being launched on the gateway subnet. Since an Aviatrix gateway must be launched on a public subnet in AWS, GCP, or OCI, if you have policies that no virtual machine instances can be launched on public subnets, this feature addresses that concern. When it is enabled, the Controller periodically monitors the selected subnet where gateway is launched from. If it detects virtual machine instances being launched, the Controller sends an alert email to admin and immediately stops the instance(s). You can exclude certain instances by entering instance IDs separated by commas. To configure: #. Go to the Gateway page. #. Highlight a gateway and click **Edit**. #. Scroll down to Monitor Gateway Subnet. #. Click **Enable** and then optionally enter excluding instance ID(s). Click **OK** when finished. Click **Disable** to remove all excluding instance ID(s). Gateway State -------------------- Gateway state is dictated by the following factors. - State of the gateway as reported by the cloud provider. - Connectivity between Controller and gateway over HTTPS (TCP port 443). - Status of critical services running on the gateway. An Aviatrix Gateway could be in any of the following states over its lifetime. **WAITING**: This is the initial state of a gateway immediately after the launch. The gateway will transition to **UP** state when the controller starts receiving keepalive messages from the newly launched gateway. **UP**: The gateway is fully functional. All critical services running on the gateway are up and the gateway and the controller are able to exchange messages with each other. **DOWN**: A gateway can be down under the following circumstances. - The Gateway and the Controller could not communicate with each other over HTTPS (443). - The Gateway instance (VM) is not in running state. - Critical services are down on the gateway. **KEEPALIVE_FAIL: The Controller did not receive the expected number of keepalive messages from the gateway during a health check. However, a tunnel to this gateway from a peered gateway is reported as UP. **CONFIG-FAIL**: Gateway could not process a configuration command from the Controller successfully. Please open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_ for assistance. If a gateway is not in **UP** state, please perform the following steps. - Examine the security policy of the Aviatrix Controller instance and make sure TCP port 443 is opened to traffic originating from gateway public IP address. - Examine the security policy of the gateway and make sure that TCP port 443 is opened to traffic originating from controller public IP address. This rule is inserted by the Aviatrix Controller during gateway creation. Please restore it if was removed for some reason. - Make sure network ACLs or other firewall rules are not configured to block traffic between controller and gateway over TCP port 443. Gateway Keepalives ----------------------------- As mentioned in the previous section, the gateway sends periodic keepalive messages to the Controller. The following templates can be used to control how frequently gateways send keepalives and how often the Controller processes these messages, which in turn will determine how quickly the Controller can detect gateway state changes. =========================== ======================= ============================= **Template name** Gateway sends keepalive Controller runs health checks =========================== ======================= ============================= Fast every 3 seconds every 7 seconds Medium every 12 seconds every 1 minute Slow every 1 minute every 5 minute =========================== ======================= ============================= Medium is the default configuration. A gateway is considered to be in **UP** state if controller receives at least 2 (out of a possible 5) messages from that gateway between two consecutive health checks. For **Fast** configuration, the Controller determines the gateway state on 2 samples, so the gateway failure detection time is between 7 seconds and 14 seconds. For example, with medium setting, gateway down detection time is between 1 minute plus 36 seconds to 2 minutes. The keepalive template is a global configuration on the Controller for all gateways. To change the keep alive template, go to: :: Settings > Advanced > Keepalive. In the dropdown menu, select the desired template. Edit Secondary IPs (for AWS) -------------------------- This feature allows you to add `secondary IP addresses <https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/MultipleIP.html>`_ to gateway instances for AWS. The format to enter the field is, for example, :: 192.168.3.11 (for single secondary IP address) 192.168.3.11-172.16.58.3 (for a multiple consecutive secondary IP addresses) The main use case for this feature is to enable you to configure source NAT function that maps to multiple IP addresses, instead of a single one. When used for this purpose, you need to go to AWS console to first allocate an `EIP <https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-eips.html>`_, then `associate each secondary IP with an EIP <https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html#using-instance-addressing-eips-associating>`_ to complete the function. This feature is currently available for AWS. Use VPC/VNet DNS Server ------------------------------------ When enabled, this feature removes the default DNS server for the Aviatrix Gateway and instructs the gateway to use the VPC/VNet DNS server configured in VPC/VNet DHCP option. When disabled, the Aviatrix Gateway will revert to use its built-in (default) DNS server. Here is one example use case to enable this feature: If you enable `Logging <https://docs.aviatrix.com/HowTos/AviatrixLogging.html>`_ on the Aviatrix Controller, all Aviatrix Gateways forward their log information to the configured log server. But if the log server is deployed on-prem with a private DNS name, the Aviatrix gateway's default DNS server cannot resolve the domain name of the private log server. By enabling the VPC/VNet DNS server, the gateway will start to use the VPC/VNet DNS server which should resolve the private DNS name of the log server. .. note:: When enabling this feature, we check to make sure the gateway can indeed reach the VPC/VNet DNS server; if not, this command will return an error. `A caveat is noted <https://docs.aviatrix.com/HowTos/transitvpc_faq.html#how-does-spoke-gateway-and-vpc-private-dns-work-together>`_ when this feature is applied to a Transit Network. Insane Mode Encryption -------------------------------- When this option is selected, the Aviatrix Controller will look for a spare /26 subnet segment to create a new public subnet "-insane" and launch the gateway on this subnet. The instance sizes that support Insane Mode are c5 series and m5 series. Insane Mode encryption is an Aviatrix technology that enables 10Gbps and higher IPsec performance between two single Aviatrix Gateway instances or between a single Aviatrix Gateway instance and on-prem Aviatrix appliance. For more info, read `this document <https://docs.aviatrix.com/HowTos/insane_mode.html>`_ to learn all about Aviatrix Insane Mode for high performance Transit Network. Encrypt EBS Volume (for AWS) ------------------------------------------ This feature only applies to AWS gateway. When enabled, the gateway EBS volume is encrypted. To configure, go to Gateway page, select the gateway, and click **Edit**. Scroll down to Encrypt Volume and click **Encrypt**. Note the encrypting action takes up to 15 minutes. For more details, open `this link <https://docs.aviatrix.com/HowTos/encrypt_ebs_volume.html>`_ Customize Spoke VPC Routes ----------------------------------------- This feature allows you to customize Spoke VPC/VNet route table entry by specifying a list of comma separated CIDRs. When a CIDR is inserted in this field, automatic route propagation to the Spoke(s) VPC/VNet will be disabled, overriding propagated CIDRs from other spokes, transit gateways and on-prem network. One use case of this feature is for a Spoke VPC/VNet that is customer facing and your customer is propagating routes that may conflict with your on-prem routes. When this is enabled on an Aviatrix Transit Gateway, all Spoke VPC/VNets route tables are customized. When it is enabled on an Spoke Gateway, only that gateway VPC/VNet route table is applied. This feature does not apply to AWS Transit Gateway (TGW) attached Spoke VPCs. To disable this feature, empty the field and click **Save**. The on-prem learned routes will be propagated in to the Spoke VPC/VNet routes. Filter Learned Routes to Spoke VPC/VNet ---------------------------------------------------- This feature allows you to filter on-prem network CIDRs to Spoke VPC/VNet route table entry. The unwanted list of CIDRs should be entered as input. This list of CIDRs should be comma separated. One use case of this feature is for a Spoke VPC/VNet that is customer facing and you do not wish your customer to access all your on-prem network CIDRs. The list of the filtered out CIDRs can be a super set of on-prem learned routes. For example, if the on-prem learned routes are 172.16.17.32/24 and 192.168.3.11/24, you can enter 172.16.17.32/16 to filter out both routes. If the filtered out CIDR is a subnet of on-prem learned CIDR, the filtered CIDR won't work. When it is applied to the Aviatrix Transit Gateway, all attached Spoke VPC/VNets will filter on the configured routes. When it is applied to a specific Spoke VPC/VNet, only the Spoke VPC/VNet route table is affected. This feature does not apply to AWS Transit Gateway (TGW) attached Spoke VPCs. Customize Advertised Spoke VPC CIDRs --------------------------------------------------- This route policy enables you to selectively exclude some VPC/VNet CIDRs from being advertised to on-prem. One use case is if you have Spoke VPC/VNets that have multiple CIDR blocks, among which some of them are overlapping. If you attach these Spoke VPC/VNets, the Aviatrix Controller will reject them as there are overlapping CIDRs. By excluding the overlapping CIDRs, you will be able to attach the Spoke VPC/VNets. When this policy is applied to an Aviatrix Transit Gateway, the list is an "Exclude list" meaning the CIDRs in the input fields will be excluded from advertising to on-prem. When this policy is applied to an Aviatrix Spoke Gateway, the list is an "Include list" meaning only the CIDRs in the input fields are advertised to on-prem. In Release 4.7 and later, the "Include list" can be network ranges that are outside of the Spoke VPC/VNet CIDR. Transit Peers As Backup to On-prem ------------------------------------------------ When this feature is enabled on a Transit Gateway, every one of its remote Transit Peers does not advertise to its on-prem network all the Spoke VPCs and on-prem routes learned by this Transit Gateway, except when the link to the on-prem goes down at which point one of the remote Transit Peers starts to advertise to its on-prem network all the Spoke VPC/VNets and on-prem routes learned by this Transit Gateway. One use case is a connected multi-site on-prem network, where each site is connected to the cloud via Aviatrix Transit Gateways and the Transit Gateways are full mesh connected. In such case, each Transit Gateway learns all Spoke VPC/VNets and on-prem network CIDRs. Without enabling this feature, route conflicts happen for the on-prem network. With this feature enabled, there is no route conflict to on-prem and any Spoke VPC/VNet has a redundant route to on-prem. Jumbo Frame ------------------------ Jumbo Frame improves Aviatrix Gateway throughput performance. This feature is enabled by default for AWS and OCI. It is not supported for Azure or GCP. To enable Jumbo Frame for an Aviatrix Gateway: #. In Aviatrix Controller, from the left sidebar, select **GATEWAY**. #. On the Gateways page, select the gateway for which you want to enable Jumbo Frame and click **Edit**. #. Scroll down to Jumbo Frame and click **Enable**. IPv6 (for AWS) ------------------------ IPv6 can be enabled on an Aviatrix Gateway deployed in AWS. One use case is to use IPv6 to resolve overlapping VPC CIDRs when doing encrypted peering. This use case requires both the VPC and EC2 instances have IPv6 enabled. When this option is enabled, Controller automatically enables IPv6 on the VPC CIDR and the subnet where the gateway is launched. It is your responsibility to enable IPv6 on any other subnets and instances. Use `Migrating to IPv6 <https://docs.aws.amazon.com/vpc/latest/userguide/vpc-migrate-ipv6.html>`_ if you need help. When building an encrypted tunnel between two identical VPC CIDRs to for networking between the instances in each VPC, the Controller uses the gateway's IPv4 EIP as tunnel end point. Find out more in `Use IPv6 for User VPN Access <https://docs.aviatrix.com/HowTos/ipv6_multivpc_vpn.html>`_. ActiveMesh Mode ------------------------------- ActiveMesh is officially supported in 5.1 release. If you deploy ActiveMesh gateway in the 5.0 beta code, please upgrade to the latest 5.1 before running it in production environment. When an Aviatrix Transit Gateway has ActiveMesh mode enabled, both primary and backup gateway forward packets in ECMP and active/active state. New and advanced features such as Multi-sites Transit solution where the Aviatrix Transit Gateway connects to multiple remote sites is only supported with ActiveMesh mode enabled on the Aviatrix Transit GW. To enable ActiveMesh mode after the Transit Gateway or Spoke Gateway is enabled, go to Gateway, highlight the gateway and click **Edit**. Scroll down to find ActiveMesh Mode, click **Enable**. OpenVPN is a registered trademark of OpenVPN Inc. .. |edit-designated-gateway| image:: gateway_media/edit-designated-gateway.png :scale: 50% .. |SNAT-customize| image:: gateway_media/SNAT-customize-6-1.png :scale: 30% .. |dnat-port-mapping| image:: gateway_media/dnat-port-mapping-6-1.png :scale: 30% .. |additional_cidr| image:: gateway_media/additional_cidr.png :scale: 30% .. |network_mapping| image:: gateway_media/network_mapping.png :scale: 30% .. |gateway_name_alias| image:: gateway_media/gateway_name_alias.png :scale: 30% .. disqus:: <file_sep> ============================================================ Transit FireNet Design Patterns ============================================================ This document describes common design patterns when Aviatrix Transit Firewall Network (Transit FireNet) is deployed. 1. Hybrid to On-prem --------------------------------------------------- |hybrid| 2. Hybrid with Insane Mode -------------------------------------------------------- FireNet supports Insane Mode. |insane| 3. FireNet in Multi-Regions --------------------------------------------------------------------------------- |multi-regions| 4. Two Firewall Networks -------------------------------------------------------- You can deploy two Firewall Networks, one dedicated for East-West traffic inspection and another for egress inspection. Note you must follow the configuration sequence below: 1. Disable the Traffic Inspection of the FireNet Gateway intended for egress control. #. Enable Egress Control for FireNet Gateway intended for egress control. #. Build connection policies. |dual_firenet| 5. Aviatrix FQDN in FireNet for Egress Control ---------------------------------------------------------------- When Aviatrix FQDN gateway is deployed in a VPC/VNet, it uses a public IP address to perform both whitelisting and NAT function for Internet-bound traffic. Sometimes these Internet bound traffic are partner API calls and these partners require to limit the number of IP addresses for each customer of theirs. In such situation, you can deploy FQDN in a centralized manner as shown in the diagram below. |fqdn_egress| 6. Central Egress in a Multi-Region Deployment -------------------------------------------------------- Since the default routes are propagated over the Aviatrix Transit Gateway peering, you can consolidate the Internet-bound egress traffic to the firewalls in one region, as shown in the diagram below. |central_egress| 7. Distributed Egress in a Multi Region Deployment ------------------------------------------------------ If you need to have a distributed egress for each region, make sure you filter out the default route 0.0.0.0/0 when you build the Aviatrix Transit Gateway peering, as shown in the diagram below. |multi_egress| 8. Ingress Protection via Aviatrix Transit FireNet ------------------------------------------------------ This Ingress Protection design pattern is to have the traffic forward to firewall instances directly in Aviatrix Transit FireNet VPC/VNet as shown in the diagram below. In this design pattern, each firewall instance must configure (1) SNAT on its LAN interface that connects to the Aviatrix FireNet Gateway and (2) DNAT to the IP of application server/load balancer. The drawback of this design is source IP address is not preserved when traffic reaches the application. For an example configuration workflow, check out `Ingress Protection via Aviatrix Transit FireNet with Fortigate <https://docs.aviatrix.com/HowTos/Ingress_Protection_Transit_FireNet_Fortigate.html>`_. |transit_firenet_ingress| .. |hybrid| image:: transit_firenet_design_patterns_media/hybrid.png :scale: 30% .. |insane| image:: transit_firenet_design_patterns_media/insane.png :scale: 30% .. |multi-regions| image:: transit_firenet_design_patterns_media/multi-regions.png :scale: 30% .. |dual_firenet| image:: transit_firenet_design_patterns_media/dual_firenet.png :scale: 30% .. |fqdn_egress| image:: transit_firenet_design_patterns_media/fqdn_egress.png :scale: 30% .. |central_egress| image:: transit_firenet_design_patterns_media/central_egress.png :scale: 30% .. |multi_egress| image:: transit_firenet_design_patterns_media/multi_egress.png :scale: 30% .. |transit_firenet_ingress| image:: ingress_firewall_example_media/Ingress_Aviatrix_Transit_FireNet_topology.png :scale: 30% .. disqus:: <file_sep> .. |win| image:: AVPNC_img/Win.png .. |mac| image:: AVPNC_img/Mac.png .. |lux| image:: AVPNC_img/Linux.png .. |bsd| image:: AVPNC_img/BSD.png .. |Client| image:: AVPNC_img/Client.png :width: 400 .. |LDAPAuth| image:: AVPNC_img/LDAPAuth.png :height: 200 .. |MacBottomBar| image:: AVPNC_img/MacBottomBar.png :height: 30 .. |MacClientLocation| image:: AVPNC_img/MacClientLocation.png :height: 50 .. |MacClientLocation2| image:: AVPNC_img/MacClientLocation2.png :width: 400 .. |MacCrendential| image:: AVPNC_img/MacCrendential.png :width: 300 .. |ProgressIcon| image:: AVPNC_img/ProgressIcon.png :width: 400 .. |SamlAuth| image:: AVPNC_img/SamlAuth.png :width: 300 .. |Settings| image:: AVPNC_img/Settings.png :width: 400 .. |TrayMenu| image:: AVPNC_img/TrayMenu.png :width: 150 .. |WinBottomBar| image:: AVPNC_img/WinBottomBar.png :height: 40 .. |WinClientLocation| image:: AVPNC_img/WinClientLocation.png :height: 400 .. |WinClientPopup| image:: AVPNC_img/WinClientPopup.png :width: 400 .. |WinClientStartUp| image:: AVPNC_img/WinClientStartUp.png :width: 400 .. |minus| image:: AVPNC_img/minus.png :height: 16 .. |add| image:: AVPNC_img/add.png :height: 16 .. |3dots| image:: AVPNC_img/3dots.png :height: 16 ============================== Aviatrix VPN Client User Guide ============================== **************************************** Installing and Launching the Application **************************************** ************* Windows |win| ************* 1. Download the Aviatrix VPN Client installer from `this link <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/AVPNC_win_x64.exe>`__ Run the installer and follow the on-screen instructions to install the application. If you have installed OpenVPN previously, TUN TAP drivers would have been installed. If they are not installed, you can install the TUN TAP at the end of the installation. 2. Save the OpenVPN configuration file (with the extension .ovpn) that was sent to you by your Admin, on to your machine. 3. Open the “Aviatrix VPN Client” application by going to “Start Menu -> Aviatrix VPN Client-> Aviatrix VPN Client”. |WinClientLocation| 4. A UAC window pops up. |WinClientPopup| 5. Allow administrator access so that the application can modify the routing tables. The Aviatrix VPN Client window should come up which should look like. |WinClientStartUp| 6. Skip to the `Using the Application <#using-the-application>`__ section if you do not need to install it on a Mac or Linux ********* Mac |mac| ********* 1. Download the Aviatrix VPN Client installer from `this link <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/AVPNC_mac.pkg>`__ Follow the on-screen instructions to install the application 2. Save the OpenVPN configuration file (with the extension .ovpn) that was sent to you by your Admin, on to your machine. 3. Start the Aviatrix VPN Client application by going to LaunchPad and clicking on “Aviatrix VPN Client”. |MacClientLocation| |MacClientLocation2| 4. A popup comes up to request sudo privelages to modify routing tables |MacCrendential| 5. This opens the application window. 6. Skip to the `Using the Application <#using-the-application>`__ section if you do not need to install it on Linux *********** Linux |lux| *********** 1. Download the Aviatrix VPN Client installer from `this link <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/AVPNC_linux.tar.gz>`__ 2. To install the application run the following commands tar -xvzf AVPC_linux.tar.gz sudo ./install.sh 3. Save the OpenVPN configuration file (with the extension .ovpn) that was sent to you by your Admin, on to your machine. 4. To open the “Aviatrix VPN Client” launch a new terminal and type AVPNC .. note:: This has been tested only on Ubuntu 16/14. Theoretically, it should work with other flavours of linux as well as long as openvpn is installed separately. .. _using_the_application: ********************* Using the Application ********************* There are 3 buttons on the bottom 1. |add| : This opens a window to choose the OpenVPN configuration (.ovpn) file. 2. |minus| : This deletes a item choosed in the Connection Profiles 3. |3dots| : This pops up a submenu including "Edit", "Sort", "Connection Log" and "Settings" 3.1 "Edit": Modify a item choosed in the Connection Profiles 3.2 "Connection Log": Show every single connection's log 3.3 "Settings": Open the advanced settings ************* Windows |win| ************* 1. There is a menu on the top of the App GUI 1.1 "File" has a menu to quit the App 1.2 "Help" has menu "About" to show the App information 2. Closing the application window hides it to the system tray |WinBottomBar| ********* Mac |mac| ********* 1. There is a menu on the top-left of the screen 1.1 "About" shows show the App information 1.2 "Quit" exit the App information 2. Closing the application window hides it to the system tray |MacBottomBar| By a right click on Windows's or a click on Mac's system tray icon to show a menu |TrayMenu| 3. There are 3 status icons that are shown in the window and on the tray. |ProgressIcon| *********************** Advanced Settings Page *********************** |Settings| Here you can perform special operations if Troubleshooting is required 1. Flush DNS: (Not for windows) Flushes the DNS configuration if there are internet issues after full tunnel VPN disconnection. Also turning the wifi/ethernet adapter on/off can fix some internet issues. 2. Kill all OpenVPN process: (Not supported on Windows) Sends a soft kill to all running OpenVPN processes 3. Force kill all OpenVPN process: Terminates other OpenVPN processes that are running abruptly 4. Check VPN DNS server reachability: (MacOS only) If this option is checked, it will apply the VPC DNS servers in the MacOS system. If it is disabled, it will use the local DNS servers or other local DNS mechanism (e.g. CISCO Umbrella) **************************** Connecting to a SAML Gateway **************************** Enter your IDP Credentials to login. Check doc `OpenVPN® with SAML Authentication <https://docs.aviatrix.com/HowTos/VPN_SAML.html>`__ for detail. ************************************************** Connecting to a Gateway without any Authentication ************************************************** Just load the OpenVPN configuration(.ovpn) file on to the VPN Client and click on “Connect”. ************************************************************* Connecting to a Gateway with Username-Password Authentication ************************************************************* CloudN VPC supports a variety of authentication methods to verify VPN user credentials. Here’s a brief overview of how to enter user credentials for different authentication methods. LDAP: Enter username and password stored on LDAP server. Check doc `LDAP Configuration for Authenticating VPN Users <https://docs.aviatrix.com/HowTos/VPNUsers_LDAP.html>`__ for detail. Google 2-step verification: Use your email address as the username. Password should be appended with the 6-digit code generated by Google authenticator app on your phone. E.g., If your email is "<EMAIL>", the following username password combination of "<EMAIL>" and "<PASSWORD>" should be used where "<PASSWORD>" is your account password and "<PASSWORD>" is the 6 digit-code. Duo Security Two-Factor Authentication: Mac and Windows users: An automatic approval request will be pushed to your registered cellphone. Select “Approve” to connect to VPN gateway. LDAP + Duo Security Two-Factor Authentication: Enter username and password for the LDAP server and an automatic approval request will be pushed to your registered cellphone. Select “Approve” to connect to VPN gateway. The username and password windows is shown |LDAPAuth| <file_sep> ====================================================================== Multi-Cloud Transit Network Workflow Instructions (AWS/Azure/GCP/OCI) ====================================================================== .. important:: If you intend to deploy a transit network using AWS Transit Gateway (TGW), your starting point is `this link <https://docs.aviatrix.com/HowTos/tgw_plan.html>`_. For building encrypted Transit in AWS/Azure/GCP/OCI or Transit network with Azure Native Peering, this document is your starting point. This workflow provides you with step-by-step instructions to build a Multi-Cloud Transit Network. This Multi-Cloud Transit Network consists of a single Aviatrix Transit Gateway and a set of Aviatrix Spoke Gateways for communications between Spoke VPC or VNet instances and your on-prem network. While the instructions below reference AWS, these functionalities apply to any public cloud in which Aviatrix Multi-Cloud Transit Network is supported. To expand your Multi-Cloud Transit Network to multiple clouds and regions, you can create Transit Gateway peering to connect two or more Aviatrix Transit Gateways that are connected to sets of Spoke Gateways. For more information, see `Aviatrix Transit Gateway Encrypted Peering. <http://docs.aviatrix.com/HowTos/transitvpc_designs.html>`_ For a design guide, see `Multi-Cloud Transit Network Design Patterns. <http://docs.aviatrix.com/HowTos/transitvpc_designs.html>`_ For more information, see `Multi-Cloud Transit Network FAQ. <http://docs.aviatrix.com/HowTos/transitvpc_faq.html>`_ For other Aviatrix functions, such as `VPN access for users <http://docs.aviatrix.com/HowTos/uservpn.html>`_ and `VPN access for sites <http://docs.aviatrix.com/HowTos/site2cloud_faq.html>`_, see the `Aviatrix Overview <http://docs.aviatrix.com/StartUpGuides/aviatrix_overview.html>`_. .. note:: For description purposes, gateway and GW are used interchangeably. Other than gateway deletion, resources created by this workflow should be deleted within the workflow. The Transit Network diagram is described as below. |Test| Planning and Prerequisites --------------------------- #. If you have not launched an Aviatrix Controller, start with `Aviatrix startup guide <http://docs.aviatrix.com/StartUpGuides/aviatrix-cloud-controller-startup-guide.html>`_ #. Identify a VPC/VNet, call it Transit VPC/VNet, in a region where you want to launch the Transit GW (`additional details <./transit_spoke_aws_requirements.html>`__) We recommend you to use the information `here <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ to create a Transit VPC/VNet. #. Create a VGW or reuse an existing VGW. The VGW should not be attached to the Transit VPC/VNet if you plan to launch Transit GW in the same VPC/VNet. This VGW can be attached to a different VPC/VNet if this VPC/VNet CIDR is different from the Transit VPC/VNet where the Transit GW is launched or in a different region and account. (see `10Gbps Transit Network use case <http://docs.aviatrix.com/HowTos/transitvpc_designs.html#gbps-transit-vpc-design>`_). This VGW should be connected to on-prem either over Direct Connect or over the Internet. #. If this is your first time using Aviatrix, make sure you go through the Aviatrix Controller on-boarding process to create an Aviatrix account that corresponds to an IAM role. For instructions on how to launch an Aviatrix Controller, check out `this link. <http://docs.aviatrix.com/StartUpGuides/aviatrix-cloud-controller-startup-guide.html>`_ .. tip:: Use the Aviatrix `"Create a VPC" <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ tool with the option "Aviatrix Transit VPC" to create a transit VPC/VNet that has all infrastructure fully populated. Log into the Aviatrix Controller ------------------------------------------- Open a browser and navigate to https://<Controller Public IP address>/. Once authenticated, select **Multi-Cloud Transit > Setup** in the left navigation bar. The Multi-Cloud Transit Network Workflow page opens. Use this page and the four tabs in the top right (Transit, Spoke, Attach/Detach, and External Connection) to set up a Multi-Cloud Transit Network. Transit ------------------------------------------- On the Multi-Cloud Transit Network Workflow page, select the **Transit** tab in the top right to launch a Transit Gateway. 1. Launch an Aviatrix Transit Gateway ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ On the Multi-Cloud Transit Network Workflow page, select the **Transit** tab in the top right to launch a Transit Gateway. The Transit GW is the hub gateway, it serves to move traffic between a Spoke VPC/VNet and an on-prem network. The Transit GW must be launched on a public subnet where its associated route table has a route 0.0.0.0/0 that points to AWS IGW. |TVPC2| ========================================== ========== **Setting** **Value** ========================================== ========== Cloud Type Currently Transit GW can launched in AWS, Azure, and GCP Gateway Name A unique name to identify the Transit GW Access Account Name An `Aviatrix account <http://docs.aviatrix.com/HowTos/aviatrix_account.html#account>`_ that corresponds to an IAM role or account in AWS Region One of the AWS regions VPC ID The Transit VPC/VNet/VCN ID Public Subnet The public subnet on which Transit GW instance is deployed Gateway Size Transit GW `instance size <http://docs.aviatrix.com/HowTos/gateway.html#select-gateway-size>`_ Allocate New EIP Select this checkbox to have the Controller allocate a new EIP and associate it with the Transit Gateway instance. If you do not select this option, the Controller looks for an allocated but unassociated EIP in the Transit GW account. Insane Mode Encryption If selected, Transit GW can peer and connect to Spoke with `Insane Mode Encryption <https://docs.aviatrix.com/HowTos/gateway.html#insane-mode-encryption>`_. Add/Edit Tags `Additional AWS Tags <http://docs.aviatrix.com/HowTos/gateway.html#add-edit-tags>`_ for the Transit GW instance ========================================== ========== .. Warning:: When selecting Transit GW instance size, choose a t2 series for Proof of Concept (POC) or prototyping only. Transit GW of t2 series instance type has a random packet drop of 3% for packet size less than 150 bytes when interoperating with VGW. This packet drop does not apply to Spoke GW. You can change the Transit GW size later by following `these instructions. <http://docs.aviatrix.com/HowTos/transitvpc_faq.html#how-do-i-resize-transit-gw-instance>`_ 2. (Optional) Enable/Disable HA to an Aviatrix Transit Gateway ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ When HA is enabled, a second Transit GW will be launched. Note both Transit GWs will be forwarding traffic in an event of tunnel failure between a Spoke VPC/VNet and Transit VPC/VNet, and between the Transit GW and VGW. For best practice, the HA GW should be launched on a different public subnet (in AWS, GCP, or OCI) in a different AZ. |HAVPC| ========================================== ========== **Setting** **Value** ========================================== ========== Aviatrix Transit Gateway Select the Transit GW for which you want to enable HA HA Gateway Subnet Select the subnet in which you want to enable HA. A best practice is to select a different public subnet from the original Transit GW in a different AZ. Allocate New EIP Select this checkbox to have the Controller allocate a new EIP and associate it with the HA Gateway instance. If you do not select this option, the Controller looks for an allocated but unassociated EIP in the Transit GW account. ========================================== ========== To disable Transit GW HA, go to the Gateway page and delete the Transit GW with -hagw in the name extension. Note: If the Transit GW is connected to VGW, you cannot disable Transit GW HA and if there are still Spoke GWs, you cannot disable Transit GW HA either. Spoke ------------------------- To launch an Aviatrix Spoke Gateway, select the **Spoke** tab in the top right of the Multi-Cloud Transit Network Workflow page of your Aviatrix Controller. 1. Launch an Aviatrix Spoke Gateway ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. Note:: If you are building Azure transit solution and do not require traffic encryption between Spoke VNet and Transit VNet, go to section "1b. Attach Azure ARM Spoke through Native Peering" section below to attach Spoke VNet directly. |launchSpokeGW| ========================================== ========== **Setting** **Value** ========================================== ========== Cloud Type Spoke GW can be launched in AWS and Azure Gateway Name A unique name to identify the Spoke GW Access Account Name An `Aviatrix account <http://docs.aviatrix.com/HowTos/aviatrix_account.html#account>`_ that corresponds to an IAM role or account in AWS Region One of the AWS regions VPC ID The Spoke VPC/VNet ID Public Subnet The public subnet where the Spoke GW instance is deployed Gateway Size Spoke GW `instance size <http://docs.aviatrix.com/HowTos/gateway.html#select-gateway-size>`_ Enable SNAT Select the option if the Spoke GW will also be the NAT gateway for the Spoke VPC/VNet Enable BGP Select this option to enable BGP for this Spoke GW Allocate New EIP If selected, the Controller allocates a new EIP and associate it with the gateway instance. If not selected, the Controller looks for an allocated but unassociated EIP in the Transit GW account. Insane Mode Encryption If selected, Transit GW can peer and connect to Spoke with `Insane Mode Encryption <https://docs.aviatrix.com/HowTos/gateway.html#insane-mode-encryption>`_. Add/Edit Tags `Additional AWS Tags <http://docs.aviatrix.com/HowTos/gateway.html#add-edit-tags>`_ for the Transit GW instance ========================================== ========== You can enable NAT function on the Spoke GW if egress to the Internet is intended to go through the Spoke GW. Once NAT is enabled, you can further configure `FQDN whitelists for egress filter. <http://docs.aviatrix.com/HowTos/FQDN_Whitelists_Ref_Design.html>`_ 2. (Optional) Enable/Disable HA to an Aviatrix Spoke Gateway ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ When HA is enabled, a second Spoke GW will be launched. Note both Spoke GWs will be forwarding traffic in an event of tunnel failure between a Spoke VPC/VNet and Transit VPC/VNet. For best practice, the HA GW should be launched on a different public subnet (in AWS, GCP, or OCI) in a different AZ. |HAVPC| ========================================== ========== **Setting** **Value** ========================================== ========== Aviatrix Spoke Gateway Select the Spoke GW for which you want to enable HA HA Gateway Subnet Select the subnet in which you want to enable HA. A best practice is to select a different public subnet from the original Spoke GW in a different AZ. Allocate New EIP Select this checkbox to have the Controller allocate a new EIP and associate it with the HA Gateway instance. If you do not select this option, the Controller looks for an allocated but unassociated EIP in the Spoke GW account. ========================================== ========== To disable Spoke GW HA, go to the Gateway page and delete the Spoke GW with -hagw in the name extension. Attach/Detach --------------------------------------- To attach or detach a Spoke Gateway to a Transit Network, select the **Attach/Detach** tab in the top right of the Multi-Cloud Transit Network Workflow page in your Aviatrix Controller. 1a. Attach: Attach Spoke Gateway to Transit Network ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This step attaches a Spoke VPC/VNet to the Transit GW Group by building an Aviatrix encrypted peering and transitive peering between the Spoke GW and the Transit GW. The Controller also instructs the Transit GW to start advertising the Spoke VPC/VNet CIDR to VGW via the established BGP session. |AttachSpokeGW| To attach a Spoke Gateway to a Transit Gateway: #. Click on the Spoke Gateway/SourceGateway dropdown menu and select the Spoke Gateway to attach. #. Click on the Transit Gateway/NextHop Gateway dropdown menu and select a Transit Gateway. #. (Optional) To create the maximum number of tunnels for the Spoke-to-Transit gateway attachment, check **Max Performance**. .. Note:: Max Performance option is valid when both the Spoke and Transit gateways are launched with Insane Mode enabled and are in the same cloud type. The number of tunnels that are created depends on the gateway instance sizes. If **Max Performance** is not checked, then only 1 tunnel is created even when Insane Mode is enabled for both Spoke and Transit Gateway. To switch between multiple tunnels or one tunnel, detach and reattach the Spoke Gateway to the Transit Gateway. #. Click Attach. To attach more Spoke VPC/VNets to this Transit GW Group, click on the Spoke Gateway/Source Gateway dropdown menu and select a new Gateway to attach. 1b. Attach Azure ARM Spoke through Native Peering ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Available in release 5.0 and later, you can build Azure transit solution without having to launch a gateway in a Spoke VNet. The use case is for building a Azure transit solution without the requirement to encrypt the traffic between the Transit VNet and the Spoke VNet. |azure_native_transit2| .. Note:: The Spoke VNet must be in the same subscription or a different subscription but in the same AD as the Transit VNet subscription. If the Spoke VNet is in the different subscription than that of the Transit VNet, follow the instruction `in this link <https://docs.microsoft.com/en-us/azure/virtual-network/create-peering-different-subscriptions>`_, and complete Step 5 to 10 for each subscription to build trust relationship. Do not perform peering function on the Azure portal. ========================================== ========== **Setting** **Value** ========================================== ========== Cloud Type Azure Transit Gateway Name A unique name to identify the Transit GW Spoke VNet Account Name An `Aviatrix account <http://docs.aviatrix.com/HowTos/aviatrix_account.html#account>`_ that corresponds to a subscription in Azure Spoke VNet Region Spoke VNet region Spoke VNet Name: Resource Group The Spoke VNet Name ========================================== ========== 2a. Detach: Detach Aviatrix Spoke Gateway ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This step detaches one Aviatrix Spoke VPC/VNet from a Transit GW Group. The Controller also instructs the Transit GW to stop advertising the Spoke VPC/VNet CIDR to VGW. #. Click on the Aviatrix Transit Gateway dropdown menu and select the Spoke Gateway. #. Click on the Aviatrix Spoke Gateway dropdown menu and select the Spoke Gateway to detach. #. Click Detach. Note that the Spoke GW is not deleted and you can use the top section of this page in the Controller to attach the Transit GW group again. To delete a Spoke GW, go to Gateway on the main navigation tab, select the gateway and click **Delete**. 2b. Detach Azure Native Spoke ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This step detaches an Azure Native Spoke from an Aviatrix Transit Gateway. #. Click on the Aviatrix Transit Gateway Name dropdown menu and select the Transit Gateway. #. Click on the Spoke VNet dropdown menu and select the name of the Spoke VNet to detach. #. Click Detach. Add More Spoke VPC/VNets ======================== Repeat steps 1a and 1b to add more Spoke VPC/VNets to the Transit GW group. |SpokeVPC| External Device ------------------------------------- To connect to or disconnect from an AWS VGW, External Device, or Azure VNG, select the **External Device** tab in the top right of the Multi-Cloud Transit Network Workflow page in your Aviatrix Controller. ======= ========================================== ========== **Setting** **Value** ========================================== ========== Cloud Type Spoke GW can be launched in AWS and Azure Gateway Name A unique name to identify the Spoke GW Access Account Name An `Aviatrix account <http://docs.aviatrix.com/HowTos/aviatrix_account.html#account>`_ that corresponds to an IAM role or account in AWS Region One of the AWS regions VPC ID The Spoke VPC/VNet ID Public Subnet The public subnet where the Spoke GW instance is deployed Gateway Size Spoke GW `instance size <http://docs.aviatrix.com/HowTos/gateway.html#select-gateway-size>`_ Enable SNAT Select the option if the Spoke GW will also be the NAT gateway for the Spoke VPC/VNet Enable BGP Select this option to enable BGP for this Spoke GW Allocate New EIP If selected, the Controller allocates a new EIP and associate it with the gateway instance. If not selected, the Controller looks for an allocated but unassociated EIP in the Transit GW account. Insane Mode Encryption If selected, Transit GW can peer and connect to Spoke with `Insane Mode Encryption <https://docs.aviatrix.com/HowTos/gateway.html#insane-mode-encryption>`_. Add/Edit Tags `Additional AWS Tags <http://docs.aviatrix.com/HowTos/gateway.html#add-edit-tags>`_ for the Transit GW instance ========================================== ========== 1. Connect: Connect to VGW/External Device/Azure VNG ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2. (Optional) Enable/Disable HA to an Aviatrix Spoke Gateway ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ When HA is enabled, a second Spoke GW will be launched. Note both Spoke GWs will be forwarding traffic in an event of tunnel failure between a Spoke VPC/VNet and Transit VPC/VNet. For best practice, the HA GW should be launched on a different public subnet (in AWS, GCP, or OCI) in a different AZ. |HAVPC| ========================================== ========== **Setting** **Value** ========================================== ========== Aviatrix Spoke Gateway Select the Spoke GW for which you want to enable HA HA Gateway Subnet Select the subnet in which you want to enable HA. A best practice is to select a different public subnet from the original Spoke GW in a different AZ. Allocate New EIP Select this checkbox to have the Controller allocate a new EIP and associate it with the HA gateway instance. If you do not select this option, the Controller looks for an allocated but unassociated EIP in the Spoke GW account. ========================================== ========== To disable Spoke GW HA, go to the Gateway page and delete the Spoke GW with -hagw in the name extension. Attach/Detach --------------------------------------- To attach or detach a Spoke Gateway to a Transit Network, select the **Attach/Detach** tab in the top right of the Multi-Cloud Transit Network Workflow page in your Aviatrix Controller. 1a. Attach: Attach Spoke Gateway to Transit Network ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This step attaches a Spoke VPC/VNet to the Transit GW Group by building an Aviatrix encrypted peering and transitive peering between the Spoke GW and the Transit GW. The Controller also instructs the Transit GW to start advertising the Spoke VPC/VNet CIDR to VGW via the established BGP session. To attach a Spoke Gateway to a Transit Gateway: #. Click on the Spoke Gateway/SourceGateway dropdown menu and select the Spoke Gateway to attach. #. Click on the Transit Gateway/NextHop Gateway dropdown menu and select a Transit Gateway. #. Click Attach. To attach more Spoke VPC/VNets to this Transit GW Group, click on the Spoke Gateway/Source Gateway dropdown menu and select a new Gateway to attach. 1b. Attach Azure ARM Spoke through Native Peering ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AWS VGW (VPN Gateway) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Aviatrix automates the process of discovering and connecting to AWS VGW. The instruction below is for connecting Aviatrix Transit GW to AWS VGW. Before executing this step, a VGW must have already been created on AWS console. Select the VGW ID in the dropdown menu. As a result of this step, a Customer Gateway and a Site2Cloud Connection between the VGW to the Aviatrix Transit GW will be automatically created. The site2cloud IPSEC tunnel establishes a BGP session to exchange routes between on-prem and the cloud. You also can view them under Customer Gateways and Site-to-Site VPN Connections of the AWS console. ========================================== ========== **Setting** **Value** ========================================== ========== Cloud Type Azure Transit Gateway Name A unique name to identify the Transit GW Spoke VNet Account Name An `Aviatrix account <http://docs.aviatrix.com/HowTos/aviatrix_account.html#account>`_ that corresponds to a subscription in Azure Spoke VNet Region Spoke VNet region Spoke VNet Name: Resource Group The Spoke VNet Name ========================================== ========== 2a. Detach: Detach Aviatrix Spoke Gateway ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This step detaches one Aviatrix Spoke VPC/VNet from a Transit GW Group. The Controller also instructs the Transit GW to stop advertising the Spoke VPC/VNet CIDR to VGW. #. Click on the Aviatrix Transit Gateway dropdown menu and select the Spoke Gateway. #. Click on the Aviatrix Spoke Gateway dropdown menu and select the Spoke Gateway to detach. #. Click Detach. Note that the Spoke GW is not deleted and you can use the top section of this page in the Controller to attach the Transit GW group again. ========================== ========== **Setting** **Value** ========================== ========== VPC ID The Transit VPC ID where Transit GW was launched Connection Name A unique name to identify the connection to VGW Aviatrix Gateway BCP ASN The BGP AS number the Transit GW will use to exchange routes with VGW Primary Aviatrix Gateway The Transit GW you created in Step 1 AWS VGW Account Name The Aviatrix account that VGW is created with. This account could be the same as the account used by Transit GW, or it could be by a different account VGW Region The AWS region where VGW is created VGW ID VGW that is created in the VGW Region in the AWS VGW Account ========================== ========== 2b. Detach Azure Native Spoke ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This step detaches an Azure Native Spoke from an Aviatrix Transit Gateway. #. Click on the Aviatrix Transit Gateway Name dropdown menu and select the Transit Gateway. #. Click on the Spoke VNet dropdown menu and select the name of the Spoke VNet to detach. #. Click Detach. Add More Spoke VPC/VNets ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Repeat steps 1a and 1b to add more Spoke VPC/VNets to the Transit GW group. You can check if routes are properly propagated by going to Multi-Cloud Transit > Advanced Config on the left sidebar, and selecting BGP. Select the Transit GW and click **Details**. The learned routes should be the list of the routes propagated from VGW. Scroll down to see the total number of learned routes. External Device --------------- To connect to or disconnect from an AWS VGW, External Device, or Azure VNG, select the **External Device** tab in the top right of the Multi-Cloud Transit Network Workflow page in your Aviatrix Controller. 1. Connect: Connect to VGW/External Device/Azure VNG ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. tip:: If you do not see the Transit GW you just created, refresh the browser. This page displays the three options to connect to a Transit GW to an on-prem network. Choose one option that meets your network requirements. - AWS VGW (This is the default setting) - External Device (over Direct Connect or over Internet) - Azure VNG as shown below. |transit_to_onprem-2| ========================================== ================ =============== =============== ================== **Transit Gateway Connect Type** **Performance** **HA** Route Limit Deployment notes ========================================== ================ =============== =============== ================== AWS VGW 1.25Gbps Active/Active 100 VGW should be detached. Use the `instruction here <https://aws.amazon.com/premiumsupport/knowledge-center/create-vpn-direct-connect/>`_ to build encryption between VGW and on-prem router. External Device Up to 10Gbps Active/Standby Unlimited VGW should be attached. Aviatrix Transit Gateway establishes BGP + IPSEC with on-prem router. Azure VNG 10Gbps Active/Active Unlimited VNG should be attached. ========================================== ================ =============== =============== ================== AWS VGW (VPN Gateway) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Aviatrix automates the process of discovering and connecting to AWS VGW. The instruction below is for connecting Aviatrix Transit GW to AWS VGW. Before executing this step, a VGW must have already been created on AWS console. Select the VGW ID in the dropdown menu. As a result of this step, a Customer Gateway and a Site2Cloud Connection between the VGW to the Aviatrix Transit GW will be automatically created. The site2cloud IPSEC tunnel establishes a BGP session to exchange routes between on-prem and the cloud. You also can view them under Customer Gateways and Site-to-Site VPN Connections of the AWS console. .. important:: You are responsible for building the connection between VGW and on-prem. The connection is either over the Internet, over Direct Connect or both. We support two patterns of connections: Detached VGW and Attached VGW. The VGW should not be attached to the Transit VPC/VNet. Currently, only one connection is supported on a specific Transit Gateway/VPC, regardless of which of the three options above is chosen. |VGW| ========================== ========== **Setting** **Value** ========================== ========== VPC ID The Transit VPC ID where Transit GW was launched Connection Name A unique name to identify the connection to VGW Aviatrix Gateway BCP ASN The BGP AS number the Transit GW will use to exchange routes with VGW Primary Aviatrix Gateway The Transit GW you created in Step 1 AWS VGW Account Name The Aviatrix account that VGW is created with. This account could be the same as the account used by Transit GW, or it could be by a different account VGW Region The AWS region where VGW is created VGW ID VGW that is created in the VGW Region in the AWS VGW Account ========================== ========== Note that the Aviatrix Transit GW can connect to a VGW that belongs to a different AWS account in a different region. It takes a few minutes for the VPN connection to come up and routes from VGW to be propagated. When the IPSEC tunnel with a VGW is up, the Controller admin should receive an email notification. If you log in to the AWS Console and select "service VPC" in the region where the VGW is, you should see Customer Gateway and VPN Connections have been created. Do not delete or modify them from AWS Console. These resources are deleted if you Disconnect the VGW. You can check if routes are properly propagated by going to Multi-Cloud Transit > Advanced Config on the left sidebar, and selecting BGP. Select the Transit GW and click **Details**. The learned routes should be the list of the routes propagated from VGW. Scroll down to see the total number of learned routes. External Device ^^^^^^^^^^^^^^^^^^^^^^^^^^^ The External Device option allows you to build IPSEC tunnel, GRE tunnel or Ethernet LAN directly to on-prem or in the cloud device. It bypasses the AWS VGW or Azure VPN gateway for exchanging routes with on-prem, thus overcoming the route limit by these native services. To learn how to leverage External Device to connect to variety of devices, read more about `External Device FAQ. <https://docs.aviatrix.com/HowTos/transitgw_external.html>`_ Follow the instructions in `this link <https://docs.aviatrix.com/HowTos/transitgw_external.html#how-to-configure>`_ to complete this Step. Azure VNG ^^^^^^^^^^^^^^^^ With this option, data packets are forwarded natively to on-prem through Azure Virtual Network Gateway (VNG) either over Express Route or Internet, and in the meantime, Aviatrix Transit Gateways are inserted in the data path between VNG and Spoke VNet. This allows you to run advanced function such as firewall inspection for on-prem to Spoke and between the Spokes. See `Multi-Cloud Transit Integration with Azure VNG <https://docs.aviatrix.com/HowTos/integrate_transit_gateway_with_expressroute.html>`_. Disconnect: Disconnect AWS VGW/External Device/Azure VNG ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use this section to disconnect AWS VGW/External Device/Azure VNG connections. To disconnect or detach one of these connections: #. Click on the **Connection Name** dropdown menu and select the connection to disconnect. #. Click Detach. View the Network Topology ------------------------------------- After setting up your Multi-Cloud Transit Network Workflow, you can view the network topology by going to the Dashboard and reviewing the Map View. Troubleshoot BGP -------------------------- To troubleshoot BGP: #. Under Multi-Cloud Transit on the left sidebar, click **BGP**. The Transit GW will have BGP Mode as Enabled. #. Click the Transit GW and click **Details** to see Advertised Networks and Learned Networks. Learned Networks are network CIDR blocks that BGP learned from VGW. Advertised Networks are Spoke VPC/VNet CIDRs. You can also click **Diagnostics**. Select one of the show commands or type in yourself if you know the commands to see more BGP details. To troubleshooting connectivity between a Spoke VPC/VNet instance and a on-prem host, follow `these steps. <http://docs.aviatrix.com/HowTos/transitvpc_faq.html#an-instance-in-a-spoke-vpc-cannot-communicate-with-on-prem-network-how-do-i-troubleshoot>`_ Disable Transit GW HA -------------------------- If you need to disable a Transit GW HA (for example, if you deployed it in the wrong subnet or AZ), use the Gateway page to do so. A best practice is to make sure there is no traffic going through the backup Transit GW before disabling it. #. Go to the Gateway page and locate the Transit GW with "-hagw" in the gateway name extension. #. Highlight the gateway and click **Delete**. Note that the Transit GW and its backup companion are in an active/active state, that is, both gateways could be forwarding traffic. As noted above, a best practice is to make sure there is no traffic going through the backup Transit GW before disabling it. Transit Network APIs ------------------------- There are multiple resources to help you automate Transit Network setup. Note that if you are building a Transit Network following the workflow, you should follow the `Terraform example <http://docs.aviatrix.com/HowTos/Setup_Transit_Network_Terraform.html>`_. Extras ----------- After you have built the Transit GW and Spokes, you can view the connection between Transit GW and VGW on the Site2Cloud page. You can also see the Spoke to Transit GW connections on the Peering page. .. Important:: Stay on the Transit Network page for any Spoke Gateway and Transit GW actions such as attaching a Spoke, detaching a Spoke, connecting to VGW and disconnecting from a VGW. Do not go to any other pages for these actions. For deleting a Spoke Gateway or Transit Gateway, go to the Gateway page, select the gateway and delete. .. |Test| image:: transitvpc_workflow_media/SRMC.png :width: 5.55625in :height: 3.26548in .. |TVPC2| image:: transitvpc_workflow_media/TVPC2.png :scale: 60% .. |HAVPC| image:: transitvpc_workflow_media/HAVPC.png :scale: 60% .. |VGW| image:: transitvpc_workflow_media/connectVGW.png :scale: 50% .. |launchSpokeGW| image:: transitvpc_workflow_media/launchSpokeGW.png :scale: 50% .. |AttachSpokeGW| image:: transitvpc_workflow_media/AttachSpokeGW.png :scale: 50% .. |SpokeVPC| image:: transitvpc_workflow_media/SpokeVPC.png :scale: 50% .. |transit_to_onprem| image:: transitvpc_workflow_media/transit_to_onprem.png :scale: 40% .. |transit_to_onprem-2| image:: transitvpc_workflow_media/transit_to_onprem-2.png :scale: 40% .. |azure_native_transit2| image:: transitvpc_workflow_media/azure_native_transit2.png :scale: 30% .. |transit_approval| image:: transitvpc_workflow_media/transit_approval.png :scale: 30% .. disqus:: <file_sep> Migrating a Join deployment to Site2Cloud deployment ====================================================== If you have deployed virtual appliance CloudN and used Join feature to connect your existing VPCs and would like to migrate to use Site2Cloud feature instead to connect to the same set of VPCs, the following steps can be a reference guide. You can choose to re-use the same CloudN for the on-prem gateway in Site2Cloud implementation or a different CloudN. For ease of reference, we call the VPC where the Join and Site2Cloud VPC gateway terminates migrating VPC. .. Note:: This migration process will have tunnel down time. It is best practice to plan the migration during a maintenance window. .. 1. Launch an Aviatrix Controller in AWS or Azure. #. From the Controller, launch an Aviatrix gateway in a migrating VPC. #. From the original CloudN where Join function was implemented, delete all participating subnets. After all subnets are deleted, delete the corresponding gateway. #. On the default routing gateway where the original CloudN is deployed, remove the routes that points to the original CloudN as the next hop to the migrating VPC. (This step is not needed if the new and the original CloudN are the same one.) #. On the Aviatrix Cloud Controller, create a Site2Cloud connection on the migrating VPC. Download the configuration template. #. On the new (this new could be the same original) CloudN, import the previously downloaded configuration template. #. Make sure the tunnel comes up. #. On the default routing gateway where the new CloudN is deployed, add a static route that points the new CloudN as the next hop to reach the migrating VPC. (This step is not needed is the new and the original CloudN are the same one.) #. The VPC migration from Join function to Site2Cloud is done. #. Repeat the above steps for more migrating VPCs. .. disqus:: <file_sep> ======================================================== Anonymous Internet Surfing ======================================================== Solution Overview ====================== Normally, when you surf an Internet website, the website administrator can easily identify where the user is located. This is done by identifying the source IP address (public IP address assigned to your location) contained in the packets. Sometimes, business needs arise when your employee's internet browsing and online research needs to be anonymous or needs to appear to originate from some other place. For example, when analysis of competitors is required or when avoiding countries' firewalls for better performance and access. This document describes how to set up anonymous browsing from a client machine by routing internet traffic through an AWS-based Gateway in a different region. Configuration Workflow ========================== Pre-Configuration Checklist ------------------------------- Before configuring VPC Site-to-Cloud peering, make sure the following prerequisites are completed. **Pre Configuration Check List** 1. Deploy the Aviatrix Controller. 2. Create AWS VPCs and Check Settings. These prerequisites are explained in detail below. Deploying the Aviatrix Controller -------------------------------------------- The Aviatrix Controller must be deployed and set up prior to configuring VPC and site peering. Please refer to the `Aviatrix Controller Getting Started Guide for AWS <https://s3-us-west-2.amazonaws.com/aviatrix-download/docs/aviatrix_aws_controller_gsg.pdf>`_ on how to deploy the Aviatrix Controller. Check and make sure you can access the Aviatrix Controller dashboard and log in with an administrator account. The default URL for the Aviatrix Controller is: https://<public ip of Aviatrix Controller> Creating AWS VPCs and Checking Settings -------------------------------------------------- - Create 2 VPCs - VPC #1 (in Region 1) with CIDR 10.1.0.0/16 and VPC #2 (in Region 2) with CIDR 10.2.0.0/16 - In VPC #1, create 2 public subnets in the same Availability Zone - 10.1.0.0/24 and 10.1.1.0/24. This means that both subnets must be associated with a route table whose default route points to IGW. - In VPC #2, create 1 public subnet - 10.2.0.0/24. This means that one subnet must be associated with a route table whose default route points to IGW. Configuration Steps --------------------------- Make sure the pre-configuration steps in the previous section are completed before proceeding. The instructions in this section will use the following architecture. The CIDR and subnets may vary depending on your VPC setup; however, the general principles will be the same. |image0| Deploying Gateways ------------------------------------------ The first step is to deploy Aviatrix Gateways in each VPC. **Instructions:** 1. Log in to the Aviatrix Controller. 2. Create Aviatrix Peering Gateway #1 in Subnet1 of VPC #1 (in Region 1). 3. Click on Gateway > New Gateway. =============================== ================================================================================ **Setting** **Value** =============================== ================================================================================ Cloud Type Choose AWS. Gateway Name This name is arbitrary (e.g. vpc-01-avx-gw) Account Name Choose the account name. Region Choose the region of VPC #1. VPC ID Choose the VPC ID of VPC #1. Public Subnet Select a public subnet where the gateway will be deployed (e.g. 10.1.0.0/24). Gateway Size t2.micro is fine for testing Enable NAT **Unmark this checkbox** (IMPORTANT) VPN Access Unmark this checkbox Designated Gateway Unmark this checkbox Allocate New EIP Unmark this checkbox Save Template Unmark this checkbox =============================== ================================================================================ 4. Click **OK**. It will take a few minutes for the gateway to deploy. Do not proceed until the gateway is deployed. 5. Create an Aviatrix VPN Gateway in Subnet2 of VPC #1 (note that VPN Gateway is in a different subnet of Peering Gateway). 6. Click on Gateway > New Gateway. =============================== =================================================== **Setting** **Value** =============================== =================================================== Cloud Type Choose AWS. Gateway Name This name is arbitrary (e.g. vpc-01-avx-vpn) Account Name Choose the account name. Region Choose the region of VPC #1. VPC ID Choose the VPC ID of VPC #1. Public Subnet Select the public subnet where the VPN gateway will be deployed (e.g. 10.1.1.0/24) Gateway Size t2.micro is fine for testing. Enable NAT Unmark this checkbox VPN Access Check this box Designated Gateway Unmark this checkbox Allocate New EIP Unmark this checkbox Enable SAML Unmark this checkbox VPN CIDR Block (e.g. 192.168.43.0/24) MFA Authentication Optional (Disable is fine for testing) Max Connections 100 is fine for testing Split Tunnel Mode No Enable ELB Yes ELB Name Leave blank is fine for testing Enable Client Cert. Sharing No Enable PBR Check this box PBR Subnet Select the subnet where Aviatrix Peering Gateway is located (e.g. 10.1.0.0/24) PBR Default Gateway Select the private IP of Aviatrix Peering Gateway (e.g. 10.1.0.138) NAT Translation Logging Unmark this checkbox Enable LDAP Optional (Unmark this checkbox is fine for testing) Save Template Unmark this checkbox =============================== =================================================== 7. Click **OK**. It will take a few minutes for the gateway to deploy. Do not proceed until the gateway is deployed. 8. Create Aviatrix Peering Gateway #2 in VPC #2. 9. Click on Gateway > New Gateway. =============================== =================================================== **Setting** **Value** =============================== =================================================== Cloud Type Choose AWS. Gateway Name This name is arbitrary (e.g. vpc-02-avx-gw) Account Name Choose the account name. Region Choose the region of VPC #2. VPC ID Choose the VPC ID of VPC #2. Public Subnet Select a public subnet where the gateway will be deployed (e.g. 10.2.0.0/24). Gateway Size t2.micro is fine for testing Enable NAT **Mark this checkbox** (IMPORTANT) VPN Access Unmark this checkbox Designated Gateway Unmark this checkbox Allocate New EIP Unmark this checkbox Save Template Unmark this checkbox =============================== =================================================== 10. Click **OK**. It will take a few minutes for the gateway to deploy. Do not proceed until the gateway is deployed. Establishing Site to Cloud Peering Connection ----------------------------------------------------------- This step explains how to establish a Site-to-Cloud (S2C) connection between two Aviatrix Gateways in VPC #1 and VPC #2. **Instructions:** 1. From the Aviatrix Controller. 2. Click Site2Cloud > Site2Cloud. 3. Click **+Add New** to establish a S2C connection from Aviatrix Peering Gateway #1 (in VPC #1) to Aviatrix Peering Gateway #2 (in VPC #2). =============================== ================================================================= **Setting** **Value** =============================== ================================================================= VPC ID/VNet Name Choose VPC ID of VPC #1. Connection Type Unmapped Connection Name This name is arbitrary (e.g. vpc01-s2c-vpc02). Remote Gateway Type Aviatrix (in this example) Tunnel Type UDP Algorithms Unmark this checkbox Encryption over DirectConnect Unmark this checkbox Enable HA Unmark this checkbox Primary Cloud Gateway Select Aviatrix Peering Gateway #1 in VPC #1 (e.g. vpc-01-avx-gw). Remote Gateway IP Address Public IP of Aviatrix Peering Gateway #2 in VPC #2 Pre-shared Key Optional Remote Subnet 0.0.0.0/0 Local Subnet IP of eth1 of Aviatrix VPN Gateway #1 (e.g. 10.1.0.190/32) =============================== ================================================================= 4. Click **OK**. 5. From the S2C connection table, select the Site2Cloud connection created above (e.g. vpc01-s2c-vpc02). 6. Select **Aviatrix** from the **Vendor** dropdown menu. 7. Click **Download Configuration** then save it. 8. Click **+Add New" to establish a Site2Cloud connection from Aviatrix Peering Gateway #2. 9. Choose VPC ID of VPC #2 from "VPC ID/VNet Name" dropdown menu. Click **Import** to upload. the downloaded configuration saved above. 10. This template file contains the necessary information to configure the new S2C connection. =============================== =================================================== **Setting** **Value** =============================== =================================================== VPC ID/VNet Name Choose VPC ID of VPC #2. Connection Type Unmapped Connection Name This name is arbitrary (e.g. vpc02-s2c-vpc01) Remote Gateway Type Aviatrix Tunnel Type UDP Algorithms Mark this checkbox Phase 1 Authentication SHA-1 Phase 2 Authentication HMAC-SHA-1 Phase 1 DH Groups 2 Phase 2 DH Groups 2 Phase 1 Encryption AES-256 Phase 2 Encryption AES-256 Encryption over DirectConnect Unmark this checkbox Enable HA Unmark this checkbox Primary Cloud Gateway Aviatrix Peering Gateway #2 (e.g. vpc-02-avx-gw) Remote Gateway IP Address Public IP of Aviatrix Peering Gateway #1 Pre-shared Key (automatically created) Remote Subnet IP of eth1 of Aviatrix VPN Gateway #1 (e.g. 10.1.0.190/32) Local Subnet 0.0.0.0/0 =============================== =================================================== Notes: The IP of eth1 of the Aviatrix VPN Gateway can be acquired from the AWS console. 11. Click **OK**. Creating an OpenVPN® User ------------------------------------------------------------ This step explains how to create a OpenVPN® user. **Instructions:** 1. From the Aviatrix Controller. 2. Click OpenVPN® > VPN Users. 3. Click button **+Add New**. =============================== =================================================== **Setting** **Value** =============================== =================================================== VPC ID Choose the VPC ID of VPC #1. LB/Gateway Name Choose the ELB in VPC #1. User Name This name is arbitrary (ex. vpn-user). User Email Email address Profile Unmarking this checkbox is fine for the testing. =============================== =================================================== 4. Click **OK**. 5. Check your email to receive a .ovpn file. Starting Anonymous Browsing -------------------------------------------- This step explains how to establish an OpenVPN® connection and surf the network anonymously. **Instructions:** 1. Enable an OpenVPN® client tool. 2. Establish an OpenVPN® connection with the ovpn file which has received in email. 3. Confirm the connectivity to public network. * Ping to www.google.com. * Check public IP address (ie. https://www.whatismyip.com/what-is-my-public-ip-address/). * Check IP location (ie. https://www.iplocation.net/). Troubleshooting =============== To check a tunnel state, go to Site2Cloud, the tunnel status will be displayed at the "status" column. To troubleshoot a tunnel state, go to Site2Cloud > Diagnostics. OpenVPN is a registered trademark of OpenVPN Inc. .. |image0| image:: Anonymous_Browsing_media/Anonymous_Browsing.PNG :width: 5.03147in :height: 2.57917in .. disqus:: <file_sep> ========================================================= Firewall Network (FireNet) Advanced Config ========================================================= Firewall Network (FireNet) Advanced Config applies to both AWS TGW-based FireNet and Aviatrix Transit FireNet. For questions about FireNet, check out the `FireNet FAQ <https://docs.aviatrix.com/HowTos/firewall_network_faq.html>`_. For questions on FireNet workflow, check out the `FireNet Workflow <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html>`_. For questions about Aviatrix Transit FireNet, check out `Transit FireNet FAQ <https://docs.aviatrix.com/HowTos/transit_firenet_faq.html#transit-firenet-faq>`_. For questions on Aviatrix FireNet workflow, check out `Transit FireNet Workflow <https://docs.aviatrix.com/HowTos/transit_firenet_workflow.html#transit-firenet-workflow-for-aws-azure>`_. Traffic Inspection ------------------------------------------------ You can enable and disable traffic inspection. When traffic inspection is disabled, FireNet Gateway loops back all packets. Egress through Firewall ----------------------------------- This is to enable Internet-bound egress traffic for inspection. To configure, go to Controller > Firewall Network > Advanced. Select one firewall domain and click the 3-dots skewer to the detail page. At Egress through Firewall, click **Enable**. Egress Static CIDRs ----------------------- You can allow egress to a subset of your IP address space from your on-prem data center to the Internet with Aviatrix Egress FireNet. Static CIDR egress is supported on Aviatrix Transit and AWS Transit Gateways (TGW). Up to 20 subnets are supported. Network List Excluded From East-West Inspection ------------------------------------------------------------------- By default, FireNet inspects all East-West (VPC/VNet to VPC/VNet) traffic but you may have an instance in the VPC/VNet which you do not want to be inspected. For example, the Aviatrix Controller deployed in the Shared Service VPC/VNet to be excluded from inspection while Shared Service VPC/VNet traffic is inspected. This improves the Controller reachability by not subjecting the Controller access to unintentional firewall policy errors. Put the CIDRs in the field **"Network List Excluded From East-West Inspection"** to exclude from being inspected by the firewall. .. Note:: 1. Maximum 50 CIDRs coma-separated are supported. 2. CIDRs are excluded from East-West inspections only. 3. In Transit FireNet, if Egress inspection is enabled, all the Egress traffic will get inspected by the firewall even for the CIDRs excluded for East-West inspection. Firewall Hashing -------------------------- Firewall Network solution supports two hashing types: - Five-tuple and - Two-tuple. By default, AWS TGW-based FireNet and Aviatrix Transit FireNet use 5-tuple hashing algorithm (source IP, source port, destination IP, destination port and protocol type) to load balance the traffic across different firewall. However, user has an option to select two-tuple (source IP and destination IP) hashing algorithm to map traffic to the available firewalls. Keep Alive via Firewall LAN Interface (AWS) --------------------------------------------- For AWS, the LAN or Management interface can be used for firewall health check and failure detection. See `below <#checking-firewall-health-in-azure-and-gcp>`_ for information on performing health checks in Azure and GCP. By default, Aviatrix Controller checks the health of a firewall in AWS by pinging the firewall's management IP address. Starting in version 6.0, you can also check the AWS firewall instance’s health by pinging its LAN interface from the connecting Aviatrix FireNet Gateway. This is an alternative approach which improves firewall failure detection time and detection accuracy. The FireNet Gateway pings the firewall instance's LAN interface every 5 seconds with a ping time out of 20ms. If the first ping times out, it immediately pings again. Two consecutive ping failures indicate that the firewall is in 'down' state and it is detached from the FireNet Gateway pool. The ping function continues and once it detects that the firewall instance has come up (pings are successful), it is attached back to the FireNet Gateway pool. With LAN interface pinging, the firewall instance fail over time is reduced. The following details describe how to enable ping on the firewall instance LAN interface. Enabling ICMP on Firewall Devices ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ **Palo Alto Network** ~~~~~~~~~~~~~~~~~~~~~~ Go to Network > Network Profiles > Interface Mgmt and create profile to allow ping. |pan_network_profile| Next, Go to Network > Interfaces, select **Ethernet 1/2**, go to the Advanced tab > Management Profile and select the profile just created in the step above. |pan_lan_attach| Commit changes **Panoroma** ~~~~~~~~~~~~~~~~~ Configure stack similar to Palo Alto Network shown above. **Check Point** ~~~~~~~~~~~~~~~~~~~~~ Go to SmartConsole > Global Properties > Firewall > Accept ICMP requests. |cp_ping_enable_1| |cp_ping_enable_2| **Fortigate (Fortinet)** ~~~~~~~~~~~~~~~~~~~~~~~~~~` Go to Network > Interfaces > Edit Interface > Mark the **Ping** checkbox. |fortigate_example_ping| Configuring Aviatrix Controller ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Go to Firewall Network > Advanced > Click the 3 vertical dots as shown below: |firewall_advanced_lan_1| The expanded view shows the firewall deployed by the Aviatrix Controller and towards the end of screen shot, one can enable/disable LAN side Health Check. |firewall_advanced_lan_ping| Verifying LAN Side ICMP Health Check ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ In this example, AWS and Check Point used to demonstrate the functionality as shown below: |example_topology_lan_ping| Go to Check Point logs and Monitoring section, notice that the ICMP health check is initiated every 5 seconds from the Aviatrix Transit FireNet Gateways. The 5 second setting is the default and cannot be changed. |cp_icmp_lan_example| Checking Firewall Health in Azure and GCP ----------------------------------------- Enabling Transit FireNet for Azure or GCP automatically creates Load Balancers in those CSPs. HTTPS in these Load Balancers perform the firewall health check (not ping). You must disable ping in the interface management profile of your Azure or GCP firewalls. In Azure: - You can check the health probe status under Monitor > Metrics. See `this article <https://docs.microsoft.com/en-us/azure/load-balancer/load-balancer-standard-diagnostics>`_ for more information. - The State column on the Gateway page in the Aviatrix Controller only reflects if the firewall is up or not. It does not reflect if the firewall is responding to health checks. You must check the health of the firewall in the Azure portal. In GCP: - You can check the health status of the backend under Network services > Load balancing > Load balancer details. See `this article <https://cloud.google.com/load-balancing/docs/health-check-concepts#lb_guide>`_ for more information. - The State column on the Gateway page in the Aviatrix Controller reflects the health status of the firewall from the GCP load balancer. .. |firewall_advanced_lan_1| image:: firewall_network_workflow_media/firewall_advanced_lan_1.png :scale: 30% .. |firewall_advanced_lan_ping| image:: firewall_network_workflow_media/firewall_advanced_lan_ping.png :scale: 30% .. |example_topology_lan_ping| image:: firewall_network_workflow_media/example_topology_lan_ping.png :scale: 30% .. |cp_icmp_lan_example| image:: firewall_network_workflow_media/cp_icmp_lan_example.png :scale: 30% .. |pan_network_profile| image:: firewall_network_workflow_media/pan_network_profile.png :scale: 30% .. |pan_lan_attach| image:: firewall_network_workflow_media/pan_lan_attach.png :scale: 30% .. |cp_ping_enable_1| image:: firewall_network_workflow_media/cp_ping_enable_1.png :scale: 30% .. |cp_ping_enable_2| image:: firewall_network_workflow_media/cp_ping_enable_2.png :scale: 30% .. |fortigate_example_ping| image:: firewall_network_workflow_media/fortigate_example_ping.png :scale: 30% .. disqus:: <file_sep> ================================= Egress Control Filter ================================= For questions, please see the `Egress FQDN FAQ <https://docs.aviatrix.com/HowTos/fqdn_faq.html>`_ or learn more about `FQDN here <https://www.aviatrix.com/learning/glossary/fqdn.php>`_. Configuration Workflow ====================== .. tip :: The instructions below assume there is already an Aviatrix Gateway running in the VPC/VNet where you wish to deploy FQDN filter. If not, follow the Egress Control workflow to first launch a gateway. Adding a New Tag --------------------- Go Security > Egress Control and click **New Tag**, as shown below: |fqdn-new-tag| Click **+ New Tag**, and enter a name for the tag, for example, prod-whitelist, as shown below: |fqdn-add-new-tag| Adding a URL List to the New Tag ------------------------------------------ Enable the new tag and click **Edit**, as shown below: |fqdn-enable-edit| Click **+ Add New** to add each URL, wild card is allowed for HTTP/HTTPS (TCP 443), as shown below. (Action "Update" means to save the rules in the tag. If gateways are attached to the tag, "Update" applies the rules to the gateways.) |fqdn-add-domain-names| Base Policy ^^^^^^^^^^^^ Base Policy is a new Action field of a rule available in Release 5.2. It only applies to a rule whose Whitelist is on TCP port 80 or 443. The default Action field is Base Policy which means if the tag is a WhiteList (which is the majority of the use case), this specific rule is to allow the domain name to pass. For the most part, you should not edit this field. There is a use case where you want to leverage the Active field. For example, you need to allow most of the FQDN names in salesforce.com except for one domain name, finance.salesforce.com. If salesforce.com provides hundreds of domain names, you would have to whitelist all of them and you cannot use ``*.salesforce.com`` as it will leak finance.salesforce.com. With the new feature, you can now configure two rules to accomplish filtering out finance.salesforce.com while allowing the rest of salesforce.com supported domain names, as shown below: ========================================== ================ ================== ============= Domain Name Protocol Port Action ========================================== ================ ================== ============= finance.salesforce.com tcp 443 Deny ``*``.salesforce.com tcp 443 Base Policy ========================================== ================ ================== ============= Attaching to Gateways ------------------------------- Click **Attach Gateway** to attach a gateway to the tag. When a gateway is attached to a tag, the gateway in the tag will be pushed for enforcement (Whitelist or Blacklist), as shown below: |fqdn-attach-spoke1| Repeat this step if you have more gateways that should be attached to this tag. |fqdn-attach-spoke2| Adding More Tags --------------------------------- Repeat the previous steps to create more tags and attach them to the same gateway or different gateways. However, if multiple tags are attached to the same gateway, then the mode (Whitelist or Blacklist) must be identical. Exception Rule =============== Exception Rule is a system-wide mode. **Exception Rule only applies to whitelist**. By default, the Exception Rule is enabled. (The Exception rule checkbox should be marked.) |exception_rule| When Exception Rule is enabled, packets passing through the gateway without an SNI field are allowed to pass. This usually happens when an application uses hard-coded destination IP addresses for HTTPS connection instead of domain names. When Exception Rule is disabled (unmark the checkbox), packets passing through the gateway without SNI field are dropped unless the specific destination IP address of the packet is listed in the Whitelist. The use case could be that certain old applications use hard coded destination IP address to access external services. If Blacklist is configured, client hello packets without SNI is allowed to pass as it should not match any rules. Export ============== This feature is available in Release 3.4 and later. Export allows you to download the configured FQDN rules on a per tag basis, in a human-readable text file format, as shown in the example below: |export| Import ======== This feature is available in Release 3.4 and later. Import allows you to upload a text file that contains FQDN rules to a specific tag. The text file can be: 1. The downloaded file from `FQDN Discovery <https://docs.aviatrix.com/HowTos/fqdn_discovery.html>`_. #. The download file from Export from a different tag. #. A text file in the format compatible to Export. Edit Source ============== Edit Source is available in Release 4.0 and later. Edit Source allows you to control which source IP in the VPC/VNet is qualified for a specific tag. The source IP can be a subnet CIDR or host IP addresses. This provides fine-grained configuration. .. important:: If Edit Source is not configured, i.e., no source IP address ranges are selected, all packets arriving at the FQDN gateway are applied to the filter tag. However if there are one or more source IP address ranges selected, any packets with source IP addresses outside those ranges are dropped. In this regard, the distinguished Source is exclusive. For example, one use case is if you have two private subnets in a VPC/VNet: one deploys dev instances and another deploys prod instances. With the Edit Source feature, the dev instances can have different tags than the prod instances. Edit Source assumes you already attached a gateway to a tag. To go to the Edit Source page, click **Edit Source** at Egress FQDN Filter on a specific tag and follow the example in the illustration below, the network appeared on the right hand of the panel go through the FQDN tag filtering while the network on the left side of the panel are dropped. |source-edit| Enabling Private Network Filtering ================================= This is a global configuration that applies to all FQDN gateways. By checking this option, destination FQDN names that translate to private IP address range (RFC 1918) are subject to FQDN whitelist filtering function. The use case is if your destination hostname is indeed a private service and you wish to apply FQDN filtering, you can enable this option. To configure this option, go to Security > Egress Control > Global Configs > Enable Private Network Filtering. FQDN names that are resolved to RFC 1918 range will be subject to FQDN filter function. Disabling Private Network Filtering =================================== This is a global configuration that applies to all FQDN gateways. By checking this option, packets with destination IP address of RFC 1918 range are not inspected. This is the default behavior. To configure, go to Security > Egress Control > Global Configs > Disable Private Network Filtering. FQDN names that are resolved to RFC 1918 range will be subject to FQDN filter function. Customizing Network Filtering ============================== This is a global configuration that applies to all FQDN gateways. When this option is selected, you can customize packet destination address ranges not to be filtered by FQDN. To configure, go to Security > Egress Control > Global Configs > Customize Network Filtering. Select pre-defined RFC 1918 range, or enter your own network range. This feature is not enabled as default. FQDN Name Caching ===================== This is a global configuration that applies to all FQDN gateways. If FQDN Name caching is enabled, the resolved IP address from FQDN filter is cached so that if subsequent TCP session matches the cached IP address list, FQDN domain name is not checked and the session is allowed to pass. We recommend disabling Caching to prevent unwanted domain names to bypass filter as they resolve to the same IP address. For example, youtube.com shares the same destination IP address range as google.com. There is minimal performance impact by disabling the cache. To configure this option, go to Security > Egress Control > Global Configs > Caching > click **Enabled** to set the toggle switch to **Disabled**. This feature is enabled as default. Exact Match ============== This is a global configuration that applies to all FQDN gateways. If a FQDN rule does not have * an exact match is expected. If this global option is not enabled, FQDN rules use regex to match any FQDN names that are subset of the name. For example, if salesforce.com is a rule and Exact Match option is enabled, finance.salesforce.com is not a match and will be dropped. This feature is not enabled as default. For support, please open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_ .. |fqdn| image:: FQDN_Whitelists_Ref_Design_media/fqdn.png :scale: 30% .. |fqdn-new-tag| image:: FQDN_Whitelists_Ref_Design_media/fqdn-new-tag.png :scale: 30% .. |fqdn-add-new-tag| image:: FQDN_Whitelists_Ref_Design_media/fqdn-add-new-tag.png :scale: 30% .. |fqdn-enable-edit| image:: FQDN_Whitelists_Ref_Design_media/fqdn-enable-edit.png :scale: 30% .. |fqdn-add-domain-names| image:: FQDN_Whitelists_Ref_Design_media/fqdn-add-domain-names.png :scale: 30% .. |fqdn-attach-spoke1| image:: FQDN_Whitelists_Ref_Design_media/fqdn-attach-spoke1.png :scale: 30% .. |fqdn-attach-spoke2| image:: FQDN_Whitelists_Ref_Design_media/fqdn-attach-spoke2.png :scale: 30% .. |source-edit| image:: FQDN_Whitelists_Ref_Design_media/source-edit.png :scale: 30% .. |export| image:: FQDN_Whitelists_Ref_Design_media/export.png :scale: 30% .. |exception_rule| image:: FQDN_Whitelists_Ref_Design_media/exception_rule.png :scale: 30% .. add in the disqus tag .. disqus:: <file_sep> ==================================== Aviatrix CoPilot Image Release Notes ==================================== .. important:: This content has moved. Please see the `Release Notes section <https://docs.aviatrix.com/copilot/latest/release-notes/index.html>`_ of the `Aviatrix CoPilot Product Documentation <https://docs.aviatrix.com/copilot/latest/index.html>`_ for CoPilot image release information. <file_sep> ===================================== Cluster Peering ===================================== .. note:: The Cluster Peering feature is deprecated. Performance Challenges ============================== Today, encrypted peering (IPsec tunnel) between two VPC/VNets is carried out by two gateways (virtual machine, or instance based), one in each VPC/VNet. This limits IPsec Stashed changes tunnel packet throughput to the throughput of a single instance. For example, AWS C4.4xlarge provides up to 1.5Gbps for an iperf test with TCP. There is no solution for use cases that require more than that throughput with one gateway instance. Each Cloud Service Provider (CSP) has its own performance limitations. For example, in AWS infrastructure, traffic leaving a VPC has a bandwidth limit of 5Gbps for one direction and 10Gbps for bi-directional traffic. This limitation applies to both intra-region VPC traffic and Internet bound traffic. For example, running an iperf test between two instances in two VPCs in the same region yields 5Gbps one way throughput and 10Gbps bi-directional traffic. Encrypted Cluster Peering Solution ================================== Aviatrix has developed a scale out IPsec capability. A VPC/VNet can deploy a cluster of gateways. Encrypted peering between two VPC/VNets is carried out by two clusters of gateways in each VPC/VNet. The deployment diagram is shown below. Aviatrix supports both inter-region cluster peering and intra-region cluster peering. In the first case, the encrypted cluster peering is over the Internet through an IGW. In the second case, the encrypted cluster peering is over native AWS peering. The deployment diagrams are described below for both cases in AWS. |image1| |image2| In this AWS example, three Aviatrix Gateways are deployed for encrypted peering between VPC-1 and VPC-2. A demux gateway is used to distribute user instance session traffic to 3 gateways. The distribution algorithm guarantees no packet for the same TCP stream is delivered out of order to the peering VPC. Performance Benchmark and Analysis (AWS) ===================================== Below is the performance benchmark for cluster peering using the iperf tool in AWS. The results are collected with encryption over AWS peering in the same region. The Aviatrix Gateway size is C4.8xlarge. The demux gateway size is C4.8xlarge. As the results show, with 4 or 5 gateways in a cluster, performance reaches the AWS VPC line rate. Adding more gateways does not improve the performance. Note that if the gateway size is C4.xlarge, more gateways are needed to achieve the AWS line rate. For information on how to run multi-stream iperf tests, check out our GitHub project. https://github.com/AviatrixSystems/PerformanceTest/blob/master/PerformanceTest.txt |image3| High Availability ================= CSP Controllers monitor the health of the peering gateways and the demux gateway. When heartbeat information from any gateway fails, the Controller will restart the failing gateways. The detection to failover is under 30 seconds. Configuration Workflow for AWS =============================== Before you start, make sure you have the latest software by checking the Dashboard. If an alert message (New !) appears, click **New!** to download the latest software. For AWS peerings, we assume you already know how to deploy the Aviatrix solution in AWS. If you need help, check out this `reference design <https://s3-us-west-2.amazonaws.com/aviatrix-download/Cloud-Controller/Cloud+Networking+Reference+Design.pdf>`__. The Cluster Peering workflow for AWS is as follows, with major steps highlighted. 1. In your Controller, create a gateway in VPC-1. Go to Gateway > New Gateway to create a gateway in VPC-1. 2. Repeat the previous step to create two more gateways in VPC-1. Note that all gateway instances must be in the same subnet. 3. Create a cluster in VPC-1. Go to Peering > Cluster Encrypted Peering > **+ New Cluster**. Make sure you highlight and select all three gateways at the Highlight and Select Gateways field. 4. Repeat the three steps above for VPC-2. 5. Create a Cluster Encrypted Peering. Go to Peering > Cluster Encrypted Peering > Cluster Peering > **+New Peering** and enter the two clusters you created in the previous steps. **Special Notes**. For AWS Gateways, select **Over AWS Peering** if the two VPCs are in the same region. Note that when this option is selected, you must have AWS peering routing PCX programmed in the routing table **only** for the subnet where cluster gateway instances are deployed. You must **NOT** program PCX for routing tables whose associated subnets are where your application EC2 instances are deployed. 1. Once peering configuration is completed, you can view it in dashboard. Cluster peering is drawn with a thicker green line. 2. Note if that you wish to add more gateways once a cluster peering has been created, you need to unpeer the cluster peering first. Add more gateways in each VPC, then create cluster peering again. 3. You can create multiple clusters in a VPC. A gateway may also belong to different clusters. For support, please open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_. .. |image1| image:: Cluster_Peering_Reference_Design_files/image002.png :width: 6.5in :height: 2.5in .. |image2| image:: Cluster_Peering_Reference_Design_files/image003.png :width: 6.5in :height: 2.5in .. |image3| image:: Cluster_Peering_Reference_Design_files/image004.png :width: 6.5in :height: 4.0in .. add in the disqus tag .. disqus:: <file_sep> =================================================== VPN Access Gateway Selection by Geolocation of User =================================================== Overview ======== If you have a global workforce that needs to access the cloud with the best user experience, building a cloud network with GeoVPN access capability is the right solution for you. The geolocation VPN feature combines the Aviatrix scale out VPN solution with latency-based routing to dynamically route VPN users to the nearest VPN access gateway based on the latency between the user and the gateways. .. note:: GeoVPN service is currently only available for AWS cloud. VPN Access Details ================== An example deployment in AWS is shown below. In this configuration, there are two VPN access gateways: one in us-west-2 and another in eu-central-1. Each VPN access gateway is fronted by a load balancer in AWS. .. note:: After releases 6.7.1436 and 6.8.1148, AWS classic Load Balancers are not supported with UserVPN gateways. Instead, `migrate <https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/migrate-classic-load-balancer.html>`_ to Network Load Balancers. |imageArchitecture| Let's look at the difference between a standard VPN access service and VPN access service with the Geolocation feature enabled: Standard VPN Service (without geolocation feature enabled) ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Without the Geolocation feature enabled, when a user connects to the VPN service, they will connect to one of the two regions' VPN gateway. Each gateway is independently administered, meaning users need a separate configuration profile for each region they will access. In this configuration, an EU-based user would be given a configuration profile for the eu-central-1 load balancer. And, a US-based user will be provided with a us-west-2 configuration profile. If either user relocates or travels to the opposite region, they will need a separate configuration profile in that region and they will need to manually switch the active configuration profile. |imageWithoutGeoVPN| Geolocation VPN Service +++++++++++++++++++++++ With the Geolocation feature enabled, when a user connects to the VPN service, they are directed to a Route 53 that uses a latency-based routing policy to choose between the available regions. In this configuration, both the EU-based user and the US-based user would be given the same configuration profile. This configuration profile will select the closest region automatically using a latency-based routing policy defined on the DNS record. |imageWithGeoVPN| Configuration Workflow ====================== 1. Create a `VPN gateway <./uservpn.html>`__ in each region. .. important:: Enable ELB on each gateway that will be associated with the GeoVPN feature. .. tip:: You must create at least one gateway to enable GeoVPN. You can add more gateways to the pool at any time. 2. Once you have at least one VPN gateway created with ELB enabled, you are ready to proceed to the enable GeoVPN feature. Click on **OpenVPN** in the navigation menu and select **Advanced**. 3. Click the **GeoVPN** tab. 4. Select the **Cloud Type** and click on the Disabled status to Enable the GeoVPN feature. |imageEnable| 5. Populate the fields: +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | **Field** | **Description** | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Account Name | Select the cloud account where the DNS domain is hosted. | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Domain Name | The hosted domain name. **IMPORTANT:** This domain name must be hosted by AWS Route53 in the selected account. | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | VPN Service Name | The hostname that users will connect to. A DNS record will be created for this name in the specified domain name. | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | ELB DNS Name | Select the first ELB name to attach to this GeoVPN name. You can add others after this feature is enabled. | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ |imageEnablePopulate| 6. Click **OK**. |imageComplete| .. note:: If enabling GeoVPN fails, make sure the Domain Name you enter is a registered name under AWS Route 53 in a public hosted zone. In addition, this Domain name must be hosted in the account that you have access privilege. If the domain name is hosted by another account, you will not be able to add DNS record. 7. For each additional region, repeat these steps: * Click **+ Add New**. * Select the **ELB DNS Name**. * Click **OK**. |imageAddAdditionalELB| .. tip:: Add encrypted peering to connect regions. Add Users +++++++++ Once you have GeoVPN enabled, you can add users. Follow these steps to add users: * Click **OpenVPN** on the left sidebar. * Click **VPN Users**. * Click **+ Add New**. * In the **VPC ID / DNS Name** dropdown menu, select the GeoVPN VPN service name created in the previous steps. * Enter the **User Name** and optionally the **User Email**. * Click **OK**. |imageAddVPNUser| Managing the GeoVPN Configuration ++++++++++++++++++++++++++++ Once you have GeoVPN feature enabled, you can centrally manage all the VPN gateways' configuration under the GeoVPN service. Follow these steps to configure them: * Click **OpenVPN** on the left sidebar. * Click **Edit Config**. * In the **VPC ID/VNet Name** dropdown menu, select the GeoVPN service name created in the previous steps. * Update the VPN configuration regarding to your requirements. Advanced Settings : Managing VPN Configuration for Individual DHCP Setup ====================================================================== GeoVPN can use DHCP Setting for DNS name resolution from the cloud private network where the VPN gateway is deployed. This reduces latency as DNS service is likely to be closer to the source of the VPN user location. Follow these steps to configure DHCP configuration for individual VPN gateway: 1. Click**OpenVPN** on the left sidebar. 2. Click **Edit Config**. 3. In the **VPC ID/VNet Name** dropdown menu, select the specific VPC ID and LB/Gateway Name instead of GeoVPN service name. 4. Update the supported VPN configuration as below regarding to your requirement in each VPN gateway. * Additional CIDRs * Nameservers * Search Domains .. note:: The attributes “Additional CIDRs, Nameservers, and Search Domains” are able to be edited for individual LB//Gateway Name only if the split tunnel mode is selected under the GeoVPN service. 5. Check this `document <https://docs.aviatrix.com/Support/support_center_openvpn_gateway.html#how-can-i-resolve-my-private-vpc-instance-s-name-when-connecting-via-remote-vpn>`_ for more info. OpenVPN is a registered trademark of OpenVPN Inc. .. |image0| image:: GeoVPN_media/image1.png .. |imageArchitecture| image:: GeoVPN_media/architecture_overview.png .. |imageWithoutGeoVPN| image:: GeoVPN_media/architecture_without_geovpn.png .. |imageWithGeoVPN| image:: GeoVPN_media/architecture_with_geovpn.png .. |imageEnable| image:: GeoVPN_media/enable_geovpn.png .. |imageEnablePopulate| image:: GeoVPN_media/enable_geovpn_populate.png .. |imageAddAdditionalELB| image:: GeoVPN_media/add_additional_elb.png .. |imageAddAdditionalELBComplete| image:: GeoVPN_media/add_additional_elb_complete.png .. |imageComplete| image:: GeoVPN_media/geovpn_complete.png .. |imageAddVPNUser| image:: GeoVPN_media/add_vpn_user.png .. disqus:: <file_sep> ========================================================= Transit FireNet Workflow for AWS ========================================================= Aviatrix Transit FireNet allows you to deploy firewall functions for the Aviatrix Multi-Cloud transit architecture. The Transit FireNet feature is integrated into the Aviatrix Transit gateway. To learn about Transit FireNet, look at the `Transit FireNet FAQ. <https://docs.aviatrix.com/HowTos/transit_firenet_faq.html>`_ If you want to deploy firewall networks in an AWS Transit Gateway (TGW) environment, your starting point is `here <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html>`_. In this example, a transit VPC with Aviatrix Gateways is deployed, and two Spoke Gateways (DEV and PROD) are attached to it. The transit VPC will have a firewall of supported vendors (Check Point, Palo Alto Networks and Fortinet etc.) deployed within it. Please see the diagram below for more details. Once the infrastructure is in place you create a policy to inspect the east-west and north-south traffic. |avx_tr_firenet_topology| Create VPCs ************* VPCs can be created manually on AWS or directly from the Aviatrix Controller. In this example, VPCs are created following the Useful Tools `Create a VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ guidelines. 1. Login to the Aviatrix Controller with a username and password. #. Navigate to Useful Tools > Create A VPC. #. Select AWS as the Cloud Type. #. Add one VPC for Transit FireNet Gateway and select the **Aviatrix Transit Firenet VPC** option as shown below. #. Create two more VPCs with no option/checkbox selected for Spoke Gateways. |create_vpc| Deploy the Transit Aviatrix Gateway ************************************ Transit Aviatrix Gateway can be deployed using the `Transit Gateway Workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-a-transit-gateway>`_. Prerequisite for AWS ~~~~~~~~~~~~~~~~~~~~~ Transit FireNet builds on the Aviatrix Transit Network where Aviatrix gateways are deployed in both the transit VPC and the spoke VPCs in AWS. ActiveMesh is enabled by default. Make sure the deployment meets the following specifications: 1. The minimum size of the Aviatrix Transit Gateway is c5.xlarge. #. The Aviatrix Transit Network must be in Connected mode. Go to Transit Network > Advanced Config > Connected Transit and click **Enable**. Procedure ~~~~~~~~~~ 1. Navigate to Multi-Cloud Transit > Setup > Transit > #1 Launch an Aviatrix Transit Gateway. #. Select the **AWS** Cloud Type. #. Enter a Gateway Name. #. Select the AWS Access Account Name. #. Select a region. #. Select the VPC ID of the AWS Transit VPC. #. Select the Public Subnet. #. Choose the **c5x.large** gateway size. #. Enable **Insane Mode Encryption** for higher throughputs (optional). #. Enable Transit VPC GW HA by navigating to Multi-Cloud Transit > Setup > Transit > #2 (Optional) Enable HA to an Aviatrix Transit Gateway. #. Select the Transit gateway and the HA Gateway Subnet. #. Click **Enable**. .. note:: The c5.xlarge instance size will be required for Insane Mode Encryption (for higher throughput). Please see an example below for Transit FireNet GW: |tr_firenet_gw| Deploy Spoke Gateways ********************** Now that there is an Aviatrix Transit Gateway, you can deploy Aviatrix Spoke Gateways in the Spoke VPCs using `Aviatrix Spoke Gateway Workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-a-spoke-gateway>`_. 1. Navigate to Multi-Cloud Transit > Setup > Spoke > #1 Launch an Aviatrix Spoke Gateway. #. Deploy a Spoke Gateway (GW) in each of the spoke VPCs using defaults, ensuring that you choose the correct Account and VPC information. #. Choose the Public Subnet. #. Enable Spoke Gateway HA by navigating to Multi-Cloud Transit > Setup > Spoke > #5 (Optional) Enable/Disable HA to an Aviatrix Spoke Gateway. .. note:: The c5.xlarge instance size will be required for Insane Mode Encryption (for higher throughput). |launch_spk_gw| Attach Spoke Gateways to Transit Network **************************************** Now that the Transit and spoke gateways are deployed, you must connect them. 1. Navigate to Multi-Cloud Transit > Setup > Attach/Detach > #1a Attach Spoke Gateway to Transit Network. #. Select one spoke at a time and attach to the Transit gateway. |attach_spk_trgw| .. note:: The Transit gateway is attached to Spoke gateways, but by default, the Transit gateway will not route traffic between Spoke gateways. Enable Connected Transit ************************ By default, Spoke VPCs are in isolated mode where the Transit will not route traffic between them. To allow the Spoke VPCs to communicate with each other, you must enable Connected Transit by navigating to Multi-Cloud Transit > Advanced Config. Under Edit Transit, select the Transit Gateway and toggle Connected Transit to **Enabled**. |connected_transit| Configure Transit Firewall Network *********************************** Now that Transit and Spoke gateways have been deployed, you must deploy and enable the firewall for traffic inspection. 1. Navigate to Firewall Network > Setup > #3a Enable Transit FireNet on Aviatrix Transit Gateway. #. Choose the Gateway Name and click **“Enable”**. |en_tr_firenet| 3. Navigate to Firewall Network > Policy > Manage FireNet Policy. #. Add spokes to the Inspected box for traffic inspection. .. note:: By default, FireNet inspects ingress (INET to VPC) and east-west traffic (VPC to VPC) only. |tr_firenet_policy| Subscribe to Firewall Vendor in AWS Marketplace *********************************************** At this point, FireNet functionality on the Transit Gateway is enabled and the FireNet policy is created for Spokes. You can now subscribe to the firewall vendor and deploy the firewall. As indicated in the Aviatrix Controller at Firewall Network > Setup > Firewall, you must subscribe to the supported firewall vendor in your AWS marketplace using an access account onboarded to the Controller. .. note:: Please subscribe to the firewall, but do not launch the firewall. |subscribe_firewall| Launch and Associate Firewall Instance ************************************** This approach is recommended if this is the first firewall instance to be attached to the gateway. This step launches a firewall instance and associates it with one of the FireNet gateways. .. important:: The Firewall instance and the associated Aviatrix FireNet gateway above must be in the same AZ, and we recommend that the Management Interface Subnet and Egress (untrust dataplane) Interface Subnet not be in the same subnet. Launch and Attach ~~~~~~~~~~~~~~~~~~~ In the Aviatrix Controller navigate to Firewall Network > Setup > Firewall > Step 2a. Provide all the required input as shown in the table and click **"Launch"**. .. important:: The vendor's firewall may take some time after launch to be available. ========================================== ========== **Setting** **Value** ========================================== ========== VPC ID The Security VPC created in Step 1. Gateway Name The primary FireNet gateway. Firewall Instance Name The name that will be displayed on AWS Console. Firewall Image The AWS AMI that you have subscribed in Step 2. Firewall Image Version Firewall instance current supported software versions. Firewall Instance Size Firewall instance type. Management Interface Subnet. Select the subnet whose name contains "gateway and firewall management" Egress Interface Subnet Select the subnet whose name contains "FW-ingress-egress". Username Applicable to Azure deployment only. "admin" as a username is not accepted. Password Applicable to Azure deployment only. Key Pair Name (Optional) The .pem file name for SSH access to the firewall instance. Attach (Optional) By selecting this option, the firewall instance is inserted in the data path to receive packet. If this is the second firewall instance for the same gateway and you have an operational FireNet deployment, you should not select this option as the firewall is not configured yet. You can attach the firewall instance later at Firewall Network > Advanced page. Advanced (Optional) Click this selection to allow Palo Alto firewall bootstrap files to be specified. IAM Role In advanced mode, create an IAM Role on the AWS account that launched the FireNet gateway. Create a policy to attach to the role. The policy is to allow access to "Bootstrap Bucket". Bootstrap Bucket Name In advanced mode, specify a bootstrap bucket name where the initial configuration and policy file is stored. ========================================== ========== Check Point Specifications ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The Check Point Firewall instance has two interfaces as described below. ======================================================== =============================== ================================ **CheckPoint VM instance interfaces** **Description** **Inbound Security Group Rule** ======================================================== =============================== ================================ eth0 (on subnet -Public-FW-ingress-egress-AZ-a) Egress or Untrusted interface Allow ALL eth1 (on subnet -dmz-firewall) LAN or Trusted interface Allow ALL (Do not change) ======================================================== =============================== ================================ Note that firewall instance eth1 is on the same subnet as FireNet gateway eth2 interface. .. important:: Starting in Release 5.4, launching Check Point firewall instances from the Aviatrix Controller automatically initiates Check Point's onboarding process. For initial login information, go to `Credentials for Checkpoint Initial Login <https://aviatrix.zendesk.com/hc/en-us/articles/4417552852109>`_. You must be registered to access the Aviatrix Customer Support website. If you are not already registered, you can sign-up at https://support.aviatrix.com. .. note:: Repeat Step 2a to launch the second firewall instance to associate with the HA FireNet gateway. Or repeat this step to launch more firewall instances to associate with the same FireNet gateway. Follow `Check Point Example <https://docs.aviatrix.com/HowTos/config_CheckPointVM.html#example-config-for-check-point-vm-in-aws>`_ to launch Check Point security gateway in AWS and for more details. Palo Alto VM-Series Specifications ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Palo instance has three interfaces as described below. ======================================================== =============================== ================================ **Palo Alto VM instance interfaces** **Description** **Inbound Security Group Rule** ======================================================== =============================== ================================ eth0 (on subnet -Public-FW-ingress-egress-AZ-a) Egress or Untrusted interface Allow ALL eth1 (on subnet -Public-gateway-and-firewall-mgmt-AZ-a) Management interface Allow SSH, HTTPS, ICMP, TCP 3978 eth2 (on subnet -dmz-firewall) LAN or Trusted interface Allow ALL (Do not change) ======================================================== =============================== ================================ Note that firewall instance eth2 is on the same subnet as FireNet gateway eth2 interface. .. important:: For Panorama managed firewalls, you need to prepare Panorama first and then launch a firewall. Look at `Setup Panorama <https://docs.aviatrix.com/HowTos/paloalto_API_setup.html#managing-vm-series-by-panorama>`_. When a VM-Series instance is launched and connected with Panorama, you need to apply a one time "commit and push" from the Panorama console to sync the firewall instance and Panorama. .. Tip:: If VM-Series are individually managed and integrated with the Aviatrix Controller, you can still use Bootstrap to save initial configuration time. Export the first firewall's configuration to bootstrap.xml, create an IAM role and Bootstrap bucket structure as indicated above, then launch additional firewalls with IAM role and the S3 bucket name to save the time of the firewall manual initial configuration. Follow `Palo Alto Network (VM Series) Example <https://docs.aviatrix.com/HowTos/config_paloaltoVM.html#example-config-for-palo-alto-network-vm-series>`_ to launch VM Series firewall in AWS and for more details. FortiGate Specifications ~~~~~~~~~~~~~~~~~~~~~~~~~ FortiGate Next Generation Firewall instance has two interfaces as described below. ======================================================== =============================== ================================ **Fortigate VM instance interfaces** **Description** **Inbound Security Group Rule** ======================================================== =============================== ================================ eth0 (on subnet -Public-FW-ingress-egress-AZ-a) Egress or Untrusted interface Allow ALL eth1 (on subnet -dmz-firewall) LAN or Trusted interface Allow ALL (Do not change) ======================================================== =============================== ================================ .. note:: Firewall instance eth1 is on the same subnet as FireNet gateway eth2 interface. .. tip:: Starting from Release 5.4, Fortigate bootstrap configuration is supported. Follow `Fortigate Example <https://docs.aviatrix.com/HowTos/config_FortiGateVM.html#example-config-for-fortigate-vm-in-aws>`_ to launch Fortigate in AWS and for more details. Associate an Existing Firewall Instance **************************************** This step is the alternative step to launching and associating a firewall instance as per above. If you already launched the firewall (Check Point, Palo Alto Network or Fortinet) instance from AWS Console, you can still associate it with the FireNet gateway. In the Aviatrix Controller, navigate to Firewall Network > Setup > Firewall > Step 2b and associate a firewall with the correct FireNet Gateway. Example Setup for "Allow All" Policy ************************************* After a firewall instance is launched, wait 5 to 15 minutes for it to become available. Time varies for each firewall vendor. In addition, please follow the example configuration guides as per below to build a simple policy on the firewall instance for a test validation that traffic is indeed being routed to the firewall instance. Palo Alto Network (PAN) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ For basic configuration, please refer to `example Palo Alto Network configuration guide <https://docs.aviatrix.com/HowTos/config_paloaltoVM.html>`_. For implementation details on using Bootstrap to launch and initiate VM-Series, refer to `Bootstrap Configuration Example <https://docs.aviatrix.com/HowTos/bootstrap_example.html>`_. FortiGate (Fortinet) ~~~~~~~~~~~~~~~~~~~~~~~~~~ For basic configuration, please refer to `example Fortinet configuration guide <https://docs.aviatrix.com/HowTos/config_FortiGateVM.html>`_. Check Point ~~~~~~~~~~~~~~~~ For basic configuration, please refer to `example Check Point configuration guide <https://docs.aviatrix.com/HowTos/config_CheckPointVM.html>`_. (Optional) Vendor Firewall Integration ***************************************** Vendor integration dynamically updates firewall route tables. The use case is for networks with non-RFC 1918 routes that require specific route table programming on the firewall appliance. 1. In the Aviatrix Controller, navigate to Firewall Network > Vendor Integration > Firewall. Select the Firewall Vendor Type and fill in the details of your firewall instance. 2. Click **Save**. 3. You can click **Show** or **Sync** to show the integration details or sync the configuration with the firewall. Verification ************** There are multiple ways to verify if Transit FireNet is configured properly: 1. Aviatrix Flightpath - Control-plane Test #. Ping/Traceroute Test between Spoke VPCs (East-West) - Data-plane Test Flight Path Test for FireNet Control Plane Verification ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Flight Path is a powerful troubleshooting Aviatrix tool which allows users to validate the control-plane and gives visibility of end to end packet flow. 1. In the Aviatrix Controller, navigate to Troubleshoot > Flight Path. #. Provide the Source and Destination Region and VPC information. #. Select ICMP and Private subnet, and run the test. .. note:: An EC2 VM instance will be required in AWS, and ICMP should be allowed in the security group. Ping/Traceroute Test for FireNet Data Plane Verification ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Once control plane is established and no problems are found in security and routing polices, data plane validation needs to be verified to make sure traffic is flowing and not blocked anywhere. There are multiple ways to check the data plane: 1. SSH to Spoke EC2 instance (e.g. DEV1-VM) and ping other Spoke EC2 to instance (e.g PROD1-VM) to make sure there is no traffic loss in the path. 2. Ping/traceroute capture can also be performed from Aviatrix Controller. Navigate to Troubleshoot > Diagnostics and perform the test. .. |subscribe_firewall| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/subscribe_firewall.png :scale: 25% .. |en_tr_firenet| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/en_tr_firenet.png :scale: 35% .. |tr_firenet_policy| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/tr_firenet_policy.png :scale: 25% .. |avx_tr_firenet_topology| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/avx_tr_firenet_topology.png :scale: 25% .. |create_vpc| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/create_vpc.png :scale: 25% .. |tr_firenet_gw| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/tr_firenet_gw.png :scale: 25% .. |launch_spk_gw| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/launch_spk_gw.png :scale: 25% .. |attach_spk_trgw| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/attach_spk_trgw.png :scale: 25% .. |connected_transit| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/connected_transit.png :scale: 25% .. disqus:: <file_sep> .. raw:: html <style> /* override table no-wrap */ .wy-table-responsive table td, .wy-table-responsive table th { white-space: normal !important; } </style> ===================================================================== Aviatrix Gateway to AWS VGW ===================================================================== Overview ----------------- This document describes how to configure an IPsec tunnel between an Aviatrix Gateway and an AWS Virtual Private Gateway (VGW). |gw2vgw| Deployment Guide ---------------------------- For this use case, we will configure the AWS VGW VPN connection first and then download the configuration from AWS and import it into Aviatrix. Create the VPN Connection +++++++++++++++++++++++++ .. note:: **Prerequisites** #. You have a VGW created and attached to a VPC. #. You have an Aviatrix Gateway provisioned in a different VPC. You will need this gateway's public IP address for the steps below. #. Log in to your AWS `VPC Dashboard <https://console.aws.amazon.com/vpc/home>`__ in the region where your VGW is located #. Create a new `Customer Gateway <https://console.aws.amazon.com/vpc/home#CreateCustomerGateway>`__. |awscg| +------------------------------+-------------------------------------------+ | Field | Description | +------------------------------+-------------------------------------------+ | Name | Enter any name here | +------------------------------+-------------------------------------------+ | Routing | Select **Static** | +------------------------------+-------------------------------------------+ | IP Address | Enter the Aviatrix Gateway's public IP | +------------------------------+-------------------------------------------+ #. Create a `VPN Connection <https://console.aws.amazon.com/vpc/home#CreateVpnConnection:>`__. |awsvpn| +------------------------------+-------------------------------------------+ | Field | Description | +------------------------------+-------------------------------------------+ | Name | Enter any name here | +------------------------------+-------------------------------------------+ | Virtual Private Gateway | Select your VGW | +------------------------------+-------------------------------------------+ | Customer Gateway | Select **Existing** | +------------------------------+-------------------------------------------+ | Routing Options | Select **Static** | +------------------------------+-------------------------------------------+ | Static IP Prefixes | Enter the CIDR(s) of the VPC where the | | | Aviatrix Gateway resides. | +------------------------------+-------------------------------------------+ | Tunnel Options | Leave blank/default | +------------------------------+-------------------------------------------+ #. Select the VPN you just created and click the **Download Configuration** button along the top. At the dialog, select **Generic** for the Vendor, **Generic** for the Platform and **Vendor Agnostic** for the Software. #. Click **Download Configuration**. You will use this file to create the other side of the tunnel. |awsdownloadvpnconfig| Configuring Aviatrix ++++++++++++++++++ #. Log in to your Aviatrix Controller. #. Follow the steps in `this </HowTos/site2cloud.html>`__ guide. Use this table for specific field values. +-------------------------------+------------------------------------------+ | Field | Description | +===============================+==========================================+ | VPC ID/VNet Name | Select the Aviatrix Gateway VPC or VNet | | | from the drop down. | +-------------------------------+------------------------------------------+ | Connection Type | Unmapped | +-------------------------------+------------------------------------------+ | Remote Gateway Type | AWS VGW | +-------------------------------+------------------------------------------+ | Algorithms | Checked | +-------------------------------+------------------------------------------+ #. Populate the remaining fields. +-------------------------------+------------------------------------------+ | Field | Description | +===============================+==========================================+ | Remote Gateway IP Address | Enter the value that matches the value | | | Tunnel Interface Configuration | | | > **Outside IP Addresses** | | | > **Virtual Private Gateway** | +-------------------------------+------------------------------------------+ | Pre-shared Key | Enter the value that matches the value | | | `Internet Key Exchange Configuration` | | | > **Pre-Shared Key** | +-------------------------------+------------------------------------------+ | Remote Subnet | Remote subnet is usually the cloud | | | networks | | | for eg., Spoke VPC which onprem wants to | | | reach to (10.20.0.0/20) | +-------------------------------+------------------------------------------+ |tunnelconfig| Test ---------- Once complete, test the communication using the tunnel. Troubleshooting ------------------------- Wait 2-3 minutes for the tunnel to come up. If it does not come up within that time, check the IP addresses to confirm that they are accurate. Additional troubleshooting is available in the **Diagnostics** tab. Appendix: Enable HA ------------------------------- You can enable HA for Aviatrix Site2Cloud connection to AWS VGW. Please add the following extra steps to the configuration. Creating an Aviatrix HA Gateway +++++++++++++++++++++++++++ Before creating a Site2Cloud connection, follow `this <https://docs.aviatrix.com/Solutions/gateway_ha.html>`__ guide's **Backup Gateway and Tunnel HA** section to create an Aviatrix HA gateway in the same VPC. Creating a VPN Connection Between VGW and the Aviatrix HA Gateway +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ From the AWS console, create a new VPN connection between VGW and Aviatrix HA Gateway. #. Create a new Customer Gateway for Aviatrix HA Gateway: +------------------------------+-------------------------------------------+ | Field | Description | +------------------------------+-------------------------------------------+ | Name | Enter any name here | +------------------------------+-------------------------------------------+ | Routing | Select **Static** | +------------------------------+-------------------------------------------+ | IP Address | Enter the Aviatrix HA Gateway's public IP | +------------------------------+-------------------------------------------+ #. Create a new VPN connection for Aviatrix HA Gateway: +------------------------------+-------------------------------------------+ | Field | Description | +------------------------------+-------------------------------------------+ | Name | Enter any name here | +------------------------------+-------------------------------------------+ | Virtual Private Gateway | Select the same VGW using for primary | | | VPN connection | +------------------------------+-------------------------------------------+ | Customer Gateway | Select CGW your just created for HA | +------------------------------+-------------------------------------------+ | Routing Options | Select **Static** | +------------------------------+-------------------------------------------+ | Static IP Prefixes | Enter the CIDR(s) of the VPC where the | | | HA Aviatrix Gateway resides. | +------------------------------+-------------------------------------------+ | Tunnel Options | Leave blank/default | +------------------------------+-------------------------------------------+ #. Download the configuration for this new VPN connection just like you did earlier for the primary VPN connection. Create Aviatrix Site2Cloud Connection with HA +++++++++++++++++++++++++++++++++++++++++++++ From Aviatrix Controller UI > Site2Cloud page, click **+ Add New**, under **Add a New Connection**, make sure **Enable HA** is checked. Additional fields are displayed when checked. .. note:: VPN information for backup needs to be obtained from the downloaded configuration of AWS VPN connection between VGW and Aviatrix HA Gateway. Follow the same steps you did for primary connection. +-----------------------------------+------------------------------------------+ | Field | Description | +===================================+==========================================+ | Backup Gateway | Select the Aviatrix HA Gateway you just | | | created | +-----------------------------------+------------------------------------------+ | Remote Gateway IP Address(Backup) | Enter the value that matches the value | | | `Tunnel Interface Configuration` | | | > **Outside IP Addresses** | | | > **Virtual Private Gateway** | +-----------------------------------+------------------------------------------+ | Pre-shared Key(Backup) | Enter the value that matches the value | | | `Internet Key Exchange Configuration` | | | > **Pre-Shared Key** | +-----------------------------------+------------------------------------------+ .. |presharedkey| Other fields should be filled as instructed in above section **Configure Aviatrix**. .. |gw2vgw| image:: s2c_vgw_media/gw_to_vgw.png :scale: 50% .. |presharedkey| image:: s2c_vgw_media/presharedkey.png .. |awscg| image:: s2c_vgw_media/aws_cg.png .. |awsvpn| image:: s2c_vgw_media/aws_vpn.png .. |awsdownloadvpnconfig| image:: s2c_vgw_media/aws_download_vpn_config.png .. |awsvpnconfig| image:: s2c_vgw_media/aws_vpn_config.png .. |avxphase1config| image:: s2c_vgw_media/avx_phase_1_config.png .. |avxphase2config| image:: s2c_vgw_media/avx_phase_2_config.png .. |tunnelconfig| image:: s2c_vgw_media/tunnelconfig.png :scale: 30% .. disqus:: <file_sep> ========================================================================================== AWS Multi-Cloud Transit BGP over LAN Workflow ========================================================================================== Introduction ============ Transit BGP to LAN allows Aviatrix Transit Gateways to communicate with a pair of instances in the same VPC in AWS without running any tunneling protocol such as IPsec or GRE. One use case is to interoperate with third-party virtual appliances such as SD-WAN cloud instances that do not have the capability to support BGP over any tunneling protocols. For example, integrating with SD-WAN gateways can be deployed as below, |sd_wan_integ_aws| where an Aviatrix Multi-Cloud Transit Gateway connects to a third-party cloud instance in the same VPC in AWS. This document describes a step-by-step instruction on how to build Aviatrix Transit Gateway to External Device using BGP over LAN in AWS. In this Tech Note, you learn the following: #. Workflow on `deploying Aviatrix Transit Solution <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_workflow.html#deploy-aviatrix-multi-cloud-transit-solution>`_ #. Workflow on `launching third-party cloud instances <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_workflow.html#launch-third-party-cloud-instances>`_ #. Workflow on `building BGP over LAN <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_workflow.html#build-bgp-over-lan>`_ For other BGP over LAN workflows, please see the documents below: - `Azure Multi-cloud Transit BGP over LAN Workflow <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_azure_workflow.html>`_ - `Aviatrix BGP over LAN with Cisco Meraki in AWS <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_with_aws_meraki_workflow.html>`_ For more information about Multi-Cloud Transit Network and External Device, please see the documents below: - `Multi Cloud Global Transit FAQ <https://docs.aviatrix.com/HowTos/transitvpc_faq.html#multi-cloud-global-transit-faq>`_ - `Global Transit Network Workflow Instructions (AWS/Azure/GCP/OCI) <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ - `Aviatrix Transit Gateway to External Devices <https://docs.aviatrix.com/HowTos/transitgw_external.html>`_ - `Transit Network Design Patterns <https://docs.aviatrix.com/HowTos/transitvpc_designs.html>`_ .. important:: - This solution supports only `ActiveMesh 2.0 <https://docs.aviatrix.com/HowTos/activemesh_faq.html#what-is-activemesh-2-0>`_, please check this doc `How to migrate to ActiveMesh 2.0 <https://docs.aviatrix.com/HowTos/activemesh_faq.html#how-to-migrate-to-activemesh-2-0>`_ for migration detail. - This solution is available to AWS and Azure. Workflow with AWS here is just an example. Please adjust the topology depending on your requirements. - Require instance size to support at least 5 interfaces such as c4.4xlarge, c5.4xlarge, and c5n.4xlarge in AWS. - LAN interfaces for Aviatrix Transit Primary and third-party cloud instance must be in the same Availability Zone. - One BGP over LAN connection per gateway is supported. The key ideas for this solution are: ---------------------------------------- - A BGP session establishes between a third-party cloud instance and Aviatrix Transit Gateway via each LAN interface in the same VPC. - Data plane traffic also runs between a third-party cloud instance and Aviatrix Transit Gateway via each LAN interface without a tunnel protocol such as IPsec and GRE. Prerequisite ==================== - This feature is available for 6.3 and later. `Upgrade <https://docs.aviatrix.com/HowTos/inline_upgrade.html>`_ Aviatrix Controller to at least version 6.3. - In this example, we are going to deploy the below VPCs in AWS: - Transit VPC (i.e. 10.1.0.0/16) by utilizing Aviatrix feature `Create a VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ with Aviatrix FireNet VPC option enabled. - Spoke VPCs (i.e. 192.168.1.0/24 and 192.168.2.0/24) by utilizing Aviatrix feature `Create a VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ as the previous step or manually deploying it in each cloud portal. Moreover, feel free to use your existing cloud network. - Third-party cloud instance has high throughput supported. Deploying the Aviatrix Multi-Cloud Transit Solution ================================================= Refer to `Global Transit Network Workflow Instructions <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ for the below steps. Please adjust the topology depending on your requirements. 1. Deploy the `Aviatrix Multi-Cloud Transit Gateway and HA <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html#step-2-deploy-the-transit-aviatrix-gateway>`_ with Insane Mode enabled. In this example, size c5n.4xlarge are selected to benchmark `performance <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_workflow.html#performance-benchmark>`_. 2. Deploy a `Spoke Gateway and HA <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html#step-3-deploy-spoke-gateways>`_ to launch Aviatrix Spoke gateway and enable HA with Insane Mode enabled in Spoke VPC. In this example, size c5n.4xlarge are selected to benchmark `performance <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_workflow.html#performance-benchmark>`_. 3. Attach `Spoke Gateways to Transit Network <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html#step-4-attach-spoke-gateways-to-transit-network>`_ to attach Aviatrix Spoke Gateways to Aviatrix Transit Gateways. Launching Third-Party Cloud Instances ================================================================================ Deploy third-party cloud instances in the same VPC where Aviatrix Transit Gateways locate. 1. Create a third-party cloud instance and put MGMT interface in public gateway subnet. 2. Create a new public WAN subnet and a dedicated routing table for WAN interface if needed. 3. Create a new private LAN subnet and a dedicated routing table (optional) for LAN interface. 4. Make sure the function "Source/Dest check on third-party cloud instance's interfaces is disabled. .. important:: The primary Aviatrix Transit Gateway must be deployed in the same available zone as the first third-party cloud instance. The HA Transit Gateway if deployed must reside in the same available zone as the second cloud instance. Building BGP over LAN ================================================ Configure BGP over LAN on the Aviatrix Transit Gateway. 1. Log in Aviatrix Controller and go to Multi-Cloud Transit > Setup > External Connection tab. 2. Select External Device > BGP > LAN. 3. Enter the following information in the fields below. +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Transit VPC Name | Select the Transit VPC ID where Transit GW was launched | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Connection Name | Provide a unique name to identify the connection to external device | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Aviatrix Transit Gateway BGP ASN | Configure a BGP AS number that the Transit GW will use to exchange routes with external device | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Primary Aviatrix Transit Gateway | Select the Transit GW | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Enable Remote Gateway HA | Check this option in this example to connect two external devices | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Remote BGP AS Number | Configure a BGP AS number that third-party cloud primary instance will use to exchange routes with Aviatrix Transit Primary | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Remote LAN IP | Use the private IP of the LAN interface of the third-party cloud primary instance | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Local LAN IP | Leave it blank and the controller will assign an IP in the same subnet where the Remote LAN IP locates. Optionally configure an IP of your choosing within the same subnet where the Remote LAN IP locates. | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Remote BGP AS Number (Backup) | Configure a BGP AS number that third-party cloud HA instance will use to exchange routes with Aviatrix Transit HA | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Remote LAN IP (Backup) | Use the private IP of the LAN interface of the third-party cloud HA instance | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Local LAN IP (Backup) | Leave it blank and the controller will assign an IP in the same subnet where the Remote LAN IP (Backup) locates. Optionally configure an IP of your choosing within the same subnet where the Remote LAN IP (Backup) locates. | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ 4. Click **Connect** to generate BGP session over LAN. (Optional) Downloading the BGP over LAN configuration sample from Aviatrix Controller ------------------------------------------------------------------------------------------------------------- 1. Navigate to Site2Cloud > Setup and select the connection that you created with Connection Name in the previous step. 2. Click **Edit**. 3. Select Vendor type, Platform, and Software. 4. Click **Download Configuration"**. Configuring BGP over LAN on Third-Party Cloud Instance ------------------------------------------------------------------------- 1. (Optional) Open the downloaded BGP over LAN configuration file. 2. Configure those related BGP and LAN info on third-party cloud instance. Verifying LAN status on Aviatrix Controller ---------------------------------------------------------- 1. Open your Aviatrix Controller and go to Site2Cloud > Setup. 2. Find the connection that you created with Connection Name in the previous step. 3. Check the Tunnel Status. |aviatrix_bgp_lan_status_1| 4. Go to Multi-Cloud Transit > List. 5. Select the Transit Primary Gateway that was created in the previous step. 6. Click **Details/Diag**. 7. Scroll down to Connections > On-prem Connections. 8. Find the connection that you created with Connection Name in the previous step and check the Tunnel Status. |aviatrix_bgp_lan_status_2| Verifying BGP Session Status on Aviatrix Controller ------------------------------------------------------------------- 1. Go to Multi-Cloud Transit > BGP. 2. Find the connection that you created with Connection Name in the previous step and check the BGP Status. |aviatrix_bgp_status| Ready to Go ================= At this point, run connectivity and performance test to ensure everything is working correctly. Performance Benchmark =========================== End-to-End traffic via Aviatrix <-> Aviatrix --------------------------------------------- The performance test is done with a pair of Aviatrix Transit Gateways as the third-party cloud instances, as shown below. Multiple flows result by using iperf3 tool with TCP 128 connections ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +-----------------------+------------------+ | Aviatrix Gateway size | Throughput (Gbps)| +-----------------------+------------------+ | C5n.4xlarge | 23 - 24 | +-----------------------+------------------+ Additional Resources =========================== Additional resources are available in this short blog post, `Need of conventional BGP support in the cloud <https://community.aviatrix.com/t/h7htvvc/need-of-conventional-bgp-support-in-the-cloud>`_. BGP over LAN Multi-Peer =========================== Overview ------------- BGP over LAN in AWS can scale up to 10 BGP over LAN peers per Transit Gateway, and 20 total per Transit Gateway pair. This provides a higher throughput, better redundancy, and a consolidation of BGP over LAN peers on a pair of Transit Gateways. ECMP is supported on all BGP over LAN connections. On-Prem to Cloud ------------------ On-Prem to Cloud connectivity can be achieved with ECMP. |bgp_lan_multipeer_onprem_cloud| When connecting multiple peers, the same BGP over LAN ENI can be reused. Under Multi-Cloud Transit Step 3, specify the ENI IP to reuse it. |bgp_lan_multipeer_same_eni| On-prem to cloud can also be achieved without ECMP. |bgp_lan_multipeer_onprem_cloud_no_ecmp| On-Prem to On-Prem Using Aviatrix Transit as a Hub -------------------------------------------------- This is the same architecture as on-prem to cloud without ECMP: |bgp_lan_multipeer_onprem_cloud_no_ecmp2| However, different ENIs must be used for each BGP over LAN peer, in order for the traffic to flow through the Aviatrix Transit Gateways. This is achieved by leaving the Local LAN IP field blank, or by specifying an IP different from any existing BGP over LAN ENIs. The Controller will allocate a new ENI in the subnet of the BGP over LAN peer specified by Remote LAN IP. Keep in mind that there is a maximum ENI count per instance, depending on the AWS instance type. Otherwise, there is no difference when it comes to performance or any other capabilities. |bgp_lan_multipeer_local_ipblank| HA with BGP over LAN Multi-Peer ------------------------------- Use Remote Gateway HA to attach peers to the secondary Transit Gateway. One BGP over LAN connection consists of 2 peers. Because a peer must be in the same AZ as the Transit Gateway it is connected to, the HA model is 2 peers, each single-attached to their Transit Gateway in their AZ. Notice the BGPoLAN-1 and BGPoLAN-2 connection names in the following diagram. |bgp_lan_multipeer_ha| Throughput with BGP over LAN Multi-Peer --------------------------------------- The aggregate throughput with 20 BGP over LAN peers and a pair of c5n.18xlarge Transit Gateways are as follows: - 460-byte packets -> 12 Gbps. - 1460-byte packets -> 40 Gbps. - 9000-byte packets -> 90 Gbps. Segmentation Domains with BGP over LAN Multi-Peer ------------------------------------------------- Segmentation domains are supported on a per BGP over LAN connection basis. If using Remote Gateway HA, then 1 BGP over LAN connection = 2 BGP over LAN peers = 1 domain. Migration with BGP over LAN Multi-Peer -------------------------------------- Additional BGP over LAN connections can be added to an existing Transit Gateway. The Gateway can have existing BGP over LAN connections. New connections can be added either with the single-ENI or the multi-ENI model. The existing connections do not need to be removed. The Transit Gateway does not need to be replaced. There is no control plane or data place disruption. Feature Interaction with BGP over LAN Multi-Peer ------------------------------------------------ FireNet is supported. A BGP over LAN connection can be part of FireNet Inspection Policies. NAT is not supported on BGP over LAN connections. The configuration is blocked. The existing Terraform module aviatrix_transit_external_device_conn supports BGP over LAN multi-peer, using the existing argument local_lan_ip. .. |transit_gateway_external_device_bgp_over_lan_diagram| image:: transit_gateway_external_device_bgp_over_lan_simulation_workflow_media/transit_gateway_external_device_bgp_over_lan_diagram.png :scale: 50% .. |aws_vgw_attach| image:: transit_gateway_external_device_bgp_over_lan_simulation_workflow_media/aws_vgw_attach.png :scale: 50% .. |aws_route_propagation_status_yes| image:: transit_gateway_external_device_bgp_over_lan_simulation_workflow_media/aws_route_propagation_status_yes.png :scale: 50% .. |aws_route_propagation_routing_entry| image:: transit_gateway_external_device_bgp_over_lan_simulation_workflow_media/aws_route_propagation_routing_entry.png :scale: 50% .. |aviatrix_transit_externel_device_lan| image:: transit_gateway_external_device_bgp_over_lan_simulation_workflow_media/aviatrix_transit_externel_device_lan.png :scale: 50% .. |aviatrix_bgp_lan_status_1| image:: transit_gateway_external_device_bgp_over_lan_simulation_workflow_media/aviatrix_bgp_lan_status_1.png :scale: 50% .. |aviatrix_bgp_lan_status_2| image:: transit_gateway_external_device_bgp_over_lan_simulation_workflow_media/aviatrix_bgp_lan_status_2.png :scale: 50% .. |aviatrix_bgp_status| image:: transit_gateway_external_device_bgp_over_lan_simulation_workflow_media/aviatrix_bgp_status.png :scale: 50% .. |sd_wan_integ_aws| image:: transitvpc_designs_media/sd_wan_integ_aws.png :scale: 30% .. |bgp_lan_multipeer_onprem_cloud| image:: transitvpc_designs_media/bgp_lan_multipeer_onprem_cloud.png :scale: 50% .. |bgp_lan_multipeer_same_eni| image:: transitvpc_designs_media/bgp_lan_multipeer_same_eni.png :scale: 50% .. |bgp_lan_multipeer_onprem_cloud_no_ecmp| image:: transitvpc_designs_media/bgp_lan_multipeer_onprem_cloud_no_ecmp.png :scale: 50% .. |bgp_lan_multipeer_onprem_cloud_no_ecmp2| image:: transitvpc_designs_media/bgp_lan_multipeer_onprem_cloud_no_ecmp2.png :scale: 50% .. |bgp_lan_multipeer_local_ipblank| image:: transitvpc_designs_media/bgp_lan_multipeer_local_ipblank.png :scale: 50% .. |bgp_lan_multipeer_ha| image:: transitvpc_designs_media/bgp_lan_multipeer_ha.png :scale: 50% .. disqus:: <file_sep> ================================================================ Encrypted Transit Approval ================================================================ Aviatrix Transit Gateway dynamically learns BGP routes from remote site, these learned routes are reported to the Controller which in turn programs route entries of a Spoke VPC/VNet route table. There are scenarios where you require an approval process before these learned CIDRs propagation take place. For example, a specific VPN may be connected to a partner network and you need to make sure undesirable routes, such as the default route (0.0.0.0/0) are not propagated into your own network and accidentally bring down the network. |transit_approval| Approval is enabled on an Aviatrix Transit Gateway. When Approval is enabled, dynamically learned routes from all remote peers trigger an email to the Controller admin. Controller admin logins in to the Controller and go to Transit Network > Approval, the admin should see not yet approved CIDRs and already approved CIDRs. Moving the routes from Pending Learned CIDRs panel to Approved Learned CIDRs panel allows those routes to be propagated. To enable Approval, go to Multi-Cloud Transit > Approval. Select the gateway and click **Learned CIDRs Approval** to set it to Enabled. When Approval is disabled, all dynamically learned routes are automatically propagated to the Spokes. Mode Gateway ---------------------- By default, Learned CIDR Approval applies to all BGP connections configured on the Multi-Cloud Transit Gateway. Mode Connection --------------------------- If Connection mode is selected, approval is applied to a selected BGP connection as shown in the dropdown menu. A BGP connection that is not configured for Approval learns all routes from its peer automatically. .. |Test| image:: transitvpc_workflow_media/SRMC.png :width: 5.55625in :height: 3.26548in .. |TVPC2| image:: transitvpc_workflow_media/TVPC2.png :scale: 60% .. |HAVPC| image:: transitvpc_workflow_media/HAVPC.png :scale: 60% .. |VGW| image:: transitvpc_workflow_media/connectVGW.png :scale: 50% .. |launchSpokeGW| image:: transitvpc_workflow_media/launchSpokeGW.png :scale: 50% .. |AttachSpokeGW| image:: transitvpc_workflow_media/AttachSpokeGW.png :scale: 50% .. |SpokeVPC| image:: transitvpc_workflow_media/SpokeVPC.png :scale: 50% .. |transit_to_onprem| image:: transitvpc_workflow_media/transit_to_onprem.png :scale: 40% .. |azure_native_transit2| image:: transitvpc_workflow_media/azure_native_transit2.png :scale: 30% .. |transit_approval| image:: transitvpc_workflow_media/transit_approval.png :scale: 30% .. disqus:: <file_sep> ################################################### AWS Global Transit Network ################################################### AWS Reference Deployment Guide ============================== This document is published by AWS Answers for `AWS Global Transit Network <https://aws.amazon.com/answers/networking/aws-global-transit-network/>`_ as Partner Offering. Aviatrix is a next generation cloud networking solution built from the ground up for the public cloud. For transit VPC design, Aviatrix provides one console for building, managing, monitoring and troubleshooting all aspects of your network connectivity. The console (controller) gives users the ability to implement Transit VPC design with a point-and-click (no CLI), `API <http://docs.aviatrix.com/HowTos/Aviatrix_Controller_API.html>`_ and `Terraform. <http://docs.aviatrix.com/HowTos/Setup_Transit_Network_Terraform.html>`_ The configuration guide can be found `at this link. <http://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ Comparing Aviatrix Global Transit Network Solution with CSR1000v Solution ============================================================================== The Aviatrix Solution has the following benefits compared to CSR1000v: **Simplicity** No Cisco CCIE, BGP, VRF and IPSEC domain expertise is required. The Aviatrix central controller builds and manages your network with software defined routing and point and click solutions deploying in minutes. **No Double Egress Charge** Aviatrix supports direct Spoke VPC to Spoke VPC connectivity without going through a transit VPC, which incurs twice the egress network charges. **Isolation By Design** An AWS Transit VPC solution with CSR1000v automatically builds a full mesh network among all Spoke VPCs, which breaks enterprise security posture as different Spoke VPCs can be owned by different business units. With the Aviatrix solution no connectivity is established until you specify. **Highly Available** Built-in gateway redundancy supports hot standby and failover in seconds. **Scalable** There are no limits on the number of spoke VPCs can be connected to on-prem via hub VPC. Aviatrix Designated Gateway summarizes all routes. Gateways can scale-up, scale-down or scale-out with a few clicks. **Visibility** A central dashboard monitors, displays and alerts link status and link latency. **Additional Benefits** Stateful firewall at the gateway to enforce security policies. OpenVPN® based user access allows end to end cloud network solution. For more details, check out docs.aviatrix.com. OpenVPN is a registered trademark of OpenVPN Inc. .. |image0| image:: media/image1.png :width: 3.5in :height: 0.5in .. |image1| image:: media/Transit.png :scale: 100% .. |image2| image:: media/DocArchitecture.png :scale: 100% .. |image6| image:: media/image6.png :width: 7in :height: 4in :scale: 150% .. add in the disqus tag .. disqus:: <file_sep>## Solutions documents will be stored here These documents are more detailed and targetted solutions addressing particular use cases **Create a directory for each paper** <file_sep> ================================================ Customize AWS-IAM-Policy for Aviatrix Controller ================================================ Introduction ============ Aviatrix provides the `default Aviatrix-AWS-IAM-Policy <https://s3-us-west-2.amazonaws.com/aviatrix-download/IAM_access_policy_for_CloudN.txt>`__ for its solution. This document provides examples on how to customize these IAM policies. The customization reduces the scope of resource privileges and helps you meet your organization's security requirements. Please do understand that without the right access and permissions, Aviatrix Controller and Gateways will not be able to function as designed and any changes you might make could disrupt your network - **we strongly request you to test all changes, thoroughly, in your sandbox/preprod/test environment before you push them to your production environment**. Please open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_, if you have any questions or issues. You can remove some of the policy rules by using this `default IAM-Policy <https://s3-us-west-2.amazonaws.com/aviatrix-download/IAM_Policy_For_Peering.txt>`__ if you only plan on using the following Aviatrix features: 1. Gateway creation without ELB (Elastic Load Balancer) 2. Encrypted-Peering 3. Transitive-Peering 4. Peering-HA (High Ability) 5. Site2Cloud 6. Controller Backup & Restore .. Note:: Most features (such as VPN with ELB/NLB, etc.) are not stated above, we recommend using the default IAM policy to avoid some issues. .. .. Note:: Both the Aviatrix Controllers and the Aviatrix Gateways need access to the IAM policies. .. .. Note:: Ensure that IAM policies are consistent across all AWS accounts that the Controllers and Gateways are located in. .. | IAM Policies Required for Aviatrix Use Cases =========================================================== IAM Policy for Aviatrix Transit Gateway & VGW -------------------------------------------------------------- .. raw:: html <iframe src="https://s3-us-west-2.amazonaws.com/aviatrix-download/aviatrix-iam-policies/transit-network/aviatrix-iam-policy-for-aws-accounts-own-aviatrix-transit-gateways.txt" height="300px" width="100%"></iframe> | IAM Policy for Aviatrix Transit VPC Spoke Gateway ------------------------------------------------------------ .. raw:: html <iframe src="https://s3-us-west-2.amazonaws.com/aviatrix-download/aviatrix-iam-policies/transit-network/aviatrix-iam-policy-for-aws-accounts-own-aviatrix-spoke-gateways.txt" height="300px" width="100%"></iframe> The next few sections provide examples on how to restrict policy rule scopes. | When to Modify AWS-IAM-Policy (aviatrix-app-role-policy) ======================================================== Before customizing the AWS-IAM-Policy for the Aviatrix Controller, follow the steps below: 1. Use the original/default Aviatrix-AWS-IAM-Policy for every Aviatrix-Cloud-Account creation. The following screenshot is the account creation during the AVX Controller Onboarding process. |image0| 2. After account creation, as an administrator, you can start editing/customizing the AWS-IAM-Policy, "aviatrix-app-role-policy" from your AWS-IAM-Policy section to increase the security level of your AWS environment/resources. Please see the following for more reference. How to Modify AWS-IAM-Policy ============================ 1. Log in to your AWS console. |image1| 2. Go to IAM service. |image2| 3. Click **Policies** and select the policy. If you have not created "aviatrix-app-policy", please see `here <http://docs.aviatrix.com/HowTos/HowTo_IAM_role.html>`__. |image3| 4. Click **Edit Policy**. |image4| Now you are ready to edit the policy! Please refer to the examples later in this document. What Permissions are Required in App Role Policy and Why ======================================================== The App role policy (`example <https://s3-us-west-2.amazonaws.com/aviatrix-download/IAM_access_policy_for_CloudN.txt>`__), has different “Actions” to allow on certain resources. Your Aviatrix Controller needs those policies to function. a. ec2 – to create/delete/list/modify VPCs, Aviatrix Gateways, security groups, route tables, tags, start instance, stop instance, reboot instance, associate/de-associate IP address, etc. b. elasticloadbalancing – to create/configure/delete/modify ELB for Aviatrix VPN Gateway c. s3 – to create/add/delete s3 buckets for save-and-restore and cloudTrail features d. sqs – to create/delete/list/send/get SQS and SQS messages for Controller-to-gateway communication e. sns – to create/delete/list/subscribe/unsubscribe SNS and SNS topic for Gateway HA feature f. route53 – to create/delete/list hosted zone, and change the resource record for GeoVPN feature g. cloudwatch – to put/delete alarm for Aviatrix Gateway HA feature h. iam – to support role-based IAM account How to Reduce APP Role Policy ============================== 1. Default APP Role-Based Policy -------------------------------- Click `here <https://s3-us-west-2.amazonaws.com/aviatrix-download/IAM_access_policy_for_CloudN.txt>`__ to see a default APP role-based policy. In the default APP role-based policy, it allows actions to apply to all resource. By changing Resource field from a wildcard ‘*’ to a more specific resource ARN can limit the service the assumed role can do. The examples are described in the later sections. 2. Use Aviatrix Tags To Limit Resource Deleting Policy Scope ------------------------------------------------------------- The Aviatrix Controller automatically creates a tag when it creates resources, such as gateways, security groups and route entries. The tag has the syntax as follows: :: aviatrix tag key = "Aviatrix-Created-Resource" aviatrix tag value = "Do-Not-Delete-Aviatrix-Created-Resource" Click `here <https://s3-us-west-2.amazonaws.com/aviatrix-download/aviatrix_customized_IAM_app_policy.txt>`_ to download a complete IAM policy that reduces the IAM app policy for deleting instances. 3. Use Condition to Allow Service Requests from Certain IP Addresses -------------------------------------------------------------------- A user can add a “Condition” field to deny all requests not initiated from the Aviatrix Controller IP address or a range of CIDRs. The following policy only allows service requests from IP address 192.0.2.0/24, or 192.168.3.11/32, or 203.0.113.0/24. :: { "Version": "2012-10-17", "Statement": { "Effect": "Deny", "Action": [ "ec2:DescribeImageAttribute", "ec2:DescribeImages", : : "ec2:DescribeVpcPeeringConnections" ], "Resource": "*", "Condition": {"NotIpAddress": {"aws:SourceIp": [ "192.0.2.0/24", "192.168.3.11/32", "203.0.113.0/24" ]}} } } We can also use "Allow" instead of using "Deny" in the "Effect" element/key. Both ways have the same behavior. See the following: Syntax: ~~~~~~~ :: { "Effect": "Allow", "Action": [ "ec2:RunInstances" ], "Resource": "*", "Condition": { "IpAddress": { "aws:SourceIp": ["AVIATRIX-CONTROLLER-IP/32"] } } } Example: ~~~~~~~~ :: { "Effect": "Allow", "Action": [ "ec2:RunInstances" ], "Resource": "*", "Condition": { "IpAddress": { "aws:SourceIp": ["172.16.17.32/32"] } } } NOTE: ~~~~~ The method of specifying the IP address of AWS instance(s) can apply to many AWS-API permissions, such as: | "ec2:Describe*", | "elasticloadbalancing:Describe*", | "route53:List*", | "route53:Get*", | "sns:List*", | "s3:List*", | "s3:Get*", | etc... | not only for "ec2:RunInstances". 4. Launch Instances(Aviatrix-Gateway) on a Specific Subnet Only from the Aviatrix Controller ------------------------------------------------------------------------------------------------------------------- Syntax: ~~~~~~~~~ :: { "Effect": "Allow", "Action": "ec2:RunInstances", "Condition": { "IpAddress": { "aws:SourceIp": [ "AVIATRIX-CONTROLLER-IP/32" ] } }, "Resource": [ "arn:aws:ec2:*:*:image/ami-*", "arn:aws:ec2:REGION:AWS-ACCOUNT-ID:subnet/SUBNET-ID", "arn:aws:ec2:REGION:AWS-ACCOUNT-ID:instance/*", "arn:aws:ec2:REGION:AWS-ACCOUNT-ID:network-interface/*", "arn:aws:ec2:REGION:AWS-ACCOUNT-ID:volume/*", "arn:aws:ec2:REGION:AWS-ACCOUNT-ID:key-pair/*", "arn:aws:ec2:REGION:AWS-ACCOUNT-ID:security-group/*" ] } Example: ~~~~~~~~ :: { "Effect": "Allow", "Action": "ec2:RunInstances", "Condition": { "IpAddress": { "aws:SourceIp": [ "172.16.17.32/32" ] } }, "Resource": [ "arn:aws:ec2:*:*:image/ami-*", "arn:aws:ec2:us-west-2:888888888888:subnet/subnet-abcd1234", "arn:aws:ec2:us-west-2:888888888888:instance/*", "arn:aws:ec2:us-west-2:888888888888:network-interface/*", "arn:aws:ec2:us-west-2:888888888888:volume/*", "arn:aws:ec2:us-west-2:888888888888:key-pair/*", "arn:aws:ec2:us-west-2:888888888888:security-group/*" ] } 5. Launching Instances on Specific VPC(s) ----------------------------------------- The policy can be modified to limit running gateways on certain VPCs only. In the following examples, we limit the role to launch an Aviatrix Gateway on AWS account 177688881379, region us-west-2, and vpc-873db7e2 and vpc-fda23c98. Note: we can use wildcard “*” to replace region, account number, or VPC ID. :: { "Effect": "Allow", "Action": [ "ec2:RunInstances" ], "Resource": "arn:aws:ec2:us-west-2:177658351379:subnet/*", "Condition": { "StringEqualsIgnoreCase": { "ec2:vpc": [ "arn:aws:ec2:us-west-2:177688881379:vpc/vpc-873db7e2", "arn:aws:ec2:us-west-2:177688881379:vpc/vpc-fda23c98" ] } } }, { "Effect": "Allow", "Action": "ec2:RunInstances", "Resource": "arn:aws:ec2:*:*:image/ami-*" }, { "Effect": "Allow", "Action": "ec2:RunInstances", "Resource": [ "arn:aws:ec2:*:*:instance/*", "arn:aws:ec2:*:*:volume/*", "arn:aws:ec2:*:*:network-interface/*", "arn:aws:ec2:*:*:key-pair/*", "arn:aws:ec2:*:*:security-group/*" ] } Syntax ~~~~~~ :: { "Effect": "Allow", "Action": "ec2:RunInstances", "Resource": "arn:aws:ec2:REGION:AWS-ACCOUNT-ID:subnet/subnet-*", "Condition": { "StringEquals": { "ec2:Vpc": [ "arn:aws:ec2:REGION:AWS-ACCOUNT-ID:vpc/vpc-abcd1234" ] }, "IpAddress": { "aws:SourceIp": [ "172.16.17.32/32" ] } } }, { "Effect": "Allow", "Action": "ec2:RunInstances", "Resource": [ "arn:aws:ec2:*:*:image/ami-*", "arn:aws:ec2:REGION:AWS-ACCOUNT-ID:instance/*", "arn:aws:ec2:REGION:AWS-ACCOUNT-ID:network-interface/*", "arn:aws:ec2:REGION:AWS-ACCOUNT-ID:volume/*", "arn:aws:ec2:REGION:AWS-ACCOUNT-ID:key-pair/*", "arn:aws:ec2:REGION:AWS-ACCOUNT-ID:security-group/*" ] } Example ~~~~~~~ :: { "Effect": "Allow", "Action": "ec2:RunInstances", "Resource": "arn:aws:ec2:us-west-2:888888888888:subnet/subnet-*", "Condition": { "StringEquals": { "ec2:Vpc": [ "arn:aws:ec2:us-west-2:888888888888:vpc/vpc-abcd1234" ] }, "IpAddress": { "aws:SourceIp": [ "172.16.17.32/32" ] } } }, { "Effect": "Allow", "Action": "ec2:RunInstances", "Resource": [ "arn:aws:ec2:*:*:image/ami-*", "arn:aws:ec2:us-west-2:888888888888:instance/*", "arn:aws:ec2:us-west-2:888888888888:network-interface/*", "arn:aws:ec2:us-west-2:888888888888:volume/*", "arn:aws:ec2:us-west-2:888888888888:key-pair/*", "arn:aws:ec2:us-west-2:888888888888:security-group/*" ] } 6. AWS S3 Permissions/Policies --------------------------------------------- The following S3 IAM-Policy examples demonstrate allowing an AWS API to write/PutObject AVX-Controller-Backup configuration file to a specified AWS-S3-Bucket. The command is issued only by your AVX Controller. Syntax: ~~~~~~~ :: { "Effect": "Allow", "Action": [ "s3:List*" ], "Resource": "arn:aws:s3:::*", "Condition": { "IpAddress": { "aws:SourceIp": [ "AVIATRIX-CONTROLLER-IP-ADDRESS/32" ] } } }, { "Effect": "Allow", "Action": [ "s3:CreateBucket", "s3:DeleteBucket" ], "Resource": "arn:aws:s3:::*aviatrix*", "Condition": { "IpAddress": { "aws:SourceIp": [ "AVIATRIX-CONTROLLER-IP-ADDRESS/32" ] } } }, { "Effect": "Allow", "Action": [ "s3:PutObject" ], "Resource": "arn:aws:s3:::YOUR-S3-BUCKET-NAME/*", "Condition": { "IpAddress": { "aws:SourceIp": [ "AVIATRIX-CONTROLLER-IP-ADDRESS/32" ] } } }, { "Effect": "Allow", "Action": [ "s3:Get*" ], "Resource": "arn:aws:s3:::YOUR-S3-BUCKET-NAME*", "Condition": { "IpAddress": { "aws:SourceIp": [ "AVIATRIX-CONTROLLER-IP-ADDRESS/32" ] } } } Example: ~~~~~~~~ :: { "Effect": "Allow", "Action":[ "s3:List*" ], "Resource": "arn:aws:s3:::*", "Condition": { "IpAddress": { "aws:SourceIp": [ "172.16.17.32/32" ] } } }, { "Effect": "Allow", "Action": [ "s3:CreateBucket", "s3:DeleteBucket" ], "Resource": "arn:aws:s3:::*aviatrix*/*" "Condition": { "IpAddress": { "aws:SourceIp": [ "172.16.17.32/32" ] } } }, { "Effect": "Allow", "Action": [ "s3:PutObject" ], "Resource": "arn:aws:s3:::*aviatrix*/*" "Condition": { "IpAddress": { "aws:SourceIp": [ "172.16.17.32/32" ] } } }, { "Effect": "Allow", "Action": [ "s3:Get*" ], "Resource": "arn:aws:s3:::*aviatrix*", "Condition": { "IpAddress": { "aws:SourceIp": [ "172.16.17.32/32" ] } } } 7. AWS-Simple-Queue Permissions/Policies --------------------------------------------------------- The following example(s) demonstrate allowing the IAM User/Role to access AWS-Simple-Queue object(s) only to the queues with names starting with the string "aviatrix". Syntax: ~~~~~~~ :: { "Effect": "Allow", "Action": [ "sqs:List*", "sqs:Get*", ], "Resource": "arn:aws:sqs:*:AWS-Account-ID:aviatrix-*" }, { "Effect": "Allow", "Action": [ "sqs:AddPermission", "sqs:ChangeMessageVisibility", "sqs:CreateQueue", "sqs:DeleteMessage", "sqs:DeleteQueue", "sqs:PurgeQueue", "sqs:ReceiveMessage", "sqs:RemovePermission", "sqs:SendMessage", "sqs:SetQueueAttributes" ], "Resource": "arn:aws:sqs:*:AWS-Account-ID:aviatrix-*" } Example: ~~~~~~~~ :: { "Effect": "Allow", "Action":[ "sqs:List*", "sqs:Get*", ], "Resource": "arn:aws:sqs:*:888888666666:aviatrix-*" }, { "Effect": "Allow", "Action":[ "sqs:AddPermission", "sqs:ChangeMessageVisibility", "sqs:CreateQueue", "sqs:DeleteMessage", "sqs:DeleteQueue", "sqs:PurgeQueue", "sqs:ReceiveMessage", "sqs:RemovePermission", "sqs:SendMessage", "sqs:SetQueueAttributes" ], "Resource": "arn:aws:sqs:*:888888666666:aviatrix-*" } .. Warning:: We do not recommend using the AWS-resource-IP checking mechanism to modify AWS-SQS API permissions. .. 8. Restricting Operations Using the AWS Resource Tag -------------------------------------------------------------------- The following example(s) demonstrate using IAM Policy to limit IAM user/role to be able to operate only on instances that have a customized AWS Resource Tag. Syntax: ~~~~~~~ :: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "ec2:StartInstances", "ec2:StopInstances", "ec2:TerminateInstances" ], "Resource": "*", "Condition": { "StringEqualsIgnoreCase": { "ec2:ResourceTag/KEY_OF_RESOURCE_TAG": "VALUE_OF_RESOURCE_TAG" } } } ] } Example: ~~~~~~~~ :: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "ec2:StartInstances", "ec2:StopInstances", "ec2:TerminateInstances" ], "Resource": "*", "Condition": { "StringEqualsIgnoreCase": { "ec2:ResourceTag/Aviatrix-Created-Resource": "*Do-Not-Delete*" } } } ] } EC2 Role Policy Examples ======================== 1. Default EC2 Role Policy ---------------------------------- The Amazon EC2 role allows EC2 instances to call AWS services on your behalf. This policy allows action “AssumeRole” to ALL roles. The default EC2 role policy allows an AWS EC2 instance to assume to any role. By changing the “Resource” field from a wildcard * to a more specific account number, the role name or prefix of the role name can limit the EC2 instance’s role. :: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "sts:AssumeRole" ], "Resource": "arn:aws:iam::*:role/aviatrix-*" }, { "Effect": "Allow", "Action": [ "aws-marketplace:MeterUsage" ], "Resource": "*" } ] } 2: Example of EC2 Role Policy with More Specific Resource Field -------------------------------------------------------------------------------- The policy attached to the Amazon EC2 role can limit the role it can assume by specifying the 12-digit AWS account number, role name, or prefix of the role name. In this example, the EC2 instance can assume role to any 12-digit AWS account with role name prefix “HR-", or AWS account number 177658388888 with role name prefix “aviatrix-", or AWS account number 188658399999, role name developer. :: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "sts:AssumeRole" ], "Resource": [ "arn:aws:iam::177658388888:role/aviatrix-*", "arn:aws:iam::*:role/aviatrix-role-app", "arn:aws:iam::*:role/HR-*", "arn:aws:iam::188658399999:role/developer" ] } ] } NOTE: Please refer to the policy example below. Aviatrix recommends our customers to add the ARN (Amazon Resource Name) of your APP-Role (aviatrix-role-app) into the "Resource" section. However, we do not recommend specifying any IP addresses such as your Aviatrix-Controller or Aviatrix-Gateway instances under the Condition section in order to avoid further unexpected issues. The best practice to specify which of your AWS instances are allowed to operate your AWS resources is to modify the APP-Role (aviatrix-role-app). Please see the examples under the `"APP Role Examples" <https://docs.aviatrix.com/HowTos/customize_aws_iam_policy.html#when-to-modify-aws-iam-policy-aviatrix-app-role-policy>`_ section of this document. Recommended: :: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "sts:AssumeRole" ], "Resource": ["arn:aws:iam::188658399999:role/aviatrix-role-app"] } ] } Not Recommended: :: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "sts:AssumeRole" ], "Condition": { "IpAddress": { "aws:SourceIp": ["172.16.31.10/32"] } }, "Resource": ["arn:aws:iam::188658399999:role/aviatrix-role-app"] } ] } .. |image0| image:: customize_aws_iam_policy_media/image1.png :width: 4.90061in :height: 2.74528in .. |image1| image:: customize_aws_iam_policy_media/image2.png :width: 3.42946in :height: 2.39623in .. |image2| image:: customize_aws_iam_policy_media/image3.png :width: 5.23044in :height: 3.58491in .. |image3| image:: customize_aws_iam_policy_media/image4.png :width: 5.13900in :height: 3.28302in .. |image4| image:: customize_aws_iam_policy_media/image5.png :width: 6.11245in :height: 3.92453in .. disqus:: <file_sep> ================== Aviatrix Secure Edge FAQ ================== What is Aviatrix Secure Edge? ---------------------- The Aviatrix Secure Edge solution enables enterprises to extend the Cloud operational model to the edge network for consistent and repeatable architecture, management, visibility, security, and control. This cloud-out architecture enables enterprises to leverage the Aviatrix platform ubiquitous support for edge connectivity. The result is secure, seamless connectivity to edge locations such as data centers, co-locations, remote sites, provider locations, branch offices, and retail stores. Benefits of the Aviatrix Secure Edge solution include: - Go-to platform for all hybrid connectivity - Centralized Control Plane across multi-cloud networks and edge locations resulting in reduced hardware and operating costs - Single pane of glass for visibility, monitoring, and troubleshooting from Aviatrix Controller and Aviatrix CoPilot - Encrypted connectivity and routing between multi-cloud networks with a private path that uses standard architecture - High Performance Encryption (HPE) support over public and private networks - Zero-touch provisioning (ZTP) for automated Edge deployments - Available in multiple form factors to support various edge requirements Aviatrix Secure Edge solution is offered in VMware ESXi and KVM form factors that lets you deploy an Edge Gateway with spoke gateway capabilities at the edge network. Aviatrix Secure Edge features include: - High-availability active-active and active-standby mode for Edge Gateways at the same site location - High Performance Encryption over private and public network for AWS, Azure, OCI and over private network for GCP - Non-HPE over private and public network on Edge to Transit Gateway connection - Custom SNAT and DNAT (A/S) on Edge to Transit Gateway connection - Network Segmentation - Transitive Routing - FireNet traffic inspection Aviatrix Secure Edge is supported on Aviatrix Controller version 6.8 onwards. For more information about Aviatrix Secure Edge use case scenarios, see `What are the use cases for Aviatrix Secure Edge?`_. For additional requirements and deployment workflow, see `Deploying Aviatrix Secure Edge <http://docs.aviatrix.com/HowTos/edge-2.0-workflow.html>`_. What are the use cases for Aviatrix Secure Edge? ------------------------------------------------ The following are examples of Aviatrix Edge use cases. - `Extend Aviatrix Cloud Networking to Edge Locations`_ - `Multi-Cloud Connectivity Using Aviatrix Secure Edge`_ - `Aviatrix Secure Edge Connectivity over Private Network`_ - `Aviatrix Secure Edge Connectivity over Public Network`_ Extend Aviatrix Cloud Networking to Edge Locations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This diagram illustrates Aviatrix Edge Gateways deployed at multiple edge locations. |edge_usecase_edge_location| Multi-Cloud Connectivity Using Aviatrix Secure Edge ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This diagram illustrates Aviatrix Edge Gateway deployed as the primary path for the multi-cloud connectivity and transit peering over the Internet for the backup path. |edge_usecase_multi_cloud| Aviatrix Secure Edge Connectivity over Private Network ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This diagram illustrates Aviatrix Edge Gateway deployed in a private network. |edge_private_network| Aviatrix Secure Edge Connectivity over Public Network ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This diagram illustrates Aviatrix Edge Gateway deployed in a public network. |edge_public_network| .. |edge_usecase_edge_location| image:: CloudN_workflow_media/edge_usecase_edge_location.png :scale: 50% .. |edge_usecase_multi_cloud| image:: CloudN_workflow_media/edge_usecase_multi_cloud.png :scale: 40% .. |edge_private_network| image:: CloudN_workflow_media/edge_private_network.png :scale: 50% .. |edge_public_network| image:: CloudN_workflow_media/edge_public_network.png :scale: 50% .. disqus:: <file_sep> ======================================= Setting up Okta SAML with Profile Attribute ======================================= This guide demonstrates the use of the **Profile** attribute in **Okta** so each SAML user can be assigned a different VPN profile. How a VPN Profile Works ----------------------------------------- The VPN profiles defined at the **Controller/OpenVPN/Profiles** contain an egress control policy. They are attached to the VPN users defined at **Controller/OpenVPN/VPN Users** for controlling their VPN egress traffic. Users without a profile is the same as having a profile with an **allow-all** policy, i.e., their egress traffic are unrestricted. For SAML VPN, the SAML user definition at the IDP has a **Profile** attribute for specifying a VPN profile, overriding the corresponding user's VPN profile assigned at the Controller. If unspecified, the corresponding VPN profile assigned at the Controller will be used. .. _okta_setup: Setting up the Okta Profile Attribute -------------------------------------------------- #. `Define a new attribute <#okta-new-attribute>`__ in the Okta User template for storing the VPN profile name. #. `Define an attribute mapping <#okta-map-attribute>`__ for the new attribute using the name **Profile** so that the SAML application knows how to compose the **Profile** information in the SAML response. #. `Assign VPN profile <#okta-fill-attribute>`__ to each SAML user. #. `Validate <#okta-validation>`__ the setup. .. _okta_new_attribute: Defining a New Attribute -------------------------------- At Okta, define a new attribute in the **User** definition template using **Okta/Directory/Profile Editor**. In this example, the new attribute is named **accessprofile** and it can store a string of up to 20 characters. 1. Open Profile Editor at **Okta/Directory/Profile Editor**. |open_profile_editor| 2. Click **Okta** on the left navigation bar to find the **User** definition template and click **Profile** to open. |open_user_template| 3. Click **Add Attribute** to add a new attribute in the user template. |profile_editor_add| 4. Define a string attribute with a name; in this example, we use **accessprofile**. |add_profile_attribute_to_user_template| .. _okta_map_attribute: Defining an Attribute Mapping ----------------------------------------- In the SAML application (**Okta/Applications/<your-vpn-saml-app>/General/SAML Settings/Edit**), define a mapping for the new attribute (e.g., **accessprofile**) using the name **Profile**. Note that the name **Profile** is required to be an exact match and the new attribute name is pre-qualified with the keyword **user** for referencing a property in the user template. |add_profile_attribute_to_app| .. _okta_fill_attribute: Assigning the VPN Profile to Each SAML User --------------------------------------------------------- For each SAML application user, edit the user record in the Okta directory for assigning the VPN profile (**Okta/Directory/People/<your-user>/Profile/Edit**). In this example, the VPN profile defined at the Controller is named **access-profile**. Currently, only one profile is allowed per SAML user. |add_profile_attribute_to_user| .. _okta_validation: Validation ------------------- The following example illustrates the use of the SAML user's **Profile** attribute explained in previous sections: * It uses an Aviatrix VPN Gateway that has **certificate sharing** enabled. That is, only one VPN user is created at the Aviatrix VPN Gateway. The corresponding **ovpn** file will be shared by all SAML VPN users defined in Okta. * Two VPN profiles are created: The **default-profile** contains a base deny-all policy and is attached to the VPN user, stopping all VPN egress traffic by default. The **access-profile** contains the desired egress-traffic-allow policies. As a result, only the SAML users who have his/her **Profile** attribute set to **access-profile** will have the right VPN access while others will be restricted by the **default-profile**. * For testing purposes, create two SAML users in Okta, respectively, with and without setting the **Profile** attribute to **access-profile**. Verify their VPN connection by checking the displayed profile of their VPN sessions at **Controller/Dashboard**. Here are the steps for setting up the example: #. Follow the guide `OpenVPN® with SAML Authentication on Okta IDP <https://docs.aviatrix.com/HowTos/UserSSL_VPN_Okta_SAML_Config.html>`__ to configure the Controller to authenticate against the Okta IDP. The Aviatrix SAML Endpoint in this example is named vpn-5-1-okta (**Controller/OpenVPN/Advanced/SAML**): |vpn-5-1-okta| #. Enable certificate sharing and split tunnel (**Controller/OpenVPN/Edit Config/<your-vpn-gw>**): |cert-sharing| #. Create a **default-profile** with base deny-all policy (**Controller/OpenVPN/Profiles/Add new**). This default-profile will be attached to the VPN user, i.e., no egress traffic is allowed by default. |default-profile| #. Create a second profile the **access-profile** with base deny-all policy and subsequently edit it to add the allowed egress traffic (**Controller/OpenVPN/Profiles/<access-profile>/Edit**). This VPN profile will be assigned to the SAML User at the Okta IDP. For the purpose of this test, it can contain any dummy policy: |access-profile| #. Create one VPN user with the **default-profile** at the Aviatrix VPN Gateway (**Controller/OpenVPN/VPN Users/Add new**): |vpn-user| #. Download the **ovpn** file of the VPN user just created and load it into the Aviatrix VPN client. |download-cert| #. Create two users in Okta (**Okta/Directory/People/Add Person**). For ease of identification, user1 is given an email address at gmail.com and user2 at yahoo.com. |add-person| #. Assign the SAML VPN application to the two users in Okta (**Okta/Directory/People/<your-saml-user>/Applications/Assign Applications**). In this example, **vpn-5-1** is our VPN SAML application. |assign-app| #. Follow Steps 1 and 2 in `Setup Okta Profile attribute <#okta-setup>`__ to define the **Profile** attribute in Okta. #. Follow `Assign VPN profile <#okta-fill-attribute>`__ to set user1's **Profile** attribute to **access-profile**. #. From the Aviatrix VPN client, make a VPN connection using user1 Okta credential and observe the result at **Controller/Dashboard**. Repeat the same for user2. The following screenshots show the results. * User1 (gmail.com) with **Profile** attribute set to **access-profile**: |browser_user_with_profile| |dashboard_user_with_profile| * User2 (yahoo.com) without setting the **Profile** attribute: |browser_user_without_profile| |dashboard_user_without_profile| .. |open_profile_editor| image:: Setup_Okta_SAML_Profile_Attribute_media/open_profile_editor.png :scale: 70% .. |open_user_template| image:: Setup_Okta_SAML_Profile_Attribute_media/open_user_template.png :scale: 70% .. |profile_editor_add| image:: Setup_Okta_SAML_Profile_Attribute_media/profile_editor_add.png :scale: 70% .. |add_profile_attribute_to_user_template| image:: Setup_Okta_SAML_Profile_Attribute_media/add_profile_attribute_to_user_template.png :scale: 70% .. |add_profile_attribute_to_app| image:: Setup_Okta_SAML_Profile_Attribute_media/add_profile_attribute_to_app.png :scale: 70% .. |add_profile_attribute_to_user| image:: Setup_Okta_SAML_Profile_Attribute_media/add_profile_attribute_to_user.png :scale: 70% .. |dashboard_user_with_profile| image:: Setup_Okta_SAML_Profile_Attribute_media/dashboard_user_with_profile.png :scale: 70% .. |browser_user_with_profile| image:: Setup_Okta_SAML_Profile_Attribute_media/browser_user_with_profile.png :scale: 70% .. |dashboard_user_without_profile| image:: Setup_Okta_SAML_Profile_Attribute_media/dashboard_user_without_profile.png :scale: 70% .. |browser_user_without_profile| image:: Setup_Okta_SAML_Profile_Attribute_media/browser_user_without_profile.png :scale: 70% .. |vpn-5-1-okta| image:: Setup_Okta_SAML_Profile_Attribute_media/vpn-5-1-okta.png :scale: 70% .. |cert-sharing| image:: Setup_Okta_SAML_Profile_Attribute_media/cert-sharing.png :scale: 70% .. |default-profile| image:: Setup_Okta_SAML_Profile_Attribute_media/default-profile.png :scale: 70% .. |access-profile| image:: Setup_Okta_SAML_Profile_Attribute_media/access-profile.png :scale: 70% .. |vpn-user| image:: Setup_Okta_SAML_Profile_Attribute_media/vpn-user.png :scale: 70% .. |download-cert| image:: Setup_Okta_SAML_Profile_Attribute_media/download-ovpn.png :scale: 70% .. |add-person| image:: Setup_Okta_SAML_Profile_Attribute_media/add-person.png :scale: 70% .. |assign-app| image:: Setup_Okta_SAML_Profile_Attribute_media/assign-app.png :scale: 70% .. disqus:: <file_sep> .. raw:: html <style> /* override table no-wrap */ .wy-table-responsive table td, .wy-table-responsive table th { white-space: normal !important; } </style> ============================================= Duo Authentication ============================================= The Aviatrix OpenVPN® solution provides Duo authentication integration. This document helps you set up Duo to connect with Aviatrix. For more information on how to configure OpenVPN®, check out `this link <http://docs.aviatrix.com/HowTos/uservpn.html>`_. You need to first have a Duo account setup. If you do not have one, please see `https://www.duosecurity.com/product <http://www.duosecurity.com/product>`__. Getting Duo API Credentials --------------------------------------- .. important:: This step requires admin privileges in Duo. You must first add an application to Duo for Aviatrix before you can connect. If you already have already completed this step, these same steps will take you to the API credentials needed to connect Aviatrix with this application. #. Log in to the Duo Admin Panel. #. Navigate to **Applications**. #. Click **Protect an Application**. #. Search for "OpenVPN" in the application list. #. Click **Protect this Application**. #. The Integration key, Secret key and API hostname are displayed. .. note:: You will need these values in Aviatrix to connect Aviatrix client to Duo. |imageDuoAppDetails| #. (optional) Update the Settings fields as required. #. (optional) Click **Save Changes**. .. note:: You may need to adjust policies to allow this application to be visible to your users. Connecting Aviatrix VPN with Duo ------------------------------------------------- .. note:: You can set up Duo at both Aviatrix VPN Gateway launch time and after Aviatrix VPN Gateway is launched. We highly recommend you configure Duo after the VPN Gateway is launched. #. Follow the `steps to create <uservpn.html#create-a-vpn-gateway>`__ a new Aviatrix Gateway. #. After the gateway is launched, in your Aviatrix Controller, go to OpenVPN® > Edit Config > Modify Authentication. Select Duo at the dropdown menu. #. Populate **Integration Key**, **Secret Key**, and **API Hostname** from the values provided by Duo application details. #. Update the **Push Mode**. +---------------------------+-----------------------------------------------+ | Push Mode | Description | +===========================+===============================================+ | Auto | Duo sends a push notification to the user's | | | mobile device(s). The VPN client will wait | | | for the user to accept this request before | | | authenticating and proceeding. | +---------------------------+-----------------------------------------------+ | Selective | This setting allows users to control which | | | method they would prefer to use for | | | authentication. | | | The server supports either Duo Push or | | | Duo Passcode. | | | The password prompt field of the VPN client | | | is used to indicate which method is requested:| | | | | | o A value of ``#push`` indicates the user | | | requests to receive a push notification. | | | | | | o A value of ``#<passcode>`` indicates the | | | user is providing the token after the ``#`` | | | to authorize. | | | | | | | | | .. note:: | | | The ``#`` is required. If you are also | | | connecting with LDAP, then the user's LDAP | | | password should be provided before the #. | +---------------------------+-----------------------------------------------+ | Token | The user must enter the current Duo Passcode | | | in the password field when prompted by the | | | VPN client. If the client prompts for a | | | username, any value is acceptable. | +---------------------------+-----------------------------------------------+ #. Click **Modify** to have the action take effect. |imageAviatrixDuo| Validating ----------------- You will need one Aviatrix VPN user to test. Validate that a VPN user is able to connect after receiving the push notification (or after entering a valid Passcode). Using **Push Mode** of ``auto`` +++++++++++++++++++++++++++++++ 1. Connect your VPN client to the VPN Gateway. .. note:: You should receive a push notification from Duo. 2. Open the Duo Mobile app and select **Confirm** for the pending request. .. note:: Once you confirm the request, the VPN client should proceed to authenticate the user. 3. Verify you are connected and can access resources in the cloud. Using **Push Mode** of ``token`` ++++++++++++++++++++++++++++++++ #. Connect your VPN client to the VPN Gateway. .. note:: You should receive a prompt to authenticate. If you do not receive a prompt, make sure ``auth-user-pass`` option is in the .ovpn configuration file. #. Open the Duo Mobile app and generate a new passcode. #. In the VPN user/password prompt, enter any value for the username field and enter the passcode from Duo Mobile app for the password. #. Verify you are connected and can access resources in the cloud. #. Note that you need to generate a new passcode for each connection. Currently, selective authentication with Duo is broken if used when combined with LDAP. This bug is expected to be fixed in a later release. OpenVPN is a registered trademark of OpenVPN Inc. .. |imageDuoAppDetails| image:: Duo_media/duo_add_app_details.png .. |imageAviatrixDuo| image:: Duo_media/aviatrix_configure_duo.png .. disqus:: <file_sep> =========================================== Google Startup Guide =========================================== The Aviatrix cloud network solution consists of two components, the Controller and Gateway, both of which are GCloud instances. The gateway is launched from the Controller browser console. This guide helps you to launch the Controller instance in GCloud: * `Prerequisites <https://docs.aviatrix.com/StartUpGuides/google-aviatrix-cloud-controller-startup-guide.html#id1>`_ * `Launching the Aviatrix Controller <https://docs.aviatrix.com/StartUpGuides/google-aviatrix-cloud-controller-startup-guide.html#option-1-copy-aviatrix-controller-image-to-your-project>`_ * `Accessing the Aviatrix Controller <https://docs.aviatrix.com/StartUpGuides/google-aviatrix-cloud-controller-startup-guide.html#id2>`_ * `Onboarding Your GCP Account to your Aviatrix Controller <https://docs.aviatrix.com/StartUpGuides/google-aviatrix-cloud-controller-startup-guide.html#id3>`_ Note that a GCloud project corresponds to an Aviatrix cloud account or an AWS (IAM) account with its own credentials. A network in a GCloud project is logically equivalent to a VPC in AWS, but with a few significant differences. For example, a network in GCloud project can have disparate subnets and a subnet can connect across regions. .. Important:: The Aviatrix Controller is a secure multi-cloud networking platform. Aviatrix recommends you deploy your Controller in clouds that offer metered pricing, then deploy your gateways in any supported cloud. Metered pricing offers you a true pay-as-you-go option without any up-front commitments or contract negotiations. The AWS and Azure clouds offer metered pricing for running the Aviatrix Controller image. The GCP and OCI clouds do not offer metered pricing for running the Aviatrix Controller image. Prerequisites ============ Get a Customer ID from Aviatrix ------------------------------- Currently, the Aviatrix Controller for GCloud is only available via community image for BYOL license. Send an email to <EMAIL> or open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_ with your organization name to request a customer ID. We offer a 30-day free trial license. Creating a Google Cloud Platform (GCloud) Account -------------------------------------------------------------- Aviatrix Cloud Connect is a software product that is launched in your own GCloud account. The Controller and the Gateways created from the Controller console are all in your own network perimeter and completely under your control. Create a GCloud account (https://cloud.google.com/). Go on to the next step if you have already done so. Note that the Controller supports multiple accounts with each one associated with a different GCloud projects, but there needs to be at least one to start with. Creating a GCloud Project -------------------------------------- Log in to your GCloud account and go to the project page: https://console.cloud.google.com/project Create a project. Go on to the next step if you have already created one. Note that the project ID will be used in referencing to this project by Aviatrix Controller. (As an example, we created a project called Aviatrix-UCC, the project ID is aviatrix-ucc-1214.) (Optional) Creating Networks ------------------------------------------ This step creates a network in the project created in the previous step. When a new project is created, a default network is created. You may skip this step if you do not need to customize the network address range by creating a new network, or go on to the next step if you have done so. Note that the Aviatrix Controller handles a GCloud network like a VPC in AWS. Whenever a network configuration is mentioned for GCloud, the term VPC is used. (The VNet is used for Azure.) At GCloud console, select the project that you have copied the Aviatrix Controller image to. Click the 3 bars. At the dropdown menu, select Networking. Click “[+] Create Network”. Note: if you plan to have multiple projects, we suggest you plan your subnets so that the network addresses do not overlap. Select Custom to create subnets. Deploying the Aviatrix Controller in GCP Marketplace (Preview mode) ======================================================================= 1. Go to the GCP marketplace. 2. Find the product "Aviatrix Secured Networking Platform - BYOL". 3. Click **LAUNCH**. |gcp_controller_gcp_marketplace_01| 4. Make sure the selected Machine type has at least 2 vCPUs with 8 GB memory. 5. Boot Disk is SSD Persistent Disk with 32 GB. |gcp_controller_gcp_marketplace_02| .. Important:: Do not check the **Firewall** box to **Allow HTTPS Traffic**. Aviatrix recommends you improve security by removing any 0.0.0.0 entries on port 443 not allowing the Aviatrix Controller to the world. 6. Click **DEPLOY**. Accessing the Aviatrix Controller ============================== After the instance is created, click the Controller instance name, and note its External IP address and Internal IP address. Go to https://External_IP_of_the_controller. At the login prompt, type "admin" for username and type the internal IP address for the password, as shown below: |image3| Follow the initial setup process to set up an admin email address and password and install the latest software. Log in again with your new admin password. .. Warning:: Any resources created by the controller, such as Aviatrix gateways, GCP routing tables, subnets, LB, etc., must be deleted from the controller console. If you delete them directly on AWS console, the Controller's view of resources will be incorrect, which will lead to features not working properly. .. Note:: Upgrade from 5.3 to 5.4 is not supported Controller needs to be migrated. Look at the GCP controller migration section in the below link. https://docs.aviatrix.com/HowTos/controller_migration.html Onboarding Your GCP Account to Your Aviatrix Controller =============================================== If no GCloud account has been set up, you will be guided through the onboarding process. It takes only a few steps. Once that is done, follow the quick tour guide to start launching gateways. For onboarding instructions on GCloud, click `this link. <http://docs.aviatrix.com/HowTos/CreateGCloudAccount.html>`_ Resource Names =============== The maximum length of a gateway cannot exceed 50 characters when configuring Aviatrix Google Cloud gateway. Other resource names like subnet and VPC have a maximum character limit of 63, a requirement for Google Cloud. Launching Gateway ================= The following gateway sizes are supported for GCloud: 'n1-standard-1','n1-highcpu-2', 'n1-standard-2', 'n1-highmem-2', 'n1-highcpu-4', 'n1-standard-4', 'n1-highmem-4', 'n1-highcpu-8', 'n1-standard-8','n1-highmem-8', 'n1-highcpu-16', 'n1-standard-16', 'n1-highmem-16','n1-highcpu-32', 'n1-standard-32', 'n1-highmem-32' Support ======= Check out the Help menu for Frequently Asked Questions (FAQs), Reference Design and Release Notes. All features have descriptions embedded and should be self-explanatory. An alert message will be displayed on the Dashboard menu when a new release becomes available. For support, please open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_. Enjoy! .. |gcp_controller_gcp_marketplace_01| image:: GoogleAviatrixCloudControllerStartupGuide_media/gcp_controller_gcp_marketplace_01.png :scale: 35% .. |gcp_controller_gcp_marketplace_02| image:: GoogleAviatrixCloudControllerStartupGuide_media/gcp_controller_gcp_marketplace_02.png :scale: 35% .. |gcp_controller_gcp_marketplace_03| image:: GoogleAviatrixCloudControllerStartupGuide_media/gcp_controller_gcp_marketplace_03.png :scale: 35% .. |image0| image:: GoogleAviatrixCloudControllerStartupGuide_media/image001.png :width: 2.90683in :height: 0.35000in .. |image1| image:: GoogleAviatrixCloudControllerStartupGuide_media/image002.png :width: 5.65559in :height: 2.77402in .. |image2| image:: GoogleAviatrixCloudControllerStartupGuide_media/image003.png :width: 5.50432in :height: 3.49607in .. |image3| image:: GoogleAviatrixCloudControllerStartupGuide_media/image004.png :width: 4.93125in :height: 2.10210in .. add in the disqus tag .. disqus:: <file_sep> ================================= Amazon GuardDuty Integration ================================= The Aviatrix Controller integrates with `Amazon GuardDuty <https://aws.amazon.com/guardduty/>`__ to provide you the IDS protection on a per account and region basis. Amazon GuardDuty continuously monitors an account's AWS environment and reports findings. GuardDuty sifts through CloudTrail logs, VPC Flow logs, and DNS logs to assess risk and generate findings. To learn more about GuardDuty, read `Amazon GuardDuty FAQ <https://aws.amazon.com/guardduty/faqs/>`__. .. note:: While there are no additional Aviatrix charges to use this feature, there are AWS charges associated with using Amazon GuardDuty. For more information, see `Amazon GuardDuty Pricing <https://aws.amazon.com/guardduty/pricing/>`__. Configuration ----------------------- To enable GuardDuty Integration, log in to the Aviatrix Controller and follow these steps: .. note:: Additional permissions must be granted in the **aviatrix-app-policy** IAM policy for each account where this feature is enabled. You may need to `update IAM policies <iam_policies.html>`__ prior to enabling this feature. #. Go to **Security** > **AWS GuardDuty**. #. Click **+ New**. #. Select the **Account Name** of the AWS account where you would like to enable GuardDuty integration. #. Select the **AWS Region**. #. Click **Enable**. |guardduty_config| .. note:: If you have already enabled GuardDuty on AWS Console, the Controller will detect, pull the information, and proceed. Integration and Enforcements ------------------------------- The Aviatrix Controller provides additional monitoring, logging and enforcement services when you enable Amazon GuardDuty from the Aviatrix Controller Console, as listed below. - Aviatrix Controller periodically polls Amazon `GuardDuty findings <https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-active.html>`_. The polling time is configurable between 5 minutes to 60 minutes. - Findings from Amazon GuardDuty are `logged <AviatrixLogging.html#id13>`__ to the Controller syslog. (Syslog can be exported to `Aviatrix supported Logging services <AviatrixLogging.html>`__.) - Findings from Amazon GuardDuty are displayed in Alert Bell on the Controller console. - In addition, if a finding is about instances in a VPC being probed by a malicious IP address, this IP address is blocked by deploying `Public Subnet Filtering Gateway <https://docs.aviatrix.com/HowTos/public_subnet_filtering_faq.html>`_, as shown in the diagram below. |public_subnet_filter| Polling Time --------------------- Go to Security > AWS GuardDuty > Change Scanning Interval. Select a time and click **Apply**. .. |guardduty_config| image:: guardduty_media/guardduty_config.png :scale: 30% .. |guardduty_acl| image:: guardduty_media/guardduty_acl.png :scale: 30% .. |public_subnet_filter| image:: public_subnet_filtering_faq_media/public_subnet_filter.png :scale: 30% .. add in the disqus tag .. disqus:: <file_sep> Use AWS Transit Gateway to Access Multiple VPCs in One Region ============================================================== This reference guide will show how you can use an AWS Transit Gateway (TGW) to allow remote users to connect to multiple VPCs in the same region. Please see the overview image below for reference. In this walkthrough, it is assumed you have created VPCs in your environment. If not, you can create and deploy VPCs directly from the Aviatrix Controller under the **Useful Tools** menu. Follow this link to learn more: `Create a VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_. |vpn_with_tgw_one_region| Creating a TGW ----------------------- The first step is to create a TGW from the Aviatrix Controller. 1. Log into to the Aviatrix Controller. 2. Navigate to the TGW Orchestrator tab on the left side of the screen and click **Plan**. 3. Next, select your cloud type. In this case, it is AWS. Fill in the remaining information, name the TGW, and click **Create**. |createTGW| To learn more about Transit Gateway deployment follow this link: `AVX Transit for AWS FAQ <https://docs.aviatrix.com/HowTos/tgw_faq.html#next-gen-transit-for-aws-faq>`_ Creating a Security Domain ---------------------------------- In the same section, under Step 2 (titled "Segment your network") in the TGW Orchestrator is the "Create a Security Domain" step. Scroll down to see this step. For this design, create three security domains: 1. Shared Service Domain 2. Dev Domain 3. Prod Domain * First, select the AWS Transit Gateway Name you created in the previous step from the dropdown menu. * Next, name the first Security Domain Name "Shared Service Domain" and click **Create**. * Repeat this process for the other two domains. |security_domain| Building Connection Policies -------------------------------------- You have now created Security Domains. The next step is to use these domains to define the connection policies. 1. First, make sure you select the AWS Transit Gateway Name created above. 2. Next, for Security Domain Name, select **Shared Services Domain**. 3. Select the Dev domain from the Domain Connection Policy List under **Not Connected** and add it to the **Connected** list. 4. Repeat this step for the Prod domain. Now, you have allowed both the Dev and Prod Domains to connect to the Shared Service Domain. |security_domains| .. note:: You can call these domains any name and use as many domains as needed. As seen in the image below Dev and Prod are simply called Domain 1 and Domain 2. Attaching VPCs to TGW ------------------------------- The next step is to attach your existing VPCs to the Transit Gateway (TGW) created above. To perform this, navigate in the Aviatrix Controller to the "Build" section under the TGW Orchestrator tab. In section 1, "Attach VPC to TGW": 1. Select the region of the TGW and your account. 2. Choose your Shared Service VPC and TGW Name. 3. Select **Shared Service Domain** for the Security Domain Name. 4. Click **Attach**. |VPC_to_TGW| Launching a VPN Gateway ----------------------------------- After attaching VPCs to the TGW, create a VPN Gateway so users can access the instances in the VPCs. 1. Navigate to the Gateway tab on the Aviatrix Controller and click **New Gateway**. 2. The cloud type is AWS. Enter a Gateway name. 3. Next, pick the region deployed in above and select the Shared Service VPC. 4. Mark the **Allocate New EIP** and **VPN Access** checkboxes. 5. Click **Create**. A new VPN Gateway will be created in the Shared Service VPC. More detailed options for deploying an Aviatrix Gateway are available here: `Gateway Options <https://docs.aviatrix.com/HowTos/gateway.html>`_. |VPN_gateway| Configuring VPN Gateway ------------------------------------ Now, in order to segment the Development and Production VPCs, enable Split Tunnel Mode on the VPN Gateway. 1. In your Aviatrix Controller, select OpenVPN® > Edit Config. 2. In "VPC ID/VNet Name" section, select the Shared Service VPC created earlier. 3. Confirm the proper LB/Gateway Name is selected. 4. In the "Modify Split Tunnel" section, add the IPv4 CIDR ranges for the Dev and Prod VPCs. |split_tunnel_CIDR| These ranges can be found by logging-into AWS and navigating to the VPC section. In your Aviatrix Controller, you can navigate to Useful Tools > VPC Tracker. There, you can view all the CIDR ranges for your VPCs. You will see your Prod and Dev VPCs there. |VPC_tracker| Configuring Aviatrix VPN Client ------------------------------------------ The first step is to add a new VPN User. 1. Navigate to OpenVPN® > VPN Users. 2. Click **Add New** and fill out the information in the fields provided. For the VPC ID, use the Shared Service VPC ID. |add_VPN_user| 3. Next, download your OpenVPN® configuration file. |download_config| 4. Download the latest Aviatrix VPN Client from the Docs page here: `Aviatrix VPN Client <https://docs.aviatrix.com/Downloads/samlclient.html>`_. 5. After installing the client, import your OpenVPN® configuration file to the Aviatrix VPN Client. Once the client is open, click **+** and choose your .ovpn file. 6. After the configuration file is imported, click **Connect**. |avtx_VPN_client_setup| You are now connected via the Aviatrix VPN Client. Test that everything has been correctly configured. 1. First, find and save the Private IP address of the EC2 instance running in either Dev or Prod VPCs. These IPs can be found in the AWS Console page under the EC2 banner. |EC2_private_IP| 2. Now, open a terminal on your computer and see if you can ping the EC2 instance using its private IP address. If you are connected to the Aviatrix VPN Client, you should see a response. 3. To check, disconnect from the Aviatrix VPN Client. You should not see a response. See below for an example of a proper ping response. |ping_test| Last Steps --------------- One last option for configuration is under Step 3 of this guide, "Connection Policies". * As a test, remove either the Dev or Prod Domain from the "Connected" list. * Remove Dev from the "Connected" list for the Shared Service Policy and run a Ping test. You should receive no response from the EC2 instance in the Development VPC. OpenVPN is a registered trademark of OpenVPN Inc. .. |vpn_with_tgw_one_region| image:: uservpn_TGW_media/userVPN_SD.png :scale: 30% .. |createTGW| image:: uservpn_TGW_media/createTGW.png :width: 5.5in :height: 2.5in .. |security_domain| image:: uservpn_TGW_media/security_domain.png :width: 5.5in :height: 2.5in .. |security_domains| image:: uservpn_TGW_media/security_domains.png :width: 5.5in :height: 2.5in .. |VPC_to_TGW| image:: uservpn_TGW_media/VPC_to_TGW.png :width: 5.5in :height: 2.5in .. |VPN_gateway| image:: uservpn_TGW_media/VPN_gateway.png :width: 5.5in :height: 2.5in .. |split_tunnel_CIDR| image:: uservpn_TGW_media/split_tunnel_CIDR.png :width: 5.5in :height: 2.5in .. |VPC_tracker| image:: uservpn_TGW_media/VPC_tracker.png :width: 5.5in :height: 2.5in .. |add_VPN_user| image:: uservpn_TGW_media/add_VPN_user.png :width: 5.5in :height: 2.0in .. |download_config| image:: uservpn_TGW_media/download_config.png :width: 5.5in :height: 2.0in .. |avtx_VPN_client_setup| image:: uservpn_TGW_media/avtx_VPN_client_setup.png :scale: 30% .. |EC2_private_IP| image:: uservpn_TGW_media/EC2_private_IP.png :scale: 30% .. |ping_test| image:: uservpn_TGW_media/ping_test.png :scale: 30% .. disqus:: <file_sep> ################################### FlightPath ################################### FlightPath is a troubleshooting tool. It retrieves and displays, in a side by side fashion, cloud provider's network related information such as Security Groups, Route table and route table entries and network ACL. This helps you to identify connectivity problems. What you need -------------- You do not need to launch Aviatrix gateways to use this tool, but you need to create Aviatrix accounts so that the Controller can use the account credentials to execute cloud provider's APIs to retrieve relevant information. How to use it ----------------- Click on the FlightPath icon on the onboarding page or Troubleshooting -> FlightPath. Select the Source side cloud type, account, region, vpc name and click one instance. Optionally, Do the same for the Destination side. Run a FlightPath Test. A report will appear. The information is arranged in three sections: Security Groups, Route table entries and Network ACL. The Security Group is what is associated with the instance, and both the route table and the Network ACL are associated with the subnet that the instance is deployed. Example -------- Here is one example to show how FlightPath works. Say a developer from BusinessOps account filed a ticket that says one instance called “DevOps Server” in the Oregon region cannot run “ssh” into the Prod instance in the California region. From the Controller browser console, click FlightPath under Troubleshooting on the navigation menu. Specify the above info and you’ll see something like the screenshot below. The highlights on each panel are the instances in question. Note the DevOps Server has IP address 10.10.0.121. |image0| Now run a FlightPath Test and you’ll see the FlightPath Report. First, check the routing table, which shows good connectivity: |image1| Scroll up and down the FlightPath Report to check other fields. Next check the Security Group. And of course, the California Prod instance does not have its “ssh” port open to the Oregon DevOps instance IP address 10.10.0.121. |image2| Problem solved in minutes! Upon further inspection, you’ll notice that the complaining instance has a “ssh” open to the entire world. You may need to notify the ticket issuer to reduce the source address scope. .. |image0| image:: flightpath_media/FlightPath1.png :width: 5.55625in :height: 3.26548in .. |image1| image:: flightpath_media/routetablecheck.png :width: 5.55625in :height: 3.26548in .. |image2| image:: flightpath_media/securitygorupcheck.png :width: 5.55625in :height: 3.26548in .. disqus:: <file_sep> ========================================================= Transit FireNet Workflow for AWS, Azure, GCP, and OCI ========================================================= If you are looking deploying firewall networks in AWS TGW environment, your starting point is `here <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html>`_. To learn about Transit FireNet, check out `Transit FireNet FAQ. <https://docs.aviatrix.com/HowTos/transit_firenet_faq.html>`_ * For a complete step-by-step guide on AWS for Transit FireNet, refer to `Transit FireNet on AWS Configuration Example Guide <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html>`_. * For a complete step-by-step guide on AWS for Transit FireNet with AWS Gateway Load Balancer (GWLB), refer to `Transit FireNet Workflow with AWS Gateway Load Balancer (GWLB) <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws_gwlb.html>`_. * For a complete step-by-step guide on Azure for Transit FireNet, refer to `Transit FireNet on Azure Configuration Example Guide <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_azure.html>`_. * For a complete step-by-step guide on GCP for Transit FireNet, refer to `Transit FireNet on GCP Configuration Example Guide <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_gcp.html>`_. * For a complete step-by-step guide on OCI for Transit FireNet, refer to `Transit FireNet on OCI Configuration Example Guide <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_oci.html>`_. Prerequisite for AWS ---------------------------------- Transit FireNet builds on the Aviatrix Transit Network where Aviatrix Gateways are deployed in both the transit VPC and the spoke VPCs in AWS. Make sure the deployment meets the following specifications. 1. ActiveMesh must be enabled when launching the Aviatrix Transit Gateway. 2. The minimum size of the Aviatrix Transit Gateway is c5.xlarge. 3. Aviatrix Transit Network must be in Connected mode. Go to Transit Network > Advanced Config > Connected Transit. Click **Enable**. Follow the `Aviatrix Transit Network workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ to deploy Aviatrix Transit Gateways and at least one Spoke Gateway. When complete, proceed to Step 1. Prerequisite for Azure ------------------------------------- Transit FireNet builds on the Aviatrix Transit Network solution where Aviatrix Gateways are deployed in Transit VNet and/or in Spoke VNet in Azure. Make sure the deployment meets the following specifications. 1. ActiveMesh must be enabled when launching the Aviatrix Transit Gateway. #. The minimum size of the Aviatrix Transit Gateway instance size is Standard_B2ms. #. Select the **Enable Transit FireNet** option when launching the Aviatrix Transit Gateway. #. Aviatrix Transit Network must be in Connected mode. Go to Transit Network > Advanced Config > Connected Transit. Click **Enable**. Follow the `Aviatrix Transit Network workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ to deploy Aviatrix Transit Gateways and attach at least one Spoke Gateway or one Spoke VNet. When you are done, proceed to Step 1. Prerequisite for GCP ------------------------ Transit FireNet builds on the Aviatrix Transit Network solution where Aviatrix Gateways are deployed in Transit VPC and/or in Spoke VPC in GCP. Make sure the deployment meets the following specifications. 1. ActiveMesh must be enabled when launching the Aviatrix Transit Gateway. #. Minimum four VPCs will be required for GCP FireNet solution with Palo Alto VM-series and all VPCs should be in same region. #. The minimum size of the Aviatrix Transit Gateway instance size is n1-standard_1. #. Select the **Enable Transit FireNet** option when launching the Aviatrix Transit Gateway. #. Aviatrix Transit Network must be in Connected mode. Go to Transit Network > Advanced Config > Connected Transit. Click **Enable**. Follow the `Aviatrix Transit Network workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ to deploy Aviatrix Transit Gateways and attach at least one Spoke Gateway or one Spoke VNet. When you are done, proceed to Step 1. Prerequisite for OCI ----------------------------- Transit FireNet builds on the Aviatrix Transit Network solution where Aviatrix Gateways are deployed in Transit VCN and/or in Spoke VCN in OCI. Make sure the deployment meets the following specifications: 1. ActiveMesh must be enabled when launching the Aviatrix Transit Gateway. #. Select the **Enable Transit FireNet** option when launching the Aviatrix Transit Gateway. #. Aviatrix Transit Gateway minimum instance size should be VM.Standard2.4 or more. Follow the `Aviatrix Transit Network workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ to deploy Aviatrix Transit Gateways and attach at least one Spoke Gateway. When you are done, proceed to Step 1. .. Note:: Transit FireNet Insane mode is not supported in Release 6.4. Enabling Transit FireNet Function ------------------------------------------------ A Transit FireNet Gateway is an Aviatrix Transit Gateway with FireNet service enabled. Starting from Release 6.0, an Aviatrix Spoke can be optionally attached to two Transit FireNet Gateways, one for east-west and north-south traffic inspection, and another for ingress/egress inspections. Enabling Transit FireNet on Aviatrix Transit Gateway ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This step defines a set of Aviatrix Transit FireNet Gateways. In the dropdown menu, select one Aviatrix Transit Gateway and click **Enable**. .. Note:: For Azure and GCP deployment, Transit FireNet function is enabled when launching the gateway, skip this step. By default, east-west and north-south traffic inspections are enabled on Transit FireNet Gateways, you can also enable Ingress/Egress inspection on the Transit FireNet Gateways. To do so, go to Firewall Network > Advanced > click the 3 dots skewer of one FireNet Gateway, enable Egress through firewall option. A deployment diagram in this option is shown as below: |single_transit_new| Starting 6.3, Aviatrix Transit FireNet solution is also supporting AWS Gateway Load Balancer (AWS GWLB). In order to use the Aviatrix Transit FireNet solution with AWS GWLB, select one Aviatrix Transit Gateway deployed in AWS from the dropdown menu, check the box "Use AWS GWLB" and click "Enable". .. note:: IAM policies needs to be updated for ingress/egress traffic. Go to Aviatrix Controller > Accounts > Access Accounts > Select AWS Account and click **Update Policy**. .. important:: Transit FireNet solution with GWLB also requires HTTPS port enable on firewall appliance to check the firewall health status at regular interval. Click `here <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_azure.html#step-9-enable-health-check-policy-in-firewall>`_ for more information. By default, east-west and north-south traffic inspections are enabled on Transit FireNet Gateways, you can also enable Ingress/Egress inspection on the Transit FireNet Gateways. To do so, go to Firewall Network > Advanced > click the 3 dots skewer of one FireNet Gateway, enable Egress through firewall option. A deployment diagram in this option is shown as below: |gwlb_tr_firenet| Enabling Transit FireNet on Aviatrix Egress Transit Gateway ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If you plan to use one set of Transit FireNet Gateways for all traffic types' inspection, skip this step. If a separate group of firewalls for Ingress/Egress traffic inspection is required, you need to deploy a second set of Aviatrix Transit Gateways called Aviatrix Egress Transit Gateway, shown as the diagram below. |dual_transit| This step defines a set of Aviatrix Egress Transit FireNet Gateways. The HA Aviatrix Egress Transit FireNet Gateway is automatically enabled in this step. Managing Transit FireNet Policy -------------------------------------- Select an Aviatrix Transit Gateway that you enabled for FireNet function in the previous step. On the left side of the panel, highlight one Spoke VPC/VNet for inspection and click **Add**. The selected Spoke VPC/VNet should appear on the right panel. For example, if traffic going in and out of VPC/VNet PROD1 where gcp-spk-prod1-gw is deployed should be inspected, move the gcp-spk-prod1-gw to the right, as shown below. |transit_firenet_policy_new| For specify more VPC/VNets for inspection, repeat this step. Deploying Firewall Instances -------------------------------------- Go to Firewall Network > Setup > Deploy Firewall Network, follow the `deployment instructions <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#a-launch-and-associate-firewall-instance>`_ to launch one or more firewall instances. Enabling Firewall Management Access ----------------------------------------------------- When this option is configured, Aviatrix Transit Gateway advertises the transit VPC/VNet CIDR to on-prem. The use case is if a firewall management console, such as Palo Alto Networks Panorama is deployed on-prem, the Panorama can access the firewalls of their private IP addresses with this option configured. Deleting Function ------------------------------------------ In the dropdown menu, select one Aviatrix Transit Gateway with FireNet function to disable it. Disabling Transit FireNet on an Aviatrix Transit Gateway ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Select a Transit FireNet Gateway to disable the function. Disabling Transit FireNet on an Aviatrix Egress Transit Gateway ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If Aviatrix Egress Transit Gateway has been configured, select one to disable the function. .. |transit_firenet_policy_new| image:: transit_firenet_workflow_media/transit_firenet_policy_new.png :scale: 40% .. |dual_transit| image:: transit_firenet_workflow_media/dual_transit.png :scale: 40% .. |single_transit_new| image:: transit_firenet_workflow_media/single_transit_new.png :scale: 40% .. |gwlb_tr_firenet| image:: transit_firenet_workflow_media/gwlb_tr_firenet.png :scale: 40% .. disqus:: <file_sep> ################################### Controller Backup and Restore ################################### When deployed in a cloud environment, the Aviatrix Controller is not in the data path as packet processing and encryption is done by the Aviatrix gateways. When the Controller is down or out of service, your network will continue to be operational and encrypted tunnels and OpenVPN® users stay connected and are not affected. Since most of the data logs are forwarded from the gateways directly, the loss of log information from the Controller is minimal. The only impact is that you cannot build new tunnels or add new OpenVPN® users. This loosely coupled relationship between the Controller and gateways reduces the impact of the availability of the Controller and simplifies your infrastructure. Since the Controller stores configuration data, it should be periodically backed up to the appropriate AWS/Azure/Google account. If a replacement Controller is launched, you can restore the configuration data from your backup. .. note:: Note: If you have the Controller HA cloud formation stack running, please make sure you delete the stack prior to stopping the existing Controller, to avoid complications and failures in this restore operation. .. important:: If you choose to migrate your Controller using backup and then restoring to a new Controller, you must reset the IP address of your newly launched Controller in CoPilot before shutting down your old CoPilot. Reset the IP address of your newly launched Controller in CoPilot > Settings > Configuration > click **Reset Controller IP**. If you fail to do so, you may be locked out of your CoPilot after the migration. Backing up the Configuration ----------------------------------------------------- Aviatrix stores the Controller backup in an AWS S3 bucket or an Azure Container. Before you begin, determine where you would like to store the backup and create either the S3 bucket or Azure Container. .. warning:: * Make sure your Controller backup and Controller restore are in the same CSP (Cloud Service Provider): AWS, Azure, or GCP and share the same basic configuration. For example, an AWS backup can only restore to another AWS Controller. * Note that in the case of AWS backups, an AWS Controller set up with IAM roles cannot backup and restore to an AWS Controller set up with a secret key, or vice versa. * (AWS) The S3 bucket you use or create for Controller HA and Backups does not need to have public access enabled and should be configured to restrict general public access. #. Log into the Controller. #. Click on the `Settings` navigation item. #. Click on the `Maintenance` sub item. #. Click on the `Backup & Restore` tab. #. Under the `Backup` section: - Select the appropriate `Cloud Type` and `Account Name`. - Populate the `S3 Bucket Name` for AWS or `Region`, `Storage Name`, and `Container Name` for Azure. .. note:: By default, only the latest configuration data is stored. Each time the configuration is backed up, it overwrites the previous one. If you would like to keep every copy, check the box `Multiple Backup`. #. Click `Enable`. |imageBackupAWS| The first time you enable this feature, the configuration will backed up to your specified location. After this, the configuration data is automatically backed up daily at 12am. Selecting the "Multiple Backup" checkbox enables the Controller to backup up to a maximum of 3 rotating backups. Each backup filename will contain the date and time of when the backup is made. Additionally, the backup without any date and time in the filename contains a copy of the latest backup. If you want to force an immediate backup (e.g. for a configuration change) you can accomplish this by clicking on the "Backup Now" button. If multiple backups are not enabled, each time the configuration is backed up, the backup up file will be overwritten. Otherwise, the oldest backed up will be overwritten. .. note:: Selecting the 'Multiple Backup' option is recommended. If the backup is already 'Enabled', go ahead and 'Disable' it, turn on the 'Multiple Backup' option and then 'Enable' the backup again. .. note:: You should enable cross-region replication in AWS when creating your S3 buckets. This ensures that an S3 bucket remains accessible if there is a regional CSP failure. The replacement Controller can retrieve and restore its backup file. Restoring the Configuration --------------------------------------- .. note:: In Private Mode, restoration can only be done in the same VPC as the previous Controller. You cannot restore a Controller that has been created in a different VPC. Click `here <https://docs.aviatrix.com/HowTos/privatemode.html>`_ for more information on Private Mode. .. warning:: * Make sure your Controller backup and Controller restore take place in the same CSP (Cloud Service Provider): AWS, Azure, or GCP and share the same basic configuration. For example, an AWS backup can only restore to another AWS Controller. * Note that in the case of AWS backups, an AWS Controller set up with IAM roles cannot backup and restore to an AWS Controller set up with a secret key, or vice versa. If you are starting from a new Controller, follow these steps to get started: #. Log in to the Controller with the `admin` username and the default password. #. Follow the initial steps to get the Controller up and running. #. Shut down the older Controller. #. Transfer the IP address to the new Controller. #. Proceed to configure the new Controller by entering an email address. #. Change your admin password. #. Enter or skip the proxy configuration. #. Allow the upgrade to run. Once you are past the initial configuration steps: #. Log into the Controller. #. Click on the `Settings` navigation item. #. Click on the `Maintenance` sub item. #. Click on the `Backup & Restore` tab. #. Under the `Restore` section: - Select the `Cloud Type` - For AWS - If you would like to use an existing account, please make sure you create one Access Account only with the EXACT Access Account Name that was used in your previous Controller. Check the box `Use Cloud Account Name` and select the account. Otherwise, enter an `Access Key` and `Secret Key` - Enter the `Bucket Name` and `File Name` of the file to restore. - For Azure - Enter the `Subscription ID` and `Certificate Path`. - Enter the `Storage Name`, `Container Name`, and `File Name` of the file to restore. #. Click **Restore**. |imageRestoreAWS| If Aviatrix Managed CloudN exists in the backup Controller, after the restore operation on the new Controller, you must navigate to the Aviatrix Managed CloudN UI and follow steps of 2.2 and 2.5 in https://docs.aviatrix.com/HowTos/CloudN_workflow.html?highlight=managed%20CloudN by entering the new FQDN or IP of the new Controller to complete the restore. You must repeat 2.2 and 2.5 on other Aviatrix Managed CloudN devices if you have more than one. .. important:: If you choose to migrate your Controller using backup and then restoring to a new Controller, you must reset the IP address of your newly launched Controller in CoPilot before shutting dow your old CoPilot. Reset the IP address of your newly launched Controller in CoPilot > Settings > Configuration > click **Reset Controller IP**. If you fail to do so, you may be locked out of your CoPilot after the migration. How to Backup configuration with AWS Encrypted Storage ------------------------------------------------------ AWS S3 allows uploaded backup files to be encrypted in the server side for more secure storage. The encryption is all done in the AWS S3 server side. This server side secure storage is in addition to the already encrypted Aviatrix Controller backups. 1. Create AWS S3 bucket ^^^^^^^^^^^^^^^^^^^^^^^ |S3Create| .. note:: Note: The S3 bucket you use or create for Controller HA and Backups does not need to have public access enabled and should be configured to restrict general public access. 2. Configure bucket server side encryption in S3 bucket properties. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |S3Properties| 3. Select either None, AES-256, AWS-KMS AWS/S3, or AWS-KMS Custom KMS ARN. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |S3SelectDefaultEncryption| |S3SelectEncryption| 4. If AWS-KMS with Custom KMS ARN is selected, additional configuration will be needed: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ a. Create a Custom Encryption Key by going to IAM->Encryption Keys->Create Key |KMSKeyCreate| b. Copy the custom Key KMS ARN to the S3 encryption property configuration. .. note:: Make sure that the custom encryption key and the S3 bucket are in the same region. c. If IAM user is used for onboarding authentication, add user "aviatrix-role-app" into the key. |KMSKeyAddUser| How to backup Controller configuration privately with Azure Private Link ------------------------------------------------------------------------ Azure Private Link enables you to access Azure PaaS Services (for example, Azure Storage and SQL Database) and Azure hosted customer-owned/partner services over a private endpoint in your virtual network. Traffic between your virtual network and the service travels the Microsoft backbone network. Exposing your service to the public internet is no longer necessary. By leveraging Azure private link, the Controller backups will happen privately from your VNET so that your blob storage account does not need to be exposed to the outside world. 1. Create an Azure Storage Account ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |AzureStorage| 2. Setup the Storage Account for Private Link ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ a. On the 'Networking' tab for the storage account creation, select Private endpoint for the connectivity method. b. Add a new private endpoint with the target of the blob storage resource and enable DNS Integration. |AzurePrivateEndpoint| .. note:: If you currently have existing private endpoints deployed, you may need to leverage an existing private zone in another subscription. This must be completed through the dedicated private endpoint creation workflow. For additional assistance with this setup please reach out to an Aviatrix Solution Engineer. 3. Verify Backup through Controller ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Once successful, backing up traffic from the Controller will be performed privately across private link so that associated storage account does not need to be accessible publicly. OpenVPN is a registered trademark of OpenVPN Inc. .. |imageBackupAWS| image:: controller_backup_media/backup_restore_backup_aws.png .. |imageRestoreAWS| image:: controller_backup_media/backup_restore_restore_aws.png .. |S3Create| image:: controller_backup_media/S3Create.png :scale: 20% .. |S3Properties| image:: controller_backup_media/S3Properties.png :scale: 20% .. |S3SelectDefaultEncryption| image:: controller_backup_media/S3SelectDefaultEncryption.png :scale: 25% .. |S3SelectEncryption| image:: controller_backup_media/S3SelectEncryption.png :scale: 25% .. |KMSKeyCreate| image:: controller_backup_media/KMSKeyCreate.png :scale: 30% :align: middle .. |KMSKeyAddUser| image:: controller_backup_media/KMSKeyAddUser.png :scale: 30% :align: middle .. |AzureStorage| image: controller_backup_media/AzureStorage.png :scale: 30% :align: middle .. |AzurePrivateEndpoint| image: controller_backup_media/AzurePrivateEndpoint.png :scale: 30% :align: middle .. disqus:: <file_sep> ================================= Gateway Audit (for AWS) ================================= The Aviatrix Controller periodically checks the Aviatrix Gateways in AWS it launched to make sure: 1. The Aviatrix Gateway instance in AWS has its IAM role aviatrix-role-ec2 attached. #. The aviatrix-role-app role exists and has policies attached to it. #. The Aviatrix Gateway instance's security group has an inbound rule that opens to the Controller EIP on port 443. When any of the above condition fails, the Controller sends an alert email to the Controller admin and logs the event. When any of the above condition fails, the gateway will not be able to receive messages from the Controller. Therefore, the event requires immediate action as it will lead to operation outage. ========================================== ================= **Audit Status** **Description** ========================================== ================= Pass The gateway has passed the most recent audit. Error(SG) The gateway instance's security group does not have an inbound rule that is open to the Controller's EIP. Error(IAM) The gateway instance's aviatrix-role-ec2 is detached from the instance profile or aviatrix-role-app does not have associated policy. ========================================== ================= Cloud Message Queue Failure ---------------------------------------- If the alert message has a title Cloud Message Queue Failure, it implies the following: 1. The gateway runs periodic APIs calls to retrieve SQS messages if any sent by the Controller. For 15 minutes, the specific gateway has been experiencing API calls failures. This does not necessarily mean the gateway has missed any messages. There may be a temporary interruption for gateway to make API calls. #. If the failure continues, a new message will be sent once a day. Please see `this document <https://aviatrix.zendesk.com/hc/en-us/articles/4406353399565-Why-do-I-get-an-email-alert-about-my-gateway-with-Cloud-Message-Queue-Failure-message->`_ to look for ways to debug and address this issue. If you need help, please open a support ticket at the `Aviatrix Support Portal <https://support.aviatrix.com>`_. .. |secondary_account| image:: adminusers_media/secondary_account.png :scale: 50% .. |account_structure| image:: adminusers_media/account_structure.png :scale: 50% .. |access_account_35| image:: adminusers_media/access_account_35.png :scale: 50% .. disqus:: <file_sep> ===================================== Environment Stamping ===================================== Objectives ========== This reference design helps you build a repeatable deployment solution that scales indefinitely, as shown in the diagram below: |image0| where the Aviatrix controller instance can be in the same or a different VPC. Each customer or managed VPC shares an identical VPC CIDR, security policies and instances. A user who connects to the management VPC should be uniquely address an instance in any given VPC by a private IP address or with a preferred name. Configuration Workflow ====================== Before you start make sure you have the latest software by checking the Dashboard. If an alert message displays, click Upgrade to download the latest software. The configuration workflow is as follows. It highlights the major steps. 1. Create a gateway in management VPC The mgmt-vpc is our management VPC with CIDR 172.31.0.0/16 in us-west-2. Click Gateway, then Create, make sure: a. The VPC ID field is the AWS VPC ID where you launch the management gateway. #. The Gateway Name in this example is mgmt-gw. #. Enable NAT is not selected. #. VPN Access is not selected. #. Create an Access Address Pool This Access Address Pool is the address range from which instance addresses are mapped to. Accessing instance is done by accessing one mapped address from the pool. Go to VPC/VNet -> Environment Stamping -> Map Instance Addresses -> Address Pool. Make sure: a. The Access Address Pool is big enough. In this example, we use 192.168.0.0/16 which gives you 16K unique IP addresses. #. Select mgmt-vpc as the gateway choice. #. Click Set. #. (Optional) Setup Instance Names envStamping integrates Route 53 private hosted zone feature to enables you to access instances with DNS names and preferred (alias) names. Skip this step if you do not wish to use names to access instances. Go to VPC/VNet -> Environment Stamping -> Setup Instance Names -> Config. Enter a private domain name. For example, mydevops.com. Click Enable. #. Create VPN gateways Create one or more VPN gateways in the management VPC for users to connect to AWS and access instances. In this example, we configure a split tunnel mode solution where only cloud bound traffic goes to the VPN tunnel. Among all fields you need to enter, make sure: | a. Enable NAT is selected. | b. VPN Access is selected. | i. VPN CIDR Block must be an address range that is outside of | management VPC and all other VPCs you intend to create. In | this example, enter 10.20.0.0/24. | ii. Split Tunnel Mode is “Yes”. | 1. Additional CIDRs: enter the Access Address Pool CIDR. In | this example, enter 192.168.0.0/16 | 2. (optional) Nameservers: enter the private DNS server of the | management VPC if Setup Instance Names is enabled. In this | example, enter 172.31.0.2 | 3. (optional) Search Domains: The private hosted zone domain | name if Setup Instance Names is enabled. In this example, | enter mydevops.com | c. Enable AWS ELB is “Yes”. | d. Save Template: check to save the template. | e. Repeat the above steps to create more VPN gateways to achieve | scalability and resilience. #. Create a managed VPC pool and its gateways This step creates a number of managed VPCs and gateways. If you already have existing VPCs, you should use Gateway tab to just create gateways. Make sure VPN access is disabled. a. Go to VPC/VNet -> Environment Stamping -> Manage VPC Pool -> Create #. Pool Name: a name for this VPC pool. Every VPC created in this pool will have a numeric number append to it. In this example, enter customer. #. Number of VPCs: the number of VPCs. In this example, enter 3. #. Check Launch Gateway i. Enable NAT: check this box if you like the gateway to also perform NAT function. #. Launch customer instances Once VPC and gateways are created, you can launch instances from AWS console or your own CloudFormation scripts. The pool of managed VPC may already have some instances. #. Map instance addresses This step scans and maps instance private addresses in managed VPC to addresses from Access Address Pool, so that you can access these instances via Access Address Pool addresses. a. Go to VPC/VNet -> Environment Stamping -> Map Instance Addresses -> Auto Mapping #. Management VPC: select the gateway for management VPC. In this example, select mgmt-gw #. Managed VPC: select one gateway from managed VPC. In this example, select customer001. Click Scan & Map. #. Repeat the above step for all the remaining gateways in managed VPC. #. Go to VPC/VNet -> Environment Stamping -> Map Instance Addresses -> List to view your instances and their mapped addresses. #. Add users Add VPN users to the cloud network. Go to VPC/VNet -> VPN Access -> Users. Use Profile to control which user can access what cloud instance/application/ports. #. Access Instances with Names When a user connects to management VPC, she can access instances in all managed VPCs. The instances can be accessed by its mapped Access Address, DNS name or nickname. When using DNS names and nicknames, make sure you include the domain name. For example, an instance with nickname webfrontend should be accessed as webfrontend.mydevops.com #. For support, please open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_ #. For feature request, click Make a wish at the bottom of each page. #. Enjoy! .. |image0| image:: EnvStamping_media/image1.png .. disqus:: <file_sep> ################################### Controller Certificate Management ################################### The Aviatrix Controller uses a self-signed certificate by default. That is why you see "Not Secure" In the browser. You can make it secure by importing a signed certificate. This documentation outlines the **Import a Certificate with Key** method. This example utilizes Godaddy as the CA. However, steps 1 and 3 should be universal for any certificate provider. Import a Certificate with Key ------------------------------------- Create Private Key and Certificate Signing Request ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1. Log into SSH on a Linux or macOS device and run the following command to create the private key: mymac$ **openssl genrsa -out my_prv.key 4096** 2. Create the CSR: - Run the following command and fill out the necessary information as it relates to your company. - Leave the password blank. mymac$ **openssl req -new -sha256 -key my_prv.key -out controller.csr** Upload the CSR to Go Daddy and Retrieve the Certificates ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1. Upload the CSR. Site Path: GoDaddy.com > SSL > Certificates > Your Desired Domain Name > Rekey & Manage > Re-Key Certificate 2. Paste the Certificate Signing Request (CSR) into the entry field. |godaddy_1| 3. Retrieve the Certificate: Site Path: GoDaddy.com > SSL > Certificates > Your Desired Domain Name > Download 4. Wait for GoDaddy to respond with Certs. This usually takes ten minutes (an email confirmation is sent). 5. Download the Certificates. |godaddy_2| Uploading the Certificates to the Controller ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Path: Controller > Certificate > Controller Certificate Management > Import Certificate with Key 1. Select “Import Certificate with Key” - The CA certificate – the file named gd_bundle - The Server certificate - the other file ending in .crt - The Private Key – the file produced in step 1 of this documentation |controller_cert_1| |controller_cert_2| The Controller signed certificate procedure is complete. Additional Notes ^^^^^^^^^^^^^^^^ - If a certificate is already present on the Controller you must disable “Import Certificate” before uploading the new certificates, otherwise an error occurs. |controller_cert_3| - The Controller will perform a validity check between the Server Certificate and the Private Key. .. |godaddy_1| image:: controller_certificate_media/godaddy_1.png :scale: 60% .. |godaddy_2| image:: controller_certificate_media/godaddy_2.png :scale: 60% .. |controller_cert_1| image:: controller_certificate_media/controller_cert_1.png :scale: 50% .. |controller_cert_2| image:: controller_certificate_media/controller_cert_2.png :scale: 100% .. |controller_cert_3| image:: controller_certificate_media/controller_cert_3.png :scale: 100% .. disqus:: <file_sep> .. toctree:: :numbered: ============================================================================== OpenVPN® with SAML Authentication on Centrify IDP ============================================================================== Overview ------------ This guide provides an example on how to configure Aviatrix to authenticate against Centrify IDP. When SAML client is used, your Aviatrix Controller acts as the Identity Service Provider (SP) that redirects browser traffic from the client to IDP for authentication. Pre-Deployment Checklist ------------------------------------ Before configuring SAML integration between Aviatrix and AWS SSO, make sure the following is completed: #. The Aviatrix Controller is set up and running. Follow `the Controller Startup Guide <https://docs.aviatrix.com/StartUpGuides/aviatrix-cloud-controller-startup-guide.html>`__ to launch the Controller. #. You have Centrify up and running with administrator access. #. You have downloaded and installed the `Aviatrix VPN client <#awsssosaml-aviatrix-client>`__. Configuration Steps: #################### #. From the Centrify App > Add New App > Custom, select SAML and click **Add**. Click **yes** and close the prompt. This lets you configure the application. #. | Configure app settings\ |image0| | Enter a name for your application, click **Save**, and go to the next page. #. Copy the metadata URL from the Trust page. |image1| Now go to your Aviatrix Controller. Create a new SAML endpoint from OpenVPN as paste the URL into the Metadata URL field. Give an endpoint name and click **OK**. |image2| #. This creates a SAML endpoint at the Aviatrix Controller. |image3| Here you can retrieve the SP metadata by clicking on the SP metadata. |image4| Copy the above metadata as text. #. Go back to the Centrify app and paste the information into the Metadata XML section. Click **Save** and go to the next section. |image5| .. note:: You can also use the URL method if you have configured signed certificates for the Aviatrix Controller, but not for the initial self-signed certificate. #. Configure the following SAML attributes (Email is the unique identifier) +----------------+---------------------+ | FirstName | LoginUser.FirstName | +----------------+---------------------+ | LastName | LoginUser.LastName | +----------------+---------------------+ | Email | LoginUser.Email | +----------------+---------------------+ Also, the custom logic needs to be set for the attributes to work setAttribute("exampleAttr", "DOMAIN\\user"); |image6| You can preview the SAML response and this step and select the user. Make sure that there are no errors. Click **Save** and go to the next tab. #. Add users. |image7| Click **Save** and go the next tab. #. Add any policies if you require them. Click **Save** and go to the next tab. #. Use the default “Directory service field” mapping. Click **Save** and go to the next tab. |image8| . #. Configure the next pages if you require them: Linked applications, Provisioning, and App Gateway if you require them. Click **Save**. The SAML configuration at the IDP is now complete. #. Test the SAML integration. Go back to your Aviatrix Controller and go to OpenVPN > Advanced > SAML tab. Click **test** for the SAML endpoint. |image9| You should get redirected to the Centrify and it may ask for credentials. If you are already logged, it redirects you back to the Controller page. |image10| Ignore the warning since you may not have a VPN client already running. #. To test the VPN integration, you need to perform 3 steps at the Aviatrix Controller. a. Configure cloud account at Accounts > access account. b. Create a VPN Gateway in the Gateway page. Mark the **VPN Enabled** and **SAML Enabled** checkboxes. c. Add a VPN user in the OpenVPN > VPN users page to the SAML VPN gateway with the respective endpoint. The certificate is emailed or can be downloaded here. #. Test VPN connectivity by installing the Aviatrix VPN client. Load the VPN certificate and click **connect**. The browser should open up. Log in at Centrify. The client then automatically connects to the VPN Gateway. Test connectivity by doing a ping to the private IP of the gateway. .. |image0| image:: centrify_media/image1.jpg .. |image1| image:: centrify_media/image2.jpg .. |image2| image:: centrify_media/image3.jpg .. |image3| image:: centrify_media/image4.jpg .. |image4| image:: centrify_media/image5.jpg .. |image5| image:: centrify_media/image6.jpg .. |image6| image:: centrify_media/image7.jpg .. |image7| image:: centrify_media/image8.jpg .. |image8| image:: centrify_media/image9.jpg .. |image9| image:: centrify_media/image10.jpg .. |image10| image:: centrify_media/image11.png <file_sep> ============================================ Periodic Ping ============================================ In very rare cases, Site2Cloud tunnels may fail to pass traffic if the tunnel is dormant for a long period of time. This is not an issue with the Aviatrix Gateways and can usually be traced to misconfigurations on the remote device. To compensate for this Periodic Ping was developed to maintain a steady flow of traffic across the tunnel. For more information on troubleshooting Site2Cloud issues, please refer to the links below. - `Troubleshooting Site2Cloud Playbook <https://docs.aviatrix.com/TroubleshootingPlaybook/troubleshooting_playbook_aviatrix_s2c_end_to_end_traffic.html>`_ - `Site2Cloud Workflow <https://docs.aviatrix.com/HowTos/site2cloud.html>`_ Controller Path -------------------------- Navigate to Controller > Gateway > select gateway > Periodic Ping. Configuration --------------------- =============================== ================================================================= **Option** **Description** =============================== ================================================================= Interval The interval the ping is sent in seconds IP Address The destination IP of a device on the remote end of the tunnel =============================== ================================================================= Set the desired values (ie, Interval 3 & IP Address 10.200.1.8) and then click **Enable**. The Gateway will now ping the remote device in intervals of seconds. The ping will originate from the Gateway's local IP. Additional Notes --------------------------- - If Periodic Ping is enabled on a Transit Gateway with BGP, **Advertise Transit VPC Network CIDR(s)** must be enabled for the ping to traverse the Site2Cloud tunnel. - - Navigate to your Aviatrix Controller > Transit Network > Advance Config > Edit Transit > select gateway > Advertise Transit VPC Network CIDR(s) > Enable. - This feature is available in software version 5.3 and above. <file_sep> ============================================================== Aviatrix Spoke Gateway to External Devices (BGP-Enabled Spoke) ============================================================== You can connect an external device (External (or 3rd Party) Router/Firewall) to Aviatrix spoke gateways that are enabled with BGP (and NAT). BGP is run on top of a site to cloud (S2C) connection that terminates on active-mesh spoke gateways. This document focuses on the External Device connecting the Aviatrix Spoke GW that is enabled with BGP. Using BGP-enabled spoke gateways is currently supported for AWS Commercial and Azure Commercial cloud service providers, including Government regions. .. note:: BGP-enabled spokes are introduced in release 6.6. Spoke gateways created prior to Aviatrix release 6.6 cannot be enabled for BGP (you enable BGP at gateway creation). Rollback to release 6.5 Aviatrix gateways is not possible if there is at least one BGP-enabled Spoke Gateway. What is a use case for connecting a BGP-enabled spoke gateway to an external router? ------------------------------------------------------------------------------------ Prior to Aviatrix release 6.6, you could enable BGP only on Aviatrix transit gateways (not spoke gateways). For software as a service (SaaS) providers with certain architectures, this meant having to deploy transit gateways for each of their tenants to enable the tenant to connect to their in-cloud network. By using BGP-enabled spoke gateways in their network architecture, SaaS providers can solve several requirements: - **Requirement**: Connect a large number of tenants \(1000+\). **Solution**: Distribute the tenants across Spoke Gateways, for horizontal scaling and blast radius minimization. - **Requirement**: Provide both dedicated tenant services, and shared services. **Solution**: Host dedicated services in tenant-specific Spoke VPCs. Host shared services in common Spoke VPCs. - **Requirement**: Onboard the tenants with BGP: dynamic control plane that fits their operational model. **Solution**: Terminate BGP on the tenant Spoke Gateways. - **Requirement**: Handle overlapping IPs across tenants, and between tenants and shared services. **Solution**: Use NAT on the tenant Spoke Gateways. - **Requirement**: Maintain isolation across tenants. **Solution**: Use segmentation domains on the tenant Spoke Gateways. - **Requirement**: Provide the highest throughput to tenant services. **Solution**: Horizontal scaling. Tenant services are directly hosted in the Spoke VPC where BGP terminates. They are directly accessed by tenants, without the Transit layer to be a bottleneck. |spokegw_external_saas_sol| How does using a BGP-enabled spoke to an external device work? -------------------------------------------------------------- The Aviatrix Spoke GW runs a BGP session to an external router to dynamically exchange routes. It also establishes an IPSEC tunnel to the router for packet forwarding (BGP is run over IPsec only). BGP is run on top of a S2C connection that terminates on active-mesh spoke gateways. All spoke gateways must be active mesh (no standalone gateway). Each spoke gateway must have a unique Autonomous System (AS) number. Note the following points: Fully integrated with ActiveMesh 2.0 control plane. Route-based only. Active/Active HA is supported towards ActiveMesh and towards on-prem with ECMP across multiple BGP connections. Active/Standby S2C is also supported. Co-existence of BGP S2C with static S2C connections under the same Spoke GW is supported. FireNet is supported. The inspection policy is the entire Spoke Gateway including all the BGP routes (not individual S2C BGP sessions). The following features are not supported on a BGP-enabled spoke gateway in the current (6.6) release: - ActiveMesh 1.0. - Mapped NAT. - Manual Spoke Encrypted peering. - User VPN. - CloudWAN. - Stateful Firewall. - Private S3. - Egress transit. - Customize Spoke VPC Routing Table. - Private VPC Default Route. - Skip Public VPC Route Table. - Select Route Tables upon Spoke Gateway Attachment to Transit. The following features configured on a Transit Gateway take no effect on a Spoke VPC equipped with a BGP-enabled Spoke Gateway (they still work for any other Spoke VPC): - Customize Attached Spoke VPC Routing Table. - Exclude Learned CIDRs to Spoke VPC. |spokegw_external_ex_arch| Interactions with Segmentation Domains ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When using BGP-enabled spoke gateways, SaaS providers can use segmentation domains per spoke gateway to enforce isolation across tenants. When segmentation domains are set per BGP-enabled spoke gateway, the site to cloud (S2C) BGP connection respects the domain of the spoke gateway for traffic enforcement and route advertisement. All S2C connections on a given spoke gateway belong to the spoke gateway domain (currently, you cannot have different S2C connections on a given spoke gateway be assigned to different domains). In the current release: - BGP routes of a tenant are always advertised to all other tenants connected with S2C BGP under the same Spoke Gateway. No segmentation policies can control that. Connection Manual BGP Advertised Network List can control it. - BGP routes of a tenant are propagated into ActiveMesh based on the connection policies of the spoke gateway. - ActiveMesh routes are advertised over BGP based on the connection policies of the Spoke. Interactions with NAT ~~~~~~~~~~~~~~~~~~~~~ In the current release, the following applies for NAT and BGP-enabled spoke gateways: - Customized NAT under Gateway config is supported (mapped NAT under S2C config is not currently supported). - S2C BGP connections are available as option in the NAT connection. - ActiveMesh connections are available in the NAT connection but ONLY for non-HPE spoke gateways. - Many:1 and 1:1 NAT are possible. - Active/Active HA for both gateways and S2C connections (with flow affinity) is supported. Route Propagation ~~~~~~~~~~~~~~~~~ Spoke VPC CIDR + BGP prefixes received on the Spoke GW are propagated into ActiveMesh (Subnets outside of RFC 1918 are programmed on the VPC RTBs). All CIDRs known to ActiveMesh (Spoke VPCs for all regions and clouds + BGP prefixes + custom advertisements, etc.) are advertised over BGP on the Spoke GW S2C BGP connections. |bgp_spoke_route_propagation| Connected Transit ~~~~~~~~~~~~~~~~~ The propagation of BGP routes learned on a Spoke GW to other Spoke GWs under the same Transit complies with Connected Transit. If Connected Transit = Disabled, those routes are not propagated to other Spoke GWs under the same Transit. In this example, 192.168.200.0/25 learned via BGP on Spoke-1-GW is not propagated to Spoke-2-GW: |bgp_spoke_connected_transit| How do I configure a BGP spoke gateway and connect it to external router? ---------------------------------------------------------------------------------------------- This section describes how to: - Create a Spoke Gateway that is BGP enabled. - Create the S2C BGP tunnel (build a site-to-cloud IPsec BGP attachment for the newly created spoke). - Configure your router with the connection details. - Configure additional settings. Step 1: Create a BGP-Enabled Spoke Gateway ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To create a BGP-enabled spoke gateway: .. note:: In the current release (6.6), BGP must be enabled at the creation of the Spoke GW. Spoke GWs created pre-6.6 cannot be enabled with BGP. A Spoke GW enabled with BGP has a few restrictions compared to a non-BGP Spoke. See the section above "How does using a BGP-enabled spoke to an external device work?" for information about restrictions. 1. Log in to the Aviatrix Controller. 2. From the sidebar, expand the Multi-Cloud Transit option, and then select **Setup**. 3. Click on **Spoke** at the top of the workflow page. The Launch an Aviatrix Spoke Gateway page opens. 4. Specify your information in step 1 and ensure you click the **Enable BGP** checkbox also: - Gateway Name: Specify the name for your spoke gateway. - Region: Select the region in which you want to deploy the spoke. - VPC ID: - Click **Enable BGP**. 5. Click **Create**. 6. (Optional) Enable HA for the spoke gateway. When HA is enabled, a second Spoke GW will be launched. For best practice, the HA GW should be launched on a different public subnet in a different Availability Zone. Note: If the Spoke GW is connected to VGW, you cannot disable Spoke GW HA. 7. Scroll back up to the top of the Launch an Aviatrix Spoke Gateway workflow page. 8. Click **External Connection**. Now that you've created the Spoke Gateway, you can connect it to the external device (device in an on-prem network). In this case, you will build a site-to-cloud (S2C) BGP over IPsec connection as instructed in the next section. Step 2: Create the S2C BGP Tunnel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To create the S2C BGP tunnel: 1. In the Multi-Cloud Transit Workflow > Setup > External Connection, select **External Device**. You use the External Device option on the Spoke Gateway to build a BGP tunnel directly to the on-prem device for exchanging routes with a remote site. 2. Select **BGP** so that the Spoke GW runs dynamic routing with remote site. 3. Select **IPsec** to run BGP and build an IPsec connection to a remote site. 4. Specify the rest of the parameters (defined below) and click **Connect**. Fill the parameters and click OK. For ActiveMesh design notes, check out `ActiveMesh Design Notes <https://docs.aviatrix.com/HowTos/activemesh_design_notes.html#configuration-notes>`_. ============================ ========== **Setting** **Value** ============================ ========== External Device Select this option to build a connection to a remote site. BGP Select BGP if the Spoke GW runs dynamic routing with remote site. Static Remote Route-Based Select this option the remote site supports route-based VPN with static configuration. IPsec Select this option to run BGP and build a IPSEC connection to a remote site. Transit VPC Name The Transit VPC ID where Transit GW was launched. Connection Name A unique name to identify the connection to external device. Aviatrix Gateway BGP ASN The BGP AS number the Spoke GW will use to exchange routes with the external device. Primary Aviatrix Gateway The Spoke GW you created. Algorithms Optional parameters. Leave it unselected if you don't know. IKEv2 Select the option to connect to the remote site using IKEv2 protocol. Enable Remote Gateway HA Select HA if there are two external devices. Over Private Network Select this option if your underlying infrastructure is private network, such as AWS Direct Connect and Azure Express Route. See "How does it work" section for more details. When this option is selected, BGP and IPSEC run over private IP addresses. BGP Remote AS Number When BGP is selected, the BGP AS number the external device will use to exchange routes Aviatrix Spoke GW. Remote Gateway IP IP address of the remote device. Pre-shared Key Optional parameter. Leave it blank to let the pre-shared key to be auto generated. Local Tunnel IP Optional parameter. This field is for the tunnel inside IP address of the Spoke gateway. Leave it blank. Remote Tunnel IP Optional parameter. This field is for the tunnel inside IP address of the External device. Leave it blank. Over Private Network(Backup) Select this option if HA is enabled. BGP Remote ASN (Backup) When BGP is selected, the remote ASN for backup should be the same as the primary remote ASN. Remote Gateway IP (Backup) IP address of the remote device. If "Private Network" is selected, enter the private IP address of the external device. Pre-shared Key (Backup) Optional parameter. Leave it blank to let the pre-shared key to be auto generated. Local Tunnel IP (Backup) Optional parameter. This field is for the tunnel inside IP address of the Spoke gateway. Leave it blank. Remote Tunnel IP (Backup) Optional parameter. This field is for the tunnel inside IP address of the External device. Leave it blank. ============================ ========== Step 3: Configure the external device ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To configure the external device: 1. From the sidebar, expand the Site2Cloud option, and then select **Setup**. From the list of connections, take note that the Status of the connection you created to the external device is Down. 2. From the table, click on the name of the connection you created to the external device (for example, Spoke-S2C-IPsec-T2Router) and then click **Edit**. The Connection Detail page opens. 3. For Vendor, select the device you are using (any device that is capable of running IPsec and BGP). (For example, **Cisco**.) 4. For Platform, select the applicable platform for the chosen device. (For example, **ISR, ASR, or CSR**.) 5. Click **Download Configuration**. Open the downloaded Aviatrix Site2Cloud configuration template. 6. Apply the following changes on your external device configuration (for example, on your CiscoASA) to configure the on-prem device with IPSEC tunnel and BGP: Crypto Policy Number Tunnel Number with Tunnel Source Make similar changes on the configuration of the backup tunnel. |spokegw_bgp_external_device_config| Step 4: Verify status of connection is UP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (Verify status of connection is Up) After configuring the router, the tunnel should change the status from down to up. Go back to the controller Site2Cloud option Setup page and click the refresh icon. Verify the status of your connection is now Up. Step 5: Verify the BGP routes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (To verify the BGP routes) On the controller, from the sidebar, expand the Multi-Cloud Transit option and then select **BGP**. Under Diagnostics, select the Gateway name (of the BGP-enabled spoke). From the predefined show list, select **show ip bgp** to verify the BGP Routes. Step 6: Customize spoke advertised VPC CIDRs ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ You can customize spoke advertised VPC CIDRs for your BGP-enabled spoke gateway. The CIDRs are propagated into ActiveMesh and into BGP as belonging to the Spoke Gateway shown in the example. The actual Spoke VPC CIDR is not advertised by default, but you can add it to the list. ActiveMesh propagation: those CIDRs are combined with the BGP prefixes received on the S2C BGP connection(s) of the Spoke GW. BGP advertisement: those CIDRs are combined with all other ActiveMesh CIDRs from the Aviatrix transit. |spokegw_external_custom_adv_cidrs| Step 7: Set Up approval for gateway learned CIDR ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ You can set up approval for gateway learned CIDRs for your BGP-enabled spoke gateways. You must select Gateway mode (connection-level route approval is currently not supported). Route approval completely blocks a BGP prefix to even be considered by the control plane. Prefixes blocked are not programmed in the gateway route table. |bgp_spoke_learned_cidr_appr| Step 8: Set Up BGP Route Control ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1. From the sidebar, expand the Multi-Cloud Transit option, and then select **Advanced Config**. 2. At the top of the page, click **Edit Spoke**. 3. Select the BGP enabled spoke gateway. 4. Specify the parameters to suit your business requirements (they are similar to BGP controls on transit gateways): Local AS Number BGP ECMP Active-Standby Gateway Manual BGP Advertised Network List Connection Manual BGP Advertised Network List (Disconnect) To disconnect the external device ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To disconnect the external device from the BGP-enabled Spoke GW: 1. Log in to Aviatrix Controller. 2. From the sidebar, expand the Multi-Cloud Transit option, and then select **Setup**. 3. In the Multi-cloud Transit Network Workflow page, click the **Detach** option. 4. In Aviatrix Spoke Gateway, select the Spoke GW you created from the list menu. 5. Click **Detach**. .. |spokegw_external_saas_sol| image:: spokegw_external_media/spokegw_external_saas_sol.png :scale: 30% .. |spokegw_external_ex_arch| image:: spokegw_external_media/spokegw_external_ex_arch.png :scale: 30% .. |spokegw_external_custom_adv_cidrs| image:: spokegw_external_media/spokegw_external_custom_adv_cidrs.png :scale: 30% .. |spokegw_bgp_external_device_config| image:: spokegw_external_media/spokegw_bgp_external_device_config.png :scale: 30% .. |bgp_spoke_connected_transit| image:: spokegw_external_media/bgp_spoke_connected_transit.png :scale: 30% .. |bgp_spoke_route_propagation| image:: spokegw_external_media/bgp_spoke_route_propagation.png :scale: 30% .. |bgp_spoke_learned_cidr_appr| image:: spokegw_external_media/bgp_spoke_learned_cidr_appr.png :scale: 30% .. disqus:: <file_sep>============================================== Security Update Policy ============================================== This page lists announcements of security fixes made in Critical Patch Update Advisories, Security Alerts, and Release Notes and it is updated when new Critical Patch Update Advisories, Security Alerts, and Release Notes are released. We currently disclose vulnerabilities and security releases via numerous channels: - `Aviatrix Controller and Gateway Release Notes <https://docs.aviatrix.com/HowTos/Controller_and_Software_Release_Notes.html>`_ - `PSIRT Advisories <https://docs.aviatrix.com/HowTos/PSIRT_Advisories.html>`_ - Early Disclosure Mailing List - Customers can also subscribe to notices of fix availability via the `Email Notifications <https://docs.aviatrix.com/HowTos/alert_and_email.html#changing-the-email-recipients-of-alert-email-notifications>`_. .. important:: While deploying our collective multi-cloud architecture, it is preferable to have the upgrades within a maintenance window. The Aviatrix Product Security Team intends to help routine operations by having quarterly security releases so that upgrade operations can be planned for in advance. If you have any questions, please open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_. Patch Tuesday ======================== The Aviatrix Product Security Team is intending to ship a security release on the 1st Tuesday of every third month. A Patch Tuesday can consist of image releases, software releases, or both. Announcements will be made two weeks before a Patch Tuesday release including whether the release will contain image or software releases. - These security releases may contain fixes for multiple CVEs. - All fixes that are included will be described in the Patch Tuesday release notes. - The schedule for the Patch Tuesday release is as follows: #. 08/02/2022 #. 11/01/2022 #. 02/07/2023 #. 05/02/2023 Unscheduled Security Releases ========================= Aviatrix attempts to ship all security fixes in a Patch Tuesday release. Exceptions to this policy may be made for critical vulnerabilities. Examples of these include: - Externally exploitable denial of service vulnerabilities affecting the data plane. - Unauthorized externally exploitable remote code execution affecting either the control plane or the data plane. - Zero-day vulnerabilities: Dependent on context, zero-day generally means a public, unpatched vulnerability. For purposes of this document, we are referring to public, unpatched vulnerabilities that are actively exploited. Early Disclosure List ========================= The intent of the early disclosure list is to notify you that an upgrade is coming at a specific date and time so that you can prepare a maintenance window to upgrade. The early disclosure email purposely limits vulnerability details prior to release so that when the public becomes aware of a vulnerability, a fix is available. Updated Software Packages ========================= An Aviatrix security update may include the following software packages: - `Controller or Gateway software Patches <https://docs.aviatrix.com/HowTos/Security_Patches.html>`_ - `Controller or Gateway software upgrades <https://docs.aviatrix.com/HowTos/Controller_and_Software_Release_Notes.html>`_ - `Controller or Gateway image upgrades <https://docs.aviatrix.com/HowTos/image_release_notes.html>`_ <file_sep> .. raw:: html <style> div[class='highlight'] pre { white-space: pre-wrap; } </style> ============================================================================== OpenVPN® with SAML Authentication on Azure AD IdP ============================================================================== Overview ----------------- This guide provides an example on how to configure Aviatrix to authenticate against Azure AD IdP. When SAML client is used, your Aviatrix Controller acts as the Identity Service Provider (ISP) that redirects browser traffic from client to IdP (e.g., Azure AD) for authentication. Pre-Deployment Checklist ------------------------------------ Before configuring SAML integration between Aviatrix and Azure AD, make sure the following is completed: #. An `Aviatrix Controller <#azureadsaml-aviatrix-controller>`__ is set up and running. #. You have an `Azure account <#azureadsaml-azure-account>`__. #. You have downloaded and installed the `Aviatrix SAML VPN client <#azureadsaml-aviatrix-client>`__. .. _azureadsaml_aviatrix_controller: Aviatrix Controller #################### If you haven’t already deployed the Aviatrix Controller, follow `the Controller Startup Guide <https://docs.aviatrix.com/StartUpGuides/aviatrix-cloud-controller-startup-guide.html>`_. .. _azureadsaml_azure_account: Azure Account ################################# Configure Azure AD on your Azure account before continuing with the configuration. .. _azureadsaml_aviatrix_client: Aviatrix VPN Client ################### All users must use the Aviatrix VPN client to connect to the system. Download the client for your OS `here <../Downloads/samlclient.html>`__. Configuration Steps ----------------------------- Follow these steps to configure Aviatrix to authenticate against your Azure AD IDP: #. Create a `Azure AD SAML Application <#azuread-saml-app>`__ for Aviatrix in the AWS Console. #. Create a `SAML Endpoint <#azuread-saml-endpoint>`__ in the Aviatrix Controller. .. _azuread_saml_app: Azure AD Custom SAML Application ################################ Before you start, pick a short name to be used for the SAML application name. In the notes below we will refer to this as **aviatrix_azuread**, but, it can be any string. We will use the string you select for the SAML application name to generate a URL for Azure AD to connect with Aviatrix. This URL is defined below as **SP_ACS_URL**. This URL should be constructed as: "https://<<<your Controller IP or host name>>>/flask/saml/sso/<<<aviatrix_azuread>>>" .. tip:: Replace **<<<your Controller IP or host name>>>** with the actual host name or IP address of your Controller and **<<<aviatrix_azuread>>>** with the string you chose to refer to the SAML application. **Connect to Azure** Log in to your Azure portal. **Create Custom SAML Application** #. Go to the Azure Active Directory service. #. Select **Enterprise Applications** under the **Manage** navigation menu item. #. Click **+ New application**. |imageAddAppsMenu| .. note:: You must be an administrator to add new Enterprise Applications. #. Click **Non-gallery application**. |imageAddAppNonGallery| #. Enter a Display Name. .. note:: Custom applications require an Azure AD Premium subscription. |imageAddAppSetName| #. Click **Add**. **Assign Users to this Application** #. Click **Users and groups** below **Manage**. #. Click **+ Add user**. #. Select a User and Role. #. Click **Assign**. |imageAssignUser| **Single Sign-on Configuration** Click **Single sign-on** below **Manage**. **Application Domain and URLs** #. Select **SAML-based Sign-on** from the **Single Sign-on Mode** dropdown menu. #. Fill out the fields below. +----------------------------+-----------------------------------------+ | Field | Value | +============================+=========================================+ | Identifier (Entity ID) | ``https://<<<your controller>>>`` | +----------------------------+-----------------------------------------+ | Reply URL | **SP_ACS_URL** | +----------------------------+-----------------------------------------+ | Show Advanced URL settings | checked | +----------------------------+-----------------------------------------+ | Sign on URL | **SP_ACS_URL** | +----------------------------+-----------------------------------------+ | Relay State | (leave blank) | +----------------------------+-----------------------------------------+ |imageSAMLSettings| **User Attributes** #. Enter **user.mail** for **User Identifier**. #. Click **View and edit all other user attributes**. #. Add the following **SAML Token Attributes** (please find the right values from your Azure user details to match firstname, lastname and email). You can also add "Profile" and send the profile name of a VPN profile - at this time,we only support attaching one profile per user via SAML. +------------------+-----------------------------------------+------------+ | NAME | VALUE | NAMESPACE | +==================+=========================================+============+ | FirstName | user.givenname | (blank) | +------------------+-----------------------------------------+------------+ | LastName | user.surname | (blank) | +------------------+-----------------------------------------+------------+ | Email | user.mail | (blank) | +------------------+-----------------------------------------+------------+ |imageUserAttrs| Note: Recently, Azure changed to a New UI "attributes & claims". The following picture is the new reference setting example. |imageUserClaims| **SAML Signing Certificate** #. Find the **Metadata XML** link. #. Click the link to download the file. |imageSAMLMetadata| **Save Application** Click **Save**. .. _azuread_saml_endpoint: Aviatrix Controller SAML Endpoint ################################# #. Log in to your Aviatrix Controller. #. Select OpenVPN > Advanced from the left sidebar. #. Select the **SAML** tab. #. Click **+ Add New**. #. Follow the table below for details on the fields in the table: +----------------------------+-----------------------------------------+ | Field | Description | +============================+=========================================+ | Endpoint Name | Pick | +----------------------------+-----------------------------------------+ | IPD Metadata Type | Text | +----------------------------+-----------------------------------------+ | IDP Metadata Text/URL | Paste in the metadata XML file contents | | | downloaded earlier. | +----------------------------+-----------------------------------------+ | Entity ID | Select **Hostname** | +----------------------------+-----------------------------------------+ | Custom SAML Request | Mark this checkbox | | Template | | +----------------------------+-----------------------------------------+ |imageAvtxSAMLEndpoint| #. Copy the following into the **Custom SAML Request Template** field: .. code-block:: xml <?xml version="1.0" encoding="UTF-8"?> <samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ID="$ID" Version="2.0" IssueInstant="$Time" Destination="$Dest" ForceAuthn="false" IsPassive="false" ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" AssertionConsumerServiceURL="$ACS"> <saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">$Issuer</saml:Issuer> </samlp:AuthnRequest> .. note:: This is required to connect with Azure AD. If you don't do this, you will receive an error message when testing. #. Click **OK*. Validating ----------------- .. tip:: Be sure to assign users to the new application in Azure AD prior to validating. If you do not assign your test user to the Aviatrix User VPN application, you will receive an error. You can quickly validate that the configuration is complete by clicking **Test** next to the SAML endpoint. |imageAvtxTestButton| .. |imageAddAppsMenu| image:: azuread_saml_media/azure_ad_new_app.png .. |imageAddAppNonGallery| image:: azuread_saml_media/azure_ad_new_app_non_gallery.png .. |imageAvtxSAMLEndpoint| image:: azuread_saml_media/avx_controller_saml.png .. |imageSPMetadataURL| image:: azuread_saml_media/sp_metadata_button.png .. |imageAvtxTestButton| image:: azuread_saml_media/avtx_test_button.png .. |imageAddAppSetName| image:: azuread_saml_media/azure_ad_add_new_step_1.png .. |imageAssignUser| image:: azuread_saml_media/azure_ad_assign_user.png .. |imageUserAttrs| image:: azuread_saml_media/azure_ad_saml_user_attrs.png .. |imageUserClaims| image:: azuread_saml_media/azure_ad_saml_user_claims.png .. |imageSAMLSettings| image:: azuread_saml_media/azure_ad_saml_settings.png .. |imageSAMLMetadata| image:: azuread_saml_media/azure_ad_saml_metadata.png <file_sep> ============================================================ AWS TGW Connect over Direct Connect ============================================================ Overview for AWS TGW Connect over Direct Connect ================================================ Amazon Web Services (AWS) enables AWS customers to integrate their Software Defined Wide Area Network (SD-WAN) devices with AWS Transit Gateway and AWS Direct Connect so they can use their existing SD-WAN devices to connect their on-premises networks to an AWS Transit Gateway. Refer to the following AWS articles for information about the attachments types involved (Transit Gateway Connect attachment and Transit Gateway Connect peer): * https://aws.amazon.com/blogs/networking-and-content-delivery/simplify-sd-wan-connectivity-with-aws-transit-gateway-connect/ * https://aws.amazon.com/blogs/networking-and-content-delivery/integrate-sd-wan-devices-with-aws-transit-gateway-and-aws-direct-connect/ In support of this, Aviatrix enables you to create one or multiple Transit Gateway Connect attachments over Direct Connect. You can also create Transit Gateway Connect peer attachments. For instructions, see the Enable AWS TGW Connect over Direct Connect section below. Enabling AWS TGW Connect over Direct Connect =========================================== To enable AWS TGW Connect over Direct Connect: 1. (On AWS) Set up the Direct Connect Gateway and the Transit virtual interface. 2. (In your Aviatrix Controller) Edit the TGW CIDR blocks. Navigate to the TGW Orchestrator > List > TGW tab. Select the gateway and edit its CIDR in the Edit TGW CIDR dialog. * The maximum number of CIDR blocks is 5. * The CIDR block must be the same as Direct Connect allowed prefix (e.g., 192.168.127.12/24). 3. (In Aviatrix Controller) Build a TGW Direct Connect attachment with allowed prefix (e.g., 192.168.127.12/24). 4. (In Aviatrix Controller) Build a TGW Connect attachment over AWS Direct Connect. In the TGW Orchestrator, in the step for Setup TGW Connect, select either the VPC attachment or the AWS Direct Connect attachment. You can build multiple TGW Connect attachments with the same transport Direct Connect attachment. 5. (In Aviatrix Controller) Build a TGW Connect peer with GRE configuration. A connect peer is a GRE tunnel. The TGW Connect attachment supports up to four GRE tunnels (connect peers). Below is the information you specify (TGW Orchestrator > List > Attachments tab > Create Connect PeerWS) to create the TGW Connect peer. For the description of each parameter, see `this AWS article: <https://aws.amazon.com/blogs/networking-and-content-delivery/integrate-sd-wan-devices-with-aws-transit-gateway-and-aws-direct-connect/>`_. Enter the information in Create Connect Peer: - Maximum number of TGW Connect peer: 4 - AWS Transit Gateway GRE address: - Peer GRE address: - BGP Inside CIDR blocks: The BGP addresses must be unique across all tunnels in a TGW. IPv6 is not supported. The following CIDR blocks are reserved and cannot be used: 169.254.0.0/29, 169.254.1.0/29, 169.254.2.0/29, 169.254.3.0/29, 169.254.4.0/29, 169.254.5.0/29, 169.254.169.252/29 - Peer ASN: 6. (On your third-party branch appliances) Complete the Connect peer configuration (GRE tunnel and BGP peering configuration). If you have the same prefix propagated into your TGW route table coming from VPN, Direct Connect, and Transit Gateway Connect attachments, AWS evaluates the best path in the following order: Priority 1 – Direct Connect Gateway attachment Priority 2 – Transit Gateway Connect attachment Priority 3 – VPN attachment TGW Connect attachment over AWS Direct Connect .. disqus:: <file_sep> .. toctree:: :numbered: ============================================================================== Aviatrix Controller Login with SAML Authentication ============================================================================== 1. Overview ------------ This guide provides an example on how to configure the Aviatrix Controller to authenticate to an IdP. When SAML is used for Controller access authentication, your Aviatrix controller acts as the Identity Service Provider (ISP) that redirects browser traffic from client to IdP (e.g., Okta) for authentication. The Aviatrix controller SAML login supports multiple SAML endpoints with varying access and utilizing different IdP's. For different IdP's, there will be links to each individual IdP integration. 2. Pre-Deployment Checklist ----------------------------- Before configuring SAML integration between Aviatrix and IdP, make sure the following is completed: #. `Aviatrix Controller <#pdc-21>`__ is setup and running #. Have a valid `IdP account <#pdc-22>`__ with admin access .. _PDC_21: 2.1 Aviatrix Controller ####################### If you haven’t already deployed the Aviatrix controller, follow `the Controller Startup Guide <https://docs.aviatrix.com/StartUpGuides/aws_getting_started_guide.html>`_. .. _PDC_22: 2.2 IdP Account ############### An IdP refers to an identity provider for SAML. This could be any provider that supports a SAML end point like `Okta <./SAML_Integration_Okta_IdP.html>`__, `OneLogin <./SAML_Integration_OneLogin_IdP.html>`__, `Google <./SAML_Integration_Google_IdP.html>`__, `AWS SSO <./SAML_Integration_AWS_SSO_IdP.html>`__, `Azure AD <./SAML_Integration_Azure_AD_IdP.html>`__, and `PingOne <./SAML_Integration_PingOne_IdP.html>`__. You will require administrator access to create IdP endpoints for SAML. Check `IdP-specific SAML Integration <#idp-integration>`__ to see a list of guides for supported IdP's 3. Configuration Steps ---------------------- Follow these steps to configure Aviatrix to authenticate against IdP: 1. Create `temporary Aviatrix SP Endpoint <#config-31>`__ for Aviatrix controller 2. Create `SAML IdP App <#config-32>`__ with specific IdP #. Retrieve `IdP Metadata <#config-33>`__ from IdP #. Update `Aviatrix SP Endpoint <#config-34>`__ with IdP metadata #. `Test the Integration <#config-35>`__ is set up correctly #. `Validate <#config-36>`__ .. _Config_31: 3.1 Create temporary Aviatrix SP Endpoint ######################################### .. note:: This step is usually completed by the Aviatrix admin. This endpoint will be updated later on in the guide. At this step, we will be using placeholder values. Choose an endpoint name for your Aviatrix SAML endpoint which will be used throughout the guide. This guide will use ``aviatrix_saml_controller`` as an example for the endpoint name. #. Login to the Aviatrix Controller #. Click `Settings` in the left navigation menu #. Select `Controller` #. Click on the `SAML Login` tab #. Click `ADD NEW` button |image3-1-1| |image3-1-2| +-------------------------+-------------------------------------------------+ | Field | Value | +=========================+=================================================+ | Endpoint Name | Enter a unique identifier for the service provider | +-------------------------+-------------------------------------------------+ | IPD Metadata Type | Text or URL (depending on what was | | | provided by the SAML provider) | | | For now, choose URL | +-------------------------+-------------------------------------------------+ | IdP Metadata Text/URL | IdP metadata URL/Text copied from the SAML | | | provider configuration | | | For now, put in a placeholder URL, | | | such as "https://www.google.com" | +-------------------------+-------------------------------------------------+ | Entity ID | Select `Hostname` for now | +-------------------------+-------------------------------------------------+ | Access | Select admin or read-only access | +-------------------------+-------------------------------------------------+ | Custom SAML Request | For now leave blank, depending on your specific | | Template | IdP, you may have to check this option | +-------------------------+-------------------------------------------------+ .. note:: Each endpoint only supports one type of access. If you need admin and read-only access, create two separate SAML apps. #. Click `OK` #. Depending on your IdP provider, you may need to upload SP metadata. After temporary SAML endpoint is created: - Click **DOWNLOAD SP METADATA** button next to the SAML endpoint and save file to your local machine - Click **SP METADATA** button, and copy the SP metadata as text .. _Config_32: 3.2 Create a SAML App for Aviatrix with the IdP ############################################### .. note:: This step is usually done by the IdP administrator. This section shows only a generalized process for creating a SAML application. Refer to the `IdP-specific SAML App Integration <#idp-integration>`_ section for links to detailed steps with each particular IdP. Create a SAML 2.0 app with the IdP Provider with the following values. #. Assertion Consumer Service URL* #. Audience URI(Entity ID)* #. SP Metadata URL #. SP Login URL #. Default RelayState* = <empty> .. important:: You can find these values in the controller under the `Settings` navigation item. Then, select `Controller` and go to the `SAML Login` tab. Click on the button for the respective value, and copy the URL on the new page. RelayState is currently not used by the Aviatrix SP |image3-2| The following SAML attributes are expected: #. FirstName #. LastName #. Email (unique identifier for SAML) .. note:: These values are case sensitive .. _Idp_Integration: **IdP-specific SAML App Integration** .. note:: You will require administrator access to create IdP endpoints for SAML. These are guides with specific IdP's that were tested to work with Aviatrix SAML integration: #. `AWS SSO <./SAML_Integration_AWS_SSO_IdP.html>`__ #. `Azure AD <./SAML_Integration_Azure_AD_IdP.html>`__ #. `Centrify <./SAML_Integration_Centrify_IdP.html>`__ #. `Google <./SAML_Integration_Google_IdP.html>`__ #. `Okta <./SAML_Integration_Okta_IdP.html>`__ #. `OneLogin <./SAML_Integration_OneLogin_IdP.html>`__ #. `PingOne <./SAML_Integration_PingOne_IdP.html>`__ Other tested IdP's include: VmWare VIDM, ForgeRock's OpenAM etc. .. _Config_33: 3.3 Retrieve IdP metadata ########################## After creating the IdP, you need to retrieve IdP Metadata either in URL or text from the IdP application created in the previous step. #. AWS SSO - provides IdP metadata URL, needs a custom SAML request template, and will need to provide SP metadata file from Aviatrix #. Azure AD - provides IdP metadata URL and needs a custom SAML request template #. Centrify - provides IdP metadata URL and will need to provide SP metadata text from Aviatrix #. Google - provides IdP metadata text #. Okta - provides IdP metadata URL #. OneLogin - provides IdP metadata URL #. PingOne - provides IdP metadata URL .. _Config_34: 3.4 Update Aviatrix SP Endpoint ############################### .. note:: his step is usually completed by the Aviatrix admin. Take note of the IdP Metadata type along with Text/URL your IdP provides, and if you need a custom SAML request template in the previous section. #. Login to the Aviatrix Controller #. Click `Settings` in the left navigation menu #. Select `Controller` #. Click on the `SAML Login` tab #. Click `Edit` button +-------------------------+----------------------------------------------------------+ | Field | Value | +=========================+==========================================================+ | Endpoint Name | Unique name that you chose in step 3.1 | +-------------------------+----------------------------------------------------------+ | IPD Metadata Type | Text or URL (depending on what was | | | provided by the SAML provider) | +-------------------------+----------------------------------------------------------+ | IdP Metadata Text/URL | IdP metadata URL/Text copied from the SAML | | | provider configuration | +-------------------------+----------------------------------------------------------+ | Entity ID | Select `Hostname` or `Custom` | +-------------------------+----------------------------------------------------------+ | Custom Entity ID | Only visible if `Entity ID` is `Custom` | +-------------------------+----------------------------------------------------------+ | Access | Select admin or read-only access | +-------------------------+----------------------------------------------------------+ | Custom SAML Request | Depending on your specific | | Template | IdP, you may have to check this option. | | | Refer to `IdP-specific Integration <#idp-integration>`__ | +-------------------------+----------------------------------------------------------+ .. note:: `Hostname` is the default for Entity ID, but if you have other apps using the same hostname, use a custom Entity ID. 6. Click `OK` .. _Config_35: 3.5 Test the Integration ######################## #. Click `Settings` in the left navigation menu #. Select `Controller` #. Click on the `SAML Login` tab #. Click the `Test` button next to your SAML endpoint name |image3-5| #. You should be redirected to IdP. Login with your test user credentials. .. important:: If everything is configured correctly, once you have authenticated, another windows should open with the test user's access. .. _Config_36: 3.6 Validate ############ #. Logout of the Aviatrix Controller #. Choose from the dropdown box your SAML endpoint name #. Login to the Aviatrix Controller by clicking the `SAML Login` button. |image3-6| #. You should be redirected to IdP. Login with your test user credentials. .. important:: If everything is configured correctly, once you have authenticated you will be redirected to the dashboard's controller. .. |logoAlias1| replace:: Aviatrix logo with red background .. _logoAlias1: https://www.aviatrix.com/news/press-kit/logo-aviatrix.png .. |logoAlias2| replace:: Aviatrix logo with transparent background .. _logoAlias2: https://www.aviatrix.com/images/logo-reverse.png .. |image3-1-1| image:: Controller_Login_SAML_media/image3-1-1.png .. |image3-1-2| image:: Controller_Login_SAML_media/image3-1-2.png .. |image3-2| image:: Controller_Login_SAML_media/image3-2.png .. |image3-5| image:: Controller_Login_SAML_media/image3-5.png .. |image3-6| image:: Controller_Login_SAML_media/image3-6.png .. disqus:: <file_sep>========================================================= Transit Connection to Cisco Router over the internet. ========================================================= 1. From the Controller go to Transit Network -> Setup -> Launch a Transit VPC GW. |image1| 2. Connect the transit VPC GW to the Cisco Router. Go to Transit Network -> Setup -> Connect to VGW/External Device. select External Device and input the following parameters. a. BGP Local AS number: ASN of the transit VPC GW b. BGP Remote AS number: ASN of the Cisco CSR c. Remote Gateway IP Address: Cisco WAN Public ip. |image2| 3. Download the configuration by going to Site2Cloud -> Click on the Connection. select generic and Download Configuration and configure on the router accordingly. |image3| The following is a sample configuration based on the site2cloud configuration above. |image4| 4. Apply the following IOS configuration to your router: |image5| Note: The tunnel IP addresses are configured accordingly with the configuration file downloaded from above. 5. After configuring the router the tunnel should change the status from down to up. |image6| 6. Go to Transit Network -> Advanced Config on the Controller and Click on Diagnostics and select the GW name from the dropdown list and select Show Ip bgp Command from the predefined Show list to verify the BGP Routes. |image7| |image8| .. |image1| image:: ./S2C_TGW_CiscoRouter_media/cisco1.png :scale: 30% .. |image2| image:: ./S2C_TGW_CiscoRouter_media/cisco2.png :scale: 30% .. |image3| image:: ./S2C_TGW_CiscoRouter_media/cisco3.png :scale: 30% .. |image4| image:: ./S2C_TGW_CiscoRouter_media/cisco4.png :scale: 30% .. |image5| image:: ./S2C_TGW_CiscoRouter_media/cisco5.png :scale: 30% .. |image6| image:: ./S2C_TGW_CiscoRouter_media/cisco6.png :scale: 30% .. |image7| image:: ./S2C_TGW_CiscoRouter_media/cisco7.png :scale: 30% .. |image8| image:: ./S2C_TGW_CiscoRouter_media/cisco8.png :scale: 30% .. disqus:: <file_sep> ========================================================= ActiveMesh FAQ ========================================================= What is Aviatrix ActiveMesh? ---------------------------------------------- ActiveMesh is the new Aviatrix Encrypted Transit Network architecture where both primary gateways and backup gateways forward packets in a load balancing fashion. The diagram below shows an ActiveMesh deployment between Spoke and Transit where each Spoke Gateway in a VPC/VNet builds two IPsec tunnels to the primary and backup transit gateways and forwards packets to both of them inside the tunnel. The load balance mechanism leverages ECMP protocol. |activemesh_spoke_transit| Can ActiveMesh be applied to Transit Gateway peering? ---------------------------------------------------------------------- Yes. ActiveMesh can be applied to connecting two Transit GWs. There are 4 tunnels established between the Transit GWs, as shown in the diagram below. |activemesh_transit_transit| Can ActiveMesh be applied to connection to VGW? -------------------------------------------------------------- Yes. Each Transit GW connecting to the VGW in ActiveMesh mode has two VPN tunnels to the VGW. What is the link for between the two ActiveMesh gateways? ---------------------------------------------------------- The link is used to forward packets when both tunnels are down out of one ActiveMesh gateway. For example, in a spoke VPC/VNet, virtual machine (EC2/GCE) traffic is forwarded to the ActiveMesh primary gateway which then forwards traffic to the AVX Transit GW. If both tunnels between the ActiveMesh spoke gateway and the Transit GW are down, the packet is forwarded by the ActiveMesh primary gateway to the backup ActiveMesh gateway. |activemesh_tunnel_failures| How do Spoke gateways load balance traffic from EC2 instance? ---------------------------------------------------------------- In the current Release 5.0, VPC route table points to only one Spoke Gateway, so there is no load balancing for traffic initiated from virtual machine instances. But once the traffic arrives at the gateway for transmission to the Spoke VPC/VNet, the traffic is load balanced across the ActiveMesh peering to the Spoke VPC/VNet Gateways. What are the advantages of ActiveMesh? -------------------------------------------------------------------------------------- The key benefits of ActiveMesh are improved network resiliency, failover convergence time and performance. How to enable ActiveMesh? -------------------------------- ActiveMesh is enabled by default. For Aviatrix Transit or Spoke Gateway launched before ActiveMesh mode becomes available, follow the `Aviatrix Encrypted Transit Network workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-a-transit-gateway>`_ to enable ActiveMesh mode. How to troubleshoot ActiveMesh Transit Gateway? ------------------------------------------------- 1. **Check IPsec Tunnel**. For BGP learned routes, check if the IPsec tunnel is up. Go to Site2Cloud > Setup. Find the connection and make sure it is in Up state. If it is not, go to Site2Cloud > Diagnostics and run **Show log**. Since all BGP sessions run inside IPsec tunnel, this is the first thing you should check. #. **Check BGP Session**. For BGP learned routes, check if BGP session is established. Go to Multi-Cloud Transit > BGP. Look for the BGP session and make sure it is in Established State. If it is not, go to the Diagnostics tab. Select the transit gateway, run commands, such as "show ip bgp". #. **Check BGP Learned Routes** For BGP learned routes, check if routes are learned. Go to Multi-Cloud Transit > BGP > Diagnostics tab. Select the transit gateway, run "show ip bgp" to make sure the transit gateway under inspection has learned the routes you are looking for. #. **Check Route Database** For all routes, check if the Controller see all the learned routes from TGW, BGP, Transit Peering, and Static. Go to Multi-Cloud Transit > List. Select the Transit Gateway and click **Show Details**. Scroll down and refresh **Route Info DB Details**. This table contains learned routes from all sources. #. **Check Aviatrix Transit Gateway Programmed Routes** Go Multi-Cloud Transit Network > List. Select the Transit Gateway, click **Actions ** > Show Details. Scroll down to the Gateway Routing Table and click to open. Make sure the route you are looking for is in the table and has a next hop with metric 100 or lower. #. **Sync Routes** If for any reason the Route Database on the Controller become inconsistent with the Aviatrix Transit Gateway route table, sync the routes to force program the routes on the gateway again. Go to Multi-Cloud Transit > Advanced Config. Select the Aviatrix Transit Gateway in question, scroll down to the Sync Controller Best Routes to Transit Gateway, click **Sync Routes**. If any of the above steps show failure, there is an error, please open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_ for more debugging assistance. If all above steps succeed, the connectivity issue lies somewhere else. Check Spoke VPC/VNet route table and TGW route table if applicable. If this is TGW based deployment, run an Audit by going to TGW Orchestrator > Audit. Any missing routes in either VPC/VNet route table or TGW route table should be discovered. How to migrate from the encrypted transit network to ActiveMesh mode? --------------------------------------------------------------------------------------------- Here are the steps: 1. Launch a new Transit GW and enable ActiveMesh on it. #. Detach a current spoke and attach it to the new Transit GW. Can ActiveMesh be applied to Azure, GCP and OCI? --------------------------------------------------------------- Yes. What is route based VPN and policy-based VPN? ---------------------------------------------------------------- Most firewalls appliances support both policy based and route based VPNs. Which one we are supposed to use in most cases doesn't really matter, but there are a couple of things to consider. Route based VPNs are more flexible, more powerful and recommended over policy based VPNs. However, a policy based VPN is usually simpler to create. A route based VPN creates a virtual IPsec interface, and whatever traffic hits that interface is encrypted and decrypted according to the phase 1 and phase 2 IPsec settings. In a policy based VPN, the tunnel is specified within the policy itself with an action of IPsec. Also, for a policy based VPN, only one policy is required. A route based VPN is created with two policies, one for inbound and another for outbound with a normal Accept action. A static route is also required for a route based VPN, so anything destined to the remote network must go through the virtual IPsec interface which was created when specifying this within the Phase 1 settings. If the VPN connection requires redundancy, a route based VPN is normally required. Does ActiveMesh support route based VPN or policy based VPN? ------------------------------------------------------------- ActiveMesh enables the Aviatrix Transit GW to connect to multiple remote sites over IPsec VPN tunnels. When you configure VPN to remote sites from Transit Network > Setup > Step 3 (Connect to VGW/External Device/Aviatrix CloudN) in the `Transit Network workflow Step 3 <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#connect-the-transit-gw-to-aws-vgw>`_, the VPN tunnel is built with route based VPN on the Aviatrix Transit Gateway. Starting from Release 6.0, ActiveMesh Transit Gateway supports both remote route based VPN and remote policy based VPN tunnels. In both cases, the Aviatrix Transit Gateway operates in route based mode. Note if the remote site is policy based static VPN, traffic must be initiated from the remote site. On the other hand, when you configure VPN to remote sites from Site2Cloud page and select a Transit GW, the VPN tunnel is built with policy based VPN. What happens when an ActiveMesh enabled gateway is stopped? ---------------------------------------------------------------------------------------- With ActiveMesh gateway, `Gateway Single AZ HA <https://docs.aviatrix.com/HowTos/gateway.html#gateway-single-az-ha>`_ is automatically enabled. That is, when an ActiveMesh gateway is stopped, the Controller automatically starts it again. Once the gateways comes up, it participates in packet forwarding again. To stop an ActiveMesh gateway, you should disable the Gateway Single AZ HA feature. Highlight the gateway at the Gateway page and click **Edit**. Scroll down to Gateway Single AZ HA and click **Disable**. What is ActiveMesh? --------------------------------------- ActiveMesh has a deterministic nature of Next Hop selection. Here is how Aviatrix Transit Gateway routing engine treats the following types of routes. ======================================================== =============== ========== **Networks** **Route Type** **Aviatrix Transit Gateway Route Propagation** ======================================================== =============== ========== Local TGW attached VPC/VNet CIDR tgwvpc Local Aviatrix Spoke gateway associated VPC/VNet CIDR vpc Local Azure Native Spoke associated VNet CIDR vpc Local Local TGW VPN dynamically learned network CIDR tgwedge Advertises TGW VPN ASN and its remote peer ASN to a remote BGP peer if it's the best route. Local TGW DXGW learned network CIDR tgwedge Advertises TGW DXGW ASN and its remote peer ASN to a remote BGP peer if it's the best route. Remote Aviatrix Transit Gateway Peering learned routes peer Advertises remote Aviatrix peer's network CIDRs to a remote BGP peer if it's the best route. Aviatrix Transit Gateway BGP learned from on-prem bgp Advertises to its remote peers by Aviatrix Transit Gateway peering if it's the best route. Aviatrix Transit Gateway statically learned from on-prem static Local Aviatrix Transit Gateway associated VPC/VNet CIDR linklocal Local Local Firewall Egress route (0.0.0.0/0) transit Local Aviatrix Transit Gateway SNAT IP address linklocal Local ======================================================== =============== ========== With this approach, there is more visibility on learned routes regarding what paths the routes are learned from. The next hop best path selection follows the priorities listed below. 1. Local #. Shortest number of ASN list #. For two identical length ASN routes, select the next hop with the lowest Metric Value #. For two identical ASN length and Metric Value routes, if ECMP is disabled (this is the default configuration), select the current best route. If there is no current best route, the next hop IP addresses are compared, the lower integer IP address is selected. #. For two identical ASN length and Metric Value routes, if ECMP is enabled, traffic is distributed to both routes using ECMP. How to migrate to ActiveMesh? -------------------------------------- There are 3 scenarios: ================================= =============================================================================================== ========== **Deployment** **Notes** **ActiveMesh 2.0 Migration** ================================= =============================================================================================== ========== Non ActiveMesh deployment the Aviatrix Transit Gateway in the deployment has been launched before Release 5.1 (10/1/2019) follow `this instructions <https://docs.aviatrix.com/HowTos/activemesh_migration.html>`_ ActiveMesh 1.0 deployment the Aviatrix Transit Gateway was launched with ActiveMesh option enabled prior to Release 6.0 migrate to ActiveMesh 2.0 by going to Settings -> Maintenance -> Migration -> ActiveMesh 2.0 Migration, click Migrate. New deployment the Aviatrix Transit Gateway was launched with ActiveMesh option enabled after Release 6.0 ActiveMesh is automatically enabled for brand new deployment on a Controller. ================================= =============================================================================================== ========== .. |activemesh_spoke_transit| image:: activemesh_faq_media/activemesh_spoke_transit.png :scale: 30% .. |activemesh_transit_transit| image:: activemesh_faq_media/activemesh_transit_transit.png :scale: 30% .. |activemesh_tunnel_failures| image:: activemesh_faq_media/activemesh_tunnel_failures.png :scale: 30% .. |activemesh_tunnel_failures| image:: activemesh_faq_media/activemesh_tunnel_failures.png :scale: 30% .. disqus:: <file_sep> ========================================================= Logging ========================================================= Introduction ================ The Aviatrix Controller and all of its managed gateways can be configured to forward logs to well known log management systems. The Controller and all of the managed gateways will forward the logs directly to the logging server and hence each of them need network connectivity to the logging server. Out of box integration is supported for the following logging service or systems. - Remote syslog (recommended) - Elastic Filebeat - Splunk Enterprise/Cloud - Sumo Logic - Datadog - Netflow - AWS CloudWatch .. note:: The Splunk, Sumo Logic, and Logstash integrations are deprecated and not supported from Release 6.8 and onwards. Instead, use rsyslog to integrate with external logging systems. In addition to standard information on syslog, Aviatrix also provides capability for user VPN connections, VPN user TCP sessions, security rule violation statistics, Gateway stats and FQDN filter violations. The Log Management System can be used to sift through the Aviatrix logs and get the meaningful trend charts that help monitor the network connectivity and user VPN sessions. The following sections provide a list of useful Aviatrix logs which can be parsed on Splunk, Sumo Logic and other log management systems to display relevant analytics of data collected from Aviatrix Controller and gateways. Aviatrix Log Format for Log Management Systems ================================================== The following types of Aviatrix log keywords can be identified by the Log Management System for further analysis: - `AviatrixVPNSession <https://docs.aviatrix.com/HowTos/AviatrixLogging.html#id1>`_ - `AviatrixUser <https://docs.aviatrix.com/HowTos/AviatrixLogging.html#id2>`_ - `AviatrixLicenseVPNUsers <https://docs.aviatrix.com/HowTos/AviatrixLogging.html#id4>`_ - `AviatrixRule <https://docs.aviatrix.com/HowTos/AviatrixLogging.html#id6>`_ - `AviatrixGwMicrosegPacket <https://docs.aviatrix.com/HowTos/AviatrixLogging.html#id7>`_ - `AviatrixGwNetStats <https://docs.aviatrix.com/HowTos/AviatrixLogging.html#id8>`_ - `AviatrixGwSysStats <https://docs.aviatrix.com/HowTos/AviatrixLogging.html#id9>`_ - `AviatrixFQDNRule <https://docs.aviatrix.com/HowTos/AviatrixLogging.html#id10>`_ - `AviatrixTunnelStatusChange <https://docs.aviatrix.com/HowTos/AviatrixLogging.html#id11>`_ - `AviatrixCMD <https://docs.aviatrix.com/HowTos/AviatrixLogging.html#id12>`_ - `AviatrixBGPOverlapCIDR <https://docs.aviatrix.com/HowTos/AviatrixLogging.html#id13>`_ - `AviatrixBGPRouteLimitThreshold <https://docs.aviatrix.com/HowTos/AviatrixLogging.html#aviatrixbgproutelimitthreshold>`_ - `AviatrixGuardDuty <https://docs.aviatrix.com/HowTos/AviatrixLogging.html#id14>`_ - `AviatrixFireNet <https://docs.aviatrix.com/HowTos/AviatrixLogging.html#id15>`_ - `AviatrixVPNVersion <https://docs.aviatrix.com/HowTos/AviatrixLogging.html#id16>`_ - `AviatrixGatewayStatusChanged <https://docs.aviatrix.com/HowTos/AviatrixLogging.html#id17>`_ Below are the details of each log keyword. AviatrixVPNSession: -------------------- This log is for gateways that have `VPN enabled <http://docs.aviatrix.com/HowTos/Cloud_Networking_Ref_Des.html>`_. To enable VPN, check "VPN Access" when launching a gateway. Logs with this prefix come from the Controller and contain information such as VPN user name, the VPN gateway IP address and name where the user connects to, client virtual IP address, connection duration, total received bytes, total transmitted bytes, and login and logout time. Two logs will be generated for each VPN connection. One is when the connection is established, the other when it is disconnected. Example logs: **Connect Log:** :: Aug 17 22:07:39 ip-172-31-46-24 cloudx_cli: AviatrixVPNSession: User=Splumo, Status=active, Gateway=splunksumo, GatewayIP=192.168.3.11, VPNVirtualIP=192.168.0.6, PublicIP=N/A, Login=2016-08-17 22:07:38, Logout=N/A, Duration=N/A, RXbytes=N/A, TXbytes=N/A **Disconnect log:** :: Aug 17 22:26:37 ip-172-31-46-24 cloudx_cli: AviatrixVPNSession: User=Splumo, Status=disconnected, Gateway=splunksumo, GatewayIP=192.168.3.11, VPNVirtualIP=192.168.0.6, PublicIP=N/A, Login=2016-08-17 22:07:38, Logout=2016-08-17 22:26:37, Duration=0:0:18:59, RXbytes=2.1 MB, TXbytes=9.03 MB AviatrixUser: -------------- This log is for gateways that have `VPN enabled <http://docs.aviatrix.com/HowTos/Cloud_Networking_Ref_Des.html>`_. To enable VPN, check "VPN Access" when launching a gateway. Logs with this prefix come from each VPN gateway managed by the controller. The log contains the information for the TCP session, such as inbound and outbound interface, source IP address, destination IP address, TTL value, protocol name, and packet length. The log record is for each packet that passes through the VPN connection from the client to the destination. Two example logs: :: Aug 17 22:15:47 ip-10-100-0-60 kernel: [14167.983249] ***AviatrixUser***:IN= OUT=eth0 SRC=192.168.0.6 DST=192.168.127.12 LEN=64 TOS=0x00 PREC=0x00 TTL=63 ID=28916 DF PROTO=TCP SPT=50428 DPT=443 WINDOW=65535 RES=0x00 SYN URGP=0 Aug 17 22:15:47 ip-10-100-0-60 kernel: [14167.968275] ***AviatrixUser***:IN= OUT=eth0 SRC=192.168.0.6 DST=10.100.0.2 LEN=66 TOS=0x00 PREC=0x00 TTL=254 ID=13309 PROTO=UDP SPT=64775 DPT=53 LEN=46 AviatrixLicenseVPNUsers: ------------------------- This log is for gateways that have `VPN enabled <http://docs.aviatrix.com/HowTos/Cloud_Networking_Ref_Des.html>`_. To enable VPN, check "VPN Access" when launching a gateway. Logs with this prefix come from the Controller and can be used to monitor the license usage of active vpn users connected to all vpn gateways. One example log: :: Sep 25 23:40:19 ip-10-40-0-133 cloudxd: AviatrixLicsenseVPNUsers: users=2 AviatrixRule: -------------- You need to configure `security policies <http://docs.aviatrix.com/HowTos/gateway.html#security-policy>`_ to see AviatrixRule log. Logs with this prefix come from each gateway managed by the controller. Any packet that triggers the security policy rule will generate a log record of this type with the first 100 bytes of the packet. It contains the information such as gateway IP address, inbound and outbound interface, MAC address, TTL value, protocol name, source IP address, destination IP address and packet length. An example for a deny rule event is shown below. The log event prefix is "AvxRl gw1 D:", where the gateway name is gw1, "D" represents Drop. :: 2019-04-10T23:33:47.217018+00:00 ip-10-240-0-44 kernel: [ 4976.320353] AvxRl gw1 D:IN=eth0 OUT=eth0 MAC=02:bd:e5:4f:d0:e2:02:d8:14:81:fc:48:08:00 SRC=10.240.1.60 DST=10.230.1.23 LEN=84 TOS=0x00 PREC=0x00 TTL=63 ID=45312 DF PROTO=ICMP TYPE=8 CODE=0 ID=2833 SEQ=1 Another example for an accept rule event is shown below. The log event prefix is "AvxRl StatefulGW2 A:", where the gateway name is StatefulGW2, "A" represents Accept. :: 2019-04-10T23:34:47.602166+00:00 ip-10-240-0-44 kernel: [ 5036.705845] AvxRl StatfulGW2 A:IN=eth0 OUT=eth0 MAC=02:bd:e5:4f:d0:e2:02:d8:14:81:fc:48:08:00 SRC=10.240.1.60 DST=10.230.1.23 LEN=84 TOS=0x00 PREC=0x00 TTL=63 ID=48453 DF PROTO=ICMP TYPE=8 CODE=0 ID=2834 SEQ=1 AviatrixGwMicrosegPacket: ------------------------- You need to configure `micro-segmentation policies <https://docs.aviatrix.com/HowTos/secure_networking_microsegmentation.html>`_ to see AviatrixGwMicrosegPacket logs. Logs with this prefix come from your configured micro-segmentation policies. These logs contain the following information: - timestamp - source IP - destination IP - protocol (for example, ICMP or TCP) - port number - if a policy is enforced - if a policy was allowed or denied - gateway name - policy ID A micro-segmentation log example is shown below: :: 2022-05-25T15:57:43.088860+00:00 ip-10-4-179-71 /usr/local/bin/avx-gw-state-sync[1168]: 2022/05/25 15:57:43 AviatrixGwMicrosegPacket: POLICY=54ea65c4-313e-4b3d-8db3-1ecc4f0981db SRC_MAC=16:06:11:d7:a1:11 DST_MAC=16:54:ec:50:09:17 IP_SZ=84 SRC_IP=10.4.187.253 DST_IP=10.5.144.38 PROTO=ICMP SRC_PORT=0 DST_PORT=0 DATA=0x ACT=PERMIT ENFORCED=true AviatrixGwNetStats: -------------------- Logs with this prefix come from each gateway managed by the controller. These logs are sampled every minute and give details about gateway network interface. Two example logs: :: 2020-06-09T17:29:31.372628+00:00 GW-test-10.23.183.116 perfmon.py: AviatrixGwNetStats: timestamp=2020-06-09T17:29:31.371791 name=test public_ip=10.23.183.116.fifo private_ip=172.31.78.160 interface=eth0 total_rx_rate=10.06Kb total_tx_rate=12.77Kb total_rx_tx_rate=2.85Kb total_rx_cum=207.16MB total_tx_cum=1.2MB total_rx_tx_cum=208.36 2020-06-12T08:30:09.297478+00:00 GW-test-10.23.183.116 perfmon.py: AviatrixGwNetStats: timestamp=2020-06-12T08:30:09.296752 name=test public_ip=10.23.183.116.fifo private_ip=172.31.78.160 interface=eth0 total_rx_rate=8.84Kb total_tx_rate=8.45Kb total_rx_tx_rate=17.29Kb total_rx_cum=4.63MB total_tx_cum=6.8MB total_rx_tx_cum=11.44MB AviatrixGwSysStats: ------------------- Logs with this prefix come from each gateway managed by the controller. These logs are sampled every minutes and give details about gateway memory, cpu and disk load. Two example logs: :: 2020-06-09T17:29:31.372822+00:00 GW-test-10.23.183.116 perfmon.py: AviatrixGwSysStats: timestamp=2020-06-09T17:29:31.371791 name=test cpu_idle=68 memory_free=414640 memory_available=1222000 memory_total=1871644 disk_total=16197524 disk_free=10982084 2020-06-12T08:22:09.295660+00:00 GW-test-10.23.183.116 perfmon.py: AviatrixGwSysStats: timestamp=2020-06-12T08:22:09.294333 name=test cpu_idle=99 memory_free=919904 memory_available=1264792 memory_total=1871644 disk_total=16197524 disk_free=11409716 AviatrixFQDNRule ---------------- You need to configure `FQDN Whitelists <http://docs.aviatrix.com/HowTos/FQDN_Whitelists_Ref_Design.html>`_ in order to see these logs. Logs with this prefix come from each gateway managed by the controller. Domain name filtering can be configured per gateway via controller. And every time a gateway tries to access a domain name, it will check if the domain name passes the configured filters. If it does, access will be allowed with the state as MATCHED, otherwise it will be discarded with state as NO_MATCH. Two example logs: :: 2019-12-12T04:33:46.892381+00:00 ip-172-32-0-6 avx-nfq: AviatrixFQDNRule2[CRIT]nfq_ssl_handle_client_hello() L#281 Gateway=spoke1-fqdn S_IP=172.16.17.32 D_IP=172.16.31.10 hostname=aviatrix-download.s3-us-west-2.amazonaws.com state=MATCHED Rule=*.amazonaws.com;1 2019-12-12T04:36:53.173210+00:00 ip-172-32-0-6 avx-nfq: AviatrixFQDNRule1[CRIT]nfq_ssl_handle_client_hello() L#281 Gateway=spoke1-fqdn S_IP=172.16.17.32 D_IP=172.16.17.32 hostname=www.yahoo.com state=NO_MATCH drop_reason=NOT_WHITELISTED AviatrixTunnelStatusChange -------------------------- Logs with this prefix come from the controller whenever a tunnel status changes. old_state means old state of the tunnel, and new_state is the new changed state of tunnel. Example log: :: 2019-11-30T15:44:52.718808+00:00 ip-172-32-0-226 cloudxd: AviatrixTunnelStatusChange: src_gw=oregon-transit(AWS us-west-2) dst_gw=192.168.3.11(NA NA) old_state=Down new_state=Up AviatrixCMD -------------------------- Logs with this prefix come from the controller whenever a CLI command is issued. It contains information on the CLI command that was issued, the results of the execution, reason a message if there is a failure and who issued the command. Example log: .. highlight:: none :: 2019-11-19T20:13:44.585942+00:00 ip-172-32-0-226 cloudxd: AviatrixCMD: action=USERCONNECT_UPGRADE_TO_VERSION, argv=['--rtn_file', '/run/shm/rtn957594707', 'userconnect_upgrade_to_version', 'upgrade-status', ''], result=Success, reason=, username=admin 2019-11-19T18:01:59.796230+00:00 ip-172-32-0-226 cloudxd: AviatrixCMD: action=TRANSIT_SPOKE_LIST, argv=['--rtn_file', '/run/shm/rtn2091225061', 'transit_spoke_list', '--spoke_only'], result=Success, reason=, username=admin AviatrixBGPOverlapCIDR ------------------------ Log messages with this prefix come from the Controller whenever it detects overlapping CIDRs between on-prem learned and Spoke VPC CIDRs. Example log: :: 2018-09-24T20:28:58.330708+00:00 ip-172-31-23-128 cloudxd: AviatrixBGPOverlapCIDR: Time Detected: 2018-09-24 20:28:58.329881 Spoke/Manual CIDRs ['10.0.0.0/8'] have a conflict with BGP Learned CIDRs [u'10.2.0.0/16', u'192.168.127.12/16'] in VPC vpc-782bb21f on connection vgw-bgp-ha. AviatrixBGPRouteLimitThreshold -------------------------------- Log messages with this prefix come from the Controller whenever it detects that total BGP routes exceed the 80 routes. (AWS VGW has a total 100 route limit.) Example log: :: 2018-09-24T20:24:50.600144+00:00 ip-172-31-23-128 cloudxd: AviatrixBGPRouteLimitThreshold: This message is alerting you that the VGW listed below currently has 89 routes, which is approaching the VGW route limits (100). You can reduce the number of routes on VGW both from on-prem side and on Aviatrix Transit gateway by enabling Route Summarization feature. Time Detected: 2018-09-24 20:24:50.599822 Connection Name: vgw-bgp-ha VGW Id: vgw-0942b724a5150bc6a AviatrixGuardDuty ------------------- Log messages with this prefix come from the Controller whenever it receives an alert message from AWS GuardDuty. Example log: :: 2018-09-23T00:00:50.369963-07:00 ip-172-31-89-197 cloudxd: AviatrixGuardDuty: Account [aws], Region [us-east-1], Instance ID [i-0a675b03fafedd3f2], at 2018-09-23T02:05:35Z, 172.16.31.10 is performing SSH brute force attacks against i-0a675b03fafedd3f2. Please tighten instance security group to avoid UnauthorizedAccess:EC2/SSHBruteForce threat. 2018-09-23T00:00:50.332066-07:00 ip-172-31-89-197 cloudxd: AviatrixGuardDuty: Account [aws], Region [us-east-1], Instance ID [i-0a675b03fafedd3f2], at 2018-09-23T06:35:40Z, Unprotected port on EC2 instance i-0a675b03fafedd3f2 is being probed. Please tighten instance security group to avoid Recon:EC2/PortProbeUnprotectedPort threat. AviatrixFireNet ----------------- Log messages with this prefix come from the Controller whenever a firewall instance state changes. Example log: :: 2019-11-19T09:38:40.070080-08:00 ip-172-31-93-101 cloudxd: AviatrixFireNet: Firewall i-021f23187b8ac81c9~~tran-fw-1 in FireNet VPC vpc-0f943cd05455358ac~~cal-transit-vpc-1 state has been changed to down. 2019-11-19T09:39:03.066869-08:00 ip-172-31-93-101 cloudxd: AviatrixFireNet: Firewall i-021f23187b8ac81c9~~tran-fw-1 in FireNet VPC vpc-0f943cd05455358ac~~cal-transit-vpc-1 state has been changed to unaccessible. 2019-11-19T09:40:12.878075-08:00 ip-172-31-93-101 cloudxd: AviatrixFireNet: Firewall i-021f23187b8ac81c9~~tran-fw-1 in FireNet VPC vpc-0f943cd05455358ac~~cal-transit-vpc-1 state has been changed to up. AviatrixVPNVersion ------------------- Log messages with this prefix come from the Controller whenever it rejects an Aviatrix VPN client connection. Example log: :: 2020-02-07T11:38:48.276150-08:00 Controller-192.168.3.11 cloudxd: AviatrixVPNVersion: The VPN connection was rejected as it did not satisfy the minimum version requirements. Current version: AVPNC-2.4.10 Required minimum version: AVPNC-2.5.7 . The rejected VPN user name is tf-aws-52-tcplb-user1 AviatrixGatewayStatusChanged ----------------------------- These log messages will be seen from the Controller's syslogs when a gateway's status changes Example log: :: 2020-03-29T00:09:13.201669+00:00 ip-10-88-1-63 cloudxd: AviatrixGatewayStatusChanged: status=down gwname=EMEA-ENG-VPNGateway Logging Configuration at Aviatrix Controller ================================================ To enable logging from the Aviatrix Controller, go to Settings > Logging. Once logging is enabled, both the Controller and all gateways will forward logs directly to the logging server. .. note:: A total of 10 profiles from index 0 to 9 are supported for remote syslog, while index 9 is reserved for CoPilot. Newly deployed gateway will be added to a profile if it is the only profile enabled in the index range of 0 to 8, If more than one profiles are enabled in the range of 0 to 8, the newly deployed gateway will not be added to any profile in the range of 0 to 8. User may use the advanced options in the logging "edit options" window to edit the exclude and include list. However newly deployed gateway will always be added to profile 9 which is reserved for Copilot to monitor. Remote Syslog ------------------ On the Aviatrix Controller: a. Profile Index: select a profile to edit #. Server: FQDN or IP address of the remote syslog server #. Port: Listening port of the remote syslog server (6514 by default) #. CA Certificate: Certificate Authority (CA) certificate #. Server Public Certificate: Public certificate of the controller signed by the same CA #. Server Private Key: Private key of the controller that pairs with the public certificate #. Protocol: TCP or UDP (TCP by default) #. Optional Custom Template: Useful when forwarding to 3rd party servers like Datadog or Sumo (Details bellow) On the Remote syslog server: a. Install rsyslog and rsyslog-gnutls packages #. Create a new config file in /etc/rsyslog.d with the similar content as in the following box depends on your rsyslog version to enable tls connection. Please make sure key paths are readable by the syslog user #. Make sure the output directory /var/log is writable by rsyslog user/daemon #. Restart rsyslog service and check port is listening and no error in /var/log/syslog #. Confirm the port is allowed in the security group / fireware for incoming traffic (version <8) :: $ModLoad imtcp $InputTCPServerRun 514 $DefaultNetstreamDriver gtls #Certificate location $DefaultNetstreamDriverCAFile /etc/cert/rsyslog-ca.pem $DefaultNetstreamDriverCertFile /etc/cert/rsyslog-crt.pem $DefaultNetstreamDriverKeyFile /etc/cert/rsyslog-key.pem $InputTCPServerStreamDriverAuthMode x509/certvalid $InputTCPServerStreamDriverMode 1 # run driver in TLS-only mode # Re-direct logs to host specific directories $template TmplMsg, "/var/log/aviatrix/%HOSTNAME%/%PROGRAMNAME%" *.info,mail.none,authpriv.*,cron.none ?TmplMsg & ~ (version >=8) :: global( DefaultNetstreamDriver="gtls" DefaultNetstreamDriverCAFile="/etc/cert/rsyslog-ca.pem" DefaultNetstreamDriverCertFile="/etc/cert/rsyslog-crt.pem" DefaultNetstreamDriverKeyFile="/etc/cert/rsyslog-key.pem" ) template(name="TmplMsg" type="list") { constant(value="/var/log/aviatrix/") property(name="hostname") constant(value="/") property(name="programname" SecurePath="replace") constant(value="") } ruleset(name="remote"){ *.info;mail.none;authpriv.*;cron.none action(type="omfile" DynaFile="TmplMsg") } module( load="imtcp" StreamDriver.Name="gtls" StreamDriver.Mode="1" StreamDriver.Authmode="anon" ) input(type="imtcp" port="514" ruleset="remote") Then 1. Go to /var/log/aviatrix directory #. Find the directory of desired controller or gateway a. Controller's directory name is in a format of Controller-public_IP_of_controller #. Gateway's directory name is in a format of GW-gateway_name-public_IP_of_gateway #. Each controller/gateway directory should have a. auth.log #. syslog Using Rsyslog to send logs to Sumo ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Since Sumo agents on the controller and gateways tend to consume a lot of cpu/memory resources, we strongly suggest that rsyslog is used instead to send logs to Sumo. This is `documented by Sumo <https://help.sumologic.com/03Send-Data/Sources/02Sources-for-Hosted-Collectors/Cloud-Syslog-Source>`_. Follow the following instructions: #. Follow the directions in `Sumo document <https://help.sumologic.com/03Send-Data/Sources/02Sources-for-Hosted-Collectors/Cloud-Syslog-Source>`_ to create a cloud syslog source on your collections. Save the token, host and tcp tls port. #. Go to Controller/Settings/Logging/Remote Syslog and enable the service #. Enter the Server ip/fqdn that you received from the first step #. Provide the port - obtained from the first step #. Upload the CA cert from Sumo pointed by their documentation #. Keep the Protocol set to TCP #. For Optional Custom Template, copy the following string and replace the string ADD_YOUR_SUMO_TOKEN_HERE with the token you received in the first step. Please do keep the square brackets around the token. .. code-block:: json <%pri%>%protocol-version% %timestamp:::date-rfc3339% %HOSTNAME% %app-name% %procid% %msgid% [ADD_YOUR_SUMO_TOKEN_HERE] %msg%\\n .. note:: The Aviatrix Controller expects certificates in PEM format. Attempting to upload the wrong format may return an Exception Error. To convert the DigiCert certificate downloaded from SumoLogic's documentation into PEM format, use the following command: openssl x509 -in DigiCertHighAssuranceEVRootCA.crt -inform der -outform pem -out DigiCertHighAssuranceEVRootCA.pem |rsyslog_template| .. |rsyslog_template| image:: AviatrixLogging_media/rsyslog_template.png :width: 6.50500in :height: 6.20500in Using Rsyslog to send logs to Datadog ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #. Go to Controller/Settings/Logging/Remote Syslog and enable the service #. Server: intake.logs.datadoghq.com #. Port: 10514 #. Protocol: TCP #. For Optional Custom Template, copy the following string and replace the string DATADOG_API_KEY with your own key. .. note:: DATADOG_API_KEY <%pri%>%protocol-version% %timestamp:::date-rfc3339% %HOSTNAME% %app-name% - - - %msg%\\n Using Rsyslog to send logs to Splunk ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #. Follow the directions in `Splunk Monitornetworkports <https://docs.splunk.com/Documentation/Splunk/latest/Data/Monitornetworkports>`_ to create a listener in Splunk. #. Go to Controller/Settings/Logging/Remote Syslog and enable the service #. Server: your Splunk server fqdn or ip #. Port: your Splunk listener port #. Protocol: TCP #. Optional Custom Template: (leave blank) Using Rsyslog to send logs to Logstash (ElasticSearch/Kibana/ELK stack) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #. Follow the directions in `Logstash TCP input <https://www.elastic.co/guide/en/logstash/current/plugins-inputs-tcp.html>`_ to create a tcp listener in Logstash. #. Go to Controller/Settings/Logging/Remote Syslog and enable the service #. Server: your Logstash server fqdn or ip #. Port: your Logstash listener port #. Protocol: TCP #. Optional Custom Template: (leave blank) A sample config of Logstash to work with Rsyslog in ELK stack v7 is :: input { syslog { port => 6514 } } output { elasticsearch { hosts => ["127.0.0.1:9200"] } } Filebeat Forwarder ----------------------- On the Aviatrix Controller: a. Server: FQDN or IP address of logstash server #. Port: Listening port of logstash server (5000 by default) #. Optional Configuration File: (Deprecated) A sample config of Logstash to work with Filebeat in ELK stack v7 is :: input { beats { port => 5000 } } filter { mutate { rename => { "[host][name]" => "[host]" } } } output { elasticsearch { hosts => ["127.0.0.1:9200"] } } Splunk Logging ------------------- On the Aviatrix Controller: a. How to configure: Manual Input or Import File #. Splunk Server: FQDN or IP address of Splunk Enterprise Server #. Splunk Server Listening Port: Listening port of Splunk Enterprise Server #. Splunk inputs.conf stanza: (Deprecated) Note: If "Import File" is selected for "How to configure", please provide the Splunk configuration file. Sumo Logic ------------------- On the Aviatrix Controller: a. Access ID : ID of SumoLogic server #. Access Key: Access key of SumoLogic server #. Source Category: The category string of the source #. Additional Configurations: (Deprecated) Steps to `upgrade <http://docs.aviatrix.com/HowTos/sumologic_upgrade.html>`_ Sumologic Collectors(eg: Controllers/Gateways) from SumoLogic servers. Please note that Sumo collector is memory intensive and needs instances with at least 2GB of memory - for AWS, t3.small, or higher depending on features deployed. DataDog Agent ------------------- You may refer to this link, `DatadogIntegration <https://docs.aviatrix.com/HowTos/DatadogIntegration.html>`_ to set up. However, based on the past year experience, the vendor has changed the client root certificates for a few times. a. You may disable DataDog Agent and re-enable it to fetch the current new root certificate. #. Or, we highly recommend to follow above 3.1.b steps to use Remote Syslog as client to forward to any servers and will not encounter any of these cert issues. Before 5.3 release, DataDog agent woulld only upload metrics from the Aviatrix Controller and Gateways - from release 5.3, we also upload syslogs to bring it on par with Sumo and Splunk agent behavior. Cloudwatch ------------------- Please follow this link `AWS CloudWatch Integration <https://docs.aviatrix.com/HowTos/cloudwatch.html>`_ for instruction. Log Management System Apps ==================================== The Aviatrix Controller can be configured to forward logs to various log management systems. Aviatrix also provides apps with prebuilt dashboards for popular log management systems like Splunk and Sumo Logic. Splunk App for Aviatrix ----------------------- Splunk app for Aviatrix can be downloaded from `Splunkbase <https://splunkbase.splunk.com/app/3585/>`_. Click `SplunkforAviatrix <https://github.com/AviatrixSystems/SplunkforAviatrix>`_ to check instructions on GitHub. **Sample** |splunk_sample| Sumo Logic App for Aviatrix --------------------------- The Sumo Logic app installation guide is also available on `GitHub <https://github.com/AviatrixSystems/SumoLogicforAviatrix>`_. **Sample** |sumo_sample| .. |splunk_sample| image:: DataAnalSplunkSumo_media/splunk_overview.png :width: 6.50000in :height: 6.55000in .. |sumo_sample| image:: DataAnalSplunkSumo_media/sumo_overview.png :width: 6.50500in :height: 6.20500in Loggly integration via Syslog ==================================== To configure Loggly integration through an intermediary syslog server relay: 1. Build an rsyslog server relay using a Linux distribution of your choice 2. Configure Aviatrix to send rsyslog traffic to the relay (section 3.1 above) 3. Follow `this document <https://www.loggly.com/docs/network-devices-and-routers/>`_ to configure the relay to send to Loggly Netflow ============= Aviatrix gateways support Netflow protocol v5 and v9. Please follow this link `Netflow Integration <https://docs.aviatrix.com/HowTos/netflow.html#netflow-integration>`_ to enable it. .. disqus:: <file_sep>======================================= PSIRT Advisories ======================================= Aviatrix Product Security Team continually tests the software product, looking for vulnerabilities and weaknesses. If you have a security issue to report, please open a support ticket at Aviatrix Support Portal at https://support.aviatrix.com. Any such findings are fed back to Aviatrix's development teams and serious issues are described along with protective solutions in the advisories below. Please note the below Aviatrix Security recommendations and communication plans: - Aviatrix strongly recommend customers to stay on the latest release to resolve features and bug issues. All fixes are in the new release; we do not patch older release versions. - Customers are strongly recommended to perform image migration 2x a year. The migration process provides the latest system level security patch - All known software vulerabilities are submitted to Mitre for CVE-ID references by Aviatrix Systems - Avitrix publish Field Notices and send alerts to Controller Admin in the Controller console when security related issues are published 23. Aviatrix Controller and Gateways - Unauthorized Access ---------------------------------------------------------- **Date** 08/02/2022 **Risk Rating** High for Gateways. **Description** Gateway APIs contain functions that are inappropriately authenticated and would allow an authenticated VPN user to inject arbitrary commands. **Impact** A successful attack would allow an authenticated VPN user to execute arbitrary comments against Aviatrix gateways. **Affected Products** Aviatrix Gateways **Solution** Upgrade your Aviatrix Controller and gateway software to: - 6.6.5712 or later - 6.7.1376 or later **Acknowledgement** Aviatrix would like to thank <NAME> from Splunk for the responsible disclosure of this issue. 22. Remote Code Execution ---------------------------------------- **Date** 05/27/2022 **Risk Rating** `AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H (10.0) <https://nvd.nist.gov/vuln-metrics/cvss/v3-calculator?vector=AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H&version=3.1>`_ **Description** Several vulnerabilities could be combined by an attacker to abuse a Gateway command mechanism that would allow arbitrary remote code execution. This vulnerability is not known to be exploited. **Impact** An unauthenticated attacker to run arbitrary commands against Aviatrix gateways. **Affected Products** Aviatrix Controller and Gateways. **Solution: Upgrade your controller and gateway software to:** - 6.4.3057 - 6.5.3233 - 6.6.5612 - 6.7.1185 21. Post-Auth Remote Code Execution ---------------------------------------- **Date** 04/11/2022 **Risk Rating** High **Description** TLDAP APIs contain functions that are inappropriately sanitized, and would allow an authenticated malicious user to inject arbitrary commands. **Impact** A local user to the controller UI could execute arbitrary code. **Affected Products** Aviatrix Controller. **Solution: Upgrade your controller and gateway software to:** - 6.4.3049 - 6.5.3166 - 6.6.5545 20. Aviatrix Controller and Gateways - Privilege Escalation ---------------------------------------- **Date** 02/03/2022 **Risk Rating** Medium **Description** The publicly disclosed CVE-2021-4034 and CVE-2022-0185 are local privilege escalation vulnerabilities disclosed in the past two weeks. When successfully executed, an attack exploiting these vulnerabilities can cause a local privilege escalation giving unprivileged users administrative rights on the target machine. The Aviatrix Gateway, Controller, and Copilot are all running vulnerable versions of the Linux packages. However, in order to successfully exploit these vulnerabilities, an attacker requires local access to our systems and no vulnerability known to us today would allow such attack. **Impact** A local user to our appliances can escalate his privileges to root. **Affected Products** Aviatrix Controller and Gateways. **Solution** - Upgrade Copilot to Release 1.6.3. - Apply security patch [AVI-2022-0001 - CVE-2021-4034 and CVE-2022-0185 Privilege Escalation Patches] to controllers. 19. Aviatrix Controller and Gateways - Unauthorized Access ---------------------------------------- **Date** 01/11/2022 **Risk Rating** High for Gateways, medium for Controller. **Description** On the Aviatrix Controller, a successful attack would allow an unauthenticated remote attacker partial access to configuration information and allow them to disrupt the service. On the gateway, a successful attack would allow an unauthenticated network-adjacent attacker (i.e.: an attacker present on the gateway's VPC) access to its API. **Impact** Access to configuration information and disruption of service. **Affected Products** Aviatrix Controller, Gateways and Copilot. **Solution** Upgrade your controller and gateway software to: - 6.4.2995 or later. - 6.5.2898 or later. 18. Aviatrix Controller - Remote file execution ---------------------------------------- **Date** 10/04/2021 **Risk Rating** Critical **Description** The Aviatrix Controller legacy API had a vulnerability allowing an unauthenticated attacker to upload arbitrary files, including .php scripts, to the filesystem. These uploaded scripts will be processed by the web frontend, allowing an attacker to run code of their choosing. **Impact** Remote file execution **Affected Product** Aviatrix Controller prior to the fixed versions. **Solution** The vulnerability has been fixed in: - UserConnect-6.2-1804.2043 or later - UserConnect-6.3-1804.2490 or later - UserConnect-6.4-1804.2838 or later - UserConnect-6.5-1804.1922 or later **CVE-ID** CVE-2021-40870 **Acknowledgement** Aviatrix would like to thank the team at Tradecraft (https://www.wearetradecraft.com/) for the responsible disclosure of these issues. 17. OpenVPN - Abitrary File Write ---------------------------------------- **Date** 8/10/2020 **Risk Rating** High **Description** The VPN service write logs to a location that is writable **Impact** Unauthorized file permission **Affected Product** Aviatrix OpenVPN R2.8.2 or earlier **Solution** Aviatrix OpenVPN OpenVPN 2.10.8 - May 14 2020 or later **CVE-ID** TBD **Acknowledgement** Aviatrix is pleased to thank <NAME>, Senior Adversarial Engineer - TeamARES from Critical Start, Inc. for reporting this vulnerability under responsible disclosure. 16. Bypass htaccess security control ---------------------------------------- **Date** 8/10/2020 **Risk Rating** Low **Description** The htaccess control to prevent requests to a cert directory can be bypassed to download files. **Impact** Excessive Permission **Affected Product** Controller 5.3.1516 **Solution** Controller R5.4.1290 (8/5/2020) or later **CVE-ID** TBD **Acknowledgement** Aviatrix would like to thank <NAME>, Senior Adversarial Engineer - TeamARES from Critical Start, Inc. for reporting this vulnerability under responsible disclosure. 15. Insecure File Permissions ---------------------------------------- **Date** 8/10/2020 **Risk Rating** Medium **Description** Several world writable files and directories were found **Impact** Excessive Permission **Affected Product** Controller 5.3.1516 **Solution** Controller R5.4.1290 (8/5/2020) or later **CVE-ID** TBD **Acknowledgement** Aviatrix would like to thank <NAME>, Senior Adversarial Engineer - TeamARES from Critical Start, Inc. for reporting this vulnerability under responsible disclosure. 14. Bypass Htaccess Security Control ---------------------------------------- **Date** 8/10/2020 **Risk Rating** Low **Description** The htaccess control to prevent requests to directories can be bypassed for file downloading. **Impact** Unauthorized file download **Affected Product** Aviatrix Controller 5.3 or earlier **Solution** Controller & Gateway upgrade R5.4.1290 (8/5/2020) or later **CVE-ID** CVE-2020-26549 **Acknowledgement** Aviatrix would like to thank <NAME>, Senior Adversarial Engineer - TeamARES from Critical Start, Inc. for reporting this vulnerability under responsible disclosure. 13. Insecure sudo rule ---------------------------------------- **Date** 8/10/2020 **Risk Rating** Medium **Description** A user account has permission to execute all commands access as any user on the system. **Impact** Excessive permission **Affected Product** Aviatrix Controller 5.3 or earlier **Solution** Controller & Gateway upgrade R5.4.1290 (8/5/2020) or later **CVE-ID** CVE-2020-26548 **Acknowledgement** Aviatrix would like to thank <NAME>, Senior Adversarial Engineer - TeamARES from Critical Start, Inc. for reporting this vulnerability under responsible disclosure. 12. Cleartext Ecryption Key Storage ---------------------------------------- **Date** 8/10/2020 **Risk Rating** High **Description** Encrypted key values are stored in cleartext in a readable file **Impact** Access to read key in encrypted format **Affected Product** Aviatrix Controller 5.3 or earlier **Solution** Controller & Gateway upgrade R5.3.1151 (6/4/2020) or later Migration required to the latest AMI Software Version 050120 (Aug 13, 2020) **CVE-ID** CVE-2020-26551 **Acknowledgement** Aviatrix would like to thank <NAME>, Senior Adversarial Engineer - TeamARES from Critical Start, Inc. for reporting this vulnerability under responsible disclosure. 11. Pre-Auth Account Takeover ---------------------------------------- **Date** 8/10/2020 **Risk Rating** Critical **Description** An API file does not require a valid session and allows for updates of account email addresses. **Impact** Access to unauthorized files **Affected Product** Aviatrix Controller 5.3 or earlier **Solution** Controller & Gateway upgrade R5.4.1290 (8/5/2020) or later **CVE-ID** CVE-2020-26552 **Acknowledgement** Aviatrix is pleased to thank <NAME>, Senior Adversarial Engineer - TeamARES from Critical Start, Inc. for reporting this vulnerability under responsible disclosure. 10. Post-Auth Remote Code Execution ---------------------------------------- **Date** 8/10/2020 **Risk Rating** High **Description** Several APIs contain functions that allow arbitrary files to be uploaded to the web tree. **Impact** Access to unauthorized files **Affected Product** Aviatrix Controller 5.3 or earlier **Solution** Controller & Gateway upgrade R6.0.2483 (8/4/2020) or later **CVE-ID** CVE-2020-26553 **Acknowledgement** Aviatrix is pleased to thank <NAME>, Senior Adversarial Engineer - TeamARES from Critical Start, Inc. for reporting this vulnerability under responsible disclosure. 9. Pre-Auth Remote Code Execution ---------------------------------------- **Date** 8/10/2020 **Risk Rating** Critical **Description** An API file does not require a valid session ID and allows arbitrary files to be uploaded to the web tree. **Impact** Access to unauthorized files **Affected Product** Aviatrix Controller 5.3 or earlier **Solution** Controller & Gateway upgrade R6.0.2483 (8/4/2020) or later **CVE-ID** CVE-2020-26553 **Acknowledgement** Aviatrix is pleased to thank <NAME>, Senior Adversarial Engineer - TeamARES from Critical Start, Inc. for reporting this vulnerability under responsible disclosure. 8. Insufficiently Protected Credentials ---------------------------------------- **Date** 8/10/2020 **Risk Rating** Critical **Description** An encrypted file containing credentials to unrelated systems is protected by a weak key. **Impact** Encryption key may not meet the latest security standard **Affected Product** Aviatrix Controller 5.3 or earlier **Solution** Controller & Gateway upgrade R5.3.1151 (6/4/2020) or later **CVE-ID** CVE-2020-26550 **Acknowledgement** Aviatrix would like to thank <NAME>, Senior Adversarial Engineer - TeamARES from Critical Start, Inc. for reporting this vulnerability under responsible disclosure. 7. Observable Response Discrepancy from API ---------------------------------------- **Date** 5/19/2020 **Risk Rating** Medium **Description** The Aviatrix Cloud Controller appliance is vulnerable to a user enumeration vulnerability. **Impact** A valid username could be used for brute force attack. **Affected Product** Aviatrix Controller 5.3 or earlier **Solution** Controller & Gateway upgrade 5.4.1204 (5/8/2020) or later **CVE-ID** CVE-2020-13413 **Acknowledgement** Aviatrix is pleased to thank <NAME>, Senior Adversarial Engineer - TeamARES from Critical Start, Inc. for reporting this vulnerability under responsible disclosure. 6. OpenVPN Client - Elevation of Privilege --------------------------------------- **Date** 5/19/2020 **Risk Rating** High **Description** The Aviatrix VPN client on Linux, macOS, and Windows is vulnerable to an Elevation of Privilege vulnerability. This vulnerability was previously reported (CVE-2020-7224), and a patch was released however the fix is incomplete. **Impact** This would impact dangerous OpenSSL parameters code execution that are not authorized. Impacts macOS, Linux and Windows clients. **Affected Product** Client VPN 2.8.2 or earlier Controller & Gateway 5.2 or earlier **Solution** Client VPN upgrade to 2.10.7 Controller & Gateway upgrade to 5.3 or later In Controller, customer must configure OpenVPN minimum client version to 2.10.7 **CVE-ID** CVE-2020-13417 **Acknowledgement** Aviatrix is pleased to thank <NAME>, Senior Adversarial Engineer - TeamARES from Critical Start, Inc. for reporting this vulnerability under responsible disclosure. 5. Cross Site Request Forgery (CSRF) --------------------------------- **Date** 5/12/2020 **Risk Rating** Critical **Description** An API call on Aviatrix Controller web interface was found missing session token check to control access. **Impact** Application may be vulnerable to Cross Site Request Forgery (CSRF) **Affected Product** Aviatrix Controller with software release 5.3 or earlier **Solution** Controller & Gateway upgrade 5.4.1204 (5/8/2020) or later **CVE-ID** CVE-2020-13412 **Acknowledgement** Aviatrix is pleased to thank <NAME>, Senior Adversarial Engineer - TeamARES from Critical Start, Inc. for reporting this vulnerability under responsible disclosure. 4. Hard Coded Credentials ------------------------- **Date** 1/16/2020 **Risk Rating** Low **Description** The Aviatrix Cloud Controller contains credentials unused by the software. This is a clean-up effort implemented to improve on operational and security maintenance. **Impact** This would impact operation and maintenance complexity. **Affected Product** Aviatrix Controller 5.3 or lower **Solution** Controller & Gateway upgrade 5.4.1204 (5/8/2020) or later Recommended: AWS Security Group settings grants only authorized Controller Access in your environment **CVE-ID** CVE-2020-13414 **Acknowledgement** Aviatrix is pleased to thank <NAME>, Senior Adversarial Engineer - TeamARES from Critical Start, Inc. for reporting this vulnerability under responsible disclosure. 3. CSRF on Password Reset ---------------------- **Date** 1/16/2020 **Risk Rating** Medium **Description** Controller Web Interface session token parameter is not required on an API call, which opens the application up to a Cross Site Request Forgery (CSRF) vulnerability. **Impact** Vulnerability could lead to the unintended reset of a user’s password. **Affected Product** Aviatrix Controller 5.3 or lower **Solution** Upgrade 5.4.1066 (must be on version is 5.0 or above) Make sure your AWS Security Group settings limit authorized Controller Access only **CVE-ID** CVE-2020-13416 2. XML Signature Wrapping in SAML ------------------------------ **Date** 2/26/2020 **Risk Rating** High **Description** An attacker with any signed SAML assertion from the Identity Provider can establish a connection (even if that SAML assertion has expired or is from a user who is not authorized to access Aviatrix).  **Impact** Aviatrix customer using SAML **Affected Product** Aviatrix Controller 5.1 or lower **Solution** Aviatrix Controller 5.2 or later Plus Security Patch “SAML XML signature wrapping vulnerability” **CVE-ID** CVE-2020-13415 **Acknowledgement** Aviatrix is pleased to thank <NAME> from Elastic for reporting this vulnerability under responsible disclosure. 1. OpenVPN Client Arbitrary File Write ------------------------------------ **Date** 1/16/2020 **Risk Rating** High **Description** Aviatrix OpenVPN client through 2.5.7 or older on Linux, MacOS, and Windows is vulnerable when OpenSSL parameters are altered from the issued value set; the parameters could allow unauthorized third-party libraries to load.  **Impact** OpenVPN client on Linux, MacOS, and Windows **Affected Product** OpenVPN Client 2.5.7 **Solution** Upgrade to VPN client v2.6 or later **CVE-ID** CVE-2020-7224 **Acknowledgement** Aviatrix is pleased to thank <NAME>, Senior Adversarial Engineer - TeamARES from Critical Start, Inc. for reporting this vulnerability under responsible disclosure. .. disqus:: <file_sep> ========================================================================================= Aviatrix NEXT GEN TRANSIT with customized SNAT and DNAT features ========================================================================================= This technical note provides a step-by-step configuration on the Aviatrix controller that will address the following requirements: 1. Spoke VPCs in Cloud need to communicate with On-Prem - https://docs.aviatrix.com/HowTos/tgw_faq.html - https://docs.aviatrix.com/HowTos/tgw_plan.html - https://docs.aviatrix.com/HowTos/tgw_build.html 2. On-Prem is not able to route RFC 1918 traffic to Cloud - Perform Customized SNAT feature for the traffic from Cloud to On-Prem - Perform DNAT feature for the traffic from On-Prem to Cloud Topology: 1. Aviatrix NEXT GEN TRANSIT FOR AWS - Spoke VPCs * 2 (for example: 10.1.0.0/16, 10.2.0.0/16) - Transit VPC * 1 (for example: 192.168.100.0/24) - AWS VGW 2. On-Prem routable CIDR (for example: 172.16.58.3/8) |SNAT_DNAT_TRANSIT_SOLUTION| Scenario: 1. Traffic from Cloud to On-Prem - When a packet sent from Spoke VPCs in Cloud enters the Aviatrix Transit Gateway, the packet’s source address needs to be changed to an IP that On-Prem is routable. (Source address translation) 2. Traffic from On-Prem to Cloud - When a packet sent from On-Prem enters the Aviatrix Transit Gateway, the packet’s destination address needs to be changed from an IP within the On-Prem routable CIDR to an IP belonging to a service in Spoke VPCs in Cloud. (Destination address translation) Follow the steps below to set up for the scenario. Step 1. Prerequisite ------------------------- 1.1. Upgrade the Aviatrix Controller to at least version UserConnect-4.7.386 - https://docs.aviatrix.com/HowTos/inline_upgrade.html 1.2. Prepare an IP mapping table for SNAT and DNAT configuration. SNAT configuration - Prepare two On-Prem routable IPs (one for the Aviatrix Transit Gateway; one for the Aviatrix Transit HA Gateway if needed) :: Example: Transit Primary Gateway: 192.168.3.11/32 Transit HA Gateway: 192.168.3.11/32 DNAT configuration - Prepare a list of IP mapping tables for the On-Prem routable CIDR to a service in Spoke VPCs corresponding to your topology - A service might be an IP belonging to Load Balancer or EIP :: Example: 172.16.17.32 <--> 10.1.0.98 192.168.3.11 <--> 10.2.0.243 Step 2. Build Aviatrix NEXT GEN TRANSIT FOR AWS ------------------------- - follow steps 1, 2, 3, 4, 4.1, 5, and 6 in the online document https://docs.aviatrix.com/HowTos/tgw_plan.html Step 3. Perform a Manual BGP Advertised Network List feature on the tunnel between Aviatrix Transit GW and AWS VGW ------------------------- - https://docs.aviatrix.com/HowTos/site2cloud.html#manual-bgp-advertised-network-list This action will advertise the On-Prem routable CIDR to On-Prem via BGP session. :: Example: On-Prem routable CIDR: 172.16.58.3/8 To configure: 3.1. Go to the Site2Cloud page and click on the tunnel between Aviatrix Transit Gateway and AWS VGW 3.2. Scroll down to the Manual BGP Advertised Network List 3.3. Enter the value of the On-Prem routable CIDR - for example: 172.16.58.3/8 3.4. Click the button "Change BGP Manual Spoke Advertisement" Step 4. Configure Aviatrix Customized SNAT function on both Transit Primary Gateway and Transit HA Gateway ------------------------- - https://docs.aviatrix.com/HowTos/gateway.html#customized-snat This action changes the packet’s source IP address from Spoke VPCs in the Cloud to an IP which belongs to an On-Prem routable CIDR. :: Example: Transit Primary Gateway: traffic from spoke VPCs 10.1.0.0/16 and 10.2.0.0/16 translates to IP 192.168.3.11 Transit HA Gateway: traffic from spoke VPCs 10.1.0.0/16 and 10.2.0.0/16 translates to IP 192.168.3.11 To configure: 4.1. Go to the Gateway page, click on the Transit Primary Gateway first. Click Edit. 4.2. Continue on to the Edit page, scroll to SNAT. Select Customized SNAT. 4.3. Select Customized SNAT 4.4. Click Add New 4.5. Enter fields for Src CIDR, protocol, Interface (select the one with VGW) and SNAT IPs as below example. 4.6. Click Save 4.7. Repeat the above steps for more entries. 4.8. Click Enable SNAT to commit. |SNAT_TRANSIT_PRIMARY| 4.9. Go to Gateway page, click on the Transit HA Gateway. Click Edit. 4.10. Repeat the above steps to configure Customized SNAT for Transit HA Gateway as shown in the example below. |SNAT_TRANSIT_HA| Step 5. Configure Aviatrix Customized DNAT function on the Transit Primary Gateway ------------------------- - https://docs.aviatrix.com/HowTos/gateway.html#destination-nat This action instructs the gateway to translate the destination address from an IP within the On-Prem routable CIDR to an IP belong to a service in Spoke VPCs in Cloud. :: Example: 172.16.17.32/32 <--> 10.1.0.98 192.168.3.113/32 <--> 10.2.0.243 To configure: 5.1. Go to the Gateway page and click on the Transit Primary Gateway. Click Edit. 5.2. Scroll down to “Destination NAT”, click Add/Edit DNAT 5.3. Click Add/Edit DNAT 5.4. Click Add New 5.5. Enter fields for Destination CIDR, protocol, Interface (select the one with VGW) and DNAT IPs as below example. |DNAT_TRANSIT_PRIMARY| 5.6. Click Save 5.7. Repeat steps 5.4, 5.5, and 5.6 for multiple entries. 5.8. Click Update to commit. Step 6. Attach spoke VPCs to an AWS Transit Gateway (TGW) ------------------------- - https://docs.aviatrix.com/HowTos/tgw_build.html Step 7. Verify traffic flow ------------------------- 7.1. SNAT - Traffic from Spoke VPC 10.1.0.0/16 to On-Prem |SNAT_10_1| - Traffic from Spoke VPC 10.2.0.0/16 to On-Prem |SNAT_10_2| 7.2. DNAT - Traffic from On-Prem to Spoke VPC 10.1.0.0/16 |DNAT_99_1| - Traffic from On-Prem to Spoke VPC 10.2.0.0/16 |DNAT_99_2| 7.3. SNAT (failover to Transit HA gateway) - Traffic from Spoke VPC 10.1.0.0/16 to On-Prem |SNAT_FAILOVER_10_1| - Traffic from Spoke VPC 10.2.0.0/16 to On-Prem |SNAT_FAILOVER_10_2| 7.4. DNAT (failover to Transit HA gateway) - Traffic from On-Prem to Spoke VPC 10.1.0.0/16 |DNAT_FAILOVER_99_1| - Traffic from On-Prem to Spoke VPC 10.2.0.0/16 |DNAT_FAILOVER_99_2| .. |SNAT_DNAT_TRANSIT_SOLUTION| image:: transit_snat_dnat_media/SNAT_DNAT_TRANSIT_SOLUTION.png :scale: 30% .. |SNAT_TRANSIT_PRIMARY| image:: transit_snat_dnat_media/SNAT_TRANSIT_PRIMARY.png :scale: 30% .. |SNAT_TRANSIT_HA| image:: transit_snat_dnat_media/SNAT_TRANSIT_HA.png :scale: 30% .. |DNAT_TRANSIT_PRIMARY| image:: transit_snat_dnat_media/DNAT_TRANSIT_PRIMARY.png :scale: 30% .. |SNAT_10_1| image:: transit_snat_dnat_media/SNAT_10_1.png :scale: 30% .. |SNAT_10_2| image:: transit_snat_dnat_media/SNAT_10_2.png :scale: 30% .. |DNAT_99_1| image:: transit_snat_dnat_media/DNAT_99_1.png :scale: 30% .. |DNAT_99_2| image:: transit_snat_dnat_media/DNAT_99_2.png :scale: 30% .. |SNAT_FAILOVER_10_1| image:: transit_snat_dnat_media/SNAT_FAILOVER_10_1.png :scale: 30% .. |SNAT_FAILOVER_10_2| image:: transit_snat_dnat_media/SNAT_FAILOVER_10_2.png :scale: 30% .. |DNAT_FAILOVER_99_1| image:: transit_snat_dnat_media/DNAT_FAILOVER_99_1.png :scale: 30% .. |DNAT_FAILOVER_99_2| image:: transit_snat_dnat_media/DNAT_FAILOVER_99_2.png :scale: 30% .. disqus:: <file_sep> ========================================================= Aviatrix Transit Gateway to External Devices ========================================================= There are four options to connect to Aviatrix Multi-Cloud Transit GW: - AWS VGW - Azure VNG - Aviatrix hardware appliance CloudN - External (or 3rd Party) Router/Firewall This document focuses on the External Device connecting the Aviatrix Transit GW. What are the use cases for connecting to an external router? -------------------------------------------------------------------------- - **Overcoming the AWS VGW 100 route limit** Typically, an Aviatrix Transit GW connects to VGW over IPsec and runs a BGP session with VGW. VGW then connects to on-prem devices. By connecting directly to an external device, the VGW is bypassed. - **Overcome AWS VGW performance reset** VGW adjusts instance size based on network bandwidth consumption, leading to unexpected outage. - **Azure Transit Network** This feature allows an Aviatrix Transit GW to connect to on-prem over Azure Express Route or Internet. - **High Performance with on-prem** By using GRE tunneling protocol, Aviatrix Multi-Cloud Transit Gateway `builds multiple GRE tunnels to on-prem routers <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_gre_high_performance_workflow.html>`_ to achieve 10Gbps throughput. - **Integrate with SD-WAN gateways deployed in the cloud** BGP over LAN as part of the External Device option provides an efficient mechanism to connect to SD-WAN cloud gateways by interoperating with them over LAN in the same VPC/VNet while exchanging routes dynamically via BGP. - **All Other Cloud Providers** Use this feature to connect to network of cloud providers such as Alibaba Cloud, Tencent Cloud, VMware Cloud, IBM Cloud and others. How does it work? ----------------------------- The Aviatrix Transit GW runs a BGP session to an external router to dynamically exchange routes. It also establishes an IPsec tunnel, GRE tunnel, or direct Ethernet to the router for packet forwarding. For IPsec tunneling, static routing option is also supported. The mechanism works for AWS Direct Connect, Azure ExpressRoute, or the Internet. Over Private Network in AWS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When the underlying infrastructure is AWS Direct Connect, the diagram is shown as below. |transitgw_private_aws| Make sure: - The VGW is attached to the Transit VPC for IPsec over Direct Connect and GRE over Direct Connect. - The external device advertises its IP address to VGW. - The external device advertises the on-prem network CIDR list to Aviatrix Transit GW. Over a Private Network in Azure ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When the underlying infrastructure is Azure Express Route, the external Device options are IPsec or LAN, as shown below. |transitgw_private_azure| Note GRE is not supported on Azure. Over the Internet ~~~~~~~~~~~~~~~~~~~~~ When connecting over the Internet, as shown below, follow the instructions in the next section. |transitgw_internet| How do I configure it? ---------------------------------- The configuration is the `External Device <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#external-device>`_ section of the Multi-Cloud Transit Network Workflow Instructions article. We assume you have already completed `Step 1 <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-an-aviatrix-transit-gateway>`_ and `Step 2 <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#optional-enable-disable-ha-to-an-aviatrix-transit-gateway>`_. Follow the instructions below. Filling the Parameters ~~~~~~~~~~~~~~~~~~~~~~~~~ Fill the parameters using the fields below and click **OK**. For ActiveMesh design notes, check out `ActiveMesh Design Notes <https://docs.aviatrix.com/HowTos/activemesh_design_notes.html#configuration-notes>`_. ============================ ========== **Setting** **Value** ============================ ========== External Device Select this option to build a connection to a remote site. BGP Select BGP if the Transit GW runs dynamic routing with remote site. Static Remote Route-Based Select this option the remote site supports route-based VPN with static configuration. Static Remote Policy-Based Select this option the remote site supports policy-based VPN with static configuration. The caveat in this mode is the remote site must always initiate the traffic. This function has been moved to `SITE2CLOUD <https://docs.aviatrix.com/HowTos/site2cloud.html>`_. IPsec Select this option to run BGP and build a IPsec connection to a remote site. GRE Select this option to run BGP and build a GRE connection to a remote site. LAN Select this option to run BGP and data plane by LAN interface with an instance in the same VPC or VNet. VPC Name/Site ID The Transit VPC/VNet ID where Transit GW was launched. Connection Name A unique name to identify the connection to external device. Aviatrix Transit GW BGP ASN The BGP AS number the Transit GW will use to exchange routes with external device. Primary Aviatrix Gateway The Transit GW you created in `Step 1 <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-a-transit-gateway>`_. If Transit DMZ is deployed, select the `Companion gateway <https://docs.aviatrix.com/HowTos/transit_dmz_faq.html#how-does-transit-dmz-actually-work>`_. Algorithms Optional parameters. Leave it unselected if you don't know. IKEv2 Select the option to connect to the remote site using IKEv2 protocol. Enable Remote Gateway HA Select HA if there are two external devices. Over Private Network Select this option if your underlying infrastructure is private network, such as AWS Direct Connect and Azure ExpressRoute. See the "How does it work" section for more details. When this option is selected, BGP and IPsec run over private IP addresses. BGP Remote AS Number When BGP is selected, the BGP AS number the external device will use to exchange routes Aviatrix Transit GW. Remote Gateway IP IP address of the remote device. If "Over DirectConnect" is selected, enter the private IP address of the external device. Pre-shared Key Optional parameter. Leave it blank to let the pre-shared key to be auto generated. Local Tunnel IP Optional parameter. This field is for the tunnel inside IP address of the Transit Gateway. Leave it blank. Remote Tunnel IP Optional parameter. This field is for the tunnel inside IP address of the external device. Leave it blank. Over DirectConnect (Backup) Select this option if HA is enabled. BGP Remote ASN (Backup) When BGP is selected, the remote ASN for backup should be the same as the primary remote ASN. Remote Gateway IP (Backup) IP address of the remote device. If "Over DirectConnect" is selected, enter the private IP address of the external device. Pre-shared Key (Backup) Optional parameter. Leave it blank to let the pre-shared key to be auto generated. Local Tunnel IP (Backup) Optional parameter. This field is for the tunnel inside IP address of the Transit Gateway. Leave it blank. Remote Tunnel IP (Backup) Optional parameter. This field is for the tunnel inside IP address of the external device. Leave it blank. ============================ ========== Downloading the Configuration ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ After the configuration is done, a connection is created. Download the configuration file. At the left navigation bar, go to Site2Cloud, click on the connection you created with Connection Name and click **Download Configuration** as shown below. Make sure you select the **Generic as Vendor** type. |download_config_external| Configuring the External Device ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Steps to 1. `Configure Cisco Router <http://docs.aviatrix.com/HowTos/Transit_ExternalDevice_CiscoRouter.html>`_ 2. `Configure Cisco ASA <http://docs.aviatrix.com/HowTos/Transit_ExternalDevice_CiscoASA.html>`_ 3. `Configure PaloAlto <http://docs.aviatrix.com/HowTos/Transit_ExternalDevice_PaloAlto.html>`_ 4. `Configure FortiGate <http://docs.aviatrix.com/HowTos/Transit_ExternalDevice_FortiGate.html>`_ 5. `Configure JuniperSRX <http://docs.aviatrix.com/HowTos/Transit_ExternalDevice_JuniperSRX.html>`_ 6. `Configure pfSense <http://docs.aviatrix.com/HowTos/Transit_ExternalDevice_pfSense.html>`_ Use the information provided in the configuration file to configure the on-prem device with IPsec tunnel and BGP. Disconnecting the External Device ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To disconnect, go to Multi-Cloud Transit > Setup > **External Connection** tab. Scroll down to section 2. Disconnect AWS VGW / External Device / Azure VNG, select the Transit GW in the dropdown menu, and click **Detach**. Appendix 1: Transit Connection to Cisco ISR/ASR Over the Internet ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The following is the topology used for the sample configuration below: |External-Device-Internet| Since over Internet, an Aviatrix Transit GW and Cisco ISR/ASR use each other's public IP to create an IPsec tunnel and establish a BGP connection. The following diagrams display mappings between a sample configuration from Step 2 above and its corresponding Cisco ISR/ASR router configuration: |transitgw_phase1| |transitgw_phase2| |transitgw_tunnel| |transitgw_bgp| Appendix 2: Transit Connection to Cisco ISR/ASR over Direct Connect ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The following is the topology used for the sample configuration below: |External-Device-DX| Since over Direct Connect, the Aviatrix Transit GW and Cisco ISR/ASR use each other's private IP to create an IPsec tunnel and establish BGP connection. .. note:: The ASN number of the Aviatrix Transit GW entered at **BGP Local AS Number** of Step 1 above should be the same as VGW's ASN number (7224 in this example). Without it, the Transit VPC/VNet CIDR advertised from VGW to on-prem ASR/ISR will be advertised by ASR/ISR back to the Aviatrix Transit GW. With the same ASN number, Aviatrix Transit GW will drop the route to Transit VPC/VNet CIDR. The following diagrams display mappings between a sample configuration from Step 2 above and its corresponding Cisco ISR/ASR router configuration: |transitgw_phase1_dx| |transitgw_phase2_dx| |transitgw_tunnel_dx| |transitgw_bgp_dx| .. |transitgw_dx| image:: transitgw_external_media/transitgw_dx.png :scale: 30% .. |transitgw_private_aws| image:: transitgw_external_media/transitgw_private_aws.png :scale: 30% .. |transitgw_private_azure| image:: transitgw_external_media/transitgw_private_azure.png :scale: 30% .. |transitgw_internet| image:: transitgw_external_media/transitgw_internet.png :scale: 30% .. |External-Device-Internet| image:: transitgw_external_media/External-Device-Internet.png :scale: 50% .. |transitgw_phase1| image:: transitgw_external_media/transitgw_phrase1.png :scale: 70% .. |transitgw_phase2| image:: transitgw_external_media/transitgw_phrase2.png :scale: 70% .. |transitgw_tunnel| image:: transitgw_external_media/transitgw_tunnel.png :scale: 70% .. |transitgw_bgp| image:: transitgw_external_media/transitgw_bgp.png :scale: 70% .. |External-Device-DX| image:: transitgw_external_media/External-Device-DX.png :scale: 50% .. |transitgw_phase1_dx| image:: transitgw_external_media/transitgw_phase1_dx.png :scale: 70% .. |transitgw_phase2_dx| image:: transitgw_external_media/transitgw_phase2_dx.png :scale: 70% .. |transitgw_tunnel_dx| image:: transitgw_external_media/transitgw_tunnel_dx.png :scale: 70% .. |transitgw_bgp_dx| image:: transitgw_external_media/transitgw_bgp_dx.png :scale: 70% .. |download_config_external| image:: transitgw_external_media/download_config_external.png :scale: 20% .. disqus:: <file_sep> =================================== Configuring Aviatrix User SSL VPN =================================== Aviatrix provides a cloud-native and feature-rich client `VPN <https://www.aviatrix.com/learning/glossary/vpn.php>`_ solution. The solution is based on OpenVPN® and is compatible with all OpenVPN® clients. In addition, Aviatrix provides its own `client that supports SAML authentication <UserSSL_VPN_Okta_SAML_Config.html>`_ directly from the client. |image0| .. note:: Only AWS is drawn in the diagram, but this feature applies equally to Azure and Google Cloud. Additional Information ------------------------------------- - `Aviatrix OpenVPN® features <./openvpn_features.html>`_ - `OpenVPN® FAQ <./openvpn_faq.html>`_ - `OpenVPN® design with multi VPC/VNets <./Cloud_Networking_Ref_Des.html>`_ Configuration Workflow ---------------------- .. important:: This document assumes you have set up an Aviatrix Controller. Please see `this guide <../StartUpGuides/aviatrix-cloud-controller-startup-guide.html>`__ for more details. There are two steps to setting up User VPN connectivity: #. `Create a VPN Gateway <#create-a-vpn-gateway>`__ #. `Add a user <#create-vpn-users>`__ You can also `watch a video <https://www.youtube.com/watch?v=bbZFa8kVUQI&t=1s>`_ to learn how to setup remote user VPN. The video is not up-to-date as the product graphics have changed, but the idea remains the same. Creating a VPN Gateway ^^^^^^^^^^^^^^^^^^^^ .. note:: The description in the steps below provides critical fields to get you started. You can make changes to set up advanced features such as `MFA <https://docs.aviatrix.com/HowTos/gateway.html#mfa-authentication>`_ and profile based access later. 1. Log in to the Aviatrix Controller. |AVTXSignIn| 2. Launch a gateway with VPN capability. * In the left sidebar, click **Gateway**. * Click **+ New Gateway** at the top of the page. |imageSelectGateway| .. important:: You need a subnet (a public subnet in AWS or GCP) in the VPC/VNet where the Gateway will be provisioned. Be sure to provision a new one or identify the correct one prior to starting this step. 3. Select the **Cloud Type** and enter a **Gateway Name**. 4. Once the Account Name` is selected, select the appropriate **Region** and **VPC** or **VNet**. 5. After selecting the desired **VPC ID/VNet Name:Resource Group**, select the **Public Subnet** where the Gateway will be provisioned. 6. Select the **Gateway Size** (t2.micro is sufficient for most test use cases). |imageCreateGateway| 7. Select **VPN Access**. Leave the Advanced Options unselected. |imageSelectVPNAccess| .. note:: Leave the Advanced Options unselected as you can configure them later. 8. At this stage, you can enable `NLB <http://docs.aviatrix.com/HowTos/gateway.html#enable-elb>`_ (NLB will be automatically created by Aviatrix.) You can specify the NLB's name or have it auto-generated by Aviatrix. 9. If you wish to create more of such VPN gateways (for example, behind NLBs for load balancing), click `Save Template`. 10. Click **OK** to create the Gateway. .. note:: Once you click **OK**, the Gateway will be provisioned and all the configuration will be applied. This will take a minute or two. VPN Users ^^^^^^^^^ Users can be added manually or authenticated with an existing LDAP server. #. Log in to the Aviatrix Controller. #. Select **OpenVPN®** on the left sidebar. #. Select **VPN Users**. |imageOpenVPNUsers| Creating VPN Users ################### 1. Click **+ Add New**. |vpnuser| #. Select the **VPC ID** where this user should be attached. The associated load balancer will appear in the **LB/Gateway Name**. #. Enter the **User Name** and **User Email**. If DUO authentication is enabled, the User Name entered must match the user name of your DUO account. The User Email is optional. #. Click **OK**. .. note:: When a user is added to the database, an email with an .ovpn file or .onc (for Chromebooks) will be sent to the user with detailed instructions. |imageAddNewVPNUser| Exporting VPN Users ############################### 1. Click the export icon. |imageExportVPNUsers| 2. Check the csv file aviatrix_vpn_users.csv in the Download folder. .. note:: If there has been an aviatrix_vpn_users.csv in the Download folder already, the OS will rename the new file with aviatrix_vpn_users(1).csv automatically. Importing VPN Users ############################### 1. Click the import icon |imageImportVPNUsers| #. Select a csv file to import. .. note:: If you are using a MacOS system, the Apple App "Numbers" can open and edit the csv file. It can export a new csv file from File > Export To > CSV. If you are using the Excel, you can export a new csv file from File > Save As. #. Click **Open** to start the process. #. Select the default **VPC ID** and **LB/Gateway Name** in **Default VPN User Settings**. .. note:: Any empty VPC ID field in a csv file will trigger a new popup window for selecting the default VPC ID. Any record in a csv file with an empty VPC ID will be filled with the values in Default VPN User Settings automatically. If all the VPC ID fields are filled in the the original csv file already, Default VPN User Settings will not appear. |imageImportVPNUsersDefaultVPCID| #. Check the Import Results. |imageImportVPNUsersResults| Downloading the VPN User Certificate ############################### You can also download the VPN user certificate to your desktop, as shown below. Load this certificate configuration file to your OpenVPN® client on your desktop. You should be able to connect then. |New_User| Detach and revoke: will not only detach the user but revoke the user certificate as well. attach: will re-attach detached users and also re-create the user certificate if the user certificate is revoked. Conclusion --------------------- You now have a working Aviatrix VPN Gateway. Users can connect and gain access to their cloud resources. Detailed audit logs are maintained and available in various logging platforms. .. note:: Audit reports are best viewed in the `Aviatrix Splunk Application <AviatrixLogging.html#splunk-app-for-aviatrix>`__. .. |image0| image:: uservpn_media/AviatrixCloudVPN.png :width: 5.55625in :height: 3.26548in .. |imageSelectGateway| image:: uservpn_media/select_gateway.png :scale: 50% .. |imageCreateGateway| image:: uservpn_media/create_new_gateway.png :scale: 50% .. |imageSelectVPNAccess| image:: uservpn_media/select_vpn_access.png .. |imageOpenVPNProfiles| image:: uservpn_media/openvpn_profiles.png :scale: 50% .. |imageOpenVPNUsers| image:: uservpn_media/openvpn_users.png .. |imageAddNewProfile| image:: uservpn_media/add_new_profile.png :scale: 50% .. |imageEditViewProfile| image:: uservpn_media/edit_view_profile.png :scale: 50% .. |imageAddProfilePolicy| image:: uservpn_media/add_profile_policy.png :scale: 50% .. |imageAddNewVPNUser| image:: uservpn_media/add_new_vpn_user.png :scale: 35% .. |New_User| image:: uservpn_media/New_User.png :scale: 15% .. |imageImportVPNUsers| image:: uservpn_media/import_vpn_users.png :scale: 100% .. |imageExportVPNUsers| image:: uservpn_media/export_vpn_users.png :scale: 100% .. |imageImportVPNUsersDefaultVPCID| image:: uservpn_media/import_vpn_users_default_vpn_settings.png :scale: 30% .. |imageImportVPNUsersResults| image:: uservpn_media/import_vpn_users_results.png :scale: 30% .. |AVTXSignIn| image:: uservpn_media/AVTXSignIn.png :scale: 20% .. |vpnuser| image:: uservpn_media/vpnuser.png :scale: 20% OpenVPN is a registered trademark of OpenVPN Inc. .. disqus:: <file_sep> ======================================= Azure Transit Network Design Patterns ======================================= There are many design patterns for networking and networking security deployment in the cloud. This document summarizes these design patterns that apply to Azure networks. Aviatrix Encrypted Transit Network ------------------------------------- In this design, all packets in flight between Spoke VNets and Transit to on-prem are encrypted. |aviatrix_transit_azure| .. Tip:: Aviatrix Transit supports high performance (Insane Mode) IPsec performance over ExpressRotue and Azure Peering. Aviatrix Transit with Native Spokes -------------------------------------- Aviatrix Transit also supports Azure native Spoke VNets. |aviatrix_transit_native_spoke| Transit FireNet with Aviatrix Spokes ------------------------------------ You can apply firewall inspections for east-west, north-south and ingress/egress traffic. |transit_firenet_aviatrix_spokes| Transit FireNet with Native Spokes ------------------------------------------- Firewall inspections can be applied to native Spoke VNet, on-prem to transit and north-south traffic. |transit_firenet_native_spokes| Please refer to `Transit FireNet Workflow for Azure Native Spoke VNets <https://docs.aviatrix.com/HowTos/transit_firenet_azure_native_spokes_workflow.html>`_ for more details. SD-WAN Integration -------------------- If you have multiple sites to connect to the cloud, you can use an Aviatrix Transit Gateway to terminate the many site2cloud to branch offices. Alternatively, you can use a SD-WAN termination point in the VNets to connect to the branches. Both options can be described in the diagram below. |transit_sdwan| Aviatrix Transit Gateway for Azure Spoke-to-Spoke Connectivity --------------------------------------------------------------- If you use Azure ExpressRoute gateway to connect Spoke VNets to on-prem, you can use Aviatrix Transit Gateway for Spoke-to-Spoke connectivity, as shown in the diagram below. To connect Spoke VNet, follow the `Step 6b in the Multi-Cloud Transit Network workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#b-attach-azure-arm-spoke-vnet-via-native-peering>`_. |transit_azure_native_spoke| Multi-Cloud Transit with Native Spokes ------------------------------------------------ Use Aviatrix Transit Gateways to interconnect transit network for a multi cloud network deployment, as shown in the diagram below. |multi_cloud_transit_native| .. |aviatrix_transit_azure| image:: azure_transit_designs_media/aviatrix_transit_azure.png :scale: 30% .. |aviatrix_transit_native_spoke| image:: azure_transit_designs_media/aviatrix_transit_native_spoke.png :scale: 30% .. |transit_firenet_aviatrix_spokes| image:: azure_transit_designs_media/transit_firenet_aviatrix_spokes.png :scale: 30% .. |transit_firenet_native_spokes| image:: azure_transit_designs_media/transit_firenet_native_spokes.png :scale: 30% .. |transit_sdwan| image:: azure_transit_designs_media/transit_sdwan.png :scale: 30% .. |transit_azure_native_spoke| image:: transitvpc_designs_media/transit_azure_native_spoke.png :scale: 30% .. |multi_cloud_transit_native| image:: transitvpc_designs_media/multi_cloud_transit_native.png :scale: 30% .. |transit_firenet| image:: transit_firenet_media/transit_firenet.png :scale: 30% .. |transit_firenet_aviatrix_egress| image:: transit_firenet_media/transit_firenet_aviatrix_egress.png :scale: 30% .. disqus:: <file_sep> ================================= Egress FQDN View Log ================================= The FQDN View Log allows you to immediately view what hostnames and sites have been blocked or passed on the `FQDN gateway. <http://docs.aviatrix.com/HowTos/FQDN_Whitelists_Ref_Design.html>`_ Select the gateway and download the text file for the FQDN log. For audit and compliance, we recommend that you to use one of our integrated `logging tools <http://docs.aviatrix.com/HowTos/AviatrixLogging.html>`_. There are additional functions associated with the FQDN View page. Detaching or Disabling FQDN ---------------------------------------- To disable FQDN function for a specific VPC/VNet, select the gateway, click Actions > **Detach/Disable FQDN**. Removing a Tag -------------------------- If you like to remove a specific tag associated with a FQDN tag, select the gateway, click Actions > **Remove Tag**. Downloading Logs --------------------------- For FQDN log on a specific gateway, select the gateway, click Actions > **Download Logs**. Editing Pass-through -------------------------- This feature allows you to specify traffic originated from certain subnets to only be NATed and bypass FQDN filter function. This configuration applies to a specific FQDN gateway. To configure, go to Security > Egress Control > Egress FQDN Gateway View. Select a gateway and click Actions > **Edit Pass-through**. Select a subnet or multi select subnets to allow bypass the filter. To configure, select one gateway, click Actions > Edit Pass-through. Select one or multiple source subnets in the VPC/VNet and click **Add** to allow these subnets to be bypassed. You can also enter IP address range manually. Enter a list of IPs separated by comma. .. |discovered_sites| image:: fqdn_discovery_media/discovered_sites.png :scale: 50% .. |fqdn-new-tag| image:: FQDN_Whitelists_Ref_Design_media/fqdn-new-tag.png :scale: 50% .. |fqdn-add-new-tag| image:: FQDN_Whitelists_Ref_Design_media/fqdn-add-new-tag.png :scale: 50% .. |fqdn-enable-edit| image:: FQDN_Whitelists_Ref_Design_media/fqdn-enable-edit.png :scale: 50% .. |fqdn-add-domain-names| image:: FQDN_Whitelists_Ref_Design_media/fqdn-add-domain-names.png :scale: 50% .. |fqdn-attach-spoke1| image:: FQDN_Whitelists_Ref_Design_media/fqdn-attach-spoke1.png :scale: 50% .. |fqdn-attach-spoke2| image:: FQDN_Whitelists_Ref_Design_media/fqdn-attach-spoke2.png :scale: 50% .. add in the disqus tag .. disqus:: <file_sep> ################################### Maintenance ################################### - `Inline Software Upgrade. <http://docs.aviatrix.com/HowTos/inline_upgrade.html>`__ - `Controller HA. <http://docs.aviatrix.com/HowTos/controller_ha.html>`__ - `Software Patches. <https://docs.aviatrix.com/HowTos/setting_software_patches.html>`__ - `Security Patches. <https://docs.aviatrix.com/HowTos/setting_security_patches.html>`__ Gateway Upgrade Status =========================== Gateway's information about upgrade and release can be checked in controller's console Settings -> Upgrade -> Gateways Upgrade Status. Gateway Upgrade Status shows the following: 1. Total number of gateways #. Gateway Names #. Gateway's current and previous software v`ersion and build number #. Gateway's upgrade status Security and Software Patches Status ======================================= Aviatrix System releases patches time to time to fulfil the security compliance and to block any security found in a code. The software and security patches status can be checked in Controller's console. For Security Patches Status go to Settings -> Maintenance -> Security Patches, select controller or gateway under Gateway / Controller Status and click Collect to check the patch status. For Software Patches Status go to Settings -> Maintenance -> Software Patches, select controller or gateway under Gateway / Controller Status and click Collect to check the patch status. .. disqus:: <file_sep> ################################### ELB Status ################################### This page enables users to view load balancer info including target health status after users launch an `Aviatrix OpenVPN Gateway <https://docs.aviatrix.com/HowTos/gateway.html?highlight=ELB#vpn-access>`_ with the option `Enable ELB <https://docs.aviatrix.com/HowTos/gateway.html#enable-elb>`_. Additionally, users are able to delete/clean up load balancer by clicking the button "DELETE" next to the load balancer name, but usually this is not required as load balancer is automatically deleted on the last user/gateway deletion. .. disqus:: <file_sep> ============================================= Admin Users and Duo Sign in ============================================= Objectives =========== This document describes a reference design using the Aviatrix Controller console’s user management and Duo authentication capability to manage multiple users with admin privileges. As the cloud Ops team continues to expand to manage more cloud deployments, each team member often needs their own username and password with admin privilege. In addition to a username and password for login credentials, a 2FA authentication can be added for enhanced security to manage cloud Controller. DUO authentication is one of the supported methods. When enabled, it requires the user to accept a push message on the user’s mobile device from DUO service in addition to username and password at the user login time. The following diagram illustrates the user relationship in a typical cloud Ops department. In this example, the Ops team has created three secondary access accounts. An access account is associated with one or more distinct cloud provider’s API credentials. Typically, a cloud account corresponds to an IAM account of a distinct AWS and/or Azure account with a credit card. A default user “admin” is created by the system. In the picture below, admin has created three secondary access accounts. Additional users in admin and access account are added by the admin or admin users. |account_structure| Configuration Workflow for Admin Users ======================================= Adding a New Admin User -------------------------------------- The page can be found at Accounts > Account Users > **+New User**. After the primary access account is created during onboarding, additional admin users can be added from this page. When an admin user is created, changed, or deleted, an email is sent to the admin’s email address as a record for bookkeeping purposes. After the user is added, the user can log in to the console with the specified username and password. The user then has full access to the console like the admin. When the user logs in to the console, the admin username will be displayed in the top right corner. Deleting an Admin User ----------------------------------- The same page can be used to delete an admin user when the user leaves the group or the user role changes. After the delete button is clicked, a confirmation email is sent to the admin’s email address. Note that an admin cannot be deleted by himself or herself though the user has the full console access. Typically, the admin user is added or deleted by the special username admin. Changing an Admin User’s Password ----------------------------------------------------- The admin user’s password can be changed at the same page. An email notification is sent to the admin’s email address after the change is successfully done. Disabling an Admin Login -------------------------------------------- **Note**: You need a local user with admin privileges to be created before you can disable the "admin" account. If you need to disable admin login for security reasons, go to Settings > Controller > Login Customization. Click **Disable** to disable the admin login. Configuration Workflow for Duo Authentication ================================================ Getting DUO API Credentials ---------------------------------------- Follow the `instruction in <http://docs.aviatrix.com/HowTos/duo_auth.html>`_ to setup DUO API credentials on the DUO Security website. Creating Duo Authentication ---------------------------------------- To enable DUO, go to Settings > Controller > Duo Login. Enter the Duo integration key, secret key, and API hostname of your account in DUO website described earlier. Currently, only DUO push is supported. Once it is created successfully, the Duo push login applies to all users (admin is exempt). Every user (listed in Settings > Manage Accounts > Users) who wishes to log in to the system must have a matching username in their DUO account. Removing Duo Authentication ------------------------------------------ The Duo authentication setup can be removed completely by clicking the Remove button on the same page. Disabling/Enabling Duo Authentication ---------------------------------------------------- The authentication can be disabled or enabled without deleting the DUO credential configuration. API Server Check ----------------------------------- This button can be used to troubleshoot Duo API server connectivity when the API failure is occurring. .. |account_structure| image:: adminusers_media/account_structure.png :scale: 50% .. disqus:: <file_sep> =========================================================================================== Site2Cloud With Customized SNAT =========================================================================================== This tech note describes how to create a Site2Cloud connection between two VPCs by using a VGW and an Aviatrix gateway. The Aviatrix gateway also serves as a source NAT device and translates source IP address of the traffic initiated from a peering VPC to an IP address selected by users. | Environment Requirements --------------------------------------------------------- There are two VPCs as illustrated in the diagram below. VPC-1's CIDR is 10.0.0.0/16 and VPC-2's CIDR is 172.19.0.0/16. The Site2Cloud connection is between a VGW in VPC-1 and an Aviatrix gateway in VPC-2. |image1| We will also configure customized SNAT at the Aviatrix gateway, which translates the source IP of traffic initiated from VPC-1 (10.0.0.0/16) to a user selected IP address (192.168.1.10 in this example). In this way, VPC-2 VMs will see all packets from VPC-1 with the same source IP address (192.168.1.10) | Steps to Configure Site2Cloud Connection and SNAT --------------------------------------------------------- + **Step 1: Install an Aviatrix gateway in VPC-2.** Download and install the Aviatrix Gateways by following the instructions in this `document <http://docs.aviatrix.com/HowTos/gateway.html>`__ Don't select "Enable SNAT" when creating the new gateway in VPC-2. + **Step 2: Create a Site2Cloud connection between a VGW in VPC-1 and an Aviatrix gateway in VPC-2** .. Note:: In the Aviatrix terminology, Site2Cloud is the name of the feature that enables connections from one site (or datacenter) to other sites (including cloud environments). .. Please follow the instructions in this `document <http://docs.aviatrix.com/HowTos/site2cloud_awsvgw.html>`__ to create the Site2Cloud connection. + **Step 3: Update VPC-1 Route Tables at AWS portal** Update VPC-1 route tables to ensure that traffic destinating to VPC-2 (172.19.0.0/16) takes the VGW as "Target": ============== ================================== **Field** **Value** ============== ================================== Destination 172.19.0.0/16 Target VGW ID ============== ================================== + **Step 4: Configure Customized SNAT at the Aviatrix gateway** **a.** Log into the Controller and go to "Gateway" page. **b.** Select the Aviatrix gateway created in VPC-2. |image2| **c.** Click "Edit" button and go to "Source NAT" section. **d.** Select "Customized SNAT". **e.** Configure the following SNAT rule. ================== ================================== **Field** **Value** ================== ================================== Source CIDR VPC-1 CIDR (10.0.0.0/16) Source Port Leave it blank Destination CIDR VPC-2 CIDR (172.19.0.0/16) Destination Port Leave it blank Protocol all Interface eth0 Mark Leave it blank SNAT IPs User selected IP (192.168.1.10) SNAT Port Leave it blank ================== ================================== |image3| **f.** Click "Save" and "Enable SNAT" buttons Test site2cloud Connection and SNAT --------------------------------------------------------- **a.** Go to the "Site2Cloud" page and verify that the Site2Cloud connection status is "Up". |image4| **b.** Pings from an opensource OS VM in VPC-1 to another opensource OS version VM in VPC-2. **c.** Turn on "tcpdump icmp -n" at the opensource OS VM in VPC-2. Verify the source IP of the pings is 192.168.1.10. .. |image1| image:: s2c_vgw_snat_media/s2c-snat.png :scale: 100% .. |image2| image:: s2c_vgw_snat_media/s2c-snat-1.PNG :scale: 100% .. |image3| image:: s2c_vgw_snat_media/s2c-snat-2.PNG :scale: 100% .. |image4| image:: s2c_vgw_snat_media/s2c-snat-3.PNG :scale: 100% .. disqus:: <file_sep> =================================================================== GCP Credentials =================================================================== Before creating a cloud account for GCloud/GCP on the Aviatrix controller, follow the steps below to make sure you have the credentials set up for API calls. 1. Create a GCloud or GCP account (https://cloud.google.com/). Continue to the next step if you have already done so. .. Note:: The Controller supports multiple accounts with each account associated with a different GCloud projects, but there needs to be at least one account to start with. 2. Create a GCloud Project. Log in to your GCloud account at https://console.cloud.google.com/project and create a project. Continue to the next step if you have already created one. Note the project ID will be used in referencing to the project by the Aviatrix Controller. (As an example, we created a project Aviatrix-UCC. The project ID is aviatrix-ucc-1214.) Enabling Compute Engine API on the Selected Project ---------------------------------------------------------------------- 1. Go to your Google Cloud Platform console, click on the dropdown menu in the top left, and select **APIs and Services. At the Dashboard, click on **Enable APIs and Services**. |image3| 2. On the Search box, enter "Compute Engine API" and select it from search results. |image2| 3. Click **Enable**. Creating a Credential File ---------------------------------- When you create a cloud account Aviatrix Controller for GCloud, you will be asked to upload a GCloud Project Credentials file. Follow the steps below to download the credential file from the Google Developer Console. 1. Open the `Credential page <http://console.developers.google.com/project/_/apiui/credential>`__. 2. Select the project you are creating credentials for. 3. At Credentials, Click **Create credentials** and select **Service account** as shown below. |service_account| 4. At the Service Accounts, enter a service account name and click **Create**. For Service account permissions, select Project, Editor, as shown below. |iam_credential| 5. Select a service account. Select the KEYS tab, click on the **ADD KEY** dropdown menu, and select **Create new key**. 6. Select the **JSON** radio button and click **CREATE**. 6. Click **Create**. The credential file downloads to your local computer. 7. Upload the Project Credential file to the Aviatrix Controller at the GCloud account create page. Note: Creating a Service Account with Restricted Access ----------------------------------------------------------------------------- We recommend creating the service account with the Editor role as mentioned, but in some cases an organization might want to further restrict permission for the service account. In such a situation Aviatrix recommendation is to have at least following roles assigned to service account so that Aviatrix can perform its functions properly, such as managing the compute resources, route tables, firewall rules, shared service VPC network, etc. 1. Compute Admin 2. Service Account User 3. Organization Administrator (required for GCP Shared VPC) 4. Project IAM Admin (required for GCP Shared VPC) |restricted_access| If an organization is currently using GCP Shared VPC or planning to use in future, then enabling Organization Administrator and Project IAM Admin is also required. In addition to restricting the GCP roles, you can restrict the rights for those roles. You can grant roles permission to perform the following tasks: :: compute.addresses.create compute.addresses.createInternal compute.addresses.delete compute.addresses.deleteInternal compute.addresses.get compute.addresses.list compute.addresses.use compute.addresses.useInternal compute.disks.create compute.disks.get compute.firewalls.create compute.firewalls.delete compute.firewalls.get compute.firewalls.list compute.firewalls.update compute.forwardingRules.create compute.forwardingRules.delete compute.forwardingRules.list compute.globalOperations.get compute.healthChecks.create compute.healthChecks.delete compute.healthChecks.useReadOnly compute.httpHealthChecks.get compute.httpHealthChecks.useReadOnly compute.images.list compute.images.useReadOnly compute.instanceGroups.create compute.instanceGroups.delete compute.instanceGroups.get compute.instanceGroups.update compute.instanceGroups.use compute.instances.create compute.instances.delete compute.instances.get compute.instances.list compute.instances.setMachineType compute.instances.setMetadata compute.instances.setTags compute.instances.start compute.instances.stop compute.instances.updateNetworkInterface compute.instances.use compute.networks.addPeering compute.networks.create compute.networks.delete compute.networks.get compute.networks.list compute.networks.removePeering compute.networks.updatePolicy compute.projects.get compute.projects.setCommonInstanceMetadata compute.regionBackendServices.create compute.regionBackendServices.delete compute.regionBackendServices.get compute.regionBackendServices.update compute.regionBackendServices.use compute.regionOperations.get compute.routes.create compute.routes.delete compute.routes.list compute.subnetworks.create compute.subnetworks.delete compute.subnetworks.get compute.subnetworks.list compute.subnetworks.use compute.subnetworks.useExternalIp compute.targetPools.addInstance compute.targetPools.create compute.targetPools.delete compute.targetPools.get compute.targetPools.removeInstance compute.targetPools.use compute.zoneOperations.get compute.zones.list iam.serviceAccounts.actAs logging.logEntries.create pubsub.subscriptions.consume pubsub.subscriptions.create pubsub.subscriptions.delete pubsub.subscriptions.get pubsub.topics.attachSubscription pubsub.topics.create pubsub.topics.delete pubsub.topics.get pubsub.topics.publish resourcemanager.projects.get Troubleshooting Tips ---------------------- If the cloud account creation fails, check the error message on your Aviatrix Controller and try again with the steps provided in this document. For additional support, please open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_ .. |image0| image:: GCloud_media/image1.png .. |image1| image:: GCloud_media/image2.png .. |image2| image:: GCloud_media/gcloud-api-library-search.png .. |image3| image:: GCloud_media/gcloud-enable-apis-and-services.png .. |service_account| image:: GCloud_media/service_account.png :scale: 30% .. |iam_credential| image:: GCloud_media/iam_credential.png :scale: 30% .. |restricted_access| image:: GCloud_media/restricted_access.png :scale: 30% .. disqus:: <file_sep> .. Note:: This guide references AWS for illustration purposes and also applies to Azure (VNet) and Google (VPC). .. =================================================== OpenVPN® Design for Multi-Accounts and Multi-VPC/VNets =================================================== This reference design helps you build an end-to-end secure cloud network, from accessing the network (AWS VPC, Azure VNet, or GCP VPC) by users to routing packets among the VPC/VNets, such that once a user is connected via VPN, she can access any private resources in the cloud no matter where that resource is. There are three use cases covered, from simple to more complex ones. You can read and decide which one suits you or combine parts from different ones to create a network that meet your requirements. You can easily build a full-mesh network. Multiple VPC/VNets in One Region ============================== The network you have in mind is shown below where all VPC/VNets are in the same region. The Aviatrix Controller instance can be in the same VPC/VNet or a different VPC/VNet. |image0| Assume you have created 4 VPC/VNets in the same region (us-west-2 in this case). You would like to use the VPC/VNet with CIDR 172.31.0.0/16 to host gateways where users connect to. After a user connects to this VPC/VNet via SSL VPN, she should be able to access any instances in the other VPC/VNets as long as her profile allows, without having to connect to each VPC/VNet with SSL VPN. Another requirement is split tunnel mode, that is, only traffic destined to the cloud goes through the SSL tunnel. If a user does general browsing on the Internet or watches movies from Hulu, traffic should be routed via WI-FI to ISP to Internet. You do not wish to pay AWS for this type of compute and network cost. Configuration Workflow --------------------------------- Tips: Hover your cursor over the fields to see their definitions. Do a software upgrade if an upgrade alert message appears on your dashboard page. The description in the steps below provides critical fields you need to select; it may not include all fields. Make sure you have the correct VPC/VNet ID and its region for the VPC/VNet ID field and region in each step. 1. Launch a gateway with VPN capability in VPC 172.31.0.0/16. * Go to the Gateway menu and create a gateway. * At the Gateway Name field, enter a distinct and convenient name. For example, mgmt-vpn-1. * Select **VPN Access**. Selecting features in the Advanced Options section is not required. Selecting Split Tunnel Mode is not required. * Select **Save Template**, if you wish to do so. This template saves you from entering repeated fields if you wish to create more gateways with the same configuration. 2. Repeat Step 1 to create more gateways with VPN enabled. Note that each gateway must have a different VPN CIDR Block and name. You may select different AZs for the Public Subnet field. 3. Configure AWS or Azure peering. * Go to Peering > AWS Peering for AWS or Peering > Azure Peering for Azure. Click **New Peering**. * For Peer1, select the Account Name, Region, and VPC ID of one of the gateways created. * Do the same for Peer2. * Click **OK**. If the new peering does not show up under the list of peerings below the popup, click **refresh**. * Repeat the above steps as many times as necessary for the gateways you created. 4. Add Users and Profiles. * Go to OpenVPN® > Profiles to create as many profiles as you please. The target field can be FQDN (DNS names or fully qualified domain name). * Go to OpenVPN® > VPN > VPN Users to add more users. Associate each user with a profile. Note that if no profile is associated, the user has full access to all resources. When a user is added to the database, an email with a .ovpn file or .onc (for Chromebooks) will be sent to the user with detailed instructions. 5. Launch VPN connections from remote users to VPC/VNet1 (172.31.0.0/16). Once the SSL VPN connection is established, this VPN user should be able to reach all instances (in all VPC/VNets) to which he/she has access permission. Multiple VPC/VNets in Multi-Regions, Split Tunnel ============================================ The network you have in mind is shown below where VPC/VNets are in different regions. The Aviatrix Controller instance can be in the same or a different VPC/VNet. |image1| In this example, Aviatrix encrypted peering is used for connecting to remote VPCs. You can also use AWS peering/Azure peering to accomplish the task. Assume you have created 4 VPC/VNets. You would like to use the VPC/VNet with CIDR 172.31.0.0/16 in us-west-2 to host gateways where users connect to. After a user connects to this VPC/VNet via SSL VPN, she should be able to access any instances in the other VPC/VNets as long as her profile allows, without having to connect to each VPC/VNet with SSL VPN. Another requirement is split tunnel mode, that is, only traffic originating from the user and destined to resources in VPC/VNets is routed through the SSL VPN tunnel. The traffic to the Internet will be routed through ISP instead of SSL VPN tunnel. Configuration Workflow ---------------------------------- Tips: Hover your cursor over the fields to see their definitions. The description in each step does not include all fields. Make sure you have the correct VPC/VNet ID and its region for the VPC ID field and region in each step. 1. Launch a gateway with VPN capability in VPC 172.31.0.0/16. * Go to the Gateway menu and click **Create**. * At the Gateway Name field, enter a distinct and convenient name. For example, mgmt-vpn-1. * Select VPN Access. * Use the default VPN CIDR Block. * Select Split Tunnel mode. | i. For the Additional CIDRs field under Split Tunnel, enter other VPC/VNet or any network CIDRs you wish to reach beyond the VPC/VNet you are connecting to. In the example shown, you should enter 10.10.0.0/16,10.5.0.0/16,10.80.0.0/16. It is a good idea to do some planning to include future VPC/VNets or network address ranges. (In a case where you never have to worry about connecting to your corporate VPN, you may consider entering the entire private network address range in the Additional CIDRs range field, separated by commas: 172.16.0.0/12,10.0.0.0/8,192.168.0.0/16. Doing so affords you to not have to reconfigure the gateway if you need to add more VPC/VNets for networking with different CIDR range in the future.) | | ii. (Optional) If you like to use private DNS name to access instance, you can fill the Nameservers and the Search Domain field under Split Tunnel. Enter your private DNS name and search domain. If you use AWS Route 53 private hosted zone and records for your host names, make sure the Nameserver is the DNS server of the VPC/VNet. In this case, you should enter "172.31.0.2". * Select **Enable ELB**. * Select **Save Template**. This Template saves you from entering repeated fields if you wish to create more gateways with the same configuration. 2. Repeat Step 1 to create more gateways with VPN enabled. You may select different AZs for the Public Subnet field. 3. Build encrypted routing networks to reach other VPC/VNets. * Launch a gateway without VPN capability in VPC/VNet 172.31.0.0/16. This is the routing gateway. Make sure: | i. At Gateway Field, give it a distinct and convenient name. For example, dev-east-1, or teamKardashian-east-1 for the Kardashian game project. | ii. VPN Access is not selected. | iii. Enable NAT is NOT selected (since step 1 has enabled NAT function for this VPC/VNet). | iv. Save Template is not selected. (so that you don’t overwrite the hard work of entering the fields of gateways with VPN enabled). * Repeat step 3 for VPC/VNet 10.10.0.0/16, 10.5.0.0/16 and 10.80.0.0/16. Select Enable NAT if you want instances in these 3 VPC/VNets to be able to reach the Internet directly. * Configure encrypted peering. Go to Peering > New Peering. Note that each VPC/VNet is represented by one or more gateways. Make sure you want to peer between two gateways without VPN capability. 4. (Optional) Set up Stateful Firewall Rules at the VPC/VNet level. * Go to Gateway and select the gateway you just created to edit Security Policies to add any policies for each VPC/VNet. 5. The steps above complete the network infrastructure setup. 6. Add Users and Profiles. * Go to OpenVPN® > Profiles to create as many profiles as you please. The target field can be FQDN (DNS names or fully qualified domain name). * Go to OpenVPN® > VPN Users to add as many users as you please. Associate each user with a profile. Note that if no profile is associated, the user has full access to all resources. When a user is added to the database, an email with an .ovpn file or .onc (for Chromebooks) will be sent to the user with detailed instructions. Multiple VPC/VNets in Multi Regions, Full Tunnel, your own firewall ============================================================== The network you have in mind is shown below where VPC/VNets are in different regions. The Aviatrix Controller instance can be in the same or a different VPC/VNet. |image2| Assume you have created 4 VPC/VNets. You would like to use the VPC/VNet with CIDR 172.31.0.0/16 in us-west-2 to host gateways where users connect to. After a user connects to this VPC/VNet via SSL VPN, she should be able to access any instances in the other VPC/VNets as long as her profile allows, without having to connect to each VPC/VNet with SSL VPN. Another requirement is full tunnel mode, that is, all traffic originated from the user is routed through SSL VPN. Your organization requires to run its own firewall function for any Internet-bound traffic. Configuration Workflow ----------------------------------- Tips: Hover your cursor over the fields to see their definitions. The description in each step does not include all fields. Make sure you have the correct VPC/VNet ID and its region for the VPC/VNet ID field and region in each step. 1. Launch a gateway with VPN capability in VPC/VNet 172.31.0.0/16. * Go to Gateway menu and click **Create**. * At the Gateway Name field, give it a distinct and convenient name. For example, mgmt-vpn-1. * The VPN CIDR Block must be a subnet that is outside your current VPC/VNet CIDR range and your laptop or device subnet range. In the example above, you may enter 192.168.2.0/24. * Full Tunnel Mode is selected. * Enable AWS ELB is selected. * Enable Policy-Based Routing (PBR) is selected. i. Note that the PBR Subnet must be a subnet that is in the same AZ as the primary subnet (Public Subnet where the gateway is launched). Enter the AWS subnet default gateway for PBR Default Gateway field. For example, if PBR Subnet is 172.31.48.0/20, the default Gateway field is 172.31.48.1. ii. (optionally) you can enable NAT Translation Logging to log every user’s each activity to every server and site. This is useful for auditing and compliance. iii. Save Template is selected. This Template saves you from entering repeated fields if you wish to create more gateways with the same configuration. 2. Repeat Step 1 to create more gateways with VPN enabled. You may select different AZs for the Public Subnet field. 3. (Optional) If you have your own routing network to route between the VPCs and one of your own backbone routers can route traffic to your own firewall for Internet-bound traffic, you can skip this step and the next two steps (step 4 and 5). * Launch a gateway without VPN capability in VPC 172.31.0.0/16. This is the routing gateway, make sure: | i. At the Gateway Field, give it a distinct and convenient name. For example, dev-east-1, or teamKardashian-east-1 for the Kardashian game project. | ii. Enable NAT is not selected. | iii. VPN Access is not selected. | iv. Save Template is not selected. (so that you don’t overwrite the hard work of entering the fields of gateways with VPN enabled). 4. (Optional) Repeat step 3 for VPC 10.10.0.0/16, 10.5.0.0/16 and 10.80.0.0/16. Select Enable NAT if you wish the instances in these VPCs to be able to reach Internet directly. 5. (Optional) Configure encrypted peering. Go to VPC/VNet Encrypted Peering > Add. Note: each VPC/VNet is represented by one or more gateways. Make sure you want to peer between two gateways without VPN capability. 6. The steps above complete the network infrastructure setup. 7. Add Users and Profiles. a. Go to OpenVPN® -> Profiles to create as many profiles as you please. The target field can be FQDN (DNS names or fully qualified domain name). b. Go to OpenVPN® > VPN Users to add as many users as you please. Associate each user with a profile. Note: if no profile is associated, the user has full access to all resources. When a user is added to the database, an email with a .ovpn file or .onc (for Chromebooks) will be sent to the user with detailed instructions. Alternatively, you can go to Controller > VPN users > Download to download the .ovpn file directly. Use an AWS Transit Gateway to Access Multiple VPCs in One Region ============================================================== You can use an AWS Transit Gateway (TGW) allow remote users to connect to multiple VPCs in the same region, as shown below. |vpn_with_tgw_one_region| User VPN Solution for Multi Cloud ==================================== With Aviatrix multi-cloud support, you can build a global VPN solution that spans to multi cloud. |vpn_tgw_multi_cloud| OpenVPN is a registered trademark of OpenVPN Inc. .. |image0| image:: Cloud_Networking_Ref_Des_media/OneRegionVPC_reference.png :width: 3.81875in :height: 2.81918in .. |image1| image:: Cloud_Networking_Ref_Des_media/MultiRegionVPC_reference.png :width: 3.61127in :height: 2.59580in .. |image2| image:: Cloud_Networking_Ref_Des_media/FullTunnelVPC_reference.png :width: 3.81875in :height: 2.80898in .. |vpn_with_tgw_one_region| image:: Cloud_Networking_Ref_Des_media/vpn_with_tgw_one_region.png :scale: 30% .. |vpn_tgw_multi_cloud| image:: Cloud_Networking_Ref_Des_media/vpn_tgw_multi_cloud.png :scale: 30% .. disqus:: <file_sep> ################################### Diagnostics ################################### Network --------- This section provides tools to test the network connectivity of the Aviatrix Controller and Gateways. Gateway Utility ~~~~~~~~~~~~~~~~~ This section provides Traceroute, Ping, and Tracepath tools to test network connectivity for Aviatrix Gateways. Network Connectivity Utility ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The Network Connectivity tool allows you to test if the Aviatrix Controller or Gateway is able to reach a host with a specified protocol and port number. .. note:: Network connectivity tests using UDP protocol cannot be used to reliably determine connectivity as load balancers or security groups could consume the UDP packet, indicating a false positive. A UDP test that says success does not gurantee UDP connectivity. However, a UDP test showing failure means there are issues with UDP connectivity. Packet Capture ~~~~~~~~~~~~~~~~ This tool enables a gateway to capture the forwarding packets for a period of time with the specified host, port, network interface, and packet length. Here are some Wireshark tips: 1. **Sort the conversations** On Wireshark, go to **Statistics** > **Conversations**. All Conversations captured are displayed in the pop-up window. For each conversation, it shows how many bytes are transferred in which direction. 2. **Filter on conversation** From the above pop-up window, select one conversation. Right-click on the conversation, select **Apply as Filter** > A <-> B. The Wireshark capture window will automatically filter the other conversation out. 3. **View Throughput** On Wireshsark, go to **Statistics** > **TCP Stream Graphs** > **Throughput**. The Throughput for this TCP session will be displayed in a pop-up window. An example screenshot on conversation filtering is shown as below. |wireshark_filter| Controller Utility ~~~~~~~~~~~~~~~~~~~~ This tool allows the Aviatrix Controller to perform a ping test to a specific host to run a network connectivity test. Controller IP Migration ~~~~~~~~~~~~~~~~~~~~~~~~~ The Controller IP Migration feature enables you to migrate your Controller’s IP address to a new IP address after you associate a new IP address in AWS, Azure, GCP, or OCI or through API. Use this feature if your Controller does not use an EIP (Elastic IP) address, load balancer, or FQDN, and you take one or more of the following actions: * Restart or reboot your Controller. * Restore your Controller from backup. * Reassociate your Controller’s IP address. In these cases, use this feature to migrate the Controller’s IP address so that the gateways managed by this Controller have the correct IP address. Most accounts use an EIP or FQDN and therefore do not need to use the Controller IP Migration feature. Remote Support ~~~~~~~~~~~~~~~~~ By enabling Remote Support, you grant privileged level access to your Aviatrix Controller and any connected Aviatrix gateways to the Aviatrix Support team. This establishes a trusted connection between your Controller and the Aviatrix diagnostic server for diagnostic purposes. When Remote Support is enabled, an Aviatrix software engineer may run scripts and CLI debugging commands on the Controller and on any connected gateways, to triage issues. This access persists until you disable Remote Support. You must disable the Remote Support option when the debugging session is complete. When Remote Support is disabled, all trusted sessions and the underlying process enabling the trusted connection are immediately terminated on your Controller and gateways. This prevents further access to your Controller and gateways. Controller Public IP ~~~~~~~~~~~~~~~~~~~~~~ This section displays the current public IP of the controller. .. raw:: html <hr width="%80"/> Gateway --------- Diagnostics ~~~~~~~~~~~~~~ Refer to `Run diagnostics on a gateway. <http://docs.aviatrix.com/HowTos/troubleshooting.html>`__ Force Upgrade ~~~~~~~~~~~~~~~ .. note:: The Force Upgrade feature is not supported from Release 6.5 and onwards. For Gateway upgrades, refer to `Upgrading the Aviatrix Cloud Network Platform <http://docs.aviatrix.com/HowTos/selective_upgrade.html>`_. This feature allows you to upgrade one particular gateway. A common use case is that during Controller upgrade, if an unpredicted network connectivity issue occurs that causes one specific gateway to fail to upgrade, you can simply solve the problem by using this feature. Service Actions ~~~~~~~~~~~~~~~~~ This section allows you to view the status of the services running on a gateway, such as rsyslog, supervisor BGP service, and so on. Furthermore, you can restart a service if there is an indication showing that the service might not be working properly. Keep Gateway on Error ~~~~~~~~~~~~~~~~~~~~~~~ By default, the Controller will roll back all the operations (gateway, EIP, security-group creations, and so on) if an error occurs during a gateway creation. However, this function allows you to keep the gateway instance for debugging purposes. This feature disables the roll back operation if the Status is set to True. Gateway Replace ~~~~~~~~~~~~~~~~~ .. note:: The Gateway Replace feature is not supported from Release 6.5 and onwards. For Gateway upgrades, refer to `Upgrading the Aviatrix Cloud Network Platform <http://docs.aviatrix.com/HowTos/selective_upgrade.html>`_. This feature allows you to replace an existing gateway that is not functional by launching a new gateway and restoring the configuration to the new gateway. Use this feature only when you have exhausted all other options. You may open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_ if you need additional support. Select a gateway in the drop down menu and click **Replace**. To run gateway diagnostics, refer to `Run diagnostics on a gateway. <http://docs.aviatrix.com/HowTos/troubleshooting.html>`__ and `Service Description of Diagnostic Result. <http://docs.aviatrix.com/HowTos/Troubleshooting_Diagnostics_Result.html>`__ .. note:: When the Controller performs a gateway replacement procedure, efforts are made to minimize the downtime. For example, when a failed Spoke Gateway is being replaced, the Controller first redirects the traffic to a healthy Spoke Gateway by modifying the Spoke VPC route table to route all instance or VM traffic to the healthy gateway, it also moves the routes from the Transit Gateways pointing to the failed Spoke Gateway to the healthy Spoke Gateway for traffic moving from Transit Gateway to Spoke Gateway. After the failed gateway is terminated and a new gateway is launched and configuration installed, the Controller then programs the Spoke VPC route table to load balancing some subnets/route table to point to the new gateway and also move the routes back on the Transit Gateways. Similar process happens when a Transit Gateway is being replaced. As a result the downtime is under 10 seconds for each gateway replacement in the Multi-Cloud Transit solution. Similarly, when a failed gateway with Site2Cloud connections are being replaced, traffic is first redirected to the other healthy gateway before the failed gateway is terminated and replaced. Session View ~~~~~~~~~~~~ This feature allows you to view active connection sessions running through Aviatrix Gateways. This is useful for troubleshooting connectivity issue. To view sessions: - go to **Troubleshoot** > **Diagnostics** > **Gateway** > **Session View** - or go to **Security** > **Stateful Firewall** > **Session View** .. raw:: html <hr width="%80"/> VPN User ---------- VPN User Diagnostics ~~~~~~~~~~~~~~~~~~~~~~ This feature provides the status diagnostic information of a VPN user. VPN User History Search ~~~~~~~~~~~~~~~~~~~~~~~~~ This tool allows you to search the VPN connection log on a particular VPN gateway with the filtering feature. .. raw:: html <hr width="%80"/> Cloud ------- Account Diagnostics ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This feature checks if the access accounts have the correct configuration to meet the Controller's requirements. .. note:: This operation may take a couple minutes to finish if there are multiple access accounts. This feature supports AWS based access accounts only. .. VPC Diagnostics with Resources Information ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The diagnostic result of this feature provides the information of a specified VPC/VNet, such as DHCP options, subnets, ACLs, route tables, security groups and VM instances configurations. VNet Route Diagnostics ~~~~~~~~~~~~~~~~~~~~~~~~ .. note:: This feature supports Azure Classic only. .. This feature provides the following operations that can be applied to a VNet: 1. Display all route tables 2. Display route table details 3. Add a route table 4. Delete a route table 5. List route table and subnet tables 6. List effective route of an instance 7. Add a route in a route table 8. Delete a route 9. Turn IP fwd ON 10. Turn IP fwd OFF 11. Get IP fwd 12. Associate a subnet to a route table 13. Dissociate a subnet from a route table Refresh Tags ~~~~~~~~~~~~~ This feature syncs up AWS VPC name tags if users change the VPC name in AWS. .. raw:: html <hr width="%80"/> Database ---------- DB Diagnostics ~~~~~~~~~~~~~~~~ This section allows you to view database tables and restart a server for functionality recovering purposes. .. warning:: We strongly advise that you contact `Aviatrix Support <https://support.aviatrix.com>`_ before performing the operations to "Drop Database" or to "Delete Collection". .. .. raw:: html <hr width="%80"/> Services ---------- This feature allows you to view the services status of the Controller and Gateways. Moreover, it provides the ability to restart the services if there is an indication showing that a particular service is not working properly. .. raw:: html <hr width="%80"/> BGP ----- This section provides the ability to view BGP configurations for diagnostics or any purposes. .. raw:: html <hr width="%80"/> System Resources ------------------ This feature allows you to set the threshold for notifications when the disk or memory usage of a Controller or Gateway has reached certain percentage of the total usage. The default behavior is to alert administrators when the disk usage crosses 90% or if memory usage crosses 80%. Network Validation: Connectivity Test --------------------------------------- When you select the **Source Network** and **Destination Network**, the Aviatrix Controller will spin up two instances and run a connectivity test. After the test completes, you can re-run the test. There is only one pair of test endpoints that is valid at any given time. If you want to test a different endpoint, delete the current pair and launch a new pair. These instances are visible in the Gateway page, under "View Instances" .. |wireshark_filter| image:: troubleshoot_diag_media/wireshark_filter.png :scale: 30% .. disqus:: <file_sep> ========================================================= Transit FireNet Workflow for Azure ========================================================= Aviatrix Transit FireNet allows you to deploy firewall functions for the Aviatrix Multi-Cloud Transit architecture. With the Transit FireNet feature, the Firewall Network (FireNet) function is integrated into the Aviatrix Transit gateway. Aviatrix Transit FireNet supports different hashing algorithms available in Azure cloud to load balance the traffic across different firewalls which includes `Hash-based distribution mode (five-tuple hash) <https://docs.microsoft.com/en-us/azure/load-balancer/load-balancer-distribution-mode#hash-based-distribution-mode>`_ and `Source IP affinity mode (three-tuple or two-tuple hash) <https://docs.microsoft.com/en-us/azure/load-balancer/load-balancer-distribution-mode#source-ip-affinity-mode>`_. To learn more about Hashing Algorithm and Transit FireNet, read the `Transit FireNet FAQ. <https://docs.aviatrix.com/HowTos/transit_firenet_faq.html>`_ To deploy firewall networks in other CSPs: - `AWS Transit Gateway (TGW) <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html>`_ - `AWS Transit FireNet multi-cloud transit <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html>`_ - `GCP Transit FireNet workflow <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_gcp.html>`_ In this example, a Transit VNet with Aviatrix Gateways is deployed, and two Spoke Gateways (DEV and PROD) are attached to it. The transit VNET will then have a firewall of supported vendors (Check Point, Palo Alto Networks and Fortinet etc.) deployed within it. Please see the diagram below for more details. Once the infrastructure is in place you create a policy to inspect the east-west and north-south traffic. |avx_tr_firenet_topology_az| Create Transit VNet ******************** VNets can be created manually on Azure or directly from the Aviatrix Controller. VNets are created following the Useful Tools `Create a VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ guidelines. 1. Login to the Aviatrix Controller with a username and password. #. Navigate to **Useful Tools -> Create A VPC**. #. Select Azure as the Cloud Type. #. Add one VNet for Transit FireNet Gateway and select **Aviatrix Transit FireNet VNet** option as shown below. #. Create two more VNets with no option/checkbox selected for Spoke Gateways. |create_vpc| Deploy the Transit Aviatrix Gateway ************************************ The Transit Aviatrix Gateway can be deployed using the `Transit Gateway Workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-a-transit-gateway>`_. Prerequisites for Azure ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Transit FireNet builds on the Aviatrix Transit Network solution where Aviatrix gateways are deployed in Transit VNet and/or in Spoke VNet in Azure. ActiveMesh is applied by default. Make sure the deployment meets the following specifications: 1. Select the option “Enable Transit FireNet” when launching the Aviatrix Transit Gateway. #. Aviatrix Transit Network must be in Connected mode. Go to Multi-Cloud Transit -> Advanced Config -> Connected Transit and ensure the option is enabled. .. important:: In Aviatrix Controller version 6.0 and prior, the minimum size of the Aviatrix Transit Gateway virtual machine is Standard_B2ms. Starting in 6.1, the minimum Transit Gateway instance size requirement is removed. Procedure ~~~~~~~~~~~~~~~~~~~~~ 1. Navigate to Multi-Cloud Transit -> Setup -> Transit -> #1 Launch an Aviatrix Transit Gateway. #. Ensure that Azure is the selected Cloud Type. #. Enter a Gateway Name. #. Select the Azure Access Account Name. #. Select a region. #. Select the VNet Name. #. Select a Public Subnet. #. Select a gateway size (default is Standard_B2ms). #. Enable Insane Mode Encryption for higher throughputs (optional). #. Enable the Transit FireNet function. #. Click Create. #. Enable Transit Gateway HA by navigating to Multi-Cloud -> Setup -> #2 (Optional) Enable HA to an Aviatrix Transit Gateway. Please see an example below for Transit FireNet GW: |tr_firenet_gw| .. note:: Insane Mode Encryption for higher throughput requires a virtual machine size. Check this `link <https://docs.aviatrix.com/HowTos/insane_mode_perf.html#azure-performance-test-results>`_ for details. Deploy Spoke Gateways *********************** Now that we have an Aviatrix Transit Gateway, we can deploy Aviatrix Spoke Gateways in the spoke VNET using `Aviatrix Spoke Gateway Workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-a-spoke-gateway>`_. 1. Navigate to Multi-Cloud Transit -> Setup -> Spoke -> #1 Launch an Aviatrix Spoke Gateway. #. Deploy a Spoke Gateway (GW) in each of the spoke VNETs using defaults while choose correct Account and VNET info. #. Choose the Public Subnet. #. Enable Spoke Gateway HA by navigating to Transit network -> Setup -> #5 (Optional) Enable/Disable HA at Spoke GW. |launch_spk_gw| Attach Spoke Gateways to Transit Network ***************************************** Now that Transit and Spoke gateways are deployed, you must connect them. 1. Navigate to Multi-Cloud Transit -> Setup -> Attach/Detach -> #1 Attach Spoke Gateway to Transit Network. #. Select one spoke at a time and attach to the Transit Gateway. |attach_spk_trgw| .. note:: The Transit gateway is attached to Spoke Gateways, but by default, Transit Gateway will not route traffic between Spoke Gateways. Enable Connected Transit ************************ By default, spoke VNETs are in isolated mode where the Transit will not route traffic between them. To allow the Spoke VNETs to communicate with each other, you must enable Connected Transit by navigating to Multi-Cloud Transit -> Advanced Config. Under Edit Transit, select the Transit Gateway and toggle Connected Transit to **Enabled**. |connected_transit| Configure Transit Firewall Network *********************************** Now that Transit and Spoke gateways have now been deployed, you must deploy and enable the firewall for traffic inspection. 1. Navigate to Firewall Network -> Setup -> Transit FireNet -> #3a Enable Transit FireNet on Aviatrix Transit Gateway. #. Choose the Aviatrix Transit Gateway and Click **Enable**. |en_tr_firenet| 3. Navigate to Firewall Network -> Policy -> Manage FireNet Policy. #. Add Spokes to the Inspected box for traffic inspection. .. note:: By default, FireNet inspects ingress (INET to VNET) and east-west traffic (VNET to VNET) only. |tr_firenet_policy| Launch and Associate Firewall Instance *************************************** This approach is recommended if this is the first firewall instance to be attached to the gateway. This step launches a Firewall instance and associates it with one of the FireNet gateways. .. important:: The Firewall instance and the associated Aviatrix FireNet gateway above must be in the same AZ, and, we recommend that the Management Interface Subnet and Egress (untrust dataplane) Interface Subnet not be in the same subnet. .. note:: By default, Aviatrix Transit Firenet uses 5 tuple hashing algorithm but that can be changed to 2 or 3 tuple as per requirement. Please check transit `firenet FAQs <https://docs.aviatrix.com/HowTos/transit_firenet_faq.html#azure>`_ for more details. Launch and Attach ~~~~~~~~~~~~~~~~~~~ In the Aviatrix Controller navigate to Firewall Network -> Setup -> Firewall -> Step 2a. Provide all the required input as shown in the table and click **"Launch"**. .. important:: The vendor's firewall may take some time after launch to be available. ========================================== ========== **Setting** **Value** ========================================== ========== VPC ID The Security VNET created in Step 1. Gateway Name The primary FireNet gateway. Firewall Instance Name The name that will be displayed on Azure Console. Firewall Image The Azure AMI that you have subscribed. Firewall Image Version Firewall supported software versions. Firewall Instance Size Firewall virtual machine size. Management Interface Subnet. Select the subnet whose name contains "gateway and firewall management" Egress Interface Subnet Select the subnet whose name contains "FW-ingress-egress". Username Applicable to Azure deployment only. "admin" as a username is not accepted. Authentication Method Password or SSH Public Key Password Applicable to Azure deployment only. Key Pair Name (Optional) The .pem file name for SSH access to the firewall instance. Attach (Optional) By selecting this option, the firewall instance is inserted in the data path to receive packet. If this is the second firewall instance for the same gateway and you have an operational FireNet deployment, you should not select this option as the firewall is not configured yet. You can attach the firewall instance later at Firewall Network -> Advanced page. Advanced (Optional) Click this selection to allow Palo Alto firewall bootstrap files to be specified. ========================================== ========== Check Point Specifications ~~~~~~~~~~~~~~~~~~~~~~~~~~~ The Check Point Security Gateway has two interfaces as described below. ======================================================== =============================== ================================ **Check Point VM interfaces** **Description** **Inbound Security Group Rule** ======================================================== =============================== ================================ eth0 (on subnet -Public-FW-ingress-egress) Egress or Untrusted interface Allow ALL eth1 (on subnet -dmz-firewall) LAN or Trusted interface Allow ALL (Do not change) ======================================================== =============================== ================================ Note that security gateway eth1 is on the same subnet as Firenet gateway eth2 interface. Check Point Security Gateway launch from the Aviatrix Controller automatically initiates the on-boarding process, configure security gateway interfaces and program RFC 1918 routes. After completing this step, user should be able to login to the Check Point Gaia console with username **admin** and provided password during launch. .. note:: Repeat Step 2a to launch the second security gateway to associate with the HA FireNet gateway. Or repeat this step to launch more security gateways to associate with the same Firenet gateway. Follow `Check Point Example <https://docs.aviatrix.com/HowTos/config_CheckPointAzure.html#launch-check-point-firewall-from-aviatrix-controller>`_ to see how to launch Check Point Security Gateway in Azure, and for more details. Palo Alto VM-Series Specifications ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Palo instance has three interfaces as described below. ======================================================== =============================== ================================ **Palo Alto VM interfaces** **Description** **Inbound Security Group Rule** ======================================================== =============================== ================================ eth0 (on subnet -Public-gateway-and-firewall-mgmt) Management interface Allow SSH, HTTPS, ICMP, TCP 3978 eth1 (on subnet -Public-FW-ingress-egress) Egress or Untrusted interface Allow ALL eth2 (on subnet -dmz-firewall) LAN or Trusted interface Allow ALL (Do not change) ======================================================== =============================== ================================ Note that firewall instance eth2 is on the same subnet as FireNet gateway eth2 interface. You can launch the Palo Alto VM Series firewall from the Aviatrix Controller and then configure it. User should be able to login to the VM-Series console with given username and password during launch. .. important:: For Panorama managed firewalls, you need to prepare Panorama first and then launch a firewall. Check out `Setup Panorama <https://docs.aviatrix.com/HowTos/paloalto_API_setup.html#managing-vm-series-by-panorama>`_. When a VM-Series instance is launched and connected with Panorama, you need to apply a one time "commit and push" from the Panorama console to sync the firewall instance and Panorama. .. Tip:: If VM-Series are individually managed and integrated with the Controller, you can still use Bootstrap to save initial configuration time. Export the first firewall's configuration to bootstrap.xml, create an IAM role and Bootstrap bucket structure as indicated above, then launch additional firewalls with IAM role and the S3 bucket name to save the time of the firewall manual initial configuration. Fortinet FortiGate Specifications ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FortiGate Next Generation Firewall instance has two interfaces as described below. ======================================================== =============================== ================================ **FortiGate VM interfaces** **Description** **Inbound Security Group Rule** ======================================================== =============================== ================================ eth0 (on subnet -Public-FW-ingress-egress) Egress or Untrusted interface Allow ALL eth1 (on subnet -dmz-firewall) LAN or Trusted interface Allow ALL (Do not change) ======================================================== =============================== ================================ .. tip:: Starting from Release 6.2, FortiGate bootstrap configuration is supported. Please refer to `FortiGate Azure Configuration Example <https://docs.aviatrix.com/HowTos/config_FortiGateAzure.html#example-config-for-fortigate-vm-in-azure>`_ for more details. Associate an Existing Firewall Instance ****************************************** This step is the alternative step to Step 2a. If you already launched the firewall (Check Point, Palo Alto Network or Fortinet) instance from Azure Console, you can still associate it with the FireNet gateway. In the Aviatrix Controller navigate to Firewall Network -> Setup -> Step 2b and associate a firewall with the correct FireNet Gateway. Vendor Firewall Integration ***************************** Vendor integration dynamically updates firewall route tables. The use case is for networks with RFC 1918 and non-RFC 1918 routes that require specific route table programming on the firewall appliance. 1. In the Aviatrix Controller, navigate to Firewall Network -> Vendor Integration -> Firewall. Select the Firewall Vendor Type and fill in the details of your firewall instance. #. Click Save. #. You can click Show or Sync to show the integration details, or sync the configuration with the firewall. .. important:: Aviatrix Controller automatically programs RFC 1918 in Check Point Security Gateway at a time of launch. This step can be skipped for Check Point if non-RFC 1918 routes programming is not required in Security Gateway. .. note:: Vendor integration is not supported for FortiGate. User needs to configure RFC 1918 static routes manually in FortiGate firewall. Enable Health Check Policy in Firewall **************************************** Aviatrix Controller uses HTTPS (TCP 443) to check the health of firewall every five seconds. You must enable this port in the firewall as per given instructions. Check Point ~~~~~~~~~~~~~~ By default, HTTPS or TCP 443 is allowed in Security Gateway. No action is required. Palo Alto Network (PAN) ~~~~~~~~~~~~~~~~~~~~~~~~~ By default, VM-Series does not allow HTTPS or TCP 443 port. Follow these steps to enable it: 1. Login to VM-Series with username and password. #. Go to Network -> Interface Mgmt under Network Profiles and click "Add". #. Give any name in "Interface Management Profile", check HTTPS checkbox under Administrative Management Service and click "OK". #. Attach Profile with LAN interface. Network -> Interfaces -> Select LAN Ethernet Interface -> Advanced -> Management Profile -> Select appropiate profile. |PAN-health-check| See an example screenshot below how to attach profile to an interface. |pan_hcheck_attach| Firewall health check probes can be verified in Monitor -> Traffic. |pan-health-probe| Fortinet FortiGate ~~~~~~~~~~~~~~~~~~ You must allow HTTPS or TCP 443 port in the FortiGate firewall to monitor the health of firewall. Please follow the steps to allow HTTPS in FortiGate: 1. Login to FortiGate's console using username and password. #. Go to Network -> Interfaces, select **port 2** and click "Edit". #. Check HTTPS checkbox under Administrative access -> IPv4 and click "OK". |health-check| The health check probes can be verified in FortiGate by navigating to Log & Report -> Local Traffic. |health-probe-logs| Example Setup for "Allow All" Policy ************************************** After a firewall instance is launched, wait for 5 to 15 minutes for it to come up. Time varies for each firewall vendor. In addition, please follow example configuration guides as below to build a simple policy on the firewall instance for a test validation that traffic is indeed being routed to firewall instance. Palo Alto Network (PAN) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For basic configuration, please refer to `example Palo Alto Network configuration guide <https://docs.aviatrix.com/HowTos/config_paloaltoVM.html>`_. For implementation details on using Bootstrap to launch and initiate VM-Series, refer to `Bootstrap Configuration Example <https://docs.aviatrix.com/HowTos/bootstrap_example.html>`_. FortiGate (Fortinet) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For basic policy configuration, please refer to `example Fortinet configuration guide <https://docs.aviatrix.com/HowTos/config_FortiGateAzure.html#configure-basic-traffic-policy-to-allow-traffic-vpc-to-vpc>`_. Check Point ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For basic policy configuration, please refer to `example Check Point configuration guide <https://docs.aviatrix.com/HowTos/config_CheckPointAzure.html#configure-basic-traffic-policy-to-allow-traffic-vnet-to-vnet>`_. Verification *************** There are multiple ways to verify if Transit FireNet is configured properly: 1. Aviatrix Flightpath - Control-plane Test #. Ping/Traceroute Test between Spoke VNETs (East-West) - Data-plane Test Flight Path Test for FireNet Control-Plane Verification ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Flight Path is a very powerful troubleshooting Aviatrix tool which allows users to validate the control-plane and gives visibility of end to end packet flow. 1. Navigate to **Troubleshoot-> Flight Path** #. Provide the Source and Destination Region and VNET information #. Select ICMP and Private subnet, and Run the test .. note:: VM instance will be required in Azure, and ICMP should be allowed in security group. Ping/Traceroute Test for FireNet Data-Plane Verification ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Once control-plane is established and no problems are found in security and routing polices, data-plane validation needs to be verified to make sure traffic is flowing and not blocking anywhere. There are multiple ways to check the data-plane: 1. SSH to Spoke EC2 instance (e.g. DEV1-VM) and ping other Spoke EC2 to instance (e.g PROD1-VM) to make sure no traffic loss in the path. 2. Ping/traceroute capture can also be performed from Aviatrix Controller. Go to **TROUBLESHOOT -> Diagnostics** and perform the test. .. |avx_tr_firenet_topology_az| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/avx_tr_firenet_topology_az.png :scale: 20% .. |insane_mode_tp| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/insane_mode_tp.png :scale: 30% .. |create_vpc| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/create_vpc.png :scale: 40% .. |tr_firenet_gw| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/tr_firenet_gw.png :scale: 35% .. |launch_spk_gw| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/launch_spk_gw.png :scale: 35% .. |attach_spk_trgw| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/attach_spk_trgw.png :scale: 35% .. |en_tr_firenet| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/en_tr_firenet.png :scale: 35% .. |tr_firenet_policy| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/tr_firenet_policy.png :scale: 35% .. |avx_tr_firenet_topology| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/avx_tr_firenet_topology.png :scale: 35% .. |connected_transit| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/connected_transit.png :scale: 40% .. |health-check| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/health-check.png :scale: 35% .. |PAN-health-check| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/PAN-health-check.png :scale: 35% .. |health-probe-logs| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/health-probe-logs.png :scale: 40% .. |pan-health-probe| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/pan-health-probe.png :scale: 40% .. |pan_hcheck_attach| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/pan_hcheck_attach.png :scale: 40% .. disqus:: <file_sep> ============================== Site2Cloud Case Study ============================== The Problem ================= Traditionally enterprises host their IT applications in their own data center or at a co-location. Remote sites typically connect to the data center via an Internet-based IPsec VPN tunnel or MPLS based private network. Such a hub and spoke architecture has been prevalent in the last 15 years. A problem with this deployment architecture is long latency or unstable Internet connectivity suffered by remote sites, especially between those in different continents. Such problems cause application time out, resulting in lost productivity and an unhappy user experience. The solution to this pain point has been to deploy some form of WAN optimization in both the remote sites and data center to reduce application latency and reduce data bandwidth. These gears are complex, expensive and not every enterprise can afford them, and in some cases, they don’t always work well. Solution: Bring Application to User ==================================== With the many regions in the world available brought by public cloud providers, such as AWS and Azure, the application latency issue can now be solved in a brand-new way. By placing applications in a region of public cloud that your remote sites are closer to than to the data center, the long latency issue is eliminated altogether. In addition, by moving servers to the cloud, you can reduce remote sites' footprint and the amount of hardware to manage, thus reducing cost for ongoing maintenance. The comparison between the two deployment architectures is described below: |image0| In the diagram above, remote sites or branch offices connect to the headquarters' data center via IPsec tunnels. International sites across continents can experience hundreds or more milliseconds in latency and in some countries, connectivity to headquarters is unstable at times. The first step in deploying an application close to the user is to build a new network architecture as shown in the right side of the diagram above. A remote site now connects via an IPsec tunnel to the closest Aviatrix Gateway in a VPC or VNet in a region closest to the site. Different remote sites may connect to different Aviatrix Gateways. For example, sites in China connect to Aviatrix Gateways in the Azure China region and sites in Europe connect to an Aviatrix Gateway in a VPC in the AWS eu-west-1 region. After the new network is deployed, you can now replicate Active Directory to VPC/VNet and deploy applications such as ERP in the cloud too. The AD authentication latency and application latency can be reduced to tens of milliseconds. In addition, the remotes are simpler with fewer hardware equipment to manage. For how to set up Site2Cloud, follow `Site2Cloud configuration guide. <http://docs.aviatrix.com/HowTos/site2cloud.html>`_ .. |image0| image:: site2cloud_media/image1.png :width: 5.03147in :height: 2.57917in .. disqus:: <file_sep> =========================================================================================== Accessing a Virtual IP address instance via Aviatrix Transit Network =========================================================================================== This document addresses the scenario where a customer on-prem firewall device needs to route encrypted traffic to a partner network in the cloud (AWS/Azure/GCP). However due to concerns for overlapping CIDR blocks to the customer network, the customer side enforces a policy that the destination IP address must be a public or a virtual IP address regardless if the partner network is in the RFC 1918 range. For example, the VPC instance IP address that the on-prem machine should send data to is 172.16.58.3, but the on-prem machine must instead send data to a virtual IP address 192.168.127.12 (or even 172.16.58.3). Normally this problem can be solved by combining `Site2Cloud <https://docs.aviatrix.com/HowTos/site2cloud.html>`_ feature and `DNAT <https://docs.aviatrix.com/HowTos/gateway.html#destination-nat>`_ feature. There are situations where there are multiple applications in different VPCs, it is desirable to access different virtual addresses without building multiple IPSEC tunnels to the cloud networks. This can be accomplished by building an Aviatrix Transit Network where Spoke VPCs host these different applications, as shown in the diagram below. |transit_publicIP| Below are the configuration steps. Step 1: Determine the virtual IP address ------------------------------------------- As this virtual IP address is what the on-prem host sees, it should not change. There are a couple of ways to determine it. You can allocate an EIP in the VPC for this virtual IP address. Make sure you don't associate this EIP to any instance. Alternatively, if the EC2 instance that on-prem hosts need to send data to has an EIP, you can use that EIP. You can also try a reserved public IP address range, for example, 100.100.x.x range, if the customer does not object. Step 2: Follow the Transit Network workflow to launch a Spoke gateway ----------------------------------------------------------------------- Login to the Controller console, go to Site2Cloud. Follow step 1 to launch a gateway in the VPC 172.16.58.3/16. In this example the gateway name is Spoke1. (You can follow the `gateway launch instructions in this <http://docs.aviatrix.com/HowTos/gateway.html>`_. Leave optional parameters unchecked.) Step 3: Customize Spoke gateway advertised routes ----------------------------------------------------------------------- Go to Gateway page, highlight the Spoke gateway created in the previous step, click Edit. Scroll down to "Customize Spoke Advertised VPC CIDRs", enter, in this example, 192.168.127.12/32 With this customization, the Spoke gateway advertises 192.168.127.12/32 to Transit Gateway and subsequently to on-prem. Step 4: Attach the Spoke gatewway --------------------------------------------- Follow the Transit Network -> Setup -> Step 6a, Attach Spoke GW to Transit VPC. Step 5: Configure DNAT on Spoke gateway ------------------------------------------ This step is to configure the Spoke gateway to translate the destination virtual IP address 192.168.127.12 to the real private IP address 172.16.58.3. At the main navigation bar, click Gateway. Highlight the Spoke gateway, and click Edit. Scroll down to Destination NAT. Follow the instructions `here <https://docs.aviatrix.com/HowTos/gateway.html#destination-nat>`_ to configure, as shown below. Note to use "Connection" field to specify the site2cloud connection name configured in Step 3. |dnat_config| Step 6. Test! --------------------------------------------------------- Test connectivity from on-prem host to the EC2 instance. For example, ping the virtual IP address 192.168.127.12 from an on-prem host machine. The ping should reach 172.16.58.3. .. |transit_publicIP| image:: transit_for_publicIP_media/transit_publicIP.png :scale: 30% .. |dnat_config| image:: transit_for_publicIP_media/dnat_config.png :scale: 30% .. disqus:: <file_sep> ============================================================= Transit Gateway Egress VPC Firewall Limitation Test Validation ============================================================= Introduction -------------- This document demonstrates that native Transit Gateway does not support multi AZ deployment for a centralized egress firewall. AWS Transit Gateway allows spoke VPCs to send Internet bound traffic through firewall instance deployed in attached egress VPC. However Transit Gateway is not aware of the state of each firewall in different AZ in the egress VPC, therefore not able to switch over to a different firewall instance when one fails. Test Validation ---------------- The test setup is described in the following. VPC1 is a Spoke VPC attached to Transit Gateway. There are three EC2 instances serving as Internet traffic sources. VPC2 is an Egress VPC and has two Available Zones (AZs). Subnet_1 (private subnet) and Subnet_2 (public subnet) are in AZ_a. Subnet_3 (private subnet) and Subnet_4 (public subnet) are in AZ_b. Both AZs (Subnet_1 in AZ_a and Subnet_3 in AZ_b) are attached to the Transit Gateway. Subnet_1 is at the top of the Transit Gateway attachment list due to AZ_a is ahead of AZ_b in alphabetical order. Each AZ has one Palo Alto Networks (PAN) firewall instance. For PAN1, its eth1/1 interface is at Subnet_2 (public subnet) and its eth1/2 interface is at Subnet_1 (private subnet). For PAN2, its eth1/1 interface is at Subnet_4 (public subnet) and its eth1/2 interface is at Subnet_3. Subnets' VPC Route Tables (RTBL) are also displayed at the diagram. |tgw_egress| The VPC1's traffic will flow through Transit Gateway and Palo Alto Networks firewall before going to Internet. We verified the data path in different scenarios and observed the following behaviors: 1. With both Subnet_1 and Subnet_3 attached to Transit Gateway, Transit Gateway forwards VPC1's Internet traffic from all three EC2 instances to PAN1. This is because PAN1's private subnet (Subnet_1) is at the top of the Transit Gateway's attachment list. Transit Gateway does not load balance traffic between the two firewalls. 2. Stop PAN1 at AWS Console. VPC1's Internet traffic is blocked. Transit Gateway does not detect PAN1's health state and does not fail over to PAN2 accordingly. 3. Restart PAN1 at AWS Console. VPC1's Internet traffic will resume by going through PAN1. 4. Stop PAN1 at AWS Console again. To resume the VPC1's traffic, we need to detach PAN1's private subnet (Subnet_1) from Transit Gateway. After it, VPC1's traffic can flow through Transit Gateway and PAN2 before going to Internet. 5. Restart PAN1 at AWS Console and re-attach PAN1's private subnet (Subnet_1) to Transit Gateway. After it, VPC1's traffic still flows through PAN2. Transit Gateway won't redirect the traffic to PAN1. Summary --------- Although Transit Gateway allows Internet bound traffic to be forwarded to firewall instances in an egress VPC, multi-AZ deployment for such firewall service is not supported. .. |tgw_egress| image:: tgw_egress_media/tgw_egress.png :scale: 70% .. add in the disqus tag .. disqus:: <file_sep> =========================== Aviatrix OpenVPN® FAQs =========================== How do I launch a VPN Gateway? ------------------------------------------- Navigate to Gateway > **+ New Gateway**. The Controller launches an Aviatrix Gateway instance in AWS/Azure/GCP. The gateway instance must be launched from a public subnet for AWS and GCP. You need to give it a name (the name is presented as a Gateway Name field), this name becomes part of the instance name with a prefix CloudOps. In the Create page, select VPN Access to enable OpenVPN® server capability. There is a default VPN CIDR “192.168.43.0/24”, but you can change it to make sure the CIDR is outside the existing and future VPC/VNet CIDR range. This VPN CIDR is where the VPN server assigns a virtual IP address to each user when she connects. You can click **Save Template** to save the gateway template. When you come to the page the next time, most of the fields are pre-populated. You may change any of the fields. How can I avoid managing multiple VPN user certs? ------------------------------------------------------------------ If you have multiple VPC/VNets, launching a VPN gateway in each VPC/VNet and creating VPN users is not the correct way of management. It forces your developers to carry multiple .ovpn certs and learn when to use which one when connecting to a VPC/VNet. `Leverage VPC/VNet-to-VPC/VNet connectivity to build a scalable solution. <http://docs.aviatrix.com/HowTos/Cloud_Networking_Ref_Des.html>`_ How do I scale out VPN solution? ---------------------------------------------- You can launch multiple `VPN gateways <https://docs.aviatrix.com/HowTos/uservpn.html>`_ in the same VPC/VNet. By default, the first VPN gateway in a VPC/VNet is launched with a NLB. Subsequent VPN gateways in the same VPC/VNet are automatically associated with the same NLB, enabling a scale out VPN solution, where the NLB load balances incoming VPN user sessions. Consistent gateway configuration is required when NLB is enabled. For example, authentication methods, tunnel modes and PBR configurations should be identical. How do I setup Okta authentication for VPN? -------------------------------------------------- An Aviatrix VPN gateway integrates seamlessly with Okta. It can authenticate VPN users to Okta service using Okta's OpenVPN® plugin in module. Follow this link for directions: `How to set up Okta for Aviatrix VPN gateway <http://docs.aviatrix.com/HowTos/HowTo_Setup_Okta_for_Aviatrix.html>`__. How do I enable Geo VPN? -------------------------------------- If you have a global workforce that needs to access the cloud, Geo VPN offers a superior solution. Geo VPN enables a VPN user to connect to the nearest VPC/VNet that hosts an Aviatrix VPN Gateway. To enable Geo VPN, go to OpenVPN® > GEO VPN. Also check out `this link <http://docs.aviatrix.com/HowTos/GeoVPN.html>`_ for help. How do I add a VPN user? ------------------------------------- After at least one gateway is created, you can add VPN users. Click OpenVPN® > VPN Users > **+Add New**. When a user is added, an email is sent to the user with instructions on how to download client software and connect to a VPN server. You can customize this email by updating the settings at OpenVPN > Advanced > Global Config > User Defined Email Notification. You could also use your own SMTP server to send these emails out by following `these instructions <https://docs.aviatrix.com/HowTos/alert_and_email.html#how-to-change-source-of-email-notification>`_. If you prefer to not share the .ovpn file with your users via email, do not enter the email address when you add a VPN user. You can then download the .ovpn file from OpenVPN > VPN Users > Select VPN User and then download the file and share it with your VPN user via your preferred file share mechanism. If you would like to assign user profile-based policies, you need to create profiles first. See the next section. What user devices are VPN client software supported? ---------------------------------------------------------- Windows, MAC, Linux, Chromebook, Android and iOS devices are supported. Is NAT capability supported on the gateway? ------------------------------------------------- Yes, you can enable NAT function at gateway launch time. When enabled, instances on the private subnet can access the Internet directly. If full tunnel mode is selected, you may want to enable NAT to allow instances in the VPC/VNet to have direct Internet access. Is full tunnel mode supported on the gateway? ------------------------------------------------------------S Yes, both split tunnel and full tunnel modes are supported. You can specify the mode at the gateway launch time. Full tunnel means all user traffic is carried through the VPN tunnel to the gateway, including Internet bound traffic. Split tunnel means only traffic destined to the VPC/VNet and any additional network range is carried through the VPN tunnel to the gateway. Any Internet bound traffic does not go through the tunnel. To enable full tunnel mode, go to Edit Config > Modify Split Tunnel, select **No**, as shown below. |full_tunnel| Can the maximum number of simultaneous connections to VPN gateway be configured? ----------------------------------------------------------------------------------------------------------- Yes, you can set the maximum number of connections at the gateway launch time. What is user profile-based security policy? -------------------------------------------- In VPN access, a user is dynamically assigned a virtual IP address when connected to a gateway. It is highly desirable to define resource access policies based on the users. For example, you may want to have a policy for all employees, a different policy for partners and a still different policy for contractors. You may even give different policies to different departments and business groups. The profile-based security policy lets you define security rules to a target address, protocol and ports. The default rule for a profile can be configured as deny all or allow all during profile creation. This capability allows flexible firewall rules based on the users, instead of a source IP address. The security policy is dynamically pushed to the landing VPN gateway when a VPN user connects. It is only active when a VPN user is connected. When a VPN user disconnects, the security policy is deleted from the VPN gateway. How do I set up profile-based security policies? -------------------------------------------------------------- When a user connects to a VPC/VNet, the security policies associated with the profile that the user is assigned to are applied to the VPN gateway instance that user logs in. This effectively blocks traffic from entering the network. Click OpenVPN® > Profiles > +New Profile to create profiles, then click **Edit Policies** to add rules. You can add multiple of them. Click **Save**. Click **Update** for the rules to take effect. |profile_config| How do I assign a user to a profile? ---------------------------------------------- When you create a VPN user at OpenVPN® > VPN Users > +Add New, you can select profile option to assign the user to a specific profile. You can also attach the user to a profile at a later time. Go to OpenVPN® > Profiles. Click **Attach User** on a specific Profile and select a user that is added to the VPN gateway. |assign_user_to_profile| What if I want to change profile policies? ----------------------------------------------------- You can change profile policies any time. However, users who are currently active in the session will not receive the new policy. The user will need to disconnect and reconnect to VPN for the new policy to take effect. How do I change a user’s profile programmatically? ------------------------------------------------------------------- The Controller provides an API which can be invoked to change a user’s profile. Refer to API documentation under the Help menu. During this operation, the user’s existing VPN session will be terminated. The new profile policy will take effect when he or she logs in again. The use case for this feature is to allow an administrator to quarantine a VPN user for security reasons. How to set User VPN License Threshold Notification? -------------------------------------------------------------------- The User VPN License Threshold Notification can be set in Aviatrix Controller. Log into the Aviatrix Controller and navigate to Settings > Controller > License. Under License, user can set the number of licenses purchased and threshold value. Once the number of licenses exceeded the threshold value an email notification will be sent. The email id which receives all the notification can be set in Email tab (Settings > Controller > Email). Is DUO multi-factor authentication supported? ------------------------------------------------------------- Yes. If your enterprise has a DUO account with multi-factor authentication, it can be integrated into the VPN solution. From Gateways tab, click **Create**. At the two-step authentication drop down menu, select DUO, then enter your company Integration Key, Secret Key, and API hostname. To obtain an Integration Key, Secret key and API hostname, log in to the DUO website, `www.duo.com <http://www.duo.com>`__ as an admin. Click on the left panel Applications and click **Protect an Application** below. Scroll down the application list and select OpenVPN® (click Protect this Application), the next page should reveal the credentials you need to configure on the Aviatrix Controller. For additional help, follow `this instruction. <http://docs.aviatrix.com/HowTos/duo_auth.html>`_ Currently, advanced features such as Trusted Device and Trusted Networks are not supported. Send us a request if you would like to integrate these features. How do I configure LDAP authentication? -------------------------------------------------- See details `here <./VPNUsers_LDAP.html>`__. Can I combine LDAP and DUO authentication? ------------------------------------------- Yes. With both LDAP and DUO authentication methods enabled on a gateway, when launching the VPN client, a remote user will have to enter his or her LDAP user credentials and then approve the authentication request received on a registered mobile device to login to the VPN. Is OKTA supported? ------------------- Yes. OKTA with MFA is also supported. Follow the `instructions <http://docs.aviatrix.com/HowTos/HowTo_Setup_Okta_for_Aviatrix.html>`__ How does Policy-Based Routing (PBR) work? ----------------------------------------------------------- When PBR is enabled at gateway launch time, all VPN user traffic that arrives at the gateway will be forwarded to a specified IP address defined as the PBR default gateway. The user must specify the PBR Subnet which in AWS must be in the same availability zone as the Ethernet 0 interface of the gateway. When the PBR feature is combined with encrypted peering capability, a VPN user should be able to access any instances in the peered VPC/VNets. This helps build an end-to-end cloud networking environment. For details, check out our `reference design <http://docs.aviatrix.com/HowTos/Cloud_Networking_Ref_Des.html>`__. Another use case for Policy-Based Routing is if you would like to route all Internet bound traffic back to your own firewall device on Prem, or log all user VPN traffic to a specific logging device. PBR lets you accomplish that. What are the monitoring capabilities? ----------------------------------------- Active VPN users are displayed on the Dashboard. Click on any username and the user VPN connectivity history is displayed. You can also disconnect a user from the dashboard. Does the Aviatrix OpenVPN® solution support SAML client? -------------------------------------------------------------------------- Yes. The Aviatrix VPN client is the only OpenVPN® based client software that supports SAML authentication from the client software itself. Read `here <https://docs.aviatrix.com/HowTos/VPN_SAML.html>`_ to learn more. When should I use the Aviatrix VPN client? -------------------------------------------------------- Aviatrix's `VPN Client <../Downloads/samlclient.html>`__ supports SAML authentication from the VPN client itself. If you need the VPN client itself to authenticate against an IDP (for example, Okta, Google, AWS SSO and Azure AD), you will need to use the Aviatrix VPN client. An Aviatrix VPN gateway can authenticate a VPN user against OKTA on behalf of a VPN user. In that case, the Aviatrix VPN client is not needed, and any OpenVPN® client software such as Tunnelblick can be supported. Are multiple VPN configuration profiles supported by the Aviatrix VPN client? -------------------------------------------------------------------------------------------------- Note that this is about the OpenVPN® configuration file that is installed on end user machines. Aviatrix's `VPN Client <../Downloads/samlclient.html>`__ allows you to load and switch between one or more VPN profiles. Load multiple configurations: #. Open the client. #. Click **Advanced**. #. Select the **Profile** tab. #. Click **Add**. #. Enter a name for the new profile. #. Select the configuration file. Switch to a different configuration: #. Open the client. #. Click **Connect** button. A dropdown menu appears. #. Select the profile from the list. What is "Client Certificate Sharing"? -------------------------------------------------- Enabling this feature allows the same user to be logged in from more than one location at a time. If this option is disabled and a user logs in from a second location, the first location will be disconnected automatically. How do I fix the Aviatrix VPN timing out too quickly? ---------------------------------------------- - How do I change the Renegotiation interval? #. Log in to your Aviatrix Controller. #. Select OpenVPN on the left sidebar, and then select **Edit Config**. #. Select the VPC/VNet (or DNS Name) and the Gateway. #. Scroll to the **Modify VPN Configuration** section. #. Click on the **Name**dropdown menu and select **Renegotiation interval**. #. Click on the **Status** toggle switch to set it to **Enabled**. #. Set the **Value (seconds)** to the desired timeout value. #. Click **OK**. |imageRenegotiationInterval| - How do I change the idle timeout? #. Log in to your Aviatrix Controller. #. Select OpenVPN on the left sidebar, and then select **Edit Config**. #. Select the VPC/VNet (or DNS Name) and the Gateway. #. Scroll to the **Modify VPN Configuration** section. #. Click on the **Name**dropdown menu and select **Idle timeout**. #. Click on the **Status** toggle switch to set it to **Enabled**. #. Set the **Value (seconds)** to the desired timeout value. #. Click **OK**. |imageIdleTimeout| Where do I find the log for the Aviatrix Client? ------------------------------------------------------------- #. Open the Aviatrix VPN Client. #. Click **Advanced**. #. Select the **Advanced** tab. #. Click **View** next to the View the log file label. |imageClientLog| Why can't my VPN client access a newly created VPC/VNet? ------------------------------------------------------------------------------ If you are using Split Tunnel mode, it is very likely that the new VPC/VNet CIDR is not part of CIDR ranges that the Aviatrix VPN gateway pushes down to the client when the VPN client connects. To fix it, follow these steps: 1. At the main navigation menu, go to OpenVPN® > Edit Config. #. Scroll down to Modify Split Tunnel, select yes to Split Tunnel Mode. #. At `Additional CIDRs <https://docs.aviatrix.com/HowTos/gateway.html#additional-cidrs>`_, enter the list of CIDR blocks including the new VPC/VNet CIDR that you wish the VPN client to access. #. When complete, click **Modify** for the configuration to take effect. #. Disconnect the VPN client and connect again. The new CIDR should take effect. How do I turn off NAT with an OpenVPN® Gateway? ------------------------------------------------------------------ An Aviatrix OpenVPN® Gateway performs a NAT function for the user's VPN traffic, effectively masking out the VPN client's virtual IP address assigned by gateway from the `VPN CIDR Block <https://docs.aviatrix.com/HowTos/gateway.html#vpn-cidr-block>`_. This does not affect profile-based policy enforcement as the landing VPN gateway has the information of the virtual IP address before NAT is performed and enforces policies based on user identification. If you do want to preserve the virtual IP address after the client packet leaves the gateway, you can do by enabling `PBR function <https://docs.aviatrix.com/HowTos/gateway.html#enable-policy-based-routing-pbr>`_. What IP Address is used for NAT'ing the VPN Clients? ------------------------------------------------------------------- If the destination is another instance within the cloud provider, then the OpenVPN gateway’s private IP address is used to NAT the OpenVPN Client's traffic. But if the destination is outside the cloud provider(the Internet), then the public IP address of the OpenVPN Gateway is used. What is User Defined Email Notification? -------------------------------------------------- User Defined Email Notification feature allows users to customize the email notification (both email content and attachment file name) for VPN client. To configure it, go to OpenVPN® > Advanced > Global Config > User Defined Email Notification to edit the file name or email content. The new email format will be used when a VPN certificate is issued. See "How do I add a VPN user?" for more info. How to customize popup messages after a VPN user is connected? ---------------------------------------------------------------------------------------- System Use Notification feature allows users to customize pop-up messages after a VPN user is connected. One use case is for customer to write their own messages for compliance. To configure it, go to OpenVPN® > Advanced > Global Config -> System Use Notification. .. note:: Please ensure that you are running Aviatrix VPN Client version 2.9 or higher to view the usage notification. How to set a minimum Aviatrix VPN client software version for OpenVPN® connection? -------------------------------------------------------------------------------------------------------------- Minimum Aviatrix VPN Client Version feature allows users to set a minimum Aviatrix VPN client software version that is allowed to connect successfully. To configure it, go to OpenVPN® -> Advanced -> Global Config -> Minimum Aviatrix VPN Client Version to set the Aviatrix VPN client version. What is Download SAML VPN Client? ----------------------------------------------- This feature only applies to VPN client using SAML authentication. It allows users to download the ovpn VPN connection cert file and the VPN client installer in a self-service manner. To configure it, go to OpenVPN® > Advanced > Global Config > Download SAML VPN Client to enable/disable this feature. |client_download| Once enabled, copy the `Download URL` link and send the link to your VPN users. When accessing the URL link, a VPN user is redirected to SAML IDP for authentication. Only after authentication, a user is allowed to access for VPN software download. Two files, the Aviatrix VPN client software and the UserVPN certificate (.ovpn file), are downloaded. Install the client package to start the VPN client software and then load the client certificate to connect to the cloud network. .. important:: 1. Only one load balancer is supported on a given Controller, implying that the system supports a fleet of UserVPN gateways behind one load balancer. Note that after releases 6.7.1436 or 6.8.1148, AWS classic Load Balancers are not supported with UserVPN gateways. Instead, `migrate <https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/migrate-classic-load-balancer.html>`_ to Network Load Balancers in your AWS account. 2. `Client Certificate Sharing <https://docs.aviatrix.com/HowTos/gateway.html#enable-client-certificate-sharing>`_ must be enabled for the UserVPN solution, implying you must first configure the VPN user on SAML IDP and on the Aviatrix Controller you need to configure only one VPN user. OpenVPN® is a registered trademark of OpenVPN Inc. .. |image1| image:: FAQ_media/image1.png .. |imageIdleTimeout| image:: FAQ_media/idle_timeout.png .. |imageClientLog| image:: FAQ_media/aviatrix_client_get_log.png .. |imageRenegotiationInterval| image:: FAQ_media/renegotiation_interval.png .. |full_tunnel| image:: FAQ_media/full_tunnel.png :scale: 30% .. |profile_config| image:: FAQ_media/profile_config.png :scale: 30% .. |assign_user_to_profile| image:: FAQ_media/assign_user_to_profile.png :scale: 30% .. |windows_client| image:: openvpn_faq_media/windows_client.png :scale: 30% .. |linux_client| image:: openvpn_faq_media/linux_client.png :scale: 30% .. |client_download| image:: openvpn_faq_media/client_download.png :scale: 30% .. disqus:: <file_sep> ============================================= Aviatrix Operations Overview ============================================= This document summarizes 10 operation services provided by Aviatrix Solutions. |aviatrix_dashboard| 1. Manageability ------------------ - **Simplicity** Point-and-Click work flow based instructions are designed for each use case and are easy to follow. Network CCIE are not required to deploy and manage the network. - **Multi Accounts** Single pane of glass to manage all your cloud accounts for networking and networking security. - **Multi-Cloud** Single pane of glass to manage all your public cloud deployment for networking and networking security. - **RBAC** Role Based Access Control allows you to manage multi accounts with fine grain access control for large organizations. - **Hitless Software Upgrade** Aviatrix software upgrades do not require the Controller nor gateway to reboot. The upgrade process takes a few minutes and does not cause any network downtime or packet loss. - **Technical Documentation** In product links to well documented and agile publishing technical documentation site. - **FAQs** A wealth of FAQs that answer commonly asked questions in problem space, benefits and useful links. - **Tech Notes** A wealth of Tech Notes that provide examples for use case specific configurations. - **Design Patterns** A wealth of Design Patterns that addresses architectural requirements for all deployments. 2. Automation --------------------- - **API** All functions support API. - **Terraform** Aviatrix provides its own Terraform Provider for Aviatrix created resources. - **Cloud Formation** Aviatrix provides Cloud Formation Scripts for AWS Controller launch and multi-account creation. - **Examples** Terraform examples are presented for various use cases. 3. Visibility ---------------- - **Geographic Map** Dashboard provides a geographical view of network topology under management. It also displays real time latency between any two nodes of deployed Aviatrix gateways. When a network connection is down, the connection becomes a red color. - **Traffic Metrics** All Controller and gateway network traffic metrics are logged and displayed in time series. - **User Activities** Active VPN users and where they connect from is displayed. VPN user session history is logged and displayed. - **AWS Transit Gateway (TGW) Orchestrator View** A graphical view that displays what Security Domain and Connection Policies that have been configured. You can find for a given VPC, what other VPCs connect to it. - **AWS Transit Gateway (TGW) Orchestrator List** Multi-panel tables list, in real time, the Spoke VPC route table and TGW route table. - **Egress FQDN Discovery** When this mode is enabled, Aviatrix gateway monitors all egress-bound HTTP/HTTPS traffic, discovers the destination domain names and generates a report. This provides you the visibility of what APIs calls your virtual machine (EC2/Azure Virtual Machine/GCE) applications are making. You can then use this visibility and turn it into FQDN filter policies. 4. Monitoring ---------------- - **Tunnel Status** Encrypted tunnels status are monitored. When a tunnel status is changed, the event is logged and alerted to the administrator. - **Gateway Status** Gateway health is monitored. If a gateway is unreachable, the gateway is restarted for recovery. - **IAM Roles & Policies** Account IAM Roles and Policies are monitored to make sure they are attached to the accounts and the policies are correct. If an anomaly is detected, the event is logged and alerted. - **AWS Transit Gateway (TGW) Orchestrator Audit** The Aviatrix Controller periodically checks the consistency between what you intend to configure on Security Domains and Connection Policies and what is reflected on AWS TGW route tables. If a discrepancy is discovered, the event is logged and alerted. - **BGP Route Conflict Monitoring** All network routes are monitored and whenever the Controller detects conflicting routes, it logs the event and sends email alerts to the admin user and Aviatrix support team. - **Account Audit** The Controller periodically audits all access accounts it manages to make sure there is no accidental deletion of IAM roles and policies. When the Controller detects errors, it logs the event and sends an email alert to the admin user and the Aviatrix support team. - **Gateway Disk/Memory Monitor** When Aviatrix gateway disk/memory reaches 95%, the Controller logs the event and sends an email alert to the admin user and the Aviatrix support team. - **VPC Tracker** Instead of using an Excel sheet, use this tool to keep track of all your network CIDRs and prevent duplicate network address ranges. - **Alert Bell** Controller monitors the route table black hole, stops the instance, etc. and displays a warning on the alert bell. 5. Logging ------------- The Controller and gateways can export logged data to the following services: - **Splunk Enterprise** - **Sumo Logic** - **Elastic Search** - **Datadog** - **Remote syslog** - **AWS CloudWatch** - **Netflow** 6. Troubleshooting -------------------------- - **Flightpath** Single pane of glass that displays information on Security Groups, VPC/VNet route entries, Network ACL, and TGW/Azure Virtual WAN/Cloude Router/Dynamic Routing Gateway Route tables in a side-by-side presentation for both source and destination. In addition, expert diagnostics identify the faulty setup in these resources. - **Trace Route & Trace Path** Use this tool to help identify the route path. - **Packet Capture** Capture packets on any gateway and download the resulting PCAP file for analysis on Wireshark. - **Network Validation** This tool can be used to test end to end connectivity. Instead of going to the cloud provider console to launch instances, this tool automatically launches two instances and tests the connectivity for you. - **Resource Lists** Lists are in use cases that retrieve in real time the cloud provider route entries. - **Trace Log** The Customer can upload a trace log to Aviatrix for in depth analysis of the events that lead to the issues. 7. High Availability ---------------------- - **Controller Backup/Restore** All configurations are backed up to data storage solutions (S3 buckets/Azure Blob Storage/Google Cloud Storage/Object Storage Service) daily and can be restored to a new Controller in the event that the existing Controller becomes unavailable. - **Controller HA** You can deploy an auto scaling group of 1 that lets AWS CloudWatch monitor the Controller health. In the event that the existing Controller becomes unavailable, it triggers an AWS Lambda function to launch a new Controller and restore its configurations. - **Active/Active Gateways** Aviatrix Gateways can be deployed Active/Active in multi-AZ and forward traffic with ECMP. 8. Compliance ------------------------ - **FIPS 140-2 Certificate** Aviatrix has achieved FIPS 140-2 compliance with certificate `#3475 <https://csrc.nist.gov/Projects/cryptographic-module-validation-program/Certificate/3475>`_. - **Security Patch** Any impacting vulnerability issues are immediately addressed by applying "Hot Fix". - **SAML Authentication** Supports SAML authentication to login to the Controller. - **LDAP** Supports LDAP authentication to login to the Controller. 9. Software and Technical Support --------------------------------------------- - `Aviatrix Support Portal <https://support.aviatrix.com>`_ Technical problem? Have no fear. Aviatrix's most capable networking engineers are ready to help you troubleshoot issues large and small and most of them are not even related to Aviatrix solutions. Aviatrix offers 24/7 support for Platinum customers. - **Fast Release Cycle** New software releases become available every 6 - 8 weeks. A new software release automatically generates notification email to the Controller admin team. - **Hot Fix** Any showstoppers or operation impacting problems are immediately addressed by "Hot Fix" patches. - **Solution Architects** Aviatrix solution architects can help you design your cloud network deployment to be simple to manage, scalable, and secure. 10. Flexible Consumption Model ---------------------------------------------- - **Pay as You Consume** No contract negotiation, no lengthy PO process, and no shelfware. Aviatrix provides a cloud consumption model with multi-dimensional Metered AMI for instant consumption and need-based scaling. - **Private Offers** Aviatrix provides a Private Offers AMI that has the same benefit as the Metered AMI but with customized pricing. - **BYOL License** Aviatrix provides subscription-based long-term contracts for organizations that seek a predictable and budget-based consumption model. .. |aviatrix_dashboard| image:: aviatrix_operations_media/aviatrix_dashboard.png :scale: 30% .. add in the disqus tag .. disqus:: <file_sep> =============================================================== Example Configuration for Palo Alto Networks VM-Series in Azure =============================================================== The example on this page walks through how to deploy the Palo Alto Networks (PAN) VM-Series firewalls in the Transit VNet, and how to inspect traffic between the two Spoke VNETs using firewall policies. Aviatrix FireNet deploys and manages firewall instances in the cloud. It greatly simplifies virtual firewall deployment and allows the firewall to inspect East-West and/or North-South traffic. FireNet allows you to scale firewall deployment to multiple Availability Zones and multiple instances/VMs in a maximum throughput Active/Active state without SNAT. |pan-gcp-azure| See `here <https://docs.aviatrix.com/HowTos/pan_bootstrap_example_azure.html>`_ for using a bootstrap configuration to set up your Palo Alto Firewall in Azure. For Palo Alto example configurations in other CSPs, see: - `Palo Alto Networks VM-Series in AWS <https://docs.aviatrix.com/HowTos/config_paloaltoVM.html>`_ - `Palo Alto Networks VM-Series in GCP <https://docs.aviatrix.com/HowTos/config_paloaltoGCP.html>`_ - `Palo Alto Networks VM-Series in OCI <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_oci.html>`_ Prerequisites ------------- Before deploying the PAN VM-Series firewall as described below, you must follow the steps `here <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_azure.html>`_ (up to but not including deploying the firewall instance) to create the necessary Spoke and Transit gateways. As per this example you would need: - Two spoke gateways in Azure (created in us-west) named azure-us-west-spoke1 and azure-us-west-spoke2 - A transit gateway in Azure (created in us-west) named azure-us-west-transit - Enable Transit FireNet for azure-us-west-transit Deploying the PAN VM-Series Firewall ------------------------------------ After completing the above prerequisites, you use the steps below to deploy a PAN firewall from the Aviatrix Controller. The specific image name to deploy is “Palo Alto Networks VM-Series Next-Generation Firewall Bundle 1”. Aviatrix has already completed the subscription to this firewall image in the Azure Marketplace. 1. In the Aviatrix Controller, navigate to Firewall Network > Setup> Firewall > 2a) Launch & Associate Firewall Instance. As per the example above, use the following criteria: ========================================== ================== **Example setting** **Example value** ========================================== ================== VPC ID azure-us-west-transit Gateway Name azure-us-west-transit-agw Firewall Instance Name azure-us-west-pan Firewall Image Palo Alto Networks VM-Series Next-Generation Firewall Bundle 1 Firewall Image Version 9.1.0 Firewall Instance Size Standard_D3-v2 Management Interface Subnet azure-us-west-transit-Public-gateway-and-firewall-mgmt-1 Do not select a subnet that begins with az-1, az-2, or az-3. Egress Interface Subnet azure-us-west-transit-Public-FW-ingress-egress-1 Do not select a subnet that begins with az-1, az-2, or az-3. Username use name of your choice Password enter/choose complex password Authentication Method Password Attach Select this checkbox Advanced Do not select this checkbox ========================================== ================= 2. Click Launch. |PAN_FW_Azure_Controller| .. Note:: Firewall deployment can take up to ten minutes. After the firewall deploys successfully the following confirmation message displays in the Controller: |firewall_launch| 3. In the Aviatrix Controller, navigate to Firewall Network > List > Firewall. This list shows all created firewalls and their management UI IP addresses. #. Click the management UI link for the Palo Alto Networks firewall you just created in Azure. #. Log in using the username and password you configured in step 1. Configuring the Palo Alto Firewall ---------------------------------- When you access the firewall, you may see an “invalid certificate” warning. Navigate past this warning and log in to the firewall using the username and password you entered when you launched your firewall instance. All of the following steps are performed in the Palo Alto firewall UI. WAN Interface Setup ------------------- 1. After logging in, navigate to Network> Interfaces> Ethernet and click ethernet1/1, which is the WAN interface. 2. In the Comment field, enter ‘WAN’. 3. Change the Interface Type to ‘Layer3’. This displays a new set of tabs, including Config and IPv4. 4. On the Config tab, configure the following: - Virtual Router: default - Security Zone: New Zone 5. In the Zone dialog, enter WAN as the new zone name and click OK. |pan_wan_azure| 6. On the IPv4 tab, select DHCP Client and clear the **Automatically create default route pointing to default gateway provided by the server** check box. LAN Interface Setup ------------------- 1. From Network> Interfaces> Ethernet, click ethernet1/2, which is the LAN interface. #. In the Comment field, enter ‘LAN’. #. Change the Interface Type to ‘Layer3’. This displays a new set of tabs, including Advanced. #. On the Other Info sub-tab, under Advanced tab, enter Management as the Management Profile name. #. Select **HTTPS** as the Administrative Management Service. This is how the Azure Internal Load Balancer (ILB) probe communicates with the firewall. # Under the Config tab for the LAN interface, configure the following: - Virtual Router: default - Security Zone: New Zone 7. In the Zone dialog, enter ‘LAN’ as the new zone name and click OK. |pan_lan_azure| 8. On the IPv4 tab, select DHCP Client and clear the **Automatically create default route pointing to default gateway provided by the server** check box. #. Click OK. Setting up Policies ------------------- On the Policies tab, do the following for intrazone-default and interzone-default: 1. Click Override at the bottom of the window. #. In the resulting Security Policy Rule dialog, click the Actions tab and enable Log at Session End. #. Click OK. Virtual Router -------------- 1. On the Network > Virtual Routers tab, ensure that the default virtual router has the ethernet1/1 and ethernet1/2 interfaces selected on the Router Settings > General tab. #. Click OK. Committing Changes ------------------ It is important to commit your changes before creating the necessary static routes in the next section. 1. Click Commit in the top right corner of the webpage. In the resulting dialog, click Commit if your dialog looks like the following: |PAN_policy_commit| #. After committing, a dialog displays indicating that the configuration was successful. Keep the firewall HTTPS session open for further configuration. Pushing RFC 1918 Routes to Firewall ----------------------------------- 1. In the Aviatrix Controller, navigate to Controller > Firewall Network > Vendor Integration and configure the fields as follows: - Transit VPC ID: azure-us-west-transit - Firewall Instance ID: azure-us-west-pan - Firewall Name: azure-us-west-pan - Firewall Vendor Type: Palo Alto Networks VM-Series - Firewall Login Username: the username you created at the beginning of this document - Firewall Login Password: <PASSWORD> - Firewall Management IP Address: Auto populated |vendor_integration_example| 2. Click Save to save the credentials. 3. Click Show to see the RFC 1918 routes that the Controller automatically programmed on the firewall. Each route has an AVX prefix to indicate this. Configuring the FireNet Policy ------------------------------ 1. In the Aviatrix Controller, navigate to Firewall Network > Policy. 2. Select each Azure Spoke gateway and click Add. You can only add one gateway at a time. |azure_paloalto_policy| The traffic entering and exiting these Spoke gateways will now be inspected. Verifying the Installed Firewall Routes --------------------------------------- You now need to verify that the RFC 1918 routes exist on the firewall. 1. In the Palo Alto firewall UI, navigate to Network > Virtual Routers and click default. #. Click the Static Routes tab. You will see the same RFC 1918 routes with AVX prefixes that were created by the Aviatrix Controller. .. |pan_lan_azure| image:: config_paloaltoVM_media/pan_lan_azure.png :scale: 35% .. |pan_wan_azure| image:: config_paloaltoVM_media/pan_wan_azure.png :scale: 35% .. |pan-gcp-azure| image:: config_paloaltoVM_media/pan-gcp-azure.png :scale: 35% .. |pan_policy_commit| image:: config_paloaltoVM_media/PAN_policy_commit.png :scale: 50% .. |PAN_FW_Azure_Controller| image:: config_paloaltoVM_media/PAN_FW_Azure_Controller.png :scale: 35% .. |azure_paloalto_policy| image:: config_paloaltoVM_media/azure_paloalto_policy.png :scale: 45% .. |firewall_launch| image:: config_paloaltoVM_media/firewall_launch.png .. |avx-firewall-step7a_UI| image:: config_paloaltoVM_media/avx-firewall-step7a_UI.png :scale: 35% .. |pan_dynamic_updates| image:: config_paloaltoVM_media/pan_dynamic_updates.png :scale: 35% .. |vendor_integration_example| image:: config_paloaltoVM_media/vendor_integration_example.png :scale: 35% .. |new_zone| image:: config_paloaltoVM_media/new_zone.png :scale: 30% .. |ipv4| image:: config_paloaltoVM_media/ipv4.png :scale: 30% .. |nat_original_packet| image:: config_paloaltoVM_media/nat_original_packet.png :scale: 30% .. |nat_translated_packet| image:: config_paloaltoVM_media/nat_translated_packet.png :scale: 30% .. |PAN-health-check| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/PAN-health-check.png :scale: 35% .. |health-probe-logs| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/health-probe-logs.png :scale: 40% .. |pan-health-probe| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/pan-health-probe.png :scale: 40% .. |pan_hcheck_attach| image:: transit_firenet_workflow_media/transit_firenet_Azure_workflow_media/pan_hcheck_attach.png :scale: 40% .. |traffic_log_vnet_to_vnet| image:: config_paloaltoVM_media/traffic_log_vnet_to_vnet.png :scale: 40% .. disqus:: <file_sep> ============================================================ Setting up a Transit Network using Aviatrix Terraform Provider ============================================================ The Aviatrix Terraform Provider is used to interact with Aviatrix resources. To learn more about Terraform, please see the `Terraform Registry <https://registry.terraform.io/>`_. Setting up a Terraform Provider ========================= :: # Configure Aviatrix provider provider "aviatrix" { controller_ip = "1.2.3.4" username = "username" password = "<PASSWORD>" version = "2.2" } # Create a record resource "aviatrix_account" "myacc" { # ... } Resources ========= These are the available resources for creating a transit VPC solution. aviatrix_transit_gateway ------------------------ Manages an Aviatrix Transit Gateway. **Example Usage** :: provider "aviatrix" { controller_ip = "1.2.3.4" username = "username" password = "<PASSWORD>" version = "2.2" } # Create a transit gateway. # Omit ha_subnet to launch transit gateway without HA. # HA subnet can later be added or deleted to enable/disable HA in transit gateway resource "aviatrix_transit_gateway" "test_transit_gw" { cloud_type = 1 account_name = "devops" gw_name = "transit" vpc_id = "vpc-abcd1234" vpc_reg = "us-east-1" gw_size = "t2.micro" subnet = "10.1.0.0/24" ha_subnet = "10.1.0.0/24" tag_list = ["key:value", "key1:value1", "key2:value2"] } +--------------+-------------------------------------------------------------------+ | cloud_type | Enter 1 for AWS cloud type. | +--------------+-------------------------------------------------------------------+ | account_name | Enter Aviatrix's cloud account name. | +--------------+-------------------------------------------------------------------+ | gw_name | Enter Gateway name for transit VPC. | +--------------+-------------------------------------------------------------------+ | vpc_id | VPC ID of transit VPC. | +--------------+-------------------------------------------------------------------+ | gw_size | Gateway size. | +--------------+-------------------------------------------------------------------+ | subnet | VPC subnet where you want to deploy transit VPC GW. | +--------------+-------------------------------------------------------------------+ | ha_subnet | (Optional) VPC subnet for HA. | +--------------+-------------------------------------------------------------------+ | tag_list | (Optional) List of tags with key/value pairs in string format. | +--------------+-------------------------------------------------------------------+ aviatrix_vgw_conn ----------------- Manages VGW connection **Example Usage** :: provider "aviatrix" { controller_ip = "1.2.3.4" username = "username" password = "<PASSWORD>" version = "2.2" } # Once this resource is created, VGW can be disconnected # from transit GW by destroying this resource using command: # terraform destroy --target aviatrix_vgw_conn.test_vgw_conn. resource "aviatrix_vgw_conn" "test_vgw_conn" { conn_name = "my_conn" gw_name = "transit" vpc_id = "vpc-abcd1234" bgp_vgw_id = "vgw-abcd1234" bgp_vgw_account = "devops" bgp_vgw_region = "us-east-1" bgp_local_as_num = "65001" } +------------------+-----------------------------------------+ | conn_name | Name for transit VPC to VGW connection. | +------------------+-----------------------------------------+ | gw_name | Transit VPC GW name. | +------------------+-----------------------------------------+ | vpc_id | Enter VPC Id of transit VPC. | +------------------+-----------------------------------------+ | bgp_vgw_id | Enter AWS VGW Id used for connection. | +------------------+-----------------------------------------+ | bgp_vgw_account | AWS Account Number of the VGW used. | +------------------+-----------------------------------------+ | bgp_vgw_region | Region of the AWS's VGW used. | +------------------+-----------------------------------------+ | bgp_local_as_num | Enter BGP Local ASN. | +------------------+-----------------------------------------+ aviatrix_spoke_gateway ---------------------- Manages an Aviatrix Spoke Gateway **Example Usage** :: provider "aviatrix" { controller_ip = "1.2.3.4" username = "username" password = "<PASSWORD>" version = "2.2" } # Launch a spoke gateway, and join with transit gateway. # Omit ha_subnet to launch spoke gateway without HA. # ha_subnet can be later added or deleted to enable/disable HA in spoke gateway # Omit transit_gw to launch spoke gateway without attaching with transit GW. # transit_gw can be later added or deleted to attach/detach from spoke gateway resource "aviatrix_spoke_gateway" "test_spoke" { cloud_type = 1 account_name = "devops" gw_name = "myspoke" vpc_id = "vpc-defg3456" vpc_reg = "us-east-1" gw_size = "t2.micro" subnet = "10.20.0.0/24" ha_subnet = "10.20.1.0/24" transit_gw = "transit" tag_list = ["key:value", "key:value1", "key:value2"] } +--------------+-------------------------------------------------------------------+ | cloud_type | Enter 1 for AWS cloud type. | +--------------+-------------------------------------------------------------------+ | account_name | Enter aviatrix cloud account name. | +--------------+-------------------------------------------------------------------+ | gw_name | Enter Gateway name for spoke gateway. | +--------------+-------------------------------------------------------------------+ | vpc_id | VPC ID for Spoke gateway. | +--------------+-------------------------------------------------------------------+ | vpc_reg | Gateway region. | +--------------+-------------------------------------------------------------------+ | gw_size | Gateway size. | +--------------+-------------------------------------------------------------------+ | subnet | VPC subnet where you want to deploy transit GW. | +--------------+-------------------------------------------------------------------+ | enable_nat | (Optional) Enter "yes" to enable NAT. | +--------------+-------------------------------------------------------------------+ | ha_subnet | (Optional) VPC subnet for HA. | +--------------+-------------------------------------------------------------------+ | transit_gw | (Optional) Transit Gateway name to join spoke Gateway with. | +--------------+-------------------------------------------------------------------+ | tag_list | (Optional) List of tags with key/value pairs in string format. | +--------------+-------------------------------------------------------------------+ Sample configuration to create complete transit VPC solution ============================================================ .. Note:: In this example, you must specify the username and password, controller_ip, account_email and other parameters. :: # Sample Aviatrix terraform configuration to create complete transit VPC solution # This configuration creates a cloud account on Aviatrix controller, launches transit gateway, creates VGW connection # with transit gateway # Launches a spoke GW, and attach with transit gateway. # Edit to enter your controller's IP, username and password to login with. provider "aviatrix" { controller_ip = "w.x.y.z" username = "username" password = "<PASSWORD>" version = "2.2" } resource "aviatrix_account" "test_acc" { account_name = "devops" account_password = "<PASSWORD>" account_email = "<EMAIL>" cloud_type = 1 aws_account_number = "123456789012" aws_iam = "true" aws_role_app = "arn:aws:iam::123456789012:role/aviatrix-role-app" aws_role_ec2 = "arn:aws:iam::123456789012:role/aviatrix-role-ec2" } # Create transit gateway # Omit ha_subnet to launch transit gateway without HA. # ha_subnet can be later added or deleted to enable/disable HA in transit gateway resource "aviatrix_transit_gateway" "test_transit_gw" { cloud_type = 1 account_name = aviatrix_account.test_acc.account_name gw_name = "transit" vpc_id = "vpc-abcd1234" vpc_reg = "us-east-1" gw_size = "t2.micro" subnet = "10.20.0.0/24" ha_subnet = "10.20.1.0/24" } # Create VGW connection with transit gateway. # Once this resource is created, VGW can be disconnected # from transit GW by destroying this resource using command: # terraform destroy --target aviatrix_vgw_conn.test_vgw_conn. resource "aviatrix_vgw_conn" "test_vgw_conn" { conn_name = "my_conn" gw_name = aviatrix_transit_gateway.test_transit_gw.gw_name vpc_id = "vpc-abcd1234" bgp_vgw_id = "vgw-abcd1234" bgp_vgw_account = aviatrix_account.test_acc.account_name bgp_vgw_region = "us-east-1" bgp_local_as_num = "65001" depends_on = ["aviatrix_transit_gateway.test_transit_gw"] } # Launch a spoke gateway, and join with transit gateway. # Omit ha_subnet to launch spoke gateway without HA. # ha_subnet can be later added or deleted to enable/disable HA in spoke gateway # Omit transit_gw to launch spoke gateway without attaching with transit gateway. # transit_gw can be later added or deleted to attach/detach from spoke gateway resource "aviatrix_spoke_gateway" "test_spoke" { cloud_type = 1 account_name = aviatrix_account.test_acc.account_name gw_name = "myspoke" vpc_id = "vpc-defg1234" vpc_reg = "us-east-1" gw_size = "t2.micro" subnet = "10.21.0.0/24" ha_subnet = "10.21.1.0/24" transit_gw = aviatrix_transit_gateway.test_transit_gw.gw_name depends_on = ["aviatrix_vgw_conn.test_vgw_conn"] } .. disqus:: <file_sep> ========================================================= Example Config for FortiGate VM in Azure ========================================================= In this document, we provide an example to set up the Fortigate Next Generation Firewall instance for you to validate that packets are indeed sent to the Fortigate Next Generation Firewall for VNet-to-VNet and from VNet to internet traffic inspection. The Aviatrix Firewall Network (FireNet) workflow launches a Fortigate Next Generation Firewall instance at `this step <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#launching-and-associating-firewall-instance>`_. After the launch is complete, the console displays the Fortigate Next Generation Firewall instance with its public IP address of management/egress interface and allows you to access the FortiGate web page. Here is the Firewall information in this example used during launch (Aviatrix Controller, Firewall Network > Setup > Step 2a) for your reference. Please adjust it depending on your requirements. ========================================== ========== **Example setting** **Example value** ========================================== ========== Firewall Image Fortinet FortiGate Next-Generation Firewall Firewall Image Version 6.4.1 Firewall Instance Size Standard_D3_v2 Egress Interface Subnet Select the subnet whose name contains "FW-ingress-egress." Username Any username except admin, sys and root Authentication Method Select Password. Input a good password of your choice Attach Mark this checkbox ========================================== ========== .. note:: Fortigate Next Generation Firewall instance has 2 interfaces as described below. Additionally, firewall instance eth1 is on the same subnet as FireNet gateway eth2 interface. ======================================================== =============================== ================================ **Fortigate VM instance interfaces** **Description** **Inbound Security Group Rule** ======================================================== =============================== ================================ eth0 (on subnet -Public-FW-ingress-egress) Egress or Untrusted interface Allow ALL eth1 (on subnet -dmz-firewall-lan) LAN or Trusted interface Allow ALL (Do not change) ======================================================== =============================== ================================ Below are the steps for initial setup. Logging in to Fortigate Next Generation Firewall ----------------------------------------------------------- After `this step <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#launching-and-associating-firewall-instance>`_ of the FireNet workflow is completed, Go back to the Aviatrix Controller Console. Go to Firewall Network workflow `Step 2a <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#launching-and-associating-firewall-instance>`_, click on the `Management UI`. It takes you to the Fortigate Next Generation Firewall you just launched as shown below. |az_avx_management_UI| .. note:: Please try to use different browser (e.g. Firefox/Chrome) if the Management UI link is not able to open on your default browser. Fortigate Next Generation Firewall Initial Setup ---------------------------------------------------------------- Once logged in with username and password provided during launch, it will ask you to do an initial setup as shown below: |fg_first_login_1| |fg_first_login_2| |fg_first_login_3| Go to Network > Interfaces and review the interface configuration before move forward. This interface configuration is done by Aviatrix Controller during the launch. |review_fg_interfaces| Create Static Routes for Routing of Traffic VNet to VNet ---------------------------------------------------------------------- For simplicity, in this example we configure the firewall to send all RFC 1918 packets to LAN port. Go to Network > State Routes to create a Static Route as the following screenshot. 1. Click **Create New**. 2. Enter the destination route in the **Destination** box. 3. In the **Gateway Address** box, you will need to enter the Azure default gateway IP on subnet -dmz-firewall-lan i.e. subnet CIDR for -dmz-firewall-lan is 10.20.0.80/28, thus the Azure default gateway IP on this subnet is 10.20.0.81. .. note:: dmz-firewall-lan subnet can be found in Aviatrix Controller. Go to Aviatrix Controller > Gateway > Select Gateway and click **Edit** > click **More details** to check all subnets. 4. Interface will be the LAN (port2) 5. Configure an appropriate admin distance if you expect overlapping routes that need to be prioritized 6. Enter comments as necessary. 7. Repeat the above steps for RFC 1918 routes. |az_fortigate_static_routes| .. important:: Load Balancer static route 172.16.31.10/32 needs to be added manually pointing to the lan interface (port 2). 172.16.31.10/32 is the health probe source address. 8. Those static routes could also be reviewed on the page Dashboard > Network > Routing. RFC 1918 routes are highlighted in red where as load balancer static route is highlighted in green. |az_fortigate_static_routes_review| (Optional) Firewall Vendor Integration ------------------------------------------------- Integrating a FortiGate firewall with the Aviatrix controller enables the controller to make automatic route updates to the FortiGate routing tables. You may also manually enable the integration with your CSP management tools. FortiGate integration is supported in AWS, Azure, and GCP clouds. Integrate the FortiGate firewall with the Aviatrix controller. 1. Generate a Firewall API Token from FortiGate. This token is required to integrate the FortiGate firewall with the Controller. 2. In the FortiGate GUI, go to System > Admin Profiles > Create New. 3. Enter the information to create the token. You must enable the Read/Write option for the network to router connection. 4. Generate the token. 5. Go to Aviatrix Controller > Firewall Network > Vendor Integration. 6. Enter the vendor firewall information in the controller. 7. Click Save, then Show, then Sync to enable the Aviatrix Controller and FortiGate firewall integration. The Aviatrix Controller is now enabled to make automatic route updates to the FortiGate routing tables. Enabling Health Check Policy in Firewall -------------------------------------------------------- Aviatrix Controller uses HTTPS (TCP 443 port) to check the health of the firewall every 5 seconds. User needs to enable this port in firewall as per given instruction. Please follow the steps to allow HTTPS in FortiGate: 1. Login to FortiGate using your username and password. #. Go to Network > Interfaces, select **port 2**, and click **Edit**. #. Mark the HTTPS checkbox under Administrative access > IPv4 and click **OK**. **Example Fortigate Port 2 Interface** |health-check| The health check probes can be verified in FortiGate by navigating to Log & Report > Local Traffic. **Example Health-Check Logs in Fortigate** |health-probe-logs| Configuring Basic Traffic Policy to Allow Traffic VNet to VNet ------------------------------------------------------------------------- In this step, we will configure a basic traffic security policy that allows traffic to pass through the firewall. Given that Aviatrix gateways will only forward traffic from the TGW to the LAN port of the Firewall, we can simply set our policy condition to match any packet that is going in/out of LAN interface. Go to Policy & Objects > Firewall Policy > Create New / Edit to configure policy as the following screenshot. ================== =============================================== **Field** **Value** ================== =============================================== Name Configure any name for this policy Incoming Interface LAN (port2) Outgoing Interface LAN (port2) Source Click on the + sign and add all Destination Click on the + sign and add all Schedule always Service ALL Action ACCEPT NAT Disabled ================== =============================================== |az_fortigate_policy_vpc_to_vpc| After validating that your traffic is being routed through your firewall instances, you can customize the security policy to tailor to your requirements. [Optional] Configuring Basic Traffic Policy to Allow Traffic VNet to Internet ------------------------------------------------------------------------------------------- In this step, we will configure a basic traffic security policy that allows internet traffic to pass through the firewall. Given that Aviatrix Gateways will only forward traffic to the LAN port of the Firewall, we simply set our policy condition to match any packet that is going in of LAN interface and going out of WAN interface. .. important:: Enable `Egress inspection <https://docs.aviatrix.com/HowTos/firewall_network_faq.html#how-do-i-enable-egress-inspection-on-firenet>`_ feature on FireNet First of all, go back to the Aviatrix Controller Console. 1. Navigate to the page Firewall Network > Advanced. 2. Click the skewer/three dot button. 3. Scroll down to Egress through Firewall and click **Enable**. 4. Verify the Egress status on the page Firewall Network > Advanced. |az_avx_egress_inspection| Secondly, go back to the Fortigate Next Generation Firewall console and navigate to Policy & Objects > IPv4 Policy > Create New / Edit to configure policy as the following screenshot. ================== =============================================== **Field** **Value** ================== =============================================== Name Configure any name for this policy Incoming Interface LAN (port2) Outgoing Interface WAN (port1) Source Click on the + sign and add all Destination Click on the + sign and add all Schedule always Service ALL Action ACCEPT NAT Enable ================== =============================================== .. important:: NAT function needs to be enabled on this VNET to Internet policy. |az_fortigate_policy_vpc_to_internet| After validating that your traffic is being routed through your firewall instances, you can customize the security policy to tailor to your requirements. Ready to Go ----------------------- Now your Security Gateway instance is configured and ready to receive packets. Next step is to validate your configurations and polices using FlightPath and Diagnostic Tools (ping, traceroute etc.). Viewing Traffic Log ----------------------------- You can view if traffic is forwarded to the firewall instance by logging in to the Fortigate Next Generation Firewall console. Go to Dashboard > FortiView Sessions or FortiView Destinations. Traffic can also be viewed from Logs & Report. .. note:: To view Forward Traffic logs under Logs & Report, go to Policy & Objects > Firewall Policy > Select a Policy and click Edit > Logging Options > Select All Sessions for Log Allowed Traffic. For VNet to VNet traffic: ***************************** Launch one instance in PROD Spoke VNet and DEV Spoke VNet. Start ping packets from a instance in DEV Spoke VNet to the private IP of another instance in PROD Spoke VNet. The ICMP traffic should go through the firewall and be inspected in the firewall. |az_fortigate_view_traffic_log_vpc_to_vpc| |az_fortigate_view_traffic_log_vpc_to_vpc_2| [Optional] For VNet to Internet traffic: *********************************************** Launch a private instance in the Spoke VNet (i.e. PROD Spoke VNet) and start ping packets from the private instance towards Internet (e.g 8.8.8.8) to verify the egress function. The ICMP traffic should go through and get inspected on firewall. .. important:: The Egress Inspection is only applicable to all VNets that deploys non-public-facing applications. If you have any Spoke VNet that has public facing web services, you should not enable Egress Inspection. This is because Egress Inspection inserts a default route (0.0.0.0/0) towards Transit GW to send the Internet traffic towards firewall to get inspected. Azure's System Default Route pointing towards Internet will be overwritten by User-defined default route inserted by the Controller. |az_fortigate_view_traffic_log_vpc_to_internet| |az_fortigate_view_traffic_log_vpc_to_internet_2| .. |review_fg_interfaces| image:: config_FortiGate_media/review_fg_interfaces.png :scale: 35% .. |az_avx_management_UI| image:: config_FortiGate_media/az_avx_management_UI.png :scale: 30% .. |fg_first_login_1| image:: config_FortiGate_media/fg_first_login_1.png :scale: 40% .. |fg_first_login_2| image:: config_FortiGate_media/fg_first_login_2.png :scale: 40% .. |fg_first_login_3| image:: config_FortiGate_media/fg_first_login_3.png :scale: 30% .. |az_fortigate_static_routes| image:: config_FortiGate_media/az_fortigate_static_routes.png :scale: 35% .. |az_fortigate_static_routes_review| image:: config_FortiGate_media/az_fortigate_static_routes_review.png :scale: 35% .. |az_fortigate_policy_vpc_to_vpc| image:: config_FortiGate_media/az_fortigate_policy_vpc_to_vpc.png :scale: 30% .. |az_fortigate_policy_vpc_to_internet| image:: config_FortiGate_media/az_fortigate_policy_vpc_to_internet.png :scale: 30% .. |az_avx_egress_inspection| image:: config_FortiGate_media/az_avx_egress_inspection.png :scale: 40% .. |az_fortigate_view_traffic_log_vpc_to_vpc| image:: config_FortiGate_media/az_fortigate_view_traffic_log_vpc_to_vpc.png :scale: 30% .. |az_fortigate_view_traffic_log_vpc_to_vpc_2| image:: config_FortiGate_media/az_fortigate_view_traffic_log_vpc_to_vpc_2.png :scale: 30% .. |az_fortigate_view_traffic_log_vpc_to_internet| image:: config_FortiGate_media/az_fortigate_view_traffic_log_vpc_to_internet.png :scale: 40% .. |az_fortigate_view_traffic_log_vpc_to_internet_2| image:: config_FortiGate_media/az_fortigate_view_traffic_log_vpc_to_internet_2.png :scale: 30% .. |health-check| image:: config_FortiGate_media/health-check.png :scale: 30% .. |health-probe-logs| image:: config_FortiGate_media/health-probe-logs.png :scale: 30% .. disqus:: <file_sep> ======================================================================================================= Using Subnet Inspection in Azure to Redirect Subnet-Level Traffic to Aviatrix Transit FireNet and NGFW ======================================================================================================= Aviatrix’s subnet inspection feature allows you to redirect subnet-level traffic to the Aviatrix Transit FireNet Gateway for inspection by a next-generation firewall (NGFW) appliance such as Checkpoint, Palo Alto Firewall, or Fortinet. Previously, traffic inspection policy could only be applied at the VNet level, which meant that traffic from all subnets in a VNet would be inspected by the NGFW. With this feature, you can assign subnets to a subnet group and specify an inspection policy for the subnet group. Traffic between subnets in different subnet groups with an inspection policy is redirected to the NGFW for inspection. .. note:: Currently, the subnet inspection feature is only available in Azure. Supported Features ================== The following features are supported when subnet groups are enabled. #. Intra-VNet and Inter-VNet traffic inspection #. ActiveMesh 2.0 #. High Performance Encryption (HPE) #. Transit FireNet High Availability (HA) mode #. Supported NGFWs: Palo Alto Networks, Checkpoint, Fortinet #. Terraform Unsupported Features ==================== The following features are not supported when subnet groups are enabled. #. Egress FireNet Inspection (Dual Transit FireNet) #. Azure Secondary CIDR not supported Disabled Features ================= The following features are not supported and are disabled when subnet groups are enabled. #. Customized SNAT on Spoke gateway #. Customized Spoke advertised CIDRs #. Customized Spoke VPC Route Table #. Filter Learned Routes to Spoke VPC #. Auto-advertised Spoke Site2Cloud CIDRs #. BGP on Spoke What is a Subnet Group? ======================= A subnet group defines a logical grouping of subnets in a VNet. A subnet group is local to a VNet and does not span across multiple VNets. Traffic between subnets in the same subnet group flows through the Azure native virtual network and is not inspected by the Aviatrix Transit FireNet NGFW. If you want to inspect traffic between subnets in the same VNet, the subnets must be in different subnet groups. Traffic Traversal in Subnet Groups ================================== When you create subnet groups in a VNet, traffic from the subnet groups is redirected to the Aviatrix Transit FireNet Gateway for inspection. To further redirect traffic to the NGFW for inspection, you must set inspection policy for the subnet groups. Traffic for subnets that are part of a subnet group but do not have an inspection policy traverse the Aviatrix Transit FireNet gateway but are not redirected to or inspected by the NGFW. Intra-Vnet Subnet Inspection for Subnets in the same Subnet Group ----------------------------------------------------------------- Traffic between VMs in the same subnet or subnet group is not inspected. If you want to inspect traffic between VMs in different subnets in the same VNet, the subnets must be in different subnet groups. For more information, refer to `Connectivity Scenarios Between VMs in Subnets <http://docs.aviatrix.com/HowTos/transit_subnet_inspection_azure.html#configuring-scenarios-between-vms-in-subnets>`_. |intraVNET_vm_segmentation| .. note:: The diagrams in the scenarios below show single gateways for brevity. High Availability (HA) configuration is supported for Spoke and Transit FireNet gateways. Intra-VNet Subnet Inspection ---------------------------- |intraVNET| Inter-VNet Subnet Inspection Over a Shared Transit FireNet ---------------------------------------------------------- |interVNET_shared_FireNet| Single Region Inter-VNet Subnet Inspection Over Transit Peering --------------------------------------------------------------- In this scenario, the blue and green subnet groups have an inspection policy, the orange subnet group does not. The traffic between the blue and green subnet groups traverses the NGFW on either side. Since the orange subnet group does not have an inspection policy, the traffic between the orange and green subnet groups is not inspected by the firewall connected to the Transit FireNet to which the orange subnet group’s Spoke is attached. However, since the green subnet group has an inspection policy, the traffic between the orange and green subnet group traverses the firewall connected to the peer Transit FireNet. |interVNET_transit_peering| Multi-Region Inter-VNet Subnet Inspection Over Transit Peering -------------------------------------------------------------- The traffic traversal is similar to the Inter-VNet Subnet Inspection Over Transit Peering scenario. |multiregionVNET| Connectivity Scenarios Between VMs in Subnets --------------------------------------------- The following tables list different scenarios for connectivity between VMs in subnets that you need to consider when using subnet groups. Intra-VNet Subnet Inspection ---------------------------- +-----------------------+-------------------------+----------------+------------------------------------------------+ | VM in Subnet A | VM in Subnet B | Connectivity | Comment | | | | Between VMs | | +=======================+=========================+================+================================================+ |Not in a subnet group | Not in a subnet group | Yes | | +-----------------------+-------------------------+----------------+------------------------------------------------+ |Not in a subnet group | In a subnet group | No | Subnet A must to be in a subnet group for | | | | | connectivity. Configure a default subnet group.| | | | | See `Important Recommendations <http://doc | | | | | s.aviatrix.com/HowTos/transit_subnet_inspe | | | | | ction_azure.html#important-recommendations>`_. | +-----------------------+-------------------------+----------------+------------------------------------------------+ |In a subnet group | In a subnet group | Yes | Subnets can either be in the same or | | | | | different subnet groups. | +-----------------------+-------------------------+----------------+------------------------------------------------+ Inter-VNet Subnet Inspection ---------------------------- +-----------------------+-------------------------+----------------+------------------------------------------------+ | Subnet A in VNet A | Subnet B in VNet B | Connectivity | Comment | | | | Between VMs | | +=======================+=========================+================+================================================+ |Not in a subnet group | Not in a subnet group | Yes | Only if VNet B has no subnet groups | | | | | configured. | | | | | See `Important Recommendations <http://doc | | | | | s.aviatrix.com/HowTos/transit_subnet_inspe | | | | | ction_azure.html#important-recommendations>`_. | +-----------------------+-------------------------+----------------+------------------------------------------------+ |In a subnet group | Not in a subnet group | No | Only if VNet B has no subnet groups | | | | | configured. Configure a default subnet group. | | | | | See `Important Recommendations <http://doc | | | | | s.aviatrix.com/HowTos/transit_subnet_inspe | | | | | ction_azure.html#important-recommendations>`_. | +-----------------------+-------------------------+----------------+------------------------------------------------+ |In a subnet group | In a subnet group | Yes | Subnets can either be in the same or | | | | | different subnet groups. | +-----------------------+-------------------------+----------------+------------------------------------------------+ Inter-VNet Subnet Inspection Over Transit Peering ------------------------------------------------- The connection behavior is the same as the Inter-VNet Subnet Inspection. +-----------------------+-------------------------+----------------+------------------------------------------------+ | Subnet A in VNet A | Subnet B in VNet B | Connectivity | Comment | | | | Between VMs | | +=======================+=========================+================+================================================+ |Not in a subnet group | Not in a subnet group | Yes | Only if VNet B has no subnet groups | | | | | configured. | | | | | See `Important Recommendations <http://doc | | | | | s.aviatrix.com/HowTos/transit_subnet_inspe | | | | | ction_azure.html#important-recommendations>`_. | +-----------------------+-------------------------+----------------+------------------------------------------------+ |In a subnet group | Not in a subnet group | No | Only if VNet B has no subnet groups | | | | | configured. Configure a default subnet group. | | | | | See `Important Recommendations <http://doc | | | | | s.aviatrix.com/HowTos/transit_subnet_inspe | | | | | ction_azure.html#important-recommendations>`_. | +-----------------------+-------------------------+----------------+------------------------------------------------+ |In a subnet group | In a subnet group | Yes | Subnets can either be in the same or | | | | | different subnet groups. | +-----------------------+-------------------------+----------------+------------------------------------------------+ Important Recommendations ------------------------- #. **There is a downtime of 10 – 20 seconds when you add or remove subnets from a subnet group. If this downtime is not acceptable, be sure to add or remove subnet groups during a maintenance window.** #. For connectivity between VMs in different subnets, the subnets must be in different subnet groups. For subnets that do not need an inspection policy, create a subnet group named default, and add the subnets to the default subnet group. All other subnets that require traffic inspection and have an inspection policy set, add the subnets to custom subnet groups. #. Only learned and Aviatrix-created routes are carried over from the subnet routing tables to the subnet group routing tables created by Aviatrix. Once a subnet is added to a group, you can manually recreate custom routes in the subnet group route table through the Azure console. Subnet Group Management Workflow ================================= To redirect subnet-level traffic to the Aviatrix Transit FireNet for inspection by an NGFW, perform the following steps. #. `Configure Subnet Groups <http://docs.aviatrix.com/HowTos/transit_subnet_inspection_azure.html#configuring-subnet-group>`_. #. `Configure Subnet Group Inspection Policy <http://docs.aviatrix.com/HowTos/transit_subnet_inspection_azure.html#configuring-subnet-group-inspection-policy>`_. Configuring Subnet Group ------------------------- To configure subnet groups, follow these steps. 1. In the Aviatrix Controller, go to: MULTI-CLOUD TRANSIT > List > Spoke > (select a Spoke) > ACTIONS > Configure Subnet Group. |configure_subnet_group| A new page opens where you can create, modify, or delete Subnet Groups. 2. Select **Create Subnet Group**. |create_subnet_group| 3. Enter a name for the subnet group. 4. Click **CREATE**. 5. Continue to **Modify Subnet Group**. |modify_subnet_group| 6. Select the subnet group you created from the Subnet Group Name pull-down menu. 7. Use the Subnet List table to add or delete the subnet group from the **Excluded Subnets** to the **Included Subnets** lists. Aviatrix Controller automatically retrieves the subnets from the Azure VNet and includes it in the list of excluded subnets. The excluded subnets include both Aviatrix-managed and user-created subnets that you created directly through the Azure console which are out-of-band from Aviatrix. To add an excluded subnet to the included subnet group, select one or more subnets from the **Excluded Subnets** list and click **ADD**. 8. Click **UPDATE**. 9. To delete a subnet from either list and move it to the other list, select one or more subnets and click **DEL**. 10. To delete a subnet group, select the subnet group from the Subnet Group Name pull-down menu and click **DELETE**. |delete_subnet_group| Configuring Subnet Group Inspection Policy ------------------------------------------ When you enable the subnet groups for a VNet, the subnet groups are available in the FireNet Policy page. Select a subnet group from the **Not Inspected list** and click **ADD** to move it to the **Inspected list**. |configure_inspection_policy| In the figure above, the Transit FireNet Gateway will redirect traffic from SPOKE_SUBNET_GROUP:spoke-east-us-a~~sg-blue to the NGFW. In the NGFW, you configure the firewall policies to either drop, log, or allow the traffic flow from the subnets in the group. .. |interVNET_transit_peering| image:: transit_firenet_workflow_media/transit_subnet_inspection_azure_media/interVNET_transit_peering.png :width: 500 .. |intraVNET_vm_segmentation| image:: transit_firenet_workflow_media/transit_subnet_inspection_azure_media/intraVNET_vm_segmentation.png :width: 500 .. |interVNET_shared_FireNet| image:: transit_firenet_workflow_media/transit_subnet_inspection_azure_media/interVNET_shared_FireNet.png :width: 500 .. |intraVNET| image:: transit_firenet_workflow_media/transit_subnet_inspection_azure_media/intraVNET.png :width: 500 .. |multiregionVNET| image:: transit_firenet_workflow_media/transit_subnet_inspection_azure_media/multiregionVNET.png :width: 500 .. |create_subnet_group| image:: transit_firenet_workflow_media/transit_subnet_inspection_azure_media/create_subnet_group.png :width: 500 .. |modify_subnet_group| image:: transit_firenet_workflow_media/transit_subnet_inspection_azure_media/modify_subnet_group.png :width: 500 .. |delete_subnet_group| image:: transit_firenet_workflow_media/transit_subnet_inspection_azure_media/delete_subnet_group.png :width: 500 .. |configure_subnet_group| image:: transit_firenet_workflow_media/transit_subnet_inspection_azure_media/configure_subnet_group.png :width: 500 .. |configure_inspection_policy| image:: transit_firenet_workflow_media/transit_subnet_inspection_azure_media/configure_inspection_policy.png :width: 500 .. disqus:: <file_sep> ==================================== NAT GW Load-balance with AZ affinity ==================================== Pre-4.2 Behavior ---------------- In VPC with multiple private route tables (ex: rtb1, rtb2, rtb3), and multiple NAT gateways (ex: gw1, gw2), the default route in the route tables points to the NAT gateway round-robbinly. * *rtb1 --> gw1* * *rtb2 --> gw2* * *rtb3 --> gw1* 4.2 Behavior ------------ In 4.2, AZ is considered when assign route tables to gateways. Route table is assigned to same AZ gateway first, if no same AZ gateway, it will assign to other AZ gateway. Before program the default route, all route tables are grouped according to AZ. .. note:: 1. AWS route table has no AZ attribute, we use the first associated subnet to decide the route table AZ. It is user's responsibility to make sure route table associated subnets belong to the same AZ. 2. If route table doesn't have any associated subnets, it is considered to be first AZ (i.e, us-east-1a for example). Case study ----------- We use the an example to show how it works. Suppose we have the following setting: * AZ1: *rtb1, rtb2, rtb3, gw1, gw2* * AZ2: *rtb4, no gateway* * AZ3: *no rtb, gw3* Round 1: Within Single AZ * AZ1: 3 rtbs are programed with 2 gateway round-robbinly. * *rtb1 --> gw1* * *rtb2 --> gw2* * *rtb3 --> gw1* * AZ2: no gateway, rtb4 is added to a pending list * AZ3: no rtb, nothing to do After 1st round, gw1 has 2 rtbs, gw2 has 1 rtbs, gw3 has 0 rtbs. There is 1 rtb in pending list. If the pending list is empty, meaning all route tables are programed to its same AZ gateway. Round 2 is skipped. Round 2: Cross AZ In this example, pending list has rtb4. We sort the gateways according to number of route tables it's already assigned to, get a list of all available gateways: *[gw3 (0), gw2 (1), gw1 (2)]* In this round, we work on route table in the pending list with the sorted list of gateways round-robbinly. * *rtb4 --> gw3* Finally, all route table has default route configured to one of the NAT gateways. * *rtb1 --> gw1, same AZ* * *rtb2 --> gw2, same AZ* * *rtb3 --> gw1, same AZ* * *rtb4 --> gw3, cross AZ* .. disqus:: <file_sep> ===================== Resolve the AWS billing issue ===================== If you have received an email from "no-reply" (<EMAIL>) with the subject "AWS Billing issue", then you need to take immediate action to resolve the same. The following are some of the errors and the resolution steps 1. Unable to send Metering record: An error occurred (AccessDeniedException) when calling the MeterUsage operation: User: arn:aws:sts::094123412341:assumed-role/aws-elasticbeanstalk-ec2-role/i-07abb25asdfasdf8 is not authorized to perform: aws-marketplace:MeterUsage ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- If you see an error like this, it is because your IAM policies attached to your controller are incorrect. Editing the IAM role to the Aviatrix controller (EC2 instance) which has a metered policy using with the following permissions: https://s3-us-west-2.amazonaws.com/aviatrix-download/iam_assume_role_policy.txt You may also need to click on Troubleshoot->Diagnostics->Services->Restart cloudxd from the controller 2. (UnrecognizedClientException) when calling the MeterUsage operation: The security token included in the request is invalid --------------------------------------------------------------------------------------------------------------------------------------------------------------- This is because you deleted or detached an IAM role or detached and attached a new IAM policy with the same name. Attach an IAM role to the controller with the following policy https://s3-us-west-2.amazonaws.com/aviatrix-download/iam_assume_role_policy.txt You may also need to click on Troubleshoot->Diagnostics->Services->Restart cloudxd from the controller 3. Unable to locate credentials --------------------------------------- This is because you deleted or detached the controller's an IAM role . Attach an IAM role to the controller with the following policy https://s3-us-west-2.amazonaws.com/aviatrix-download/iam_assume_role_policy.txt You may also need to click on Troubleshoot->Diagnostics->Services->Restart cloudxd from the controller 4.Credentials were refreshed, but the refreshed credentials are still expired ----------------------------------------------------------------------------------------------- This is a boto issue https://github.com/boto/boto3/issues/1751 Ensure the IAM role is correct https://s3-us-west-2.amazonaws.com/aviatrix-download/iam_assume_role_policy.txt You will need to detach the aviatrix-role-ec2 IAM role and re-attach it back to the Aviatrix controller instance to fix the issue 5. access_key ---------------- This could be because you deleted or detached or edited the controller's IAM role . Attach an IAM role to the controller with the following policy https://s3-us-west-2.amazonaws.com/aviatrix-download/iam_assume_role_policy.txt You may also need to click on Troubleshoot->Diagnostics->Services->Restart cloudxd from the controller 6. Timeout or Unreachable host errors ------------------------------------------------ Check the firewall and ACL rules of yor controller's VPC. You will need to ensure that the controller has valid internet access. This could also be a temporary network failure issue and might resolve by itself <file_sep> ========================================================= PrivateS3 Workflow ========================================================= Below is the workflow for PrivateS3. To learn more about PrivateS3, see `PrivateS3 FAQ <https://docs.aviatrix.com/HowTos/sfc_faq.html>`_. Launching an Aviatrix Gateway ------------------------------------- Go to Gateway > New Gateway to launch an Aviatrix Gateway. Specify the Gateway Name, Access Account Name, Region, VPC ID, Public Subnet, and Gateway Size. Leave all other fields as default. Select the region where you want the S3 buckets to be explicitly allowed or denied access through PrivateS3. Creating Access Accounts -------------------------------- PrivateS3 automatically scans the S3 buckets owned by the `Access Accounts <https://docs.aviatrix.com/HowTos/aviatrix_account.html>`_. Create one Access Account if you have not done so. Enabling/Updating PrivateS3 ---------------------------------------- .. tip:: If you don't see the gateway just launched, refresh the browser. Each AWS S3 bucket has a unique FQDN name. For example, if a full URL to access a file in S3 is https://avx-backup.s3-us-west-2.amazonaws.com/init.txt, then the bucket's FQDN name is either avx-backup.s3-us-west-2.amazonaws.com or avx-backup.s3.us-west-2.amazonaws.com. =================================== ================== **Setting** **Value** =================================== ================== Gateway Name Select a gateway launched in the previous step for PrivateS3 service. Source CIDR Range This field represents a scope of on-prem network address range, it is used to check if PrivateS3 filtering function should be applied for a given packet source IP address. This address range does not need to be precise. Enter a summary list of the on-prem network address range separated by comma. For example, 10.0.0.0/8. Access Accounts You can select multiple accounts and move them to the right panel. The Controller scans S3 of the selected accounts every 30 minutes to discover any new S3 buckets. =================================== ================== Click **Enable**. If PrivateS3 has been enabled, use this step to update changes in Source CIDR Range or Access Accounts. Once PrivateS3 is enabled, Controller creates an AWS NLB and attach the PrivateS3 gateway to it. The NLB serves as load balancer to forward S3 HTTPS request to the gateways. Once PrivateS3 is enabled, you can repeat the previous steps to create more Aviatrix Gateways in the same VPC and attach them to the NLB. Once PrivateS3 is enabled on the selected accounts, the Controller scans every 30 minutes S3 buckets of the selected accounts in the region where Aviatrix PrivateS3 gateway is deployed. When new S3 buckets are discovered, an email will be sent to the Controller admin. The admin should login to the Controller, go to Security > PrivateS3 > Step 4 to take actions on the new buckets. The actions are either Allow or Deny. Updating S3 Bucket Policy --------------------------------------- Filter on S3 buckets with policy New. Change it to either Allow or Deny. You can change all buckets to Allow All or Deny All. Viewing/Deleting PrivateS3 -------------------------------------- When PrivateS3 is enabled, Aviatrix Controller creates an AWS Network Load Balancer (NLB) and attaches Aviatrix gateway to it. More Aviatrix Gateways can be launched and attached to this NLB. The NLB front ends the pool of Aviatrix gateways and distributes S3-related HTTPS requests to the attached gateways. The View displays relevant data for troubleshooting and visibility. =================================== ================== **Setting** **Value** =================================== ================== PrivateS3 NLB Name AWS NLB created by Aviatrix Controller when PrivateS3 is enabled. NLB Status The status of the NLB created Aviatrix Controller. PrivateS3 true/false to indicate if PrivateS3 is enabled or not. Region AWS region where PrivateS3 gateways are launched. PrivateS3 DNS Name Resolution IP This filed displays the AWS internal NLB private IP address created by the Controller AFTER you complete this step of attaching the bucket URL to the FIRST gateway. It will take some time while the NLB is created. If you are repeating this step for additional gateways, the NLB IP should be autopopulated when you choose the first gateway that the URL was attached to. Use the displayed IP address for your on-prem DNS configuration in the next step. PrivateS3 DNS Name This field displays the DNS name of the NLB created by Aviatrix Controller for PrivateS3 function. =================================== ================== Additional Configuration 1: Create an On-Prem DNS Private Zone ------------------------------------------------------------------------------ Create a private zone on your on-prem DNS server so that all S3 bucket names resolve to the PrivateS3 private IP address displayed from Step 2 in the "S3 Bucket FQDN Name Resolution IP" field. Note this IP address must be reachable from on-prem either by Direct Connect or VPN over Internet. Note depending on how application invokes S3 function, for example, by using "wget", "curl", "aws s3", or "aws2 s3", the generated FQDN name for the S3 object access may be different. There are 3 formats. 1. bucket-name.s3.region.amazonaws.com. Example, business-owner-bucket.s3.us-west-2.amazonaws.com #. bucket-name.s3-region.amazonaws.com. Example, business-owner-bucket.s3-us-west-2.amazonaws.com #. bucket-name.s3.amazonaws.com. Example, business-owner-bucket.s3.amazonaws.com (apply to us-east-1 region) You may need to create a private zone for each region and domain name format. For example, create a zone with domain name s3.us-west-2.amazonaws.com, another zone with domain name s3-us-west-2.amazonaws.com. .. tip:: Use DNS wildcard for record. For example, use *.s3.us-west-2.amazonaws.com that resolves to an A record that is the private IP address of the PrivateS3 internal NLB. Additional Configuration 2: S3 Endpoint --------------------------------------------------------- PrivateS3 does not require a S3 endpoint, however, S3 endpoint in the VPC where PrivateS3 gateways are deployed helps forwarding traffic to S3 services without routing through the Internet. Configuring an S3 endpoint is outside the scope of the PrivateS3 workflow. Log into the AWS Console to create an S3 endpoint. Adding More PrivateS3 Gateways --------------------------------------------------------------- When you want to scale-out and add more gateways to the pool, follow these steps. 1. Deploy a new gateway in a subnet in the same VPC by navigating to Gateway > New Gateway. Specify the Gateway Name, Access Account Name, Region, VPC ID, Public Subnet, and Gateway Size. Leave all other fields as default. #. Navigate to Security > Private S3 and choose the initially deployed gateway from the dropdown menu under the Gateway name. #. Following fields will be automatically populate based on the earlier deployed Gateway in the same VPC: Source CIDR Range, S3 Bucket FQDN Name Resolution IP, NLB DNS, S3 Bucket Name. #. Click **Attach**, which will add this new gateway as a Target in the correct Target Group for the NLB created. This completes the configuration needed to add a new gateway to the pool. Additional Read ------------------------- Additional read can be found in this short blog, `Secure, Cost Effective and Private S3 access via PrivateLink for Partners with Visibility and Troubleshooting Tools <https://community.aviatrix.com/t/60hz6nx/secure-cost-effective-and-private-s3-access-via-privatelink-for-partners-with-visibility-and-troubleshooting-tools>`_. .. |sfc| image:: sfc_media/sfc .png :scale: 30% .. |s3_endpoint| image:: sfc_media/s3_endpoint .png :scale: 30% .. |sft_deployment| image:: sfc_media/sft_deployment .png :scale: 30% .. |sft_aviatrix| image:: sfc_media/sft_aviatrix .png :scale: 30% .. |s3_public_vif| image:: sfc_media/s3_public_vif .png :scale: 30% .. disqus:: <file_sep> =============================================== Configuring Azure Multi-Peer BGP Over LAN Workflow =============================================== Introduction ^^^^^^^^^^^^^^^^ This document provides step-by-step instructions for building BGP over LAN connections between an Aviatrix Transit Gateway and one or more External Devices in Azure. Transit BGP over LAN allows Aviatrix Transit Gateways to communicate with multiple instances in different VNets in Azure without running any tunneling protocol such as IPsec or GRE. One use case is to interoperate with third-party virtual appliances such as SD-WAN cloud instances that do not have the capability to support BGP over any tunneling protocols. For example, integrating with SD-WAN gateways can be deployed as below, where Aviatrix Multi-Cloud Transit Gateways connect to third-party cloud instances in another VNet in Azure. |NVA_scale_out_concept| Related Topics ^^^^^^^^^^^^^^^^ * `Azure Multi-Cloud Transit BGP over LAN Workflow <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_azure_workflow.html?highlight=bGP%20over%20LAN#azure-multi-cloud-transit-bgp-over-lan-workflow>`_ * `Azure Multi-Peer BGP over LAN with Azure Route Server Integration <https://docs.aviatrix.com/HowTos/azure_bgpolan_multi-peer_ars.html>`_ * `AWS Multi-Cloud Transit BGP over LAN Workflow <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_workflow.html?highlight=bGP%20over%20LAN#aws-multi-cloud-transit-bgp-over-lan-workflow>`_ * `GCP Multi-Peer BGP over LAN Workflow <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_gcp_workflow.html?highlight=bGP%20over%20LAN#gcp-multi-peer-bgp-over-lan-workflow>`_ Prerequisites ^^^^^^^^^^^^^^^^ * Aviatrix Controller is updated to software version 6.8 or above. * Transit Gateways are deployed with BGPoLAN enabled with the required number of interfaces, which is based on the number of BGP over LAN connections you need. * In the single-attach use case, each BGP peer requires one BGPoLAN NIC on a single Aviatrix Transit Gateway. * In the dual-attach use case—that is, a scenario where the BGP peer needs to establish a BGP session to both Transit Gateways for high-availability reasons—a single BGP peer requires one BGPoLAN NIC on **both** Aviatrix Transit Gateways. Deploying Aviatrix Multi-Cloud Transit Solution ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Refer to `Global Transit Network Workflow Instructions <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ for more detailed instructions for the steps below. Adjust the topology depending on your requirements. 1. Deploy an `Aviatrix Multi-Cloud Transit Gateway and HA <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_azure.html#step-1-create-transit-vnet>`_  with Insane Mode encryption enabled in the Transit VNet. 2. Deploy a `Spoke Gateway <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_azure.html#step-3-deploy-spoke-gateways>`_. If desired, you can deploy this gateway with HA and enable Insane Mode encryption in the Spoke VNet(s). Note that HA and Insane Mode are not required. Building BGP over LAN ^^^^^^^^^^^^^^^^^^^^^^ Deploy the Aviatrix Transit Gateway with all the required BGP interfaces. 1. Log into the Aviatrix Controller. 2. Navigate to Multi-Cloud Transit > Setup > Transit. 3. Use the settings below to deploy the Aviatrix Transit Gateway. +--------------------------------+------------------------------------------------------------+ | **Setting** | **Value** | +--------------------------------+------------------------------------------------------------+ | Cloud Type | Azure ARM | +--------------------------------+------------------------------------------------------------+ | Gateway Name | Provide a unique name to identify the Transit Gateway. | +--------------------------------+------------------------------------------------------------+ | Access Account Name | Select the appropriate Azure account. | +--------------------------------+------------------------------------------------------------+ | VNet Name: Resource Group | Select the VNet where the Transit Gateway will be deployed.| +--------------------------------+------------------------------------------------------------+ | Public Subnet | Select the subnet the Transit Gateway interface will use. | +--------------------------------+------------------------------------------------------------+ | Gateway Size | Select an instance size that allows interfaces to be | | |created for all BGP peers. | +--------------------------------+------------------------------------------------------------+ | Allocate New EIP | Mark this checkbox if you want a new EIP allocated. | +--------------------------------+------------------------------------------------------------+ | EIP | If you choose to use an existing EIP, enter it here. | +--------------------------------+------------------------------------------------------------+ | Insane Mode Encryption | Mark this checkbox to enable high throughput encryption. | | |.. important:: | | | Insane Mode is mandatory when configuring | | | BGP over LAN for a Transit Gateway deployed in Azure. | +--------------------------------+------------------------------------------------------------+ |Enable Transit FireNet Function | Mark this checkbox to enable Transit FireNet. | +--------------------------------+------------------------------------------------------------+ | BGP over LAN | Mark this checkbox to enable BGP over LAN functionality. | +--------------------------------+------------------------------------------------------------+ | Add/Edit Tags | Select this box to add additional tags. | +--------------------------------+------------------------------------------------------------+ |Create_Transit-GW| 4. Click **Create**. 5. (Optional) If you want to enable HA to an Aviatrix Transit Gateway, complete Step 2 of the UI workflow - Enable/Disable HA to an Aviatrix Transit Gateway. Configuring BGP over LAN on Aviatrix Transit Gateway ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1. Log into the Aviatrix Controller. 2. Navigate to Multi-Cloud Transit > Setup > External Connection tab. 3. Select the following radio buttons: External Device > BGP > LAN. 4. Enter the following information in the fields provided. +--------------------------------+-------------------------------------------------------------------------------+ | **Setting** | **Value** | +--------------------------------+-------------------------------------------------------------------------------+ | VPC Name / Site ID | Select the Transit VNet ID where the Transit Gateway was deployed. | +--------------------------------+-------------------------------------------------------------------------------+ | Connection Name | Provide a unique name to identify the connection to the external device. | +--------------------------------+-------------------------------------------------------------------------------+ | Aviatrix Gateway BGP ASN | Provide the BGP AS number that is configured on the Transit Gateway and that | | | will be used to exchange routes with the external device. | +--------------------------------+-------------------------------------------------------------------------------+ | Primary Aviatrix Gateway | Select the Transit Gateway. | +--------------------------------+-------------------------------------------------------------------------------+ | Enable Remote Gateway HA | Mark this checkbox to connect two external devices configured as an HA pair. | +--------------------------------+-------------------------------------------------------------------------------+ | BGP Activemesh |Mark this checkbox to enable full mesh BGP connections to the external devices | | |from the primary and HA Transit gateways. Only to be used for Azure Route | | |Server Integration. | +--------------------------------+-------------------------------------------------------------------------------+ | Remote BGP AS Number |Configure the BGP AS number that the third-party cloud instance will use to | | |exchange routes with the Aviatrix Transit Gateway. | +--------------------------------+-------------------------------------------------------------------------------+ | Remote LAN IP |Enter the private IP of the LAN interface of the third-party cloud primary | | |instance. | +--------------------------------+-------------------------------------------------------------------------------+ | Local LAN IP |The Controller will automatically show the IP assigned to the BGPoLAN | | |interface that will be used for this specific peering. | +--------------------------------+-------------------------------------------------------------------------------+ |Remote BGP AS Number (Backup) |Enter the BGP AS number that the third-party HA cloud instance will use to | | |exchange routes with the Aviatrix HA Transit Gateway. | +--------------------------------+-------------------------------------------------------------------------------+ | Remote LAN IP (Backup) |Enter the private IP of the LAN interface of the third-party HA cloud | | |instance. | +--------------------------------+-------------------------------------------------------------------------------+ | Local LAN IP (Backup) |The Controller will automatically show the IP assigned to the BGPoLAN | | |interface that will be used for this specific peering. | +--------------------------------+-------------------------------------------------------------------------------+ |Create_BGPoLAN_connection| Click **Connect** to generate the BGP sessions. Verify the Connection ^^^^^^^^^^^^^^^^^^^^^^ At this point, run a connectivity and performance test to ensure everything is working correctly. .. |NVA_scale_out_concept| image:: azure_bgpolan_multi_peer_media/NVA_scale_out_concept.png :scale: 60% .. |Create_Transit-GW| image:: azure_bgpolan_multi_peer_media/Create_Transit-GW.png :scale: 60% .. |Create_BGPoLAN_connection| image:: azure_bgpolan_multi_peer_media/Create_BGPoLAN_connection.png :scale: 60% .. disqus:: <file_sep>Aviatrix Secure Edge Design Patterns ==================================== This document describes common design patterns for deploying Aviatrix Edge Gateways. Single Edge Gateway Attachment to Transit Gateway over Private Network ---------------------------------------------------------------------- In this design, a single Edge Gateway attached to an Aviatrix Transit Gateway over a private network, such as AWS Direct Connect, Azure Express Route, and GCP Interconnect. |edge_private_network| The key ideas for this scenario are: - WAN router runs a BGP session for underlay CSP to exchange routes with the CSP and the CSP advertises the Transit CIDR. - Edge Gateway LAN interface runs a BGP session to the LAN BGP router where the LAN BGP router advertises edge location network address range to Edge Gateway LAN interface. - Edge Gateway is attached to the Aviatrix Transit Gateway in the Transit VPC where Aviatrix Transit Gateway advertises all Spoke CIDRs to Edge Gateway and Edge Gateway advertises edge location network to the Aviatrix Transit Gateway. - Edge Gateway registration via Management with default route towards the Internet Firewall or router. Registration can be done via the Internet such as per the diagram or via private network. Single Edge Gateway Attachment to Transit Gateway over Public Network --------------------------------------------------------------------- In this design, a single Edge Gateway attached to an Aviatrix Transit Gateway over the public network. Key ideas are similar to Attachment over Private Network design except the WAN Router provides Internet connectivity to Transit .. Important:: If you have multiple Edge Gateways, make sure each Edge Gateway has a unique WAN Public IP. |edge_public_network| Single Transit Gateway with Redundant Edge Gateways --------------------------------------------------- In this design, multiple Edge Gateways are deployed to provide redundancy over a single private network circuit. Multiple Edge Gateways can be deployed in Active-Active mode with ECMP or Active-Standby. .. Important:: In the Active-Active deployment model, the network device connected to Edge Gateways needs to be able to handle asymmetric routing. .. Note:: Active-Active mode can support more than 2 Edge Gateways. While there is no maximum number of Edge Gateways, Aviatrix recommends a maximum of 4. |edge-single-transit-redundant| Single Transit Gateway with Redundant Edge Gateways and Circuits ----------------------------------------------------------------- In this design, multiple Edge Gateways are deployed with redundant private network circuits. Multiple Edge Gateways can be deployed in Active-Active mode with ECMP or Active-Standby. .. Important:: In the Active-Active deployment model, the network device connected to Edge Gateways needs to be able to handle asymmetric routing. .. Note:: Active-Active mode can support more than 2 Edge Gateways. While there is no maximum number of Edge Gateways, Aviatrix recommends a maximum of 4. |edge-redundant-circuit| Multi-Cloud Transit Networking with Edge Gateway ------------------------------------------------ In a multi-cloud setup scenario, Edge Gateway can function as a transitive router providing high-performance encryption and routing the traffic between cloud service providers. The key ideas for this scenario are: - Edge Gateway is attached to multiple Transit Gateways (for example, Transit in AWS and Transit in Azure) - Transitive Routing feature is enabled on Edge Gateway. - (Optional) Transit Peering over Public Network between Transit in AWS and Transit in Azure. - By default, Transit Peering will be the preferred path. To make Transit Peering less preferred, use `Connection AS Path Prepend feature <https://docs.aviatrix.com/HowTos/transit_advanced.html#connection-as-path-prepend>`_. - Edge redundancy can be achieved by deploying multiple Edge Gateways in Active-Active or Active-Standby configurations. |edge-multiple-transit-single-edge| .. |edge-redundant-circuit| image:: CloudN_workflow_media/edge-redundant-circuit.png :scale: 40% .. |edge_private_network| image:: CloudN_workflow_media/edge_private_network.png :scale: 40% .. |edge_public_network| image:: CloudN_workflow_media/edge_public_network.png :scale: 40% .. |edge-single-transit-redundant| image:: CloudN_workflow_media/edge-single-transit-redundant.png :scale: 40% .. |edge-multiple-transit-single-edge| image:: CloudN_workflow_media/edge-multiple-transit-single-edge.png :scale: 40% <file_sep> ========================================================= AWS Transit Gateway Orchestrator ========================================================= The AWS Transit Gateway (TGW) Orchestrator is a feature in Aviatrix Controller. It provides a point-and-click workflow to build a transit network and manages all network routing updates. The Orchestrator runs AWS APIs and uses building blocks such as AWS Transit Gateway, Transit Gateway route tables and VPC route tables, to automate the transit network deployment. In addition, the Orchestrator extends the AWS native service to include multi cloud support and a scale out architecture for firewall deployment. Whatever requirements you have in mind, the Orchestrator has you covered. Here is what you can do with the Orchestrator. 1. Build a Basic Transit Network ------------------------------------ Use the Orchestrator to build a basic transit network with the following benefits: - **Point-and-Click** The point-and-click workflow is simple to follow and easy to deploy. - **Multi Account** Supports up to three cross accounts VPC attachments to TGW with a single pane of glass. - **Route Propagation** The Orchestrator periodically polls the TGW route table to monitor route changes from on-prem and automatically programs Spoke VPC route tables. - **Direct Connect** TGW Direct Connect Gateway (DXGW) support. - **Internet VPN** TGW VPN support. - **100 Routes** Supports up to 100 routes (Per AWS VPN route table and DXGW route table limits). - **View** Graphic view of TGW VPC attachments. - **List** List view of TGW route table entries and VPC route table entries. - **Monitoring** Continuous monitoring of the configuration consistency and alerting for out-of-band changes. - **Terraform** Terraform Generator that exports what you have configured. Use it for replication and expansion. |basic| 2. Build a Transit Network with Segmentation ----------------------------------------------- Layering on the basic transit network, you can use the Orchestrator to add network segmentation: - **Isolation** Create network isolation by defining multiple Security Domains where VPCs in one domain cannot communicate with VPCs in another domain. - **Policy** Create network connection of isolated segments by defining connection policies that allow one domain to communicate with another domain. - **Route Propagation** Builds network segmentation by creating multiple TGW route tables and automatically updates all TGW route table propagations. - **Unlimited Multi Account** Support unlimited cross account VPC attachments to TGW with a single pane of glass. |with_security_domain| 3. Build a Transit Network with Multi Cloud Spokes ---------------------------------------------------- By deploying an Aviatrix Transit Gateway, you can use the Orchestrator to extend the deployment to include multi cloud Spokes. - **Azure** Connect Azure VNets as Spokes to the AWS transit network. - **GCP** Connect GCP VPCs as Spokes to the AWS transit network. |multi_cloud| 4. Build a Full Mesh Cloud Backbone --------------------------------------------------------------- By deploying multiple Aviatrix Transit Gateways, you can build a full mesh cloud backbone. - **Azure** Connect Azure transit network with the AWS transit network. - **GCP** Connect GCP transit network with the AWS transit network. - **InsaneMode Performance** Encrypted cloud backbone with InsaneMode high performance throughput. - **Agility** Spin up your cloud backbone in minutes. No contract, no wait for months. |cloud_backbone| .. |basic| image:: aws_transit_gateway_orchestrator_media/basic.png :scale: 30% .. |with_security_domain| image:: aws_transit_gateway_orchestrator_media/with_security_domain.png :scale: 30% .. |multi_cloud| image:: aws_transit_gateway_orchestrator_media/multi_cloud.png :scale: 30% .. |multi_cloud| image:: aws_transit_gateway_orchestrator_media/multi_cloud.png :scale: 30% .. |cloud_backbone| image:: aws_transit_gateway_orchestrator_media/cloud_backbone.png :scale: 30% .. |multi-region| image:: tgw_design_patterns_media/multi-region.png :scale: 30% .. |insane-mode| image:: tgw_design_patterns_media/insane-mode.png :scale: 30% .. |transit-DMZ| image:: tgw_design_patterns_media/transit-DMZ.png :scale: 30% .. disqus:: <file_sep> ============================ Aviatrix Glossary ============================ This Glossary provides definitions of Aviatrix products, features, tools, and general terminology. ACE (Aviatrix Certified Engineer) Training ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The Aviatrix Certified Engineer (ACE) program is a multi-cloud networking and security certification available to technical professionals and cloud practitioners. The program offers an overview of the networking industry’s move from on-premise to cloud servers, the main cloud service providers (AWS, Azure, GCP, and OCI) and their platforms, the necessity of multi-cloud networking architecture, and case studies that demonstrate how multi-cloud networking architecture has benefitted specific customers. ActiveMesh ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The new Aviatrix Encrypted Transit Network architecture where both primary gateways and backup gateways forward data packets in a load-balancing fashion to maximize performance. ActiveMesh is a step beyond a full-mesh structure, in which every node in the network is connected to every other node. Aviatrix Controller ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A central console or single pane of glass that provides visibility and control for your multi-cloud network, including its gateways, users, security, and operations. The platform uses the centralized intelligence and knowledge of the controller to dynamically program both native cloud network constructs and Aviatrix’s own advanced services. Aviatrix CoPilot ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The visibility and analytics companion to Aviatrix Controller that provides a global operational view of your multi-cloud network. CoPilot provides accurate, real-time information about your controller-managed environment from the location and health status of all managed resources to detailed flow records for traffic traversing any gateway. Copilot dynamically renders visualizations (maps, graphs, charts, and reports) to give you deep visibility into your enterprise class network across a single or multiple clouds. CoPilot provides interactive diagnostic tools for locating and troubleshooting network issues and enhanced security features for detecting and blocking threats trying to penetrate the network. Aviatrix FireNet ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A turnkey or ready-made network solution to deploy firewall instances in the cloud. FireNet significantly simplifies firewall instance deployment and allows the firewall instances to inspect traffic between VPCs/VNets/VCNs (East West) traffic, between VPCs/VNets/VCNs and the Internet (Egress) traffic, and VPC/VNet/VCN to on-prem (North South) traffic. FireNet also allows you to scale firewall deployment to multiple Availability Zones and multi-instances so that your network can grow with your company. Aviatrix CloudN ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Manages and automates secure connectivity of on-prem Cisco IOS Routers to the cloud. Aviatrix Edge ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The hardware/virtual appliance provided by Aviatrix as an alternative to SDWAN solutions (formerly known as CloudN or ExoGateway). Aviatrix Edge connects different CSP (Cloud Service Provider) networks in its multi-cloud networking architecture framework. Aviatrix Gateway ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ An Aviatrix gateway is a virtual router you deploy in your network to route traffic in accordance with the connection and security policies you define in Aviatrix Secure Cloud Network Platform. Aviatrix gateways support the connectivity requirements of cloud networks that use a transit hub-and-spoke architecture and are available in different types: Transit, Spoke, Egress, VPN, and NAT. **Transit**: Connectivity between on-prem and the cloud. Site-to-cloud single region or multiple region and site-to-cloud single cloud or multiple cloud. For advanced transit networking, connectivity between one region to another or one cloud to another. **Spoke**: Connectivity between the Spoke VPC/VNet to the Transit. Deployed on the Spoke VPC/VNet. A spoke gateway can also be a site-to-cloud landing option. **Egress**: An Aviatrix gateway that performs the function of cloud-to-Internet egress filtering and egress security. Connectivity between a VPC/VNet and the Internet. **VPN**: An Aviatrix gateway that performs the function of VPN connectivity. Connectivity between your partners/branches and your cloud services for site-to-cloud VPN access (deployed on the partner/branch side). Also connectivity between your remote users and the cloud for dynamic enforcement to differentiate the different users connecting into the cloud. Useful for companies that have no on-prem data center (all resources are in the cloud). **NAT**: An Aviatrix gateway that performs the NAT function. Egress FQDN Filtering ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Secures VPC/VNet/VCN Egress by filtering outbound traffic to the Internet. This feature enables companies to discover what Internet sites their cloud apps are communicating with, push filtering policies instantly to one VPC or hundreds of VPCs, move from NAT Gateway (IP address based) to Fully Qualified Domain Name (FQDN) filtering, and audit all events, including the packets. You can view Egress FQDN filtering in the Aviatrix Controller or by exporting logs to Splunk, Sumologic, and Datadog to standardize reporting and correlate events. FlowIQ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Aviatrix CoPilot’s dynamic topology mapping, which helps companies maintain an accurate view of their global multi-cloud networks. FlowIQ helps you analyze global network traffic flows using global heat maps and time series trend charts to easily pinpoint and troubleshoot traffic anomalies. ThreatIQ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Aviatrix CoPilot feature that enables you to monitor for security threats in your Aviatrix cloud network, set alerts when threats are detected in the network traffic flows, and block traffic that is associated with threats. All of these capabilities apply to your entire cloud network (multi-cloud or single cloud) that is managed by Aviatrix Controller. .. disqus:: <file_sep>.. image:: ./media/image1.png :width: 3.5in :height: 0.5in ####################################################### Enterprise Cloud Adoption Journey: Technical Challenges ####################################################### Technical Whitepaper ==================== Last updated: May 11, 2017 Introduction ============ The enterprise journey to cloud adoption can be driven by two different types of incentives. The business drives one type, building new, transformative capabilities. Here the cloud is an enabler that did not exist in the past. The other type is focused on optimizing the legacy data center environments within IT to contain evolving pressures. These two types are usually happening in parallel. In all cases, cloud adoption is accelerating, and along with it an increasing number of challenges. Competitive pressures on businesses to move more quickly and be more agile, are forcing decisions on where to deploy new applications. The public cloud is a resource for creating new disruptive applications that would be difficult if not impossible to implement in other means. It provides competitive leverage to not only new businesses but existing enterprises. Additionally, massive application workloads like Enterprise Resource Planning applications (ERP), large custom applications, high performance computing applications and backup and disaster recovery applications are migrating to the public cloud out of necessity to mitigate the constant strain to keep costs under control over time. Most enterprises are stepping into the cloud with a hybrid approach. Aviatrix for Hybrid Cloud enables enterprises to design, configure and operate secure and scalable hybrid cloud networks to migrate, access and run applications in the public cloud. Business Drivers to Migrate to the Hybrid Cloud =============================================== This is a typical list of CIO and enterprise motives that drive the move of enterprise applications to the cloud. New transformative business models ---------------------------------- - pay-as-you-go flexibility to expand / reduce IT footprint as needed - untested workloads, “fail-fast, fail-cheap” POC’s - apps with cloud native architecture, rapid flex-up and scale-out Disaster recovery and high availability --------------------------------------- - geo-dispersed sites - system redundancy - significantly easier and automated periodic testing Cost savings ------------ - especially storage costs and high-performance computing - limited IT staff and resource growth - temporary scale up **and** scale down in capacity demands International expansion and collaboration ----------------------------------------- - M&A activities resulting in geographically dispersed disparate systems - expansion into new global markets Compelling events ----------------- - expiring data center equipment support - expiring data center leases Compliance ---------- - requirements for local data hosting in the region being served vs centralized Use Cases ========== The following use cases represent examples of the above scenarios. Use Case #1: Home grown (legacy) applications --------------------------------------------- HR departments may have large workloads: recruitment management, relocation, benefits administration, human capital management, finance and accounting, SCM/procurement, expense reporting, time management, etc. These applications may be used sporadically and have low performance requirements, making them an ideal choice to offload from on-premises and into the cloud. Other legacy applications used by finance/legal departments may be used infrequently and have low performance needs, as well as legacy custom stubs for SSO or employee VPN access all would benefit by moving to the cloud. Offloading these applications means that IT can reallocate this hardware to applications that require more steady computing power, or decommission the hardware altogether. Either scenario means time and efficiency gains for the IT department, without any noticeable change in performance from end users. Use Case #2: Disaster recovery and high availability ---------------------------------------------------- Instances in the cloud are not much different than instances in the data center in terms of failure possibilities. This includes server/service/VM failures and reboots, zone failures, and multi-zone cloud failures. To achieve multiple 9s of availability, processes need to be in place for these types of failure mechanisms, including the need to automate everything and do on-going assurance testing on a regular basis. Cloud customers can use hybrid clouds to promote both DR and HA, oftentimes extending DR protection to important, yet previously unprotected systems. Use Case #3: Big data, storage and backup/archiving ---------------------------------------------------- Enterprises have accumulated huge volumes of data, stored in databases, which power the applications that their end users and customers rely on every day. These applications often involve many VMs as part of their architecture, and their databases often hold terabytes worth of data, even though much of that data lays “at rest” for large portions of the time. There are two major benefits to getting these applications and their datasets into the cloud. First, a greatly reduced on-premises hardware footprint by reducing both servers and storage. Second, these applications can now benefit from the elasticity of the cloud, by easily adding more compute (for the application) or storage (for the databases) whenever needed. Use Case #4: DevOps/QA/Test ---------------------------- Developers need an agile, flexible, dynamic environment for developing and testing software applications. Moving CI/CD applications for development and testing to the cloud has clear benefits, including cost savings and increased time-to-market. These applications are lower-risk, lower performance, mostly self-contained with no dependencies, and good “phase 1” candidates for migration. Use Case #5: International expansion ------------------------------------ Businesses that expand internationally may need applications and data to be closer to the new locations. This could be due to localization requirements, minimizing latencies to apps/data, or compliance reasons. A new acquisition or merger could result in almost instantly geographically dispersed public clouds that now need to be peered or connected back to other data centers. Technical Challenges ==================== The technical requirements and challenges enterprises face during this journey to the cloud are multi-faceted. Enterprise applications represent a significant on premise investment with critical value, and years of development. Even with a “lift and shift” methodology, organizations may struggle with inherent interdependencies to move them, along with the data, to the public cloud. One of the CIO’s highest priorities must be to minimize risk when the move is made as these applications usually are mission critical. Latency ------- The demands on performance and user experiences with cloud based applications can sometimes be subpar, resulting in not only user frustrations but real business financial impacts. The roles of both the Internet and cloud computing complicate latency, with networks broken down into hundreds of components, and layers of virtualization and virtualized network infrastructure. Bringing the applications closer to the end-user is oftentimes the most viable and flexible solution to reduce latencies, since there are few restrictions on physical location that exist with custom engineered direct connections. Security -------- Enterprises must minimize risk migrating applications to the cloud. Cloud computing and security go hand in hand. Cloud environments face many of the same threats as traditional corporate networks, but due to the vast amount of data stored on cloud servers, providers become an attractive target. Network security groups allow organizations to shield parts of their public cloud from direct outside access -- like a firewall. Hybrid and multicloud environments present new cloud security challenges and risks as data moves between on premises and the cloud. If custom Internet-bypassing connections are used, no native end-to-end encryption is provided. Agile role-based secure access ------------------------------ As enterprises move applications to the public cloud, the users and organizations owning the applications now have interconnects to the public cloud that did not exist previously. These interconnects must be secure. Companies have a need to authenticate and enable their mobile employees to securely access the companies evolving network via the Internet with a secure VPN solution. This solution must be easily deployed, managed, highly scalable, and agile to meet the constantly evolving network topologies caused by migrating applications. Multi-vendor cloud providers ---------------------------- To enable geographically dispersed data redundancy, and other types of redundancy, or to support unique workloads, it is common to buy cloud services from more than one vendor. While each has its own uniqueness and strengths, the IT organization wants to minimize operational complexities and create inter-cloud connections that are visible, manageable, robust, scalable, and easy to deploy. Enterprises need to plan ahead by assuming hybrid IT will be the future and take steps accordingly. Hybrid management systems, integration, workload portability, automation and skills using various public cloud platforms are all important investments to make early in the cloud deployment process. Custom network configurations ----------------------------- Creating and securely connecting the on-premise datacenter to the cloud resources is often slow and manual. Seamless extension of the private IP address space into the public cloud such that resources in the public cloud are easily accessible, reducing the attack surface, reducing issues with overlapping IP address space is a key challenge facing network engineers. Large data center and cloud environments have complex network configurations and settings to satisfy regulatory and internal policies. Matching the workload compute and storage requirements to the cloud services is not the total solution – mapping of the existing network environment to the cloud network can be very daunting and error prone. Enterprise workloads may need to be configured for specific sub-networks, VLANs and use of specific IP address ranges as well as physical IP address. It can take weeks to provision secure connectivity, involving complex router configurations managed by network experts and expensive installations. Aviatrix hybrid cloud networking provides a one-click software-only model to set up encrypted connections to public clouds in minutes, with the ability to extend the private IP network to public clouds. Throughput/Performance ----------------------- Cloud performance depends on network performance. While cloud providers like to talk about the latest software offerings, the speed and capacity of the cloud provider’s network will usually be a determining factor for the viability of any cloud-based software application. The key measure of network performance is throughput – sometimes called bandwidth. What is critical for networks in cloud computing is not only achievable performance, but consistency of performance, which is important when sending large amounts of data between servers. One of the latest trends is buying network capacity on an incremental basis, just like any other cloud resource. Other cloud provider direct connect solutions also add bandwidth improvements for transferring large amounts of data when more capacity is needed. However, these solutions do not provide native end-to-end security. Summary ======= The enterprise cloud adoption journey is just that – a journey. New technical solutions are appearing at an ever-increasing rate, as well as new challenges they bring. A well thought out migration plan that includes all the aspects of vendor features, performance, security and networking is required. Aviatrix provides an innovative Cloud Networking software solution that simplifies connectivity to the cloud in a secure and scalable way. At Aviatrix, we believe that networking is a foundational element of cloud computing and, should be as dynamic, scalable, and elastic as compute and storage. Aviatrix for Hybrid Cloud eliminates the complexity of connecting to and across public clouds with a simple mesh architecture, and is fully integrated with Amazon Web Services (AWS), Microsoft Azure and Google Cloud Platform. <file_sep>************* Security FAQs ************* Browse Questions ================= `Is customer data contained in the customer's AWS account?`_ `Will the controller and gateway need to reach out to Aviatrix to receive commands or send routing data to Aviatrix?`_ `Do we need a controller in each cloud environment (i.e., one for AWS, one for Azure, etc.)? If not, how do we do multi-cloud traffic steering?`_ `How are Aviatrix instances hardened?`_ `Does Aviatrix Controller have a database running?`_ `How does a Gateway device communicate/authenticate to the controller?`_ `Is Aviatrix SOC2 certified?`_ `Is Aviatrix PCI-DSS compliant?`_ `Is Aviatrix HIPAA compliant?`_ `Is Aviatrix FedRamp compliant?`_ `Is Aviatrix software in compliance with Section 508, IT Accessibility Standards?`_ `Is Aviatrix FIPS 140-2 certified?`_ `Can Aviatrix software support GovCloud implementation?`_ `Do Aviatrix Controller and Gateway instances support running an anti-malware agent?`_ `Is it possible to do OS disk encryption on Aviatrix Gateway instances without taking the Gateway down?`_ `Can a customer create their own custom hardened image for the Aviatrix Controller or Gateway instances?`_ `Can we install tools on the Aviatrix Gateway instances for monitoring network traffic and resource consumption?`_ `Can we patch the Aviatrix Controller and Gateway instances using our Systems Manager agent?`_ `Does Aviatrix implement Secure Coding and Development practices to ensure that the software is not vulnerable to DDoS, SQL Injection and/or Cross Site Scripting Attacks?`_ `Does Aviatrix software support IKEv2?`_ `Does Aviatrix software support role-based access control (RBAC)?`_ `What IAM policy is required to use Aviatrix?`_ `Can I use a custom SSL Certificate for the Controller and Gateway instances?`_ `How is data encrypted during transmission from source Controller to destination Gateway?`_ Is customer data contained in the customer's AWS account? --------------------------------------------------------- Yes, all Aviatrix AMI is deployed in the customer’s private cloud environment. Will the controller and gateway need to reach out to Aviatrix to receive commands or send routing data to Aviatrix? --------------------------------------------------------------------------------------------------------------------------------------- No, customers' configuration data is never accessed by Aviatrix. The only time Aviatrix receives information from a customer is:  * When a customer pushes log data to our encrypted customer S3 bucket for technical support. * For customers using a BYOL license, the license activity (acquisition and retiring a license) is validated to the Aviatrix license server.  Do we need a controller in each cloud environment (i.e., one for AWS, one for Azure, etc.)? If not, how do we do multi-cloud traffic steering?   --------------------------------------------------------------------------------------------------------------------------------------- No, you don’t. One Aviatrix Controller manages cloud deployment in AWS, Azure, GCP, and OCI. Aviatrix Controller launches Gateways in each cloud and orchestrates policies to build network segmentation and secure connectivity. How are Aviatrix instances hardened? ------------------------------------ The Aviatrix Controller and Gateway instances are virtual machines using an opensource OS which is maintained specifically for Aviatrix for infrastructure services. All OS patches go through our full QA process and are managed in the releases of the Aviatrix software. * Users cannot login to Aviatrix Controller or Gateway instances, as SSH access is disabled. * Both Controller and Gateway instances have hard disk encryption, using AWS Elastic Block Storage (EBS) encryption. For more information, see AWS' documentation: https://docs.aviatrix.com/HowTos/FAQ.html#encrypt-controller-ebs-volume and https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html. * Aviatrix Gateway instances' inbound security group only opens to the Controller EIP on port 443. See additional detail here `How do I secure the Controller access? <https://docs.aviatrix.com/HowTos/FAQ.html#how-do-i-secure-the-controller-access>`_ Does Aviatrix Controller have a database running? ------------------------------------------------- Controller instances have a local MongoDB database installed, however this is not acccessible to end users. How does a Gateway device communicate/authenticate to the controller?  ------------------------------------------------------------------------------------------------------------------------------------------------------------------- Controllers send messages to your SQS or via HTTPS to the Gateway. Gateways pull messages from SQS.   Is Aviatrix SOC2 certified? --------------------------- Yes, Aviatrix is SOC2 Type 1 and Type 2 certified. Is Aviatrix PCI-DSS compliant?  ------------------------------ Aviatrix is not in-scope for PCI-DSS compliance. We do not process credit card information, nor do we have access to the customer’s data. Aviatrix software is deployed in the customer’s private network. Is Aviatrix HIPAA compliant? ------------------------------ Aviatrix is not in-scope for HIPAA compliance. We do not process PHI/ePHI nor do we have access to the customer’s data. Aviatrix software is deployed in the customer’s private network. Internally, the company hires Third Party Administrator (TPA) for HR benefit services. We collect the business associate agreement for TPAs.   Is Aviatrix FedRamp compliant? ------------------------------ Aviatrix is not in-scope for FedRamp compliance because it is not a SaaS product and Aviatrix software is installed in the federal network. However, Aviatrix is currently certified for SOC2 and we are also working on additional readiness for other frameworks such as NIST 800-171, ISO 27002, HIPAA and PCI. Is Aviatrix software in compliance with Section 508, IT Accessibility Standards? --------------------------------------------------------------------------------------------------- Aviatrix covers Level AA ready under the VPAT (Voluntary Product Accessibility Template) standards. You can access the Accessibility Conformance Report `here <https://aviatrix.com/wp-content/uploads/2022/06/2022-Aviatrix-VPAT2.4-RevINT-1.pdf>`_. Is Aviatrix FIPS 140-2 certified?  --------------------------------- Yes. https://docs.aviatrix.com/HowTos/fips140-2.html  Can Aviatrix software support GovCloud implementation?   ------------------------------------------------------ Yes. We support AWS GovCloud infrastructure.    Do Aviatrix Controller and Gateway instances support running an anti-malware agent? -------------------------------------------------------------------------------------- Because Aviatrix is an appliance, we do not allow customer SSH access to install anti-malware software on the instances. Is it possible to do OS disk encryption on Aviatrix Gateway instances without taking the Gateway down?  ------------------------------------------------------------------------------------------------------- No, customers are not allowed to add additional software code in Aviatrix Gateway instance. The instance is implemented with hard disk encryption using Elastic Block Store (EBS) encryption. Below are additional details for this technology.  * https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html   * https://docs.aviatrix.com/HowTos/encrypt_ebs_volume.html  * https://docs.aviatrix.com/HowTos/encrypt_ebs_volume.html#how-to-encrypt-gateway-ebs-volume-via-aviatrix-controller  Can a customer create their own custom hardened image for the Aviatrix Controller or Gateway instances? ----------------------------------------------------------------------------------------------------- No. Because Aviatrix is an appliance, the instances are not accessible to install custom software. Can we install tools on the Aviatrix Gateway instances for monitoring network traffic and resource consumption?  ---------------------------------------------------------------------------------------------------------------------- No, however, we support integrations to top SIEM platforms for your internal Threat/SOC operations. We currently support the following: * Remote syslog (recommended to use)  * AWS CloudWatch  * Splunk Enterprise  * Datadog  * Elastic Filebeat  * Sumo Logic  * Netflow  See the Logging documentation for details on how to configure this: https://docs.aviatrix.com/HowTos/AviatrixLogging.html  Can we patch the Aviatrix Controller and Gateway instances using our Systems Manager agent? --------------------------------------------------------------------------------- No, our instances are appliances and customer SSH access is disabled. To patch Aviatrix Controller and Gateway instances, customers need to log into their Controller management console and update to the latest Aviatrix version.  Does Aviatrix implement Secure Coding and Development practices to ensure that the software is not vulnerable to DDoS, SQL Injection and/or Cross Site Scripting Attacks? ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Aviatrix security measures for SDLC include access, change, vulnerability, threat intelligence and risk management safeguards. To ensure we protect our software code from known attacks like CSS, SQL Injection, and DDOS, we run vulnerability scans prior to each release to detect and mitigate any possible attacks. We also work closely with security researchers to detect zero day threats and we work with Coalfire to anually perform source code review and independent penetration testing. Does Aviatrix software support IKEv2? -------------------------------------- IKEv2 is currenty supported for site2cloud tunnels. IKEv2 for Transit is in our roadmap.  Does Aviatrix software support role-based access control (RBAC)? ---------------------------------------------------------------- Yes, RBAC in Aviatrix Controller is available in version 5.4 or greater. The default roles available out of the box are admin and read_only. Customers can add custom RBAC permission groups in the Aviatrix Controller, and assign users to an RBAC Group. See detail here: https://docs.aviatrix.com/HowTos/rbac_faq.html |security_rbac_1| |security_rbac_2| What IAM policy is required to use Aviatrix? -------------------------------------------- Since Aviatrix is an appliance deployed in your AWS account, you will create your AWS IAM Policy. When you launch Aviatrix, some services will deploy an IAM Policy to operate, however, it is the customer’s responsibility to edit the policy to your internal policy. When you edit the policy, we recommend you perform internal testing. The default IAM Policies used for Aviatrix are documented here: https://docs.aviatrix.com/HowTos/customize_aws_iam_policy.html?highlight=iam%20policy#iam-policies-required-for-aviatrix-use-cases See a sample of how to edit your IAM Policy for Aviatrix: https://docs.aviatrix.com/HowTos/customize_aws_iam_policy.html Can I use a custom SSL Certificate for the Controller and Gateway instances? ---------------------------------------------------------------------------- Yes, you can. To implement the SSL Certificate for your controller, go to Setting > Advanced > Security sub tab. Note that SSL verification check is not enabled by default and should be enabled by a customer |security_bulletin_faq_certificate| How is data encrypted during transmission from source Controller to destination Gateway? -------------------------------------------------------------------------------------------- By default, data transfer is over a TCP connection with TLSv1.2 for encryption. Customers have the option to downgrade the TLS Version used due to internal dependency conflicts. You can configure this in Aviatrix Controller by clicking on Settings > Advanced > Security. How does Aviatrix encrypt data in transit? -------------------------------------------------------------------------------------------- Aviatrix 6.5 and above, Aviatrix implements a secured framework based on PKI/X.509 protocol to communicate between Controller and Gateway. How does Aviatrix handle security patch? -------------------------------------------------------------------------------------------- A security patch resolves software vulnerabilities and will be applied to the compatible software versions as stated in the release notes. When a patch is released, there will be a field notice to Aviatrix Controller via email. How do I stay up to date with the latest security vulnerabilities? -------------------------------------------------------------------------------------------- We recommend customers to deploy the latest image, upgrading to the latest software version, and staying on top of any security patch released. Guaranteeing security against vulnerabilities is a sustained effort and it is Aviatrix's policy to address them continuously. Does Aviatrix have a ISO 27002 Certification? -------------------------------------------------------------------------------------------- ISO 27002 is a work in progress. |security_bulletin_faq_encrypted_transmission| .. |security_rbac_1| image:: security_bulletin_media/security_bulletin_faq_rbac_1.png .. |security_rbac_2| image:: security_bulletin_media/security_bulletin_faq_rbac_2.png .. |security_bulletin_faq_certificate| image:: security_bulletin_media/security_bulletin_faq_certificate.png .. |security_bulletin_faq_encrypted_transmission| image:: security_bulletin_media/security_bulletin_faq_encrypted_transmission.png .. disqus:: <file_sep> .. toctree:: :numbered: ============================================================================== Centrify IdP for SAML Integration ============================================================================== Overview ------------ This guide provides an example on how to configure Aviatrix to authenticate against Centrify IdP. When SAML client is used, your Aviatrix controller acts as the Identity Service Provider (SP) that redirects browser traffic from client to IdP for authentication. Before configuring SAML integration between Aviatrix and Centrify, make sure you have a valid Centrify account with administrator access. Configuration Steps ------------------- Follow these steps to configure Aviatrix to authenticate against your Azure AD IdP: Step 1. Retrieve `Aviatrix SP Metadata <#centrify-saml-sp-metadata>`__ from the Aviatrix Controller Step 2. Create a `Centrify SAML Application <#centrify-saml-app>`__ for Aviatrix Step 3. Retrieve `Centrify IdP metadata <#centrify-idp-metadata>`__ Step 4. Update `Aviatrix SP Endpoint <#centrify-update-saml-endpoint>`__ in the Aviatrix Controller Step 5. `Test the Integration <#centrify-test-integration>`__ is Set Up Correctly .. _centrify_saml_sp_metadata: Step 1. Retrieve Aviatrix SP Metadata from Aviatrix Controller ############################################################### Before creating the Centrify SAML Application, Centrify requires the Service Provider (SP) metadata file from the Aviatrix Controller. You can create a temporary SP SAML endpoint to retrieve the SP metadata for now. Later on in the guide, the SP SAML endpoint will be updated. Follow one of the links below according to your use case: #. If integrating Centrify IdP with `Controller Login SAML Config <https://docs.aviatrix.com/HowTos/Controller_Login_SAML_Config.html#config-31>`_ #. If integrating Centrify IdP with `OpenVPN with SAML Authentication <https://docs.aviatrix.com/HowTos/VPN_SAML.html#config-31>`_ For Centrify, right click the **SP Metadata** button next to the SAML endpoint and save the file. |image3| Here you can retrieve the SP metadata by clicking on the SP metadata |image4| .. tip:: Copy the above metadata as text. It will be pasted into the Centrify IdP in the later steps. .. note:: You can also use URL method if you have configured signed certificates for the Aviatrix Controller, but not for the initial self-signed certificate. .. _centrify_saml_app: Step 2. Create a Centrify SAML App for Aviatrix ############################################### 1. From the Centrify App->Add New App->Custom, select SAML and click on “Add”. Click yes and close the prompt. This lets you configure the application. 2. Configure app settings. Enter a name for your application, click Save and go to the next page |image0| 3. In the Metadata XML section, paste the SP metadata that was copied in the `previous section (Step 1) <#centrify-saml-sp_metadata>`_ Click on “Save” and go to the next section |image5| .. note:: You can also use URL method if you have configured signed certificates for the Aviatrix Controller, but not for the initial self-signed certificate. 4. Configure the following SAML attributes (Email is the unique identifier) +----------------+---------------------+ | FirstName | LoginUser.FirstName | +----------------+---------------------+ | LastName | LoginUser.LastName | +----------------+---------------------+ | Email | LoginUser.Email | +----------------+---------------------+ Also, the custom logic needs to be set for the attributes to work setAttribute("exampleAttr", "DOMAIN\\user"); |image6| You can preview the SAML response and this step and select the user. Make sure that there are no errors. Click “Save” and go to the next tab #. Add users |image7| Click “Save” and go the next tab #. Add any policies if you require them. Click “Save” and go to the next tab #. Use the default “Directory service field” mapping. Click “Save” and go to the next tab |image8| #. Configure the next pages if you require them, "Linked applications","Provisioning", "App Gateway" if you require them. Click “Save”. The SAML configuration at the IdP is now complete .. _centrify_idp_metadata: Step 3. Retrieve Centrify IdP metadata ####################################### #. Copy the metadata URL from the Trust page. |image1| .. _centrify_update_saml_endpoint: Step 4. Update Aviatrix SP Endpoint ########################### .. note:: This step is usually completed by the Aviatrix admin. Centrify IdP provides IdP Metadata through URL obtained in `Retrieve Centrify IdP metadata (Step 3) <#centrify-idp-metadata>`_. Continue with updating Aviatrix SAML Endpoint by visiting one of the following links based on your use case: #. If integrating Centrify IdP with `Controller Login SAML Config <https://docs.aviatrix.com/HowTos/Controller_Login_SAML_Config.html#config-34>`_ #. If integrating Centrify IdP with `OpenVPN with SAML Authentication <https://docs.aviatrix.com/HowTos/VPN_SAML.html#config-34>`_ +----------------------------+-----------------------------------------+ | Field | Description | +----------------------------+-----------------------------------------+ | Endpoint Name | ``[Endpoint Name]`` | +----------------------------+-----------------------------------------+ | IPD Metadata Type | URL | +----------------------------+-----------------------------------------+ | IdP Metadata Text/URL | Paste in the **Issuer URL** obtained | | | from the `Centrify app <#centrify-idpimetadata>`_. | +----------------------------+-----------------------------------------+ | Entity ID | Select `Hostname` | +----------------------------+-----------------------------------------+ | Access | Select admin or read-only access | +----------------------------+-----------------------------------------+ | Custom SAML Request | Unchecked | | Template | | +----------------------------+-----------------------------------------+ .. note:: Each endpoint only supports one type of access. If you need admin and read-only access, create two separate SAML apps. `Hostname` is the default for Entity ID, but if you have other apps using the same hostname, use a custom Entity ID. .. _centrify_test_integration: Step 5. Test the Integration ############################# .. tip:: Be sure to assign users to the new application in Centrify prior to validating. If you do not assign your test user to the Aviatrix SAML application, you will receive an error. Continue with testing the integration by visiting one of the following links based on your use case: 1. If integrating Centrify IdP with `Controller Login SAML Config <https://docs.aviatrix.com/HowTos/Controller_Login_SAML_Config.html#config-35>`_ #. Click `Settings` in the left navigation menu #. Select `Controller` #. Click on the `SAML Login` tab 2. If integrating Centrify IdP with `OpenVPN with SAML Authentication <https://docs.aviatrix.com/HowTos/VPN_SAML.html#config-35>`_ #. Expand `OpenVPN®` in the navigation menu and click `Advanced` #. Stay on the `SAML` tab You can quickly validate that the configuration is complete by clicking on the **Test** button next to the SAML endpoint. .. |image0| image:: centrify_media/image1.jpg .. |image1| image:: centrify_media/image2.jpg .. |image2| image:: centrify_media/image3.jpg .. |image3| image:: centrify_media/image4.jpg .. |image4| image:: centrify_media/image5.jpg .. |image5| image:: centrify_media/image6.jpg .. |image6| image:: centrify_media/image7.jpg .. |image7| image:: centrify_media/image8.jpg .. |image8| image:: centrify_media/image9.jpg .. |image9| image:: centrify_media/image10.jpg .. |image10| image:: centrify_media/image11.png <file_sep> ========================================================= PrivateS3 FAQ (AWS) ========================================================= What is the security exposure when uploading files to AWS S3 over Direct Connect? -------------------------------------------------------------------------------------------------------- If you leverage the high-speed AWS Direct Connect to transfer files and objects to/from S3, the current solution is to use public VIF where AWS advertise the entire S3 public address ranges to on-prem. This implies that all on-prem users can upload to any S3 bucket, including to their personal S3 buckets on their own personal accounts, leading to confidential data leakage. The current solution is described as below. |s3_public_vif| In the diagram above, there is no VPC involved when using public VIF. Data is directly transferred to and from S3 riding on the Direct Connect link. In another scenario where an instance in a VPC trying to access S3 buckets, you can specify an S3 private Endpoint. The advantage is such that packets do not get routed over Internet and instead packets are routed to S3 via AWS network. However, the endpoint is still represented by the public CIDR blocks representing AWS S3 in the region as shown below, in another words, someone with the valid credential to access the S3 Endpoint can transfer objects to his/her own S3 buckets. |s3_endpoint| Note that an Endpoint policy controls who can use the Endpoint service, but it does not control which destination S3 bucket the request can be granted. Same issue of data leakage occurs if you upload files to S3 over public Internet. What is Aviatrix PrivateS3? ----------------------------------------------- Aviatrix PrivateS3 is a feature that allows you to leverage AWS Direct Connect to transfer objects and files between on-prem and S3 while giving you control of the S3 buckets by the ability to whitelist the S3 buckets. |sft_aviatrix| What are the benefits of PrivateS3? ---------------------------------------------------------------------------- The key benefits are: 1. Transferring objects/data between on-prem and S3 by leveraging Direct Connect without using public VIF. #. The ability to control which S3 buckets can be accessed. #. The ability to deploy multiple Aviatrix Gateways to load balance the data traffic. How does PrivateS3 work? ------------------------------------- PrivateS3 works as follows. 1. Customer on-prem resolves all S3 bucket names under management to the private IP address of the Aviatrix gateway created and managed in AWS internal NLB. #. The Controller scans periodically (every 30 minutes) S3 buckets in the selected region and accounts. #. The Controller sends email notification to the admin for newly discovered S3 buckets. All S3 buckets are denied access by default. #. The admin logs into the Controller to approve or deny access to the discovered S3 buckets. #. When Aviatrix PrivateS3 gateway receives the packets, it uses its FQDN feature to filter out any buckets names that are not on the allowed list, thus preventing data leakage. How do I deploy PrivateS3? ------------------------------------- Follow the `PrivateS3 Workflow <https://docs.aviatrix.com/HowTos/privateS3_workflow.html>`_ for deployment. Can PrivateS3 work for traffic initiated from a VPC? ---------------------------------------------------------------- PrivateS3 is optimized for managing S3 access from on-prem. For traffic initiated from VPC, use `Aviatrix FQDN feature <https://docs.aviatrix.com/HowTos/fqdn_faq.html>`_ for not only S3 access control but also all Internet-bound egress control. Is there an additional AWS data charge by going through the Aviatrix Gateway? ------------------------------------------------------------------------------------------------ No, there is no data charge by AWS for using PrivateS3. Normally AWS charges data transfer for data traffic leaving a VPC, however in this case, data transfer is through an AWS VPC endpoint to S3 which is free of charge. Can PrivateS3 be deployed in TGW environment? --------------------------------------------------------------- Yes. You can deploy PrivateS3 in a Spoke VPC in the TGW environment, as shown in the diagram below. |sft_deployment| Can Direct Connect termination VPC be in a different region of managed S3 buckets? -------------------------------------------------------------------------------------------------------- Yes. For example, the Direct Connect private VIF terminates in a VPC in us-west-2 and your S3 buckets are in us-east-1. You should launch the PrivateS3 gateway in a VPC in us-east-1 and make sure there is private connectivity to this VPC from on-prem. Can PrivateS3 gateway be in a different region of managed S3 buckets? --------------------------------------------------------------------------------------- Yes. However, in such case, you will not be able to leverage the S3 Gateway Endpoint service to route packets to S3 within AWS network. PrivateS3 will forward traffic to public Internet to reach S3 in a different region. Can PrivateS3 solution scale out? ------------------------------------------ Yes. You can launch multiple PrivateS3 gateways in a multi-AZ fashion in a VPC. Aviatrix Controller automatically creates and manages AWS internal NLB to load balance the S3 access requests. How can I test PrivateS3? ----------------------------------- There is a simple method to simulate DNS resolution to the PrivateS3 internal NLB. Launch a Linux instance or host, in sudo mode, edit file /etc/hosts. Add S3 bucket FQDN names to this file, as shown in the example below, where 192.168.3.11 is the PrivateS3 NLB IP address. This IP address can be found `here <https://docs.aviatrix.com/HowTos/privateS3_workflow.html#step-5-view-delete-privates3>`_. |dns_emulation| You can then run an AWS CLI command, such as "aws s3 ls", you should be able to see the list of S3 buckets on the Access Account in the region where a PrivateS3 gateway is launched. Below is another example of uploading a file to S3 using AWS CLI. :: ubuntu@ip-172-32-1-144:~$ aws s3 cp init-cfg.txt.3 s3://sxw-new-bucket-2 upload: ./init-cfg.txt.3 to s3://sxw-new-bucket-2/init-cfg.txt.3 To test on a Window's machine, you modify file at c:\Windows\System32\Drivers\etc\hosts. An example instruction is shown `here. <https://gist.github.com/zenorocha/18b10a14b2deb214dc4ce43a2d2e2992#2-modify-your-hosts-file>`_ How do I troubleshoot PrivateS3? ------------------------------------------- PrivateS3 combines FQDN feature and stateful firewall feature. 1. Go to Security > Egress Control > Egress FQDN Filter. There should be a tag automatically created. Click **Edit** to see if the desired S3 bucket name is configured. #. Go to Gateway, select one PrivateS3 gateway, and click **Edit**. Scroll down to Destination NAT to make sure the DNAT rule is configured. Does AWS S3 list command work? ----------------------------------------------- Yes. AWS S3 CLI "list" command requires s3.region.amazonaws.com in the bucket rule where region is represented. This is automatically populated by the Controller. Can Aviatrix Spoke Gateways be used for PrivateS3 function? --------------------------------------------------------------------------- No, Aviatrix Spoke Gateways cannot be used for PrivateS3 function. This is because PrivateS3 requires certain DNAT rule that conflict with Spoke Gateway forwarding function. Is an S3 endpoint required for PrivateS3? ------------------------------------------------ No. An S3 endpoint in the VPC where PrivateS3 gateways are deployed is not required for PrivateS3 to work. However, creating an S3 endpoint allows traffic to be forwarded to S3 service without going through the Internet. .. |sfc| image:: sfc_media/sfc .png :scale: 30% .. |s3_endpoint| image:: sfc_media/s3_endpoint .png :scale: 30% .. |sft_deployment| image:: sfc_media/sft_deployment .png :scale: 30% .. |sft_aviatrix| image:: sfc_media/sft_aviatrix .png :scale: 30% .. |s3_public_vif| image:: sfc_media/s3_public_vif .png :scale: 30% .. |dns_emulation| image:: sfc_media/dns_emulation .png :scale: 30% .. disqus:: <file_sep>.. meta:: :description: Upgrade Aviatrix Controller and Gateways :keywords: Style Guide, Documentation .. raw:: html <style> .wy-table-responsive table td, .wy-table-responsive table th { white-space: normal !important; } </style> <style> /* Heading styles */ h1 .toc-backref{ font-family: "Interstate Lt"; font-size: 32px; font-style: normal; font-weight: 300; color: #9B59B6 ; } h2 .toc-backref { font-family: "Interstate Lt"; font-size: 28px; font-style: normal; font-weight: 300; color: #9B59B6 !important; } h3 .toc-backref { font-family: "Avenir"; font-size: 24px; font-style: normal; font-weight: 300; color: #9B59B6 !important; } h4 .toc-backref{ font-family: "Interstate Lt"; font-size: 20px; font-style: normal; font-weight: 300; color: #9B59B6 !important; } h5 .toc-backref{ font-family: "Interstate Lt"; font-size: 18px; font-style: normal; font-weight: 300; color: #9B59B6 !important; } h6 * { font-family: "Avenir", sans-serif; font-size: 18px; font-style: normal; font-weight: 400; color: #9B59B6 !important; } </style> ============================================= Upgrade Aviatrix Controller and Gateways ============================================= .. contents:: :local: :backlinks: entry .. important:: Aviatrix strongly recommends you perform the tasks in the operations checklist including a dry run upgrade and system backup before upgrading your deployment of the Aviatrix network platform. Taking the time to perform dry runs and backing up your Aviatrix Platform configuration reduces the potential for issues during the upgrade and allows you to easily restore your configuration if there are issues after the upgrade. Correct any issues you find during your preparation before proceeding with an Aviatrix upgrade. If you cannot resolve all issues after following the preparation and dry run procedures, please open a ticket with `Aviatrix Support <https://support.aviatrix.com/>`_. Overview of the Aviatrix Controller and Gateways Upgrade =========================================================================== Aviatrix encourages you to keep your platform controller and gateways up to date to ensure you are operating the most secure and highest performing versions available. To facilitate less disruptive upgrades and reduce maintenance windows Aviatrix provides a rolling selective upgrade process. You can choose to upgrade all Aviatrix gateways in all regions simultaneously or select specific gateways and regions to upgrade in logical groups conforming to your network update policies and maintenance windows. Perform all preparatory tasks and verify all prerequisites are satisfied before performing Aviatrix upgrades. For more information, see Preparing to Upgrade the Aviatrix Network Platform. You can perform the following operations: * Performing a Platform Software Upgrade Dry Run * Performing a Gateway Software Upgrade Dry Run * Upgrading the Platform Software * Upgrading the Gateway Software * Rolling Back the Gateway Software * Upgrading the Gateway Image Incremental upgrades are only available in Aviatrix 6.5 and later releases. If you are upgrading from a release prior to 6.5, it is strongly recommended to open a ticket with `Aviatrix Support <https://support.aviatrix.com/>`_ before proceeding with any upgrade. This is necessary to ensure a thorough review and redesign of your network architecture to align with the latest best practices and supported versions. About Aviatrix Upgrade ---------------------------- There are two types of upgrades for the Aviatrix Platform and gateways: * **Software Upgrade** Platform and gateway software upgrades replace the relevant Aviatrix controller and gateway packages, configuration files, and binaries without disrupting network traffic or replacing the gateways. All software upgrades are hitless. * **Image Upgrade** Gateway image upgrades replace the current gateways. Traffic throughput is briefly disrupted during image upgrades. There are two types of patch updates: * **Security Patches** Security patches are released when security updates to underlying software components become available. Most security patches are hitless. Review the release notes for the patch to discover if the upgrade is hitless or disruptive. * **Software Patches** Software patches are released to address compatibility issues when they arise. You should apply the patches to the Aviatrix system when they become available if you are using any applications or configurations affected by the patch. Most software patches are hitless. Review the release notes for the patch to discover if the upgrade is hitless or disruptive. About Release Numbers ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Aviatrix release numbers follow the Major.Minor.Build format. For example, the release number 6.5.100 indicates: * 6 is the major release number. * 5 is the minor release number. * 100 is the build number. Each release type has different functionality parameters. * **Major** Includes new features and updates that affect the platform infrastructure and user interfaces. * **Minor** Includes modified and new small features and updates that may affect the platform infrastructure and user interfaces. * **Build** Corrected issues and feature enhancements. Upgrade Options ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ When you initiate an upgrade, Aviatrix automatically presents the most recently published build for the selected major or minor release version. **Upgrading Build Version** When you upgrade from one build version of a minor release to another build of the same minor release, the available version may skip over previously released build numbers. For example, you could upgrade from 6.6.100 to the latest build 6.6.900 and the system skips any intermediate builds. **Upgrading Minor Releases of Controller and Gateways** When upgrading from one minor version of a major release to another, it is necessary to follow a sequential upgrade process and cannot skip over intermediate minor release versions. Each minor release must be upgraded sequentially. For instance, when upgrading from 6.5.current to 6.8.latest, the intermediate releases 6.6.latest and 6.7.latest must be upgraded first. Valid upgrade paths to a new minor release are determined by the current build (the one currently running) and the latest build available on the Aviatrix server. **Upgrading Major Releases of Controller and Gateways** When upgrading from one major release to another, it is required to perform a sequential upgrade and not skip over intermediate major release versions. Each major release must be upgraded in sequence. You also need to go through all the minor releases within each major release before moving on to the next major release. For example, if you are currently on version 6.6.current and want to upgrade to version 8.0, you need to: #. Upgrade from 6.6 to the latest minor release in the 6.x series (for example, 6.6.current to 6.6.latest, then to 6.7.latest, then 6.7.latest to 6.8.latest, and so on) until you reach the latest minor release in the 6.x series. #. Once you have upgraded through all the minor releases in the 6.x series, you can then move on to the major release 7.0. #. From 7.0, continue upgrading through all the minor releases in the 7.x series until you reach the latest minor release in the 7.x series. #. Upgrade from the latest minor release in the 7.x series to version 8.0. Upgrade Parameter Definitions ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ **Platform Upgrade Window Parameter Definitions** - **Previous Version** Previous version of the controller. - **Current Version** Current version of the controller. - **Kernel Version** Version of the controller's Linux kernel. - **Release Versions** The upgrade option between the currently running version of the controller and the latest release available on the Aviatrix release server. For example, if you are running Aviatrix Platform 6.4.321 and the latest release available on the release server is 6.6.123 the Release Version field displays: UserConnect-6.6.123 (6.5,6.6). This indicates you must successively upgrade to 6.5 then upgrade to 6.6 to bring the platform up to the latest available version. - **Target Release Version** New version of the Aviatrix Platform to which you are upgrading. If you do not specify a release number, the system automatically selects the latest build of the major and minor release currently running on the platform controller. The version cannot be a version earlier than the release currently running on the platform controller. **Selective Gateway Upgrade Window Parameter Definitions** - **Current Version** Current software version running on the gateway. - **Previous Version** If the gateway has never been upgraded there is no version number. If the gateway has been upgraded at least once, this is the software version the gateway ran before the last upgrade. - **Target Version** Software version to which the gateway can be upgraded. It is the same version as the current version of the platform controller. - **Previous Image Version** If the gateway OS has never been upgraded there is no version number. If the gateway OS has been upgraded at least once, this is the image version the gateway ran before the last upgrade. - **Current Image Version** Current version of the gateway underlying OS. - **Target Image Version** Every gateway software version matches a unique recommended OS version that may change over time. This version is determined by a compatibility matrix. This field displays the OS version that will be used in case of an OS upgrade. - **Kernel Version** Version of the gateway OS kernel. - **Rollback Version** Software version to which the gateway can be rolled back. It is the same version as the previous version of the platform controller. - **Rollback Image Version** OS version that will be used in case of a gateway software rollback. Depending on the system compatibility matrix, this version can be higher, lower, or the same OS version currently running on the gateway. - **Account** Account attached to the gateway. - **Cloud** Cloud provider hosting the gateway. - **Region** Cloud region where the gateway is deployed. - **Gateway Type** Gateway persona: transit, spoke, or standalone. - **Gateway Role** Primary or secondary. Upgrading OpenVPN Users -------------------------------------------------------- Most upgrades do not impact connected OpenVPN users. In some cases, OpenVPN service needs to be restarted as part of the software upgrade. For example, upgrading to a new SSL version for security patches. In these cases, connected OpenVPN users are disconnected and need to reconnect after the upgrade. If a release requires stopping and restarting the service, the information is included in the release notes. Rollbacks do disrupt services. If there is only one OpenVPN gateway in service, all user connections are lost and users cannot reconnect until the gateway is available. If there are other OpenVPN gateways available, the disconnected users can attempt to log in again and land on the available gateways. Upgrading HA Gateways in an Active Mesh Topology -------------------------------------------------------- Gateway traffic is briefly affected and there is a drop in throughput when you perform a gateway image upgrade, and when a gateway software upgrade is rolled back. If Aviatrix ActiveMesh mode is enabled and only one gateway in an ActiveMesh pair is selected for an upgrade, the system gracefully drains the traffic away from one of the gateways so it can be replaced. If both gateways in an ActiveMesh pair are selected, the gateways are replaced simultaneously without any additional safeguards. * If the gateway has BPG peers, the BGP process is shut down and the protocol reconverges to elect alternative routes. * The tunnel interfaces are shut down. The controller recalculates alternative routes and distributes them to the gateways within the Aviatrix network. * If the selected gateway is a spoke, the controller modifies the underlay cloud routing table of the selected gateway that was acting as the next hop for the default route or RFC1918 routes. The HA peer is selected as the next hop. Prepare for the Aviatrix Upgrade =========================================================================== Aviatrix recommends you perform the tasks in the Operations Checklist before upgrading your deployment of the Aviatrix network platform. Taking the time perform dry runs and backing up your Aviatrix Platform configuration reduces the potential for issues during the upgrade and allows you to easily restore your configuration if there are issues after the upgrade. Correct any issues you find during your preparation before proceeding with an Aviatrix upgrade. Before you perform the Aviatrix Upgrade, perform the following tasks: #. Go through the `Upgrade Operations Checklist`_. #. Complete the `Preupgrade Tasks for Controller and Gateways`_. **Upgrade Operations Checklist** -------------------------------------------------------- Understanding the Release Contents ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To understand the contents and potential impact of upgrading to a specific software release, see `Aviatrix Controller and Gateway Software Release Notes <https://docs.aviatrix.com/HowTos/Controller_and_Software_Release_Notes.html>`_. To understand the contents and potential impact of upgrading to a specific image release, see `Aviatrix Controller and Gateway Image Release Notes <https://docs.aviatrix.com/HowTos/image_release_notes.html>`_. **Verify DNS Settings** The Aviatrix Controller must have a reliable DNS resolution service available. Aviatrix recommends using the default 8.8.8.8 for the DNS IP address. Using the default address is not required, but your network must be able to resolve public names and have uninterrupted access to the DNS name resolver. **AWS and Azure DNS Settings** If the controller is running on AWS or Azure, you can go to the controller Settings for the DNS and Disable the VPC or VNET DNS Server to force the controller to use 8.8.8.8. Verify Public Internet Access ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Verify access to the public internet from the Aviatrix Controller. The controller must be open for inbound traffic on port 443 and outbound traffic on port 22. Aviatrix recommends you enable security groups to restrict access. Go to the Network tab on the Diagnostics page under Troubleshooting and perform the following tasks. * Ping a widely known public hostname or IP address with the Controller Utility. * Ping www.security.aviatrix.com from TCP/443 with the Network Connectivity Utility. * Ping www.github.com from port TCP/443 with the Network Connectivity Utility. * Ping www.github.com from port TCP/22 with the Network Connectivity Utility. Verify Account Permissions and Access ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Go to the Accounts page and perform the following tasks. * Go to the Accounts Audit tab under Accounts and perform an Account Audit. Correct any reported issues. * Verify all accounts can access all connected cloud resources. * Verify the Aviatrix primary access account is available and that the account credentials are valid. * The IAM policies must be configured as recommended by Aviatrix. For more information, see Controller Instance Requirements. * If you are migrating your Aviatrix Platform Controller to a new image, verify the new image has all required accounts and permissions before migrating the controller. If you are restoring an image from a backup, the required accounts and permissions should all be available. Migration operations fail if there is not at least one Aviatrix backup file available. Verify Controller and Gateway Status ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Go to the Controller Dashboard and check the status of the Aviatrix Platform Controller and gateways. * Verify all gateways are up and the status is green. * Verify all tunnels are up and the status is green. AWS Specific Upgrade Checklist ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ **Verify Controller HA Version** You should be running the latest version of the Controller HA application before upgrading. If there is a newer version of Controller HA available, you should upgrade by disabling and reenabling the Controller HA feature. For more information, see https://docs.aviatrix.com/HowTos/controller_ha.html . **Verify Controller HA is Enabled** If you use Controller HA do not disable your HA configuration before upgrading the platform controller or gateways. If you do disable Controller HA before upgrading, the system deploys a new controller and restores the most recent backup. **Settings for t2 and t3 Instances** If your Aviatrix Controller is in AWS and running on a t2 or t3 instance type and you are planning a platform image upgrade, you must set the T2/T3 Unlimited attribute to enabled. For more information, see https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/burstable-performance-instances-unlimited-mode-concepts.html. Rules for Upgrading the Controller and Gateways ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ In addition to satisfying the requirements and following recommendations in the Operations Checklist, you must follow these rules when you are upgrading your Aviatrix Platform. * Upgrade the platform controller before upgrading the individual gateways. Platform controller versions cannot be behind gateway versions. * All gateways must be running the same version as the platform controller before you can upgrade the platform controller. * Follow the valid upgrade options. **Note:** The ability to run different gateway software versions facilitates rolling upgrades and software rollback functions. Running different software versions in your network is not a valid operational design implementation. Preupgrade Tasks for Controller and Gateways -------------------------------------------------------- Check the following prerequisites before you upgrade your controller and gateways: Before upgrading your controller and gateways, check the following prerequisites: Inspect the Current Controller CPU Utilization ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ . Inspect the current Controller's overall CPU and memory utilization from *CoPilot UI > Monitor > Performance* or from *Controller UI > DASHBOARD > Controller Metrics*: - Ensure that the CPU utilization of the Controller is no more than 50%. - Verify that the memory utilization of the Controller is no more than 60%. These utilization thresholds should be met before initiating the upgrade. . Check the Controller storage usage from *CoPilot UI > Monitor > Performance* or from *Controller UI > DASHBOARD > Controller Metrics*: - If you are upgrading to version 6.8, add additional disks. Add approximately 2.5MB per tunnel. - Ensure that the Controller has enough free disk space (at least 30% free) for the upgrade. - If the available disk space is insufficient, resize the Controller disk to an appropriate size before proceeding with the upgrade. Perform Controller and CoPilot Backup ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Perform a full backup of the CoPilot and the Controller: - Before initiating the upgrade process, it is crucial to perform a full backup of both Copilot and the Controller. - Save the previous backup in case it is needed for restoration purposes. For more details, see `Controller Backup and Restore <https://docs.aviatrix.com/HowTos/controller_backup.html>`_. Check for the Non-HA (High Availability) Gateways ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Check for the non-HA gateways: - Determine whether your environment includes any non-HA gateways. - Please note that the upgrade procedure provided below is designed for environments with HA gateways. - If your environment does not have HA gateways and extensively uses S2C, it is recommended to consult Aviatrix Support before proceeding with the upgrade. (Optional) Set up a Testing Environment ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Before proceeding with the upgrade in the production environment, it is highly recommended to establish a dedicated testing environment. This environment should closely mirror the production setup, including hardware, software, and configurations. By doing so, you can simulate the production conditions and assess the compatibility and performance of the upgraded software in a controlled manner. Only when the testing phase is successfully completed, and all identified issues have been resolved, should you proceed with the upgrade in the production environment. Procedures for Upgrading Aviatrix Controller and Gateways =========================================================================== This section outlines the general Controller and gateway upgrade instructions. General Controller and Gateways Upgrade Guidance -------------------------------------------------------- * Upgrade the Controller before upgrading the Gateways: - It is important to upgrade the Controller first, ensuring it is at the desired release version. - Once the Controller is successfully upgraded, proceed to upgrade the Gateways. * Upgrade from the current version to the latest release version within the current release: - Verify that the latest release version is available for your current release. - Consult the documentation specific to your current release version for detailed upgrade instructions. - Follow the provided steps to upgrade both the Controller and Gateways to the latest release version. * Upgrade from the current release (for example, version N) to a higher release (N+1 release): - Note that both the Controller and Gateways do not support multi-hop upgrades. - Upgrade sequentially from one adjacent version to another. - Determine the higher release version (N+1) to which you wish to upgrade. * Upgrade HA (High Availability) gateways first, then upgrade primary gateways: - To ensure proper continuity and system availability, it is recommended to upgrade HA gateways before upgrading primary gateways. This sequence minimizes any potential disruptions during the upgrade process. .. note:: It is recommended to schedule upgrades during a maintenance window when short periods of traffic disruption can be tolerated. In HA setups, the disruption should be minimal. .. list-table:: Upgrade Steps Outline :widths: 20 80 :header-rows: 1 * - Step No. - Description * - 1 - Back up Copilot and the Controller * - 2 - Upgrade Controller to the latest release version of the current release. * - 3 - Upgrade HA Gateways to the latest release version of the current release. * - 4 - Upgrade primary gateways to the latest release version of the current release. * - 5 - Upgrade Controller from current release (for example, version N) to a higher release (N+1 release). * - 6 - Upgrade HA Gateways from the current release (for example, version N) to a higher release (N+1 release). * - 7 - Upgrade primary gateways from the current release (for example, version N) to a higher release (N+1 release). Single-Version Upgrade for Controller and Gateways -------------------------------------------------------- A single-version Controller and Gateway upgrade refer to: * Upgrade from the current version to the latest release version within the current release. * Upgrade from the current release (for example, version N) to a higher release (N+1 release). Before you upgrade your Controller and Gateways, it is highly recommended to check the `Preupgrade Tasks for Controller and Gateways`_. - Before proceeding with the upgrade in the production environment, perform the upgrade in a testing environment. - It is important to upgrade the Controller first, ensuring it is at the desired release version. - Once the Controller is successfully upgraded, proceed to upgrade the Gateways. This section instructs on how to perform single-version Controller and Gateway upgrade. .. note:: Aviatrix recommends you perform a dry run upgrade on the platform controller and gateways before you execute the upgrade. A dry run is a sanity and health check that verifies there are no potential upgrade restrictions or conflicts before upgrading the software on the platform controller and selected gateways. Network issues, version conflicts, and other upgrade blocker issues are reported. Review the dry run upgrade results and correct any issues before proceeding with the upgrade. Performing a Platform Software Upgrade Dry Run ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To perform a platform software upgrade dry run: #. Click on Settings in the Aviatrix Controller main menu and select Maintenance. #. Optional. In the Platform Upgrade window, enter the target major and minor release number in the Release Version field. For example, 6.5. If you do not specify a release number, the system automatically selects the latest build of the major and minor release currently running on the platform controller. #. Click on Dry Run. #. After the progress meter closes, review the information in the Upgrade Result window. * If there are no errors, you can continue with the upgrade process. * If there are errors, you must resolve them before continuing with the upgrade. 5. Close the Upgrade Result window. Upgrade your Controller ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Perform the following steps to upgrade your Controller to a desired version: #. Log in to your Controller UI. #. Go to *SETTINGS > Maintenance*, and click *Upgrade* to open the upgrade panel. #. Under the *Platform Upgrade* section, enter the release number to which you want to upgrade. By default, it will upgrade to the latest version of the current release. Alternatively, you can specify a specific release version. #. Click *PLATFORM UPGRADE* to initiate the Controller upgrade process. Performing a Gateway Software Upgrade Dry Run ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To perform a gateway software upgrade dry run: #. Click on Settings in the Aviatrix Controller main menu and select Maintenance. Gateways can only be upgraded to the latest version of the platform controller software. The system automatically selects the platform Controller's current software version and the compatible gateway image version for that software version. #. In the Selective Gateway Upgrade window, click on Dry Run. #. After the progress meter closes, review the information in the Upgrade Result window. #. If there are no errors, you can continue with the upgrade process. #. If there are errors, you must resolve them before continuing with the upgrade. #. Close the Upgrade Result window. Upgrade your Gateways ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Perform the following steps to upgrade your Gateways to a desired version: #. Log in to your Controller UI. #. Go to **SETTINGS > Maintenance**, and click **Upgrade** to open the upgrade panel. #. Go to the *Selective Gateway Upgrade* section, and choose the gateways you want to upgrade from the dropdown list. However, please note that the system will upgrade the Controller first and then the gateways. #. Click **Dry Run** to check for potential issues. #. (Optional) If any issues are reported, address and fix them accordingly. #. Click **SOFTWARE UPGRADE** to upgrade the selected gateways. #. Wait for the upgrade process to complete and verify that you receive a successful upgrade message. .. note:: * Upgrade HA (High Availability) gateways first, then upgrade primary gateways: - To ensure proper continuity and system availability, it is recommended to upgrade HA gateways before upgrading primary gateways. This sequence minimizes any potential disruptions during the upgrade process. * After upgrading your HA gateways, upgrade the primary gateways. Multiple-Version Upgrade for Controller and Gateways -------------------------------------------------------- The multiple-version upgrade refers to: Upgrade Controller and Gateways from one version to another, where there are multiple intermediate versions between the current version and the target version. When upgrading from one minor version of a major release to another or from one major release to another, it is necessary to follow a sequential upgrade process and cannot skip over intermediate release versions. Before Upgrade ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Before you upgrade your Controller and Gateways, it is highly recommend to check the xref:controller-upgrade-workflow.adoc[General Controller and Gateways Upgrade Guidance]. - Before proceeding with the upgrade in the production environment, perform the upgrade in a testing environment. - It is important to upgrade the Controller first, ensuring it is at the desired release version. - Once the Controller is successfully upgraded, proceed to upgrade the Gateways. Perform the Pre-upgrade Tasks ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #. Check and perform all the pre-upgrade tasks. #. Check the Upgrade Checklist #. Perform all the items listed in the upgrade checklist. Check your Controller Version and Determine the Upgrade Path ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ You need to identify your current Controller release version and the major release version that you want to upgrade to. Determine the Controller version you are running: #. On CoPilot UI, click the caret (^) symbol on the top left. #. Look for the version number under *Aviatrix Controller*. .. note:: If you are currently using Aviatrix Controller version 6.5 or earlier, it is strongly recommended to open a ticket with `Aviatrix Support <https://support.aviatrix.com/>`_ before proceeding with any upgrade. This is necessary to ensure a thorough review and redesign of your network architecture to align with the latest best practices and supported versions. Determine your Controller License and Image ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Log into your cloud provider to check your license information and Controller image information. * If your Controller is not using the Bring Your Own License (BYOL) license or your Controller image is 2021 or earlier: #. Perform Controller Migration to use the latest BYOL controller image. #. If your Controller did not have a fixed EIP, go to **Controller UI > SETTINGS > CoPilot Association** to update your CoPilot Association to point to the new EIP of the Controller. * If your Controller is already using a BYOL license but does not have an ABUP (Aviatrix Bring Your Own Support) customer ID: #. Subscribe to the *Aviatrix Secure Networking Platform 2208-Universal 24x7 Support* subscription offer license . #. Apply your new Customer ID on the **Controller UI > SETTINGS > License** page. Upgrade Controller and Gateways ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Follow the outlined steps below to upgrade your Controller and Gateways basing on your start version and end version. For the detailed upgrade procedure for a single-version upgrade, see `Single-Version Upgrade for Controller and Gateways`_. Multiple-Version Upgrade Starting from Version 6.5 ******************************************************* .. list-table:: Multi-Version Upgrade Starting from Version 6.5 :widths: 30 30 50 :header-rows: 1 * - Upgrade Start Version - Upgrade End Version - Upgrade Steps * - 6.5 - 6.8 - #. Upgrade your Controller Software to version 6.6. #. Upgrade your gateway images [Note1]_ to version 6.6. #. Upgrade your Controller Software to version 6.7. #. Upgrade the software of gateways to version 6.7. #. Upgrade your Controller Software to version 6.8. #. Upgrade your gateway images [Note2]_ to version 6.8. * - 6.5 - 6.9 - #. Upgrade your Controller Software to version 6.6. #. Upgrade your gateway images [Note1]_ to version 6.6. #. Upgrade your Controller Software to version 6.7. #. Upgrade the software of gateways to version 6.7. #. Upgrade your Controller Software to version 6.8. #. Upgrade your gateway images [Note2]_ to version 6.8. #. Upgrade your Controller Software to version 6.9. #. Upgrade your gateway images [Note3]_ to version 6.9. .. note:: .. [Note1] Image upgrade required if the gateways are not running the latest released image for that version. See table below. .. [Note2] Image upgrade required for raccoon to strongswan gateway migration, gateway pull mode migration, and active-mesh migration. .. [Note3] There is a performance enhancement in the latest images for 6.9 and 7.0. Image upgrades are highly recommended for transit gateways and optional for spoke gateways. Gateway Images that Do not Require Additional Image Upgrade ************************************************************* .. list-table:: Gateway Images that Do not Require Additional Image Upgrade :widths: 13 16 16 16 16 18 :header-rows: 1 * - Upgrade-to-Version - AWS - Azure - GCP - OCI - Alibaba * - 6.6 - hvm-cloudx-aws-031222 - aviatrix-companion-gateway-v8 - gw-base-04102021 - aviatrix_gateway_54_1042_20210426_patched_v2 - hvm-cloudx-aliyun-122520 * - 6.7 - hvm-cloudx-aws-031722 - aviatrix-companion-gateway-v10u - gw-base-04092022 - aviatrix_gateway_54_20220323 - hvm-cloudx-aliyun-042322 * - 6.8 - hvm-cloudx-aws-080322 - aviatrix-companion-gateway-v13u - gw-base-08032022 - aviatrix_gateway_54_20220323 - hvm-cloudx-aliyun-062422 * - 6.9 - hvm-cloudx-aws-030923 - aviatrix-companion-gateway-v15u-6-9 - gw-base-08032022 - aviatrix_gateway_54_20220323 - hvm-cloudx-aliyun-062422 Multiple-Version Upgrade Starting from Version 6.6 ************************************************************* .. list-table:: Multi-Version Upgrade Starting from Version 6.6 :widths: 30 30 50 :header-rows: 1 * - Upgrade Start Version - Upgrade End Version - Upgrade Steps * - 6.6 - 6.8 - #. Upgrade your Controller Software to version 6.7. #. Upgrade the software of gateways to version 6.7. #. Upgrade your Controller Software to version 6.8. #. Upgrade your gateway images [Note2]_ to version 6.8. * - 6.6 - 6.9 - #. Upgrade your Controller Software to version 6.7. #. Upgrade the software of gateways to version 6.7. #. Upgrade your Controller Software to version 6.8. #. Upgrade your gateway images [Note2]_ to version 6.8. #. Upgrade your Controller Software to version 6.9. #. Upgrade your gateway images [Note3]_ to version 6.9. .. note:: .. [Note2] Image upgrade required for raccoon to strongswan gateway migration, gateway pull mode migration, and active-mesh migration. .. [Note3] There is a performance enhancement in the latest images for 6.9 and 7.0. Image upgrades are highly recommended for transit gateways and optional for spoke gateways. Multiple-Version Upgrade Starting from Version 6.7 ************************************************************ .. list-table:: Multi-Version Upgrade Starting from Version 6.7 :widths: 30 30 50 :header-rows: 1 * - Upgrade Start Version - Upgrade End Version - Upgrade Steps * - 6.7 - 6.8 - #. Upgrade your Controller Software to version 6.8. #. Upgrade your gateway images [Note2]_ to version 6.8. * - 6.7 - 6.9 - #. Upgrade your Controller Software to version 6.8. #. Upgrade your gateway images [Note2]_ to version 6.8. #. Upgrade your Controller Software to version 6.9. #. Upgrade your gateway images [Note3]_ to version 6.9. .. note:: .. [Note2] Image upgrade required for raccoon to strongswan gateway migration, gateway pull mode migration, and active-mesh migration. .. [Note3] There is a performance enhancement in the latest images for 6.9 and 7.0. Image upgrades are highly recommended for transit gateways and optional for spoke gateways. Multiple-Version Upgrade Starting from Version 6.8 ****************************************************************** .. list-table:: Multi-Version Upgrade Starting from Version 6.8 :widths: 30 30 50 :header-rows: 1 * - Upgrade Start Version - Upgrade End Version - Upgrade Steps * - 6.8 - 6.9 - #. Upgrade your Controller Software to version 6.9. #. Upgrade your gateway images [Note3]_ to version 6.9. .. note:: .. [Note3] There is a performance enhancement in the latest images for 6.9 and 7.0. Image upgrades are highly recommended for transit gateways and optional for spoke gateways. Upgrading the Gateway Image ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Traffic is briefly disrupted during the image upgrade in cluster configurations. **Note:** If ActiveMesh mode is not enabled or you are or running ActiveMesh 1.0, please open an Aviatrix Support ticket before attempting an upgrade. To perform a gateway image upgrade: #. Click on Settings in the Aviatrix Controller main menu and select Maintenance. #. In the Selective Gateway Upgrade window, select the gateways to be upgraded. The system automatically selects the platform controller current software version and the compatible gateway image version for that software version. #. Click on Image Upgrade. You can follow the status in the progress window. #. Verify the gateway upgrade by reviewing the gateway information in the Current Image Version column. Verify your Upgrade Status =========================================================================== After performing an upgrade, it is important to verify the upgrade status to ensure that it has been completed successfully. Verify Controller Upgrade Status -------------------------------------------------------- #. Go to your Controller upgrade window from **Controller UI > Settings > Maintenance > Upgrade**. #. Check if the upgrade window displays a message indicating that the Controller upgrade has been completed successfully. #. Ensure that the displayed Controller version is updated to the latest version. If the above conditions are met, it means that your Controller upgrade has been successfully completed. Verify Gateway Upgrade Status -------------------------------------------------------- After you have completed the upgrade, you can: #. Go to **Controller UI > Settings > Maintenance > Selective Gateway Upgrade** to check the gateway upgrade status. Alternatively, you can also go to *CoPilot UI > Gateways > Gateway Management > Upgrade Controller* to check the gateway upgrade status. #. Look for the **Update Status** field. * If the **Update Status** displays "complete" on the Controller UI or "Upgrade Completed" on the CoPilot UI, it indicates that the gateway upgrade has been successfully completed. Alternatively, you can check the current version on the *Controller Upgrade* card. * If the **Update Status** shows any other status, it means that your gateway upgrade has failed. Rolling Back Gateway Software =========================================================================== You can roll back gateway software upgrades to the previous version. However, you cannot roll back platform Controller, CA Access Gateway (CAAG), or CloudN upgrades. Gateway software rollbacks are briefly disruptive because the gateway is replaced. The gateway image version may also change during the software rollback. If the gateway to be rolled back is running the same image version before and after upgrading, when you roll back to the older software version the system creates a new gateway with the same image and the older software version. Gateway software rollbacks are briefly disruptive. You can only roll back the gateway software to the previous platform controller version running on the gateway. To perform a gateway software rollback: #. Click on Settings in the Aviatrix Controller main menu and select Maintenance. #. In the Selective Gateway Upgrade window, select the gateways to be rolled back. The system automatically selects the platform controller previous version for the rollback target. #. Click on Software Rollback. You can follow the status in the progress window. #. Verify the gateway software rollback by reviewing the gateway information in the Current Version column. Troubleshooting =========================================================================== In rare cases where the controller and a group of gateways are selected for upgrade and a fatal bug is discovered in the new software, a situation where the controller and gateways are stuck running different versions could develop. If this condition occurs assistance from Aviatrix Support is required. For example: * A controller and gateways are running version 6.5.200. * You upgrade the controller and a subset of gateways to 6.5.300. * You rollback the gateways to 6.5.200 because of a bug in the 6.5.300 software. * Now the controller is running 6.5.300 and all gateways are running 6.5.200, and the gateways cannot be upgraded to 6.5.300 because of the bug. * The bug is resolved in controller version 6.5.400, so you want to upgrade to 6.5.400 to resolve the issue. However, this is not supported because the controller and gateways must be running the same software version before the controller can be upgraded. * In this corner case, you must contact Aviatrix Support to upgrade the controller to the newer version. Support will diagnose the issue and provide the API operation required to perform the Controller upgrade. .. |upgrade.build.release| image:: selective_upgrade_media/upgrade.build.release.png :scale: 100% .. |upgrade.minor.release| image:: selective_upgrade_media/upgrade.minor.release.png :scale: 100% .. |upgrade.major.release| image:: selective_upgrade_media/upgrade.major.release.png :scale: 100% .. |upgrade.mixed.versions| image:: selective_upgrade_media/upgrade.mixed.versions.png :scale: 75% .. |upgrade.mixed.versions.fail| image:: selective_upgrade_media/upgrade.mixed.versions.fail.png :scale: 75% .. |upgrade.gateway.reroute| image:: selective_upgrade_media/upgrade.gateway.reroute.png :scale: 100% <file_sep> ================================= AWS IAM Policies ================================= The Aviatrix Controller in AWS is launched by `a CloudFormation script <https://docs.aviatrix.com/documentation/latest/getting-started/getting-started-guide-aws.html>`_. During the launch time, two IAM roles are created, aviatrix-role-ec2 and aviatrix-role-app. Two associated IAM policies are also created, `aviatrix-assume-role-policy <https://s3-us-west-2.amazonaws.com/aviatrix-download/iam_assume_role_policy.txt>`_ and `aviatrix-app-policy <https://s3-us-west-2.amazonaws.com/aviatrix-download/IAM_access_policy_for_CloudN.txt>`_. These two roles and their associated policies allow the Controller to use AWS APIs to launch gateway instances, create new route entries and build networks. As more features are added by Aviatrix with each release, the IAM Access Policy may need to be updated to allow the Controller to launch new services. This document shows you, an Aviatrix user, how to update your AWS IAM policies in the Aviatrix Controller and in AWS. .. note:: Please note that both the Aviatrix Controllers and the Aviatrix Gateways need access to the IAM policies. .. note:: Please ensure that IAM policies are consistent across all AWS accounts that the Controllers and Gateways are located in. Auditing and Updating AWS IAM Policies in the Aviatrix Controller ----------------------------------------------------------------------------------- To update your AWS IAM policies from your Aviatrix Controller, log in to the Controller. #. Select Accounts > Access Accounts from the lefthand menu. #. Select an AWS account and click **Audit** near to the top of the page. If this account needs an update, text under Account Audit at the top of the page reads "[Account Name] is not using the latest IAM policy." #. If the account is not using the latest IAM policy, click **Update Policy**. The latest IAM policy will be updated for this account. Updating IAM Policies in AWS ----------------------------------------- This section describes how to update IAM policies from your AWS Console. In AWS, you can update IAM policies by replacing them. Follow these steps to update IAM policies **for each AWS account** that you set up in the Controller. Start with your `primary account <onboarding_faq.html#what-is-the-aviatrix-primary-access-account>`__ (the account you set up during onboarding) and then on to each `secondary account <aviatrix_account.html#setup-additional-access-account-for-aws-cloud>`_ if there is any. #. Log in to your account on the AWS Console. #. Click on the Services dropdown menu in the top left and select **IAM**. #. Click **Policies** on the left. #. On the Policies page, enter "aviatrix-app-policy" in the Search field. Click **aviatrix-app-policy** in the table. #. On the Summary page for **aviatrix-app-policy**, click **Edit policy** at the top of the table. #. On the Edit aviatrix-app-policy page, select the **JSON** tab. #. Replace the entire text by the latest policy in `this link <https://s3-us-west-2.amazonaws.com/aviatrix-download/IAM_access_policy_for_CloudN.txt>`__ #. Click **Review policy** to make sure there is no syntax error. #. Click **Save changes** to apply the new "aviatrix-app-policy." #. It may take a few minutes for the policy to take effect. .. disqus:: <file_sep> ================================= OpenVPN® with SAML Authentication ================================= Overview ----------------------- There are two methods to authenticate a VPN client: `Okta API Token <https://docs.aviatrix.com/HowTos/HowTo_Setup_Okta_for_Aviatrix.html>`_ or an Aviatrix SAML client. This document shows you how to set up VPN authentication using an Aviatrix SAML client. The Aviatrix user VPN is one of the OpenVPN® based remote VPN solutions that provides a VPN client with SAML authentication capability. This step-by-step guide shows you how to use an Aviatrix SAML client to authenticate an IdP. When a SAML client is used, the Aviatrix Controller acts as the service provider (SP) that redirects browser traffic from the client to the IdP for authentication. For different IdPs, there will be links to each individual IdP integration. Pre-Deployment Checklist --------------------------------------- Before configuring the SAML integration between Aviatrix and your IdP, make sure the following is completed: #. The `Aviatrix Controller <#pdc-21>`__ is set up and running. #. You have a valid `IdP account <#pdc-22>`__ with admin access. #. You have `Downloaded and installed <#pdc-23>`__ the Aviatrix SAML client. .. _PDC_21: Aviatrix Controller ####################### If you haven’t already deployed the Aviatrix Controller, follow `these instructions <../StartUpGuides/aviatrix-cloud-controller-startup-guide.html>`__ to deploy the Aviatrix Controller. .. _PDC_22: IdP Account ############### An identity provider (IdP) is any provider that supports a SAML endpoint like `Okta <./SAML_Integration_Okta_IdP.html>`__, `OneLogin <./SAML_Integration_OneLogin_IdP.html>`__, `Google <./SAML_Integration_Google_IdP.html>`__, `AWS SSO <./SAML_Integration_AWS_SSO_IdP.html>`__, `Azure AD <./SAML_Integration_Azure_AD_IdP.html>`__, and `PingOne <./SAML_Integration_PingOne_IdP.html>`__. Administrator access is required to create IdP endpoints for SAML. For a list of supported IdPs, see `IdP-specific SAML App Integration <https://docs.aviatrix.com/HowTos/Controller_Login_SAML_Config.html#IdP-specific>`_. .. _PDC_23: Aviatrix VPN Client ####################### All users must use the Aviatrix VPN client to connect to the system. Download the client for your OS `here <http://docs.aviatrix.com/Downloads/samlclient.html>`__. Configuration -------------------- The configuration consists of 8 parts: 1. Create a `temporary Aviatrix SP Endpoint <#config-31>`__ for Aviatrix. 2. Create a `SAML IdP App <#config-32>`__ with specific IdP. 3. Retrieve `IdP Metadata <#config-33>`__ from IdP. 4. Update the `Aviatrix SP Endpoint <#config-34>`__ with IdP metadata. 5. `Test the SAML Integration <#config-35>`__. 6. Launch an `Aviatrix Gateway <#config-36>`__. 7. Create `Aviatrix VPN user(s) <#config-37>`__. 8. `Test VPN Connectivity <#config-38>`__. .. _Config_31: Creating a Temporary Aviatrix SP Endpoint ########################################### .. note:: This step is usually completed by the Aviatrix admin. This endpoint will be updated later on in the guide; at this step, we will be using placeholder values. Choose an endpoint name for your Aviatrix SAML endpoint which will be used throughout the guide. This guide will use ``aviatrix_saml_controller`` as an example for the endpoint name. #. Log in to the Aviatrix Controller and go to OpenVPN > Advanced > SAML > click **+ Add New**. +-------------------------+--------------------------------------------------------+ | Field | Value | +=========================+========================================================+ | Endpoint Name | Enter a unique identifier for the service provider. | +-------------------------+--------------------------------------------------------+ | IPD Metadata Type | Text or URL (depending on what was | | | provided by the SAML provider). | | | For now, choose URL. | +-------------------------+--------------------------------------------------------+ | IdP Metadata Text/URL | IdP metadata URL/Text copied from the SAML | | | provider configuration | | | For now, put in a placeholder URL, | | | such as "https://www.google.com." | +-------------------------+--------------------------------------------------------+ | Entity ID | Select `Hostname` for now. | +-------------------------+--------------------------------------------------------+ | Sign Authn Requests | Sign the cert when requesting to IDP from client. | +-------------------------+--------------------------------------------------------+ | Access | (Removed from 6.0 and later) Select admin or read-only | | | access. | +-------------------------+--------------------------------------------------------+ | Custom SAML Request | For now leave blank, depending on your specific | | Template | IdP, you may have to mark this checkbox. | +-------------------------+--------------------------------------------------------+ |create-endpoint| .. note:: Each endpoint only supports one type of access. If you need admin and read-only access, create two separate SAML apps. #. Click **OK**. #. Depending on your IdP provider, you may need to upload SP metadata. After temporary SAML endpoint is created: - Right-click the **SP Metadata** button next to the SAML endpoint and save the file to your local machine. - Click **SP Metadata** and copy the SP metadata as text. .. _Config_32: Creating a SAML App for Aviatrix with the IdP ############################################### .. note:: This step is usually done by the IdP administrator. This section shows only a generalized process for creating a SAML application. Refer to the `IdP-specific SAML App Integration <#IdP-integration>`_ section for links to detailed steps with each particular IdP. Create a SAML 2.0 app with the IdP Provider with the following values. #. Assertion Consumer Service URL* #. Audience URI(Entity ID)* #. SP Metadata URL* #. SP Login URL* #. Default RelayState* = <empty> #. Application username = IdP username You can find these values in your Controller. Go to Settings > Controller > select the SAML Login tab. * Assertion Consumer Service URL (ACS URL) - Click **SP ACS URL** in the URL column of the SAML Endpoints table. * Audience URI (Entity ID) Click **SP Metadata** to open the metadata. Find this URL listed by "entityID." |imagespmetadata| * SP Metadata URL - Click **SP Metadata** to open this metadata. You can also click the download icon next to SP Metadata in the SAML Endpoints table to download the metadata file. * SP Login URL - Click **Test** to open this URL. RelayState is currently not used by the Aviatrix SP. |values-in-controller| The following SAML attributes are expected: #. FirstName #. LastName #. Email (unique identifier for SAML) .. note:: These values are case sensitive. .. _IdP_Integration: **IdP-specific SAML App Integration** .. note:: You will require administrator access to create IdP endpoints for SAML. These are guides with specific IdP's that were tested to work with Aviatrix SAML integration: #. `AWS SSO <./SAML_Integration_AWS_SSO_IdP.html>`__ #. `Azure AD <./SAML_Integration_Azure_AD_IdP.html>`__ #. `Centrify <./SAML_Integration_Centrify_IdP.html>`__ #. `Google <./SAML_Integration_Google_IdP.html>`__ #. `Okta <./SAML_Integration_Okta_IdP.html>`__ #. `OneLogin <./SAML_Integration_OneLogin_IdP.html>`__ #. `PingOne <./SAML_Integration_PingOne_IdP.html>`__ Other tested IdPs include: VmWare VIDM, ForgeRock's OpenAM etc. .. _Config_33: Retrieving IdP Metadata ########################## After creating the IdP, you need to retrieve IdP Metadata either in URL or text from the IdP application created in the previous step. #. AWS SSO - provides IdP metadata URL, needs a custom SAML request template, and will need to provide SP metadata file from Aviatrix. #. Azure AD - provides IdP metadata URL and needs a custom SAML request template. #. Centrify - provides IdP metadata URL and will need to provide SP metadata text from Aviatrix. #. Google - provides IdP metadata text. #. Okta - provides IdP metadata text. #. OneLogin - provides IdP metadata URL. #. PingOne - provides IdP metadata URL. .. _Config_34: Updating Aviatrix SP Endpoint ############################### .. note:: This step is usually completed by the Aviatrix admin. Take note of the IdP Metadata type along with Text/URL your IdP provides, and if you need a custom SAML request template in the previous section. #. In your Controller, go to OpenVPN® > Advanced > on the SAML tab, click **+ Add New**. +----------------------------+----------------------------------------------------------+ | Field | Description | +----------------------------+----------------------------------------------------------+ | Endpoint Name | Unique name that you chose in the "Creating a Temporary | | | Aviatrix SP Endpoint" section above. | +----------------------------+----------------------------------------------------------+ | IPD Metadata Type | Text or URL (depending on what was | | | provided by the SAML provider). | +----------------------------+----------------------------------------------------------+ | IdP Metadata Text/URL | Paste in the IdP metadata URL/Text | | | copied from the SAML provider | | | configuration. | +----------------------------+----------------------------------------------------------+ | Entity ID | Select **Hostname** or **Custom**. | +----------------------------+----------------------------------------------------------+ | Custom Entity ID | Only visible if the Entity ID is **Custom**. | +----------------------------+----------------------------------------------------------+ | Access | Select admin or read-only access. | +----------------------------+----------------------------------------------------------+ | Custom SAML Request | Depending on your specific IdP, | | Template | you may have to mark this checkbox. | | | Refer to `IdP-specific Integration <#IdP-integration>`_. | +----------------------------+----------------------------------------------------------+ .. note:: `Hostname` is the default for Entity ID, but if you have other apps using the same hostname, use a custom Entity ID. .. _Config_35: Testing the Integration ######################## .. note:: Have an instance of the VPN client running. If you do not, it might throw a warning. #. Log in to the Aviatrix Controller. #. Select OpenVPN® > Advanced on the left sidebar. #. Stay on the SAML tab. #. Select the row that was created in the previous step (that includes your endpoint name). #. Click on the **Test** action. #. You should be redirected to the IdP. Now, you can log in and should be redirected back to the Controller. .. _Config_36: Launching Aviatrix Gateway ########################### .. note:: This step is usually completed by the Aviatrix admin. 1. In your Controller, go to Gateway > click **+ New Gateway**. 2. Select the appropriate values for where to provision this Gateway. 3. Mark the **VPN Access** checkbox, the **Advanced** checkbox, and then the **Enable SAML** checkbox. |gateway-options| 4. Leave the default settings for everything else. 5. Click **OK** to launch the gateway. .. _Config_37: Creating VPN User(s) ###################### +----------------------------+-----------------------------------------+ | Field | Description | +----------------------------+-----------------------------------------+ | VPC ID | Select the VPC/VNet where the Gateway | | | was created. | +----------------------------+-----------------------------------------+ | LB/Gateway Name | Select the appropriate load balancer | | | or gateway. | +----------------------------+-----------------------------------------+ | User Name | Name of the VPN user | +----------------------------+-----------------------------------------+ | User Email | Any valid email address (this is where | | | the cert file will be sent). | | | Alternatively, you can download the cert| | | if you don't enter an email. | +----------------------------+-----------------------------------------+ | SAML Endpoint | Select the SAML endpoint. | +----------------------------+-----------------------------------------+ .. note:: SAML supports shared certificates. You can share the certificate among VPN users or create more VPN users. .. _Config_38: Testing VPN Connectivity ######################### 1. Download and install the Aviatrix VPN client for your platform from `here <https://aviatrix-systems-inc-docs.readthedocs-hosted.com/Downloads/samlclient.html>`__. 2. Launch the Aviatrix client and load the certificate ("Load config") that you downloaded/received from email on the Testing the Integration section above. 3. Click **Connect**. This should launch the browser instance and prompt you for authentication, if not already logged in. 4. If the connection is successful, the client icon should turn green. 5. You can ensure VPN connectivity by trying to ping the private IP of the gateway you launched or any other instance in the same cloud network. ============================ SAML Profile as an Attribute ============================ The VPN user gets a VPN profile rule configured to the one that is attached to the VPN User from the OpenVPN > Profiles page. If preferred, this can also be passed as attribute from the IDP. The IDP could send the "Profile" attribute along with the existing "FirstName," "LastName," and "Email" attributes. If the "Profile" attribute is set and the value sent from the IDP matches with any of the profile names configured from the Controller, the profile rules are applied accordingly. Note that if the IDP sends an invalid or empty Profile attribute, the default profile association is used. This way Profile associations can be configured at IDP instead of configuring at the Controller. Multiple Profiles is supported when using Profile as attribute starting with `release 5.4 <https://docs.aviatrix.com/HowTos/UCC_Release_Notes.html#r5-4-1066-4-1-2020>`__. Multiple profiles can be added separated by commas. Note that mixing of base rules is not allowed. The profile association can be verified from the Dashboard page after the VPN user has connected. These are guides with specific IdP's that were tested to work with Aviatrix SAML integration: #. `Okta <./Setup_Okta_SAML_Profile_Attribute.html>`__ #. `PingOne <./Setup_PingOne_SAML_Profile_Attribute.html>`__ OpenVPN is a registered trademark of OpenVPN Inc. .. |image3-1-1| image:: SSL_VPN_SAML_media/image3-1-1.png :scale: 70% .. |create-endpoint| image:: SSL_VPN_SAML_media/create-endpoint.png :scale: 60% .. |values-in-controller| image:: SSL_VPN_SAML_media/values-in-controller.png :scale: 60% .. |gateway-options| image:: SSL_VPN_SAML_media/gateway-options.png :scale: 60% .. |imagespmetadata| image:: SSL_VPN_SAML_media/SPMetadata.png :scale: 80% .. disqus:: <file_sep> .. role:: orange .. raw:: html <style> .orange { color: #FFB366; } </style> ===================================================================== Aviatrix Gateway to pfSense ===================================================================== Overview ---------------- This document describes how to configure an IPsec tunnel between an Aviatrix Gateway and a pfSense firewall using Aviatrix Site2Cloud. Adding a Site2Cloud Tunnel in Aviatrix Controller ------------------------------------------------------------ 1. Log in to your Aviatrix Controller. 2. Select Site2Cloud on the left navigation bar. 3. Click **+ Add New** near the top of the Site2Cloud tab. 4. Under Add a New Connection, enter the following: +-------------------------------+------------------------------------------+ | Field | Expected Value | +===============================+==========================================+ | VPC ID / VNet Name | Select the VPC/VNet where this tunnel | | | will terminate in the cloud. | +-------------------------------+------------------------------------------+ | Connection Type | Unmapped unless there is an | | | overlapping CIDR block. | +-------------------------------+------------------------------------------+ | Connection Name | Name this connection. This connection | | | represents the connectivity to the | | | edge device. | +-------------------------------+------------------------------------------+ | Remote Gateway Type | Generic | +-------------------------------+------------------------------------------+ | Tunnel Type | UDP | +-------------------------------+------------------------------------------+ | Algorithms | Unmark this checkbox | +-------------------------------+------------------------------------------+ | Encryption over ExpressRoute/ | Unmark this checkbox | | DirectConnect | | +-------------------------------+------------------------------------------+ | Enable HA | Unmark this checkbox | +-------------------------------+------------------------------------------+ | Primary Cloud Gateway | Select the Gateway where the tunnel will | | | terminate in this VPC/VNet. | +-------------------------------+------------------------------------------+ | Remote Gateway IP Address | IP address of the pfSense device. | +-------------------------------+------------------------------------------+ | Pre-shared Key | Optional. Enter the pre-shared key for | | | this connection. If nothing is entered | | | one will be generated for you. | +-------------------------------+------------------------------------------+ | Remote Subnet | Enter the CIDR representing the network | | | behind the edge device that this tunnel | | | supports. | +-------------------------------+------------------------------------------+ | Local Subnet | The CIDR block that should be advertised | | | on pfSense for the cloud network (will | | | default to the VPC/VNet CIDR block) | +-------------------------------+------------------------------------------+ 5. Click **OK**. Creating an IPsec Tunnel in pfSense --------------------------------------------- 1. Log in to your pfSense dashboard. 2. In the VPN menu, select **IPsec**. 3. Click **+ Add P1**. 4. Populate the fields according to your preferences. The important fields are (with :orange:`extra emphasis` on a few key fields): *General Information* +-------------------------------+------------------------------------------+ | Field | Expected Value | +===============================+==========================================+ | Key exchange version | IKEv1 | +-------------------------------+------------------------------------------+ | Remote Gateway | Enter the public IP address of the | | | Aviatrix Gateway here. | +-------------------------------+------------------------------------------+ *Phase 1 Proposal* +-------------------------------+------------------------------------------+ | Field | Expected Value | +===============================+==========================================+ | Authentication Method | Mutual PSK | +-------------------------------+------------------------------------------+ | My identifier | My IP address | +-------------------------------+------------------------------------------+ | :orange:`Peer identifier` | :orange:`IP address. Enter the Public` | | | :orange:`IP address of the remote` | | | :orange:`Aviatrix Gateway` | +-------------------------------+------------------------------------------+ | Pre-Shared Key | Enter the PSK from the Site2Cloud tunnel | | | creation step. | +-------------------------------+------------------------------------------+ *Phase 1 Proposal (Algorithms)* +-------------------------------+------------------------------------------+ | Field | Expected Value | +===============================+==========================================+ | Encryption Algorithm | AES - 256 bits | +-------------------------------+------------------------------------------+ | Hash Algorithm | SHA1 | +-------------------------------+------------------------------------------+ | DH Group | 2 (1024 bit) | +-------------------------------+------------------------------------------+ *Advanced Options* +-------------------------------+------------------------------------------+ | Field | Expected Value | +===============================+==========================================+ | Disable rekey | :orange:`Unchecked` | +-------------------------------+------------------------------------------+ |imageExamplePfSenseConfiguration| 5. Click **Save**. 6. Add a Phase 2 entry. |imageExamplePfSensePhase2Config| 7. Save the Phase 2 entry. 8. Test to make sure the tunnel is up. .. |imageExamplePfSenseConfiguration| image:: CloudToPfSense_media/IKEv1.png .. |imageExamplePfSensePhase2Config| image:: CloudToPfSense_media/example_phase2_config.png .. disqus:: <file_sep> ============================================================== Ingress Protection via Aviatrix Transit FireNet with Fortigate ============================================================== This document illustrates a widely deployed architecture for Ingress traffic inspection/protection firewall that leverages AWS Load Balancers, `Transit FireNet for AWS <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html>`_ and `Fortigate VM in AWS <https://docs.aviatrix.com/HowTos/config_FortiGateVM.html#example-config-for-fortigate-vm-in-aws>`_. Ingress traffic from Internet forwards to firewall instances first in Aviatrix Transit FireNet VPC and then reaches to application servers as shown in the diagram below. In this design pattern, each firewall instance must perform #. Source NAT (SNAT) on its LAN interface that connects to the Aviatrix FireNet gateway #. Destination NAT (DNAT) to the IP of application server or application load balancer |transit_firenet_ingress| .. note:: This design pattern also supports multiple of firewalls (scale out fashion) for each Aviatrix Transit FireNet gateway. This document describes a step-by-step Ingress Protection via Aviatrix Transit FireNet with Fortigate deployment workflow for R6.1 and later. In this note you learn how to: #. Workflow on Transit FireNet for AWS #. Workflow on AWS Application Load Balancer #. Workflow on Firewall instances - Fortigate For more information about Transit FireNet, please check out the below documents: `Transit FireNet FAQ <https://docs.aviatrix.com/HowTos/transit_firenet_faq.html>`_ `Firewall Network Design Patterns <https://docs.aviatrix.com/HowTos/firewall_network_design_patterns.html>`_ Prerequisite ==================== First of all, `upgrade <https://docs.aviatrix.com/HowTos/inline_upgrade.html>`_ Aviatrix Controller to at least version 6.1 In this example, we are going to deploy the below VPCs in AWS - Aviatrix Transit FireNet VPC (i.e. 10.70.0.0/16) - Aviatrix Spoke VPC for Application (i.e. 10.3.0.0/16) Workflow on Transit FireNet for AWS ===================================== Refer to `Transit FireNet Workflow for AWS doc <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html>`_ for the below steps. Please adjust the topology depending on your requirements. Step 1.1. Deploy VPCs for Transit FireNet and Spoke for Applicaton ----------------------------------------------------------------- - Create an Aviatrix Transit VPC by utilizing Aviatrix feature `Create a VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ with Aviatrix FireNet VPC option enabled - Create an Aviatrix Spoke VPC for Application by utilizing Aviatrtix feature `Create a VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ as the previous step or manually deploying it in AWS portal. Moreover, feel free to use your existing VPC. Step 1.2. Deploy Aviatrix Multi-Cloud Transit Gateway and HA ---------------------------------------------------------- - Follow this step `Deploy the Transit Aviatrix Gateway <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html#step-2-deploy-the-transit-aviatrix-gateway>`_ to launch Aviatrix Transit gateway and enable HA in Transit FireNet VPC - Connected Transit mode is not necessary for this Ingress inspection solution. Step 1.3. Deploy Spoke Gateway and HA ----------------------------------- - Follow this step `Deploy Spoke Gateways <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html#step-3-deploy-spoke-gateways>`_ to launch Aviatrix Spoke gateway and enable HA in Spoke VPC for Application Step 1.4. Attach Spoke Gateways to Transit Network ------------------------------------------------ - Follow this step `Attach Spoke Gateways to Transit Network <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html#step-4-attach-spoke-gateways-to-transit-network>`_ to attach Spoke Gateways to Transit Gateways Step 1.5. Configure Transit Firewall Network ------------------------------------------------ - `Configure Transit Firewall Network <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html#step-6-configure-transit-firewall-network>`_ - Adding spoke to the Inspected box for traffic inspection in 2> Manage FireNet Policy is not necessary for this Ingress solution as inbound traffic hit firewall instances first. Step 1.6. Launch and Associate Firewall Instance ------------------------------------------------ - `Subscribe Firewall Vendor in AWS Marketplace <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html#step-7-subscribe-firewall-vendor-in-aws-marketplace>`_ for Fortigate Next Generation Firewall - Launch Fortigate Firewall instance for each Aviatrix Transit FireNet gateway by following this `step <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html#fortigate-specifications>`_ +--------------------------+-------------------------------------------------------------+ | **Example setting** | **Example value** | +--------------------------+-------------------------------------------------------------+ | Firewall Image | Fortinet FortiGate Next-Generation Firewall | +--------------------------+-------------------------------------------------------------+ | Firewall Image Version | 6.4.2 | +--------------------------+-------------------------------------------------------------+ | Firewall Instance Size | c5.xlarge | +--------------------------+-------------------------------------------------------------+ | Egress Interface Subnet | Select the subnet whose name contains "FW-ingress-egress". | +--------------------------+-------------------------------------------------------------+ | Key Pair Name (Optional) | The .pem file name for SSH access to the firewall instance. | +--------------------------+-------------------------------------------------------------+ | Attach | Check | +--------------------------+-------------------------------------------------------------+ - Wait for a couple of minutes for the Fortigate Firewall instances to turn into Running Instance state - Will walk through how to set up basic configuration for FortiGate (Fortinet) in the later section 'Workflow on Firewall instances - Fortigate'. Please move on to the next section 'Workflow on AWS Application Load Balancer' first Workflow on AWS Application Load Balancer ========================================= This workflow example describes how to #. place an internet-facing AWS Load Balancer to load balance traffic to firewall instances in Transit FireNet #. place an internal AWS Load Balancer to load balance traffic to private application server in Application Spoke #. set up the related network components and private application web server with HTTP and port 8080 Please adjust the settings depending on your requirements. Step 2.1. Create an AWS Application Load Balancer with scheme Internet-facing ----------------------------------------------------------------------------- In Transit FireNet VPC, create an internet-facing AWS Application Load Balancer by following the steps below: - Select Application Load Balancer HTTP/HTTPS |Ingress_ALB| - Select items as follows in Step 1: Configure Load Balancer +---------------------+------------------------+-------------------------------------------------------------------+ | **Section** | **Field** | **Value** | +---------------------+------------------------+-------------------------------------------------------------------+ | Basic Configuration | Scheme | internet-facing | +---------------------+------------------------+-------------------------------------------------------------------+ | | IP address type | ipv4 | +---------------------+------------------------+-------------------------------------------------------------------+ | Listeners | Load Balancer Protocol | HTTP | +---------------------+------------------------+-------------------------------------------------------------------+ | | Load Balancer Port | 8080 | +---------------------+------------------------+-------------------------------------------------------------------+ | Availability Zones | VPC | Aviatrix Transit FireNet VPC | +---------------------+------------------------+-------------------------------------------------------------------+ | | Availability Zones | select the subnet with *-Public-FW-ingress-egress-AZ-* in each AZ | +---------------------+------------------------+-------------------------------------------------------------------+ |Ingress_Internet_ALB_Step_1_Configure_Load_Balancer| - Create a security group with Protocol TCP and Port 8080 in Step 3: Configure Security Groups |Ingress_Internet_ALB_Step_3_Configure_Security_Groups| - Select items as follows in Step 4: Configure Routing +--------------------------------+---------------+-------------------+ | **Section** | **Field** | **Value** | +--------------------------------+---------------+-------------------+ | Target group | Target group | New target group | +--------------------------------+---------------+-------------------+ | | Target type | Instance | +--------------------------------+---------------+-------------------+ | | Protocol | HTTP | +--------------------------------+---------------+-------------------+ | | Port | 8080 | +--------------------------------+---------------+-------------------+ | Health checks | Protocol | HTTPS | +--------------------------------+---------------+-------------------+ | | Path | / | +--------------------------------+---------------+-------------------+ | Advanced health check settings | Port | override with 443 | +--------------------------------+---------------+-------------------+ | | Success codes | 302 | +--------------------------------+---------------+-------------------+ |Ingress_Internet_ALB_Step_4_Configure_Routing| - Select firewall instances and click the button "Add to registered" in Step 5: Register Targets |Ingress_Internet_ALB_Step_5_Register_Targets_1| - Confirm the selected firewall instances are placed under the section "Registered targets" |Ingress_Internet_ALB_Step_5_Register_Targets_2| - Review the configuration in Step 6: Review |Ingress_Internet_ALB_Step_6_Review| - Wait for a couple of minutes and check firewall instances' healthy Status behind AWS Application Load Balancer |Internet_ALB_WEB_HTTP_8080_tg_healthcheck| .. note:: Targets healthy status behind AWS load balancer can be found on the page "EC2 -> Target groups -> selecting the target group -> Targets" in AWS portal. Step 2.2. Launch an Apache2 Web server in Application Spoke ----------------------------------------------------------- In Application Spoke, create a virtual machine and install Apache2 HTTP Server with custom port 8080 as a web application server. +---------------------+-------------------+ | **Example setting** | **Example value** | +---------------------+-------------------+ | Protocol | HTTP | +---------------------+-------------------+ | Port | 8080 | +---------------------+-------------------+ .. Note:: Refer to `Install The Latest Apache2 HTTP Server ( 2.4.34 ) On other opensource OS Servers <https://websiteforstudents.com/install-the-latest-apache2-2-4-34-on-ubuntu-16-04-17-10-18-04-lts-servers/>`_ to install Apache2 HTTP Server Refer to `How To Change Apache Default Port To A Custom Port <https://www.ostechnix.com/how-to-change-apache-ftp-and-ssh-default-port-to-a-custom-port-part-1/>`_ to use custom port 8080 Step 2.3. Create an AWS Application Load Balancer with scheme Internal ---------------------------------------------------------------------- In Application Spoke VPC, create an internal AWS Application Load Balancer by refering to the steps below: - Select Application Load Balancer HTTP/HTTPS |Ingress_ALB| - Select items as follows in Step 1: Configure Load Balancer +---------------------+------------------------+-------------------------------------------------------------------+ | **Section** | **Field** | **Value** | +---------------------+------------------------+-------------------------------------------------------------------+ | Basic Configuration | Scheme | internal | +---------------------+------------------------+-------------------------------------------------------------------+ | | IP address type | ipv4 | +---------------------+------------------------+-------------------------------------------------------------------+ | Listeners | Load Balancer Protocol | HTTP | +---------------------+------------------------+-------------------------------------------------------------------+ | | Load Balancer Port | 8080 | +---------------------+------------------------+-------------------------------------------------------------------+ | Availability Zones | VPC | Aviatrix Spoke VPC for application | +---------------------+------------------------+-------------------------------------------------------------------+ | | Availability Zones | select the subnet where private application servers locate | +---------------------+------------------------+-------------------------------------------------------------------+ |Ingress_Internal_ALB_Step_1_Configure_Load_Balancer| - Create a security group with Protocol TCP and Port 8080 in Step 3: Configure Security Groups - Select items as follows in Step 4: Configure Routing +--------------------------------+---------------+-------------------+ | **Section** | **Field** | **Value** | +--------------------------------+---------------+-------------------+ | Target group | Target group | New target group | +--------------------------------+---------------+-------------------+ | | Target type | Instance | +--------------------------------+---------------+-------------------+ | | Protocol | HTTP | +--------------------------------+---------------+-------------------+ | | Port | 8080 | +--------------------------------+---------------+-------------------+ | Health checks | Protocol | HTTP | +--------------------------------+---------------+-------------------+ | | Path | / | +--------------------------------+---------------+-------------------+ | Advanced health check settings | Port | traffic port | +--------------------------------+---------------+-------------------+ | | Success codes | 200 | +--------------------------------+---------------+-------------------+ - Select private application server and click the button "Add to registered" in Step 5: Register Targets - Review the configuration in Step 6: Review |Ingress_Internal_ALB_Step_6_Review| Workflow on Firewall instances - Fortigate ========================================== This is just a simple example to set up Firwall for Ingress traffic. Please adjust the security settings depending on your requirements. Step 3.1. Set up basic configuration for FortiGate (Fortinet) ------------------------------------------------------------- - Refer to `Fortigate Example <https://docs.aviatrix.com/HowTos/config_FortiGateVM.html#example-config-for-fortigate-vm-in-aws>`_ to launch Fortigate in AWS and for more details. - `Reset Fortigate Next Generation Firewall Password <https://docs.aviatrix.com/HowTos/config_FortiGateVM.html#reset-fortigate-next-generation-firewall-password>`_ - `Configure Fortigate Next Generation Firewall port1 with WAN <https://docs.aviatrix.com/HowTos/config_FortiGateVM.html#configure-fortigate-next-generation-firewall-port1-with-wan>`_ - `Configure Fortigate Next Generation Firewall port2 with LAN <https://docs.aviatrix.com/HowTos/config_FortiGateVM.html#configure-fortigate-next-generation-firewall-port2-with-lan>`_ - `Create static routes for routing traffic to Spoke VPC <https://docs.aviatrix.com/HowTos/config_FortiGateVM.html#create-static-routes-for-routing-of-traffic-vpc-to-vpc>`_ Step 3.2. Configure Destination NAT (DNAT) to the FQDN/IP of Internal Application Load Balancer ----------------------------------------------------------------------------------------------- - Login Fortigate GUI - Navigate to the page "Policy & Objects -> Virtual IPs" - Click the button "+ Create New" - Enter fields for Name, Comments, Interface, Type, External IP address, Mapped address, and Port Forwarding as follows: +-----------------+-----------------------+-----------------------------------------------+ | **Section** | **Example setting** | **Example value** | +-----------------+-----------------------+-----------------------------------------------+ | Edit Virtual IP | VIP type | IPv4 | +-----------------+-----------------------+-----------------------------------------------+ | | Name | DNAT-to-Internal-ALB-WEB-HTTP-8080 | +-----------------+-----------------------+-----------------------------------------------+ | | Comments | DNAT-to-Internal-ALB-WEB-HTTP-8080 | +-----------------+-----------------------+-----------------------------------------------+ | Network | Interface | WAN (port1) | +-----------------+-----------------------+-----------------------------------------------+ | | Type | FQDN | +-----------------+-----------------------+-----------------------------------------------+ | | External IP address | Private IP of interface WAN (port1) | +-----------------+-----------------------+-----------------------------------------------+ | | Mapped address | Create a new tag 'Internal-ALB-WEB-HTTP-8080' | +-----------------+-----------------------+-----------------------------------------------+ | Port Forwarding | Status | enable | +-----------------+-----------------------+-----------------------------------------------+ | | Protocol | TCP | +-----------------+-----------------------+-----------------------------------------------+ | | External service port | 8080 | +-----------------+-----------------------+-----------------------------------------------+ | | Map to port | 8080 | +-----------------+-----------------------+-----------------------------------------------+ |Ingress_Fortigate_DNAT| - Create a tag for Mapped address by clicking the button "+ Create" |Ingress_Fortigate_DNAT_Mapped_address| - Enter fields for Name, Type, FQDN, and Interface for Mapped address as follows: +---------------------+---------------------------------------------------------------------------------------------+ | **Example setting** | **Example value** | +---------------------+---------------------------------------------------------------------------------------------+ | Name | Internal-ALB-WEB-HTTP-8080 | +---------------------+---------------------------------------------------------------------------------------------+ | Type | FQDN | +---------------------+---------------------------------------------------------------------------------------------+ | FQDN | DNS name of the internal AWS Application Load Balancer which is created in the previos step | +---------------------+---------------------------------------------------------------------------------------------+ | Interface | any | +---------------------+---------------------------------------------------------------------------------------------+ |Ingress_Fortigate_DNAT_Mapped_address_2| .. important:: FQDN is the DNS name of the 'internal' AWS Application Load Balancer not 'internet-facing' AWS ALB. .. note:: DNS name of the AWS Application Load Balancer can be found on the page "EC2 -> Load Balancing -> Load Balancers -> selecting the Load balancer -> Description -> DNS name" Step 3.3. Apply Destination NAT (DNAT) and configure Source NAT (SNAT) on firewall's LAN interface in Firewall Policy to allow Ingress traffic ---------------------------------------------------------------------------------------------------------------------------------------------- - Navigate to the page "Policy & Objects -> Firewall Policy" - Click the button "+ Create New" - Enter fields for Name, Incoming Interface, Outgoing Interface, Source, Destination, Service, Action, NAT, IP Pool Configuration as follows: +----------------------------+-----------------------+---------------------------------------------------------------------------------------------------+ | **Section** | **Example setting** | **Example value** | +----------------------------+-----------------------+---------------------------------------------------------------------------------------------------+ | Edit Policy | Name | Ingress-WEB-HTTP-8080 | +----------------------------+-----------------------+---------------------------------------------------------------------------------------------------+ | | Incoming Interface | WAN (port1) | +----------------------------+-----------------------+---------------------------------------------------------------------------------------------------+ | | Outgoing Interface | LAN (port2) | +----------------------------+-----------------------+---------------------------------------------------------------------------------------------------+ | | Source | all | +----------------------------+-----------------------+---------------------------------------------------------------------------------------------------+ | | Destination | Select the Virtual IPs 'DNAT-to-Internal-ALB-WEB-HTTP-8080' which is created in the previous step | +----------------------------+-----------------------+---------------------------------------------------------------------------------------------------+ | | Service | Create a new service for HTTP-8080 | +----------------------------+-----------------------+---------------------------------------------------------------------------------------------------+ | | Action | ACCEPT | +----------------------------+-----------------------+---------------------------------------------------------------------------------------------------+ | Firewall / Network Options | NAT | Enable | +----------------------------+-----------------------+---------------------------------------------------------------------------------------------------+ | | IP Pool Configuration | Use Outgoing Interface Address | +----------------------------+-----------------------+---------------------------------------------------------------------------------------------------+ .. important:: To enable DNAT function, need to select 'Virtual IPs' for Destination under Edit Policy. To enable SNAT function, need to enable NAT with IP Pool Configuration under Firewall / Network Options. |Ingress_Fortigate_Firewall_policy| - Create a new service for HTTP-8080 by clicking the button "+ Create" +------------------+---------------------+-----------------------+ | **Section** | **Example setting** | **Example value** | +------------------+---------------------+-----------------------+ | New Service | Name | HTTP-8080 | +------------------+---------------------+-----------------------+ | | Category | Web Access | +------------------+---------------------+-----------------------+ | Protocol Options | Protocol Type | TCP/UDP/SCTP | +------------------+---------------------+-----------------------+ | | Address | IP Range with 0.0.0.0 | +------------------+---------------------+-----------------------+ | | Destination Port | TCP with port 8080 | +------------------+---------------------+-----------------------+ |Ingress_Fortigate_Firewall_policy_service| - Review Firewall Policy |Ingress_Fortigate_Firewall_policy_review| Step 3.4. Repeat the above steps for all your firewall instances ---------------------------------------------------------------- Step 3.5. Reference -------------------- - Inbound application traffic with firewall resiliency in `Amazon Web Services (AWS) Reference Architecture <https://www.fortinet.com/content/dam/fortinet/assets/white-papers/wp-aws-reference-architecture.pdf>`_ - INBOUND APPLICATION TRAFFIC WITH FIREWALL RESILIENCY in `wp-aws-transit-gateway-cloud-services.pdf <https://www.fortinet.com/content/dam/fortinet/assets/white-papers/wp-aws-reference-architecture.pdf>`_ - `FortiGate Cookbook <https://docs.fortinet.com/document/fortigate/6.2.4/cookbook/954635/getting-started>`_ Ready to go! ============= Now firewall instances and private application server are ready to receive Ingress traffic! Open your browser and access the DNS of AWS Internet Application Load Balancer with HTTP and port 8080. |Ingress_private_WEB_server_access| .. |transit_firenet_ingress| image:: ingress_firewall_example_media/Ingress_Aviatrix_Transit_FireNet_topology.png :scale: 30% .. |Ingress_ALB| image:: ingress_protection_transit_firenet_fortigate_media/Ingress_ALB.png :scale: 30% .. |Ingress_Internet_ALB_Step_1_Configure_Load_Balancer| image:: ingress_protection_transit_firenet_fortigate_media/Ingress_Internet_ALB_Step_1_Configure_Load_Balancer.png :scale: 30% .. |Ingress_Internet_ALB_Step_3_Configure_Security_Groups| image:: ingress_protection_transit_firenet_fortigate_media/Ingress_Internet_ALB_Step_3_Configure_Security_Groups.png :scale: 30% .. |Ingress_Internet_ALB_Step_4_Configure_Routing| image:: ingress_protection_transit_firenet_fortigate_media/Ingress_Internet_ALB_Step_4_Configure_Routing.png :scale: 30% .. |Ingress_Internet_ALB_Step_5_Register_Targets_1| image:: ingress_protection_transit_firenet_fortigate_media/Ingress_Internet_ALB_Step_5_Register_Targets_1.png :scale: 30% .. |Ingress_Internet_ALB_Step_5_Register_Targets_2| image:: ingress_protection_transit_firenet_fortigate_media/Ingress_Internet_ALB_Step_5_Register_Targets_2.png :scale: 30% .. |Ingress_Internet_ALB_Step_6_Review| image:: ingress_protection_transit_firenet_fortigate_media/Ingress_Internet_ALB_Step_6_Review.png :scale: 30% .. |Internet_ALB_WEB_HTTP_8080_tg_healthcheck| image:: ingress_protection_transit_firenet_fortigate_media/Internet_ALB_WEB_HTTP_8080_tg_healthcheck.png :scale: 30% .. |Ingress_Internal_ALB_Step_1_Configure_Load_Balancer| image:: ingress_protection_transit_firenet_fortigate_media/Ingress_Internal_ALB_Step_1_Configure_Load_Balancer.png :scale: 30% .. |Ingress_Internal_ALB_Step_6_Review| image:: ingress_protection_transit_firenet_fortigate_media/Ingress_Internal_ALB_Step_6_Review.png :scale: 30% .. |Ingress_Fortigate_DNAT| image:: ingress_protection_transit_firenet_fortigate_media/Ingress_Fortigate_DNAT.png :scale: 30% .. |Ingress_Fortigate_DNAT_Mapped_address| image:: ingress_protection_transit_firenet_fortigate_media/Ingress_Fortigate_DNAT_Mapped_address.png :scale: 30% .. |Ingress_Fortigate_DNAT_Mapped_address_2| image:: ingress_protection_transit_firenet_fortigate_media/Ingress_Fortigate_DNAT_Mapped_address_2.png :scale: 30% .. |Ingress_Fortigate_Firewall_policy| image:: ingress_protection_transit_firenet_fortigate_media/Ingress_Fortigate_Firewall_policy.png :scale: 30% .. |Ingress_Fortigate_Firewall_policy_service| image:: ingress_protection_transit_firenet_fortigate_media/Ingress_Fortigate_Firewall_policy_service.png :scale: 30% .. |Ingress_Fortigate_Firewall_policy_review| image:: ingress_protection_transit_firenet_fortigate_media/Ingress_Fortigate_Firewall_policy_review.png :scale: 30% .. |Ingress_private_WEB_server_access| image:: ingress_protection_transit_firenet_fortigate_media/Ingress_private_WEB_server_access.png :scale: 30% .. disqus:: Ingress Protection via Aviatrix Transit Firenet for Multiple Applications In case customer has a use case where they want to inspect traffic for multiple applications using the same FW, in that case we need to add more NAT rules on the firewall. Recommended Steps Create an additional subnet in the security VPC (/24) for the LB Create additional ALB/NLB based on the number of applications Add a SNAT/DNAT same as above for each application mapping it for the specific LB <file_sep> ################################### Advanced ################################### - Tunnel - Keepalive - Password Management - Certificates .. disqus:: <file_sep> ============================================ Aviatrix Gateway to Check Point(R80.10) ============================================ This document describes how to build an IPsec tunnel based Site2Cloud connection between Aviatrix Gateway and Check Point Firewall. To simulate an on-prem Check Point Firewall, we use a Check Point CloudGuard IaaS firewall VM at AWS VPC. .. note:: If you do not have access to AWS, you can simulate an on-prem Firewall by deploying the Palo Alto Firewall in any other cloud (such as Microsoft Azure, Google Cloud Platform, or Oracle Cloud Infrastructure). The network setup is as follows: **VPC1 (with Aviatrix Gateway)** *VPC1 CIDR: 10.12.0.0/16* *VPC1 Public Subnet CIDR: 10.12.0.0/23* *VPC1 Private Subnet CIDR: 10.12.2.0/23* **VPC2 (with Check Point Security Gateway)** *VPC2 CIDR: 10.24.0.0/16* *VPC2 Public Subnet CIDR: 10.24.0.0/23* *VPC2 Private Subnet CIDR: 10.24.2.0/23* Launching Check Point Security Gateway VM ========================================= Launch a CheckPoint VM with at least two network interfaces. One interface serves as a WAN port and is in VPC2's public subnet. The other interface serves as a LAN port and is in VPC2's private subnet. Collect the public IP address of the WAN port. Creating Site2Cloud Connection at Aviatrix Controller ====================================================== 1. Go to Gateway > New Gateway to launch an Aviatrix Gateway at VPC1's public subnet. Collect both public and private IP addresses of the Gateway. 2. Go to the Site2Cloud and click **Add New** to create a Site2Cloud connection: =============================== ================================================================= **Field** **Value** =============================== ================================================================= VPC ID/VNet Name Choose VPC ID of VPC1 Connection Type Unmapped Connection Name Arbitrary (e.g. avx-cp-s2c) Remote Gateway Type Generic Tunnel Type UDP Algorithms Unmark this checkbox Encryption over Direct Connect Unmark this checkbox Enable HA Unmark this checkbox Primary Cloud Gateway Select Aviatrix Gateway created above Remote Gateway IP Address Public IP of CheckPoint-VM WAN port Pre-shared Key Optional (auto-generated if not entered) Remote Subnet 10.24.2.0/23 (VPC2 private subnet) Local Subnet 10.12.2.0/23 (VPC1 private subnet) =============================== ================================================================= 3. Go to the Site2Cloud page. From the Site2Cloud connection table, select the connection created above (e.g. avx-cp-s2c). Select **Generic** from **Vendor** drop down list and click **Download Configuration** to download the Site2Cloud configuration. Save the configuration file for configuring CheckPoint-VM. Downloading and Install SmartConsole ==================================== 1. Using a browser, connect to the Gaia Portal of the CheckPoint-VM at https://CheckPoint-VM_Public-IP: 2. Click **Download Now!** as shown below to download SmartConsole. |image1| 3. Install SmartConsole at your local machine and launch SmartDashboard. Creating Network Objects at SmartConsole ========================================= 1. At the Check Point SmartDashboard window, go to New > Network and create two objects. |image2| 2. Create one network for private subnet of VPC2 (Check Point VPC). |image3| =============================== ================================================================= **Field** **Value** =============================== ================================================================= Name Arbitrary (e.g. CP-Private-Subnet) IPv4 Network Address VPC2 private subnet CIDR IPv4 Net mask VPC2 private subnet mask =============================== ================================================================= 3. Create one network for private subnet of VPC1 (Aviatrix Gateway VPC). |image4| =============================== ================================================================= **Field** **Value** =============================== ================================================================= Name Arbitrary (e.g. AVX-Private-Subnet) IPv4 Network Address VPC1 private subnet CIDR IPv4 Net mask VPC1 private subnet mask =============================== ================================================================= Configuring Check Point Security Gateway with VPN ================================================== 1. At the SmartDashboard window, go to **Gateways and services** > double-click on the gateway. |image5| |image6| =============================== ================================================================= **Field** **Value** =============================== ================================================================= IPv4 Address Private IP of CheckPoint VM WAN port Network Security Select **IPsec VPN** =============================== ================================================================= 2. Go to Network management > **VPN domain** > click **Manually defined** and select the network created previously (see the "Creating Network Objects at SmartConsole" section above). |image7| 3. Go to Network management > double-click "eth0" (Check Point WAN port). Select **External (leads out to the Internet)**. |image8| 4. Go to Network management > double-click "eth1" (Check Point LAN port). Click on modify. Select **Override > this network (internal) > specific > select network created previously (see the "Create Network Objects at SmartConsole" above). |image9| 5. Double-click on gateway as shown in step 1 above > **IPsec VPN** > **link selection** > statically NATted IP > public IP of CheckPoint WAN port. Click on source IP settings > select manual > in selected address from topology table > select the private IP of CheckPoint wan port. |image10| 6. Double-click on the gateway as shown in step 1 above > VPN advanced and leave it as it is to use the community settings and leave NAT traversal turned on. |image11| Configuring an Interoperable Device to Represent Aviatrix Gateway ================================================================== 1. Go to Gateways and services > New network objects > Interoperable devices > click **Add new** and then use the image below to create a new interoperable device to represent Aviatrix Gateway. |image12| |image13| 2. Double-click on Interoperable device > avx-gwv (created in step 1 of this section) > General properties. The IPv4 address will be the public IP of the Aviatrix Gateway. |image14| 3. Double-click on Interoperable device > avx-gwv (created in step 1 in this section) > Topology > Manually defined > select the network for private subnet of VPC1 (Aviatrix Gateway VPC) network created above. |image15| 4. Double-click on Interoperable device > avx-gwv (created in step 1 of this section) > IPsec VPN - Link Selection > select Always use this IP address > Main Address. |image16| 5. Double-click on Interoperable device > avx-gwv (created in step 1 of this section) > IPsec VPN – VPN advanced window. Select **Use the community settings**. |image17| Creating a VPN Community ========================== 1. Click on VPN communities on the smart console. Then, create a Star Community as shown below. |image18| |image19| 2. After creating the VPN community, double-click on the created VPN community > Gateway tab. Then, select the gateway created above (see the "Configuring Check Point Security Gateway with VPN" section). |image20| 3. Double-click on created VPN community > Encryption > Encryption window and select the options according to the Site2Cloud configuration downloaded previously (see the "Create Site2Cloud Connection at Aviatrix Controller" section above). |image21| 4. Double-click on created VPN community > Tunnel management and then select one VPN tunnel per gateway pair. |image22| 5. Double-click on created VPN community > VPN routing > select as shown in the image below. |image23| 6. Double-click on created VPN community > Shared secret > Advanced Settings - Shared Secret window. Enter the Shared Secret by copying the Pre-Shared Key from the Site2Cloud configuration downloaded previously (see the "Create Site2Cloud Connection at Aviatrix Controller" section above). |image24| 7. Double-click on the created VPN community > Advanced > enter the Phase1 and Phase2 parameters according to the Site2Cloud configuration downloaded previously (see the "Create Site2Cloud Connection at Aviatrix Controller" section above). |image25| Creating Firewall Rule for VPN Traffic ======================================= Go to security and policies. Add a policy and click **Install Policy**. |image26| Troubleshooting and Verifying at Check Point Security Gateway ================================================================ 1. Go to **Logs and monitor** > Add a new tab. Then, click on **Open Tunnel & User Monitoring**. |image27| 2. Click **IPsec VPN** to see the tunnel status. |image28| |image29| Troubleshooting and Verifying at Aviatrix Controller ======================================================== 1. At the Aviatrix Controller, go to the **Site2Cloud** page. Verify that the status of the Site2Cloud connection is up. |image30| 2. At the **Site2Cloud - Diagnostics** page, run various diagnostics commands. |image31| =============================== ================================================================= **Field** **Value** =============================== ================================================================= VPC ID/VNet Name VPC1 (Aviatrix Gateway VPC) ID Connection Name of the Site2Cloud connection created previously (see the "Create Site2Cloud Connection at Aviatrix Controller" section above) Gateway Name of the Aviatrix Gateway Action One of the supported diagnostics commands =============================== ================================================================= 3. Below is the sample output for ping from an instance in Aviatrix private subnet to an instance in CheckPoint private subnet. |image32| .. |image1| image:: ./s2c_checkpoint_r88_media/image1.png :width: 100% .. |image2| image:: ./s2c_checkpoint_r88_media/image2.png :width: 100% .. |image3| image:: ./s2c_checkpoint_r88_media/image3.png :width: 50% .. |image4| image:: ./s2c_checkpoint_r88_media/image4.png :width: 50% .. |image5| image:: ./s2c_checkpoint_r88_media/image5.png :width: 100% .. |image6| image:: ./s2c_checkpoint_r88_media/image6.png :width: 100% .. |image7| image:: ./s2c_checkpoint_r88_media/image7.png :width: 100% .. |image8| image:: ./s2c_checkpoint_r88_media/image8.png :width: 50% .. |image9| image:: ./s2c_checkpoint_r88_media/image9.png :width: 75% .. |image10| image:: ./s2c_checkpoint_r88_media/image10.png :width: 75% .. |image11| image:: ./s2c_checkpoint_r88_media/image11.png :width: 75% .. |image12| image:: ./s2c_checkpoint_r88_media/image12.png :width: 75% .. |image13| image:: ./s2c_checkpoint_r88_media/image13.png :width: 75% .. |image14| image:: ./s2c_checkpoint_r88_media/image14.png :width: 75% .. |image15| image:: ./s2c_checkpoint_r88_media/image15.png :width: 75% .. |image16| image:: ./s2c_checkpoint_r88_media/image16.png :width: 75% .. |image17| image:: ./s2c_checkpoint_r88_media/image17.png :width: 75% .. |image18| image:: ./s2c_checkpoint_r88_media/image18.png :width: 100% .. |image19| image:: ./s2c_checkpoint_r88_media/image19.png :width: 100% .. |image20| image:: ./s2c_checkpoint_r88_media/image20.png :width: 50% .. |image21| image:: ./s2c_checkpoint_r88_media/image21.png :width: 75% .. |image22| image:: ./s2c_checkpoint_r88_media/image22.png :width: 75% .. |image23| image:: ./s2c_checkpoint_r88_media/image23.png :width: 75% .. |image24| image:: ./s2c_checkpoint_r88_media/image24.png :width: 75% .. |image25| image:: ./s2c_checkpoint_r88_media/image25.png :width: 75% .. |image26| image:: ./s2c_checkpoint_r88_media/image26.png :width: 100% .. |image27| image:: ./s2c_checkpoint_r88_media/image27.png :width: 100% .. |image28| image:: ./s2c_checkpoint_r88_media/image28.png :width: 100% .. |image29| image:: ./s2c_checkpoint_r88_media/image29.png :width: 100% .. |image30| image:: ./s2c_checkpoint_r88_media/image30.png :width: 100% .. |image31| image:: ./s2c_checkpoint_r88_media/image31.png :width: 100% .. |image32| image:: ./s2c_checkpoint_r88_media/image32.png :width: 90% <file_sep> ================================================================ Transit List ================================================================ Config Private VPC Default Route -------------------------------------------- This feature allows to configure default route in private VPC only. This is only supported for AWS Spoke gateway. Skip Public VPC Route Table --------------------------------------- Route Table Optimization allows customer to skip public VPC route table programming. This is only supported for AWS Spoke gateway and ActiveMesh 2.0. Customize Spoke CIDR and this feature are mutually exclusive. Auto Advertise Spoke Site2Cloud CIDRs ---------------------------------------------------- Dynamic Route updates on Spoke for Site2Cloud allows regional redundancy for Overlapping and Non-overlapping CIDRs. Route will be Auto Advertised or Removed for Remote and Local Virtual CIDRs when: 1. S2C connection is created/deleted #. S2C connection status change up/down #. Spoke to Transit link goes down This feature is supported for mapped S2C connections only and on the following clouds. * AWS and AWS-Gov * GCP * Azure and Azure-Gov <file_sep> =============================================== Insane Mode Encryption FAQ =============================================== This document discusses Aviatrix High Performance Multi-Cloud Transit Network and answers related questions. Why is Transit VPC/VNet performance capped at 1.25Gbps? ------------------------------------------------------------------------- In the current Transit VPC/VNet solution, the throughput is capped at 1.25Gbps regardless if you have a 10Gbps connection between an on-prem network and the cloud (Direct Connect (DX)/ExpressRoute/FastConnect/InterConnect) link. The reason is that in the Transit VPC/VNet deployment there is an IPsec session between VGW/VPN Gateway and Transit Gateway and VGW/VPN Gateway has a performance limitation. `AWS VGW <https://aws.amazon.com/vpc/faqs/>`_ and other Cloud Service Providers' IPsec VPN solutions have a `published performance cap <https://aws.amazon.com/vpc/faqs/>`_ of 1.25Gbps. Why is that? Most virtual routers or software-based routers are built with general purpose CPUs. Despite the vast CPU technology advancement, why doesn't IPsec performance scale further? It turns out the problem lies in the nature of tunneling, a common technique in networking to connect two endpoints. When two general purpose server or virtual machine-based routes are connected by an IPsec tunnel, there is one UDP or ESP session going between the two machines, as shown below. |tunnel_diagram| In the above diagram, the virtual router has multiple CPU cores, but since there is only one tunnel established, the Ethernet Interface can only direct incoming packets to a single core, thus the performance is limited to one CPU core, regardless how many CPU cores and memory you provide. This is true not only for IPsec, but also for all tunneling protocols, such as GRE and IPIP. What is Aviatrix high performance Insane Mode Encryption? --------------------------------------------------------------------------- Aviatrix Insane Mode tunneling techniques establishes multiple tunnels between the two virtual routers, thus allowing all CPU cores to be used for performance scaling with the CPU resources, as shown below. |insane_tunnel_diagram| With Aviatrix Insane Mode tunneling, IPsec encryption can achieve 10Gbps, 25Gbps and beyond, leveraging the multiple CPU cores in a single instance, VM or host. What are the use cases for Insane Mode? ------------------------------------------------------- - High performance `Encrypted Transit <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ - High performance `Encrypted Peering <https://docs.aviatrix.com/HowTos/peering_faq.html>`_ performance - High performance encryption over Direct Connect/ExpressRoute/FastConnect/InterConnect - Overcome VGW performance limit and 100 route limits How can I deploy Aviatrix Insane Mode? ----------------------------------------------------------- Aviatrix Insane Mode is integrated into the Transit Network solution to provide 10Gbps performance between on-prem and Transit VPC/VNet with encryption. For VPC/VNet to VPC/VNet, Insane Mode can achieve 25 - 30Gbps. Insane Mode can also be deployed in a flat (as opposed to Transit VPC/VNet) architecture for 10Gbps encryption. The diagram below illustrates the high performance encryption between Transit VPC/VNet and on-prem, between Transit VPC/VNet and Spoke VPC/VNet. |insane_transit| What are the performance benchmarks? --------------------------------------------- Insane Mode is available on AWS, Azure, GCP, and OCI. For more performance test results and information about how to tune your environment to get the best performance, see `this document. <https://docs.aviatrix.com/HowTos/insane_mode_perf.html?highlight=performance%20benchmark#activemesh-insane-mode-encryption-performance>`_ How does Insane Mode work? ----------------------------- When a gateway is launched with `Insane Mode enabled <https://docs.aviatrix.com/HowTos/gateway.html#insane-mode-encryption>`_, a new /26 public subnet is created where the Insane Mode gateway is launched on. Insane Mode builds high performance encryption tunnel over private network links. The private network links are Direct Connect (DX)/AWS Peering (PCX), Azure ExpressRoute, GCP FastConnect, and OCI InterConnect. For Insane Mode between two gateways, between a Transit GW and a Spoke Gateway, or between a Transit GW and a Transit GW (Transit Peering), the Aviatrix Controller automatically creates the underlying peering connection and builds the tunnels over it. Since Insane Mode tunnels are over private network links, the VPC/VNet route architecture is described as below, where virtual machine (EC2/GCE/OC) instances associated route entry to the remote site point to Aviatrix Gateway, and the Aviatrix Gateway instance associated route entry to remote site points to PCX or VGW. |insane_routing| What is Aviatrix Insane Mode High-Performance Encryption over the internet? --------------------------------------------------------------------------- Aviatrix Insane Mode over the internet builds high-performance encryption (HPE) tunnels over public IP addresses between two intercloud transit peering gateways. For instance, when a transit gateway peering is established between AWS and Azure, the Aviatrix Controller allocates EIP addresses then builds the HPE tunnels over the public IP addresses between the two transit gateways, establishing one-to-one connections. Insane Mode over the internet for GCP transit gateway peering configuration differs from AWS, Azure, and OCI. Because GCP Ethernet interface supports only one public IP address, HPE tunnels are built to the same public IP address on the GCP transit gateway, establishing one-to-many connections. To establish peered transit gateways over the internet, refer to `Multi-cloud Transit Gateway Peering over Public Network Workflow <https://docs.aviatrix.com/HowTos/transit_gateway_peering_over_public_network_workflow.html>`_. What are the performance benchmarks for Insane Mode over the internet? ---------------------------------------------------------------------- Aviatrix Insane Mode HPE over the internet throughput performance is dependant on the number of HPE tunnels that are configured. The supported range is up to 20 HPE tunnels. What is the Aviatrix hardware appliance CloudN? -------------------------------------------------- Aviatrix offers a 1U rack mountable hardware appliance deployed in the datacenter. It works with the Aviatrix gateway. The Aviatrix appliance CloudN specification: ======================== ======================================= ================= Aviatrix CloudN Specification Notes ======================== ======================================= ================= Dimension 1U rack mount Server HPE ProLiant DL360 Gen10 Xeon Gold 6130 CPU 16 cores Memory 64GB PCIe 3.0 10/25Gbps Ethernet port 2 x SFP+ 1 LAN port and 1 WAN port 1Gbps Ethernet port RJ45 1 Management port ======================== ======================================= ================= More information on HPE ProLiant DL360 Gen10 Server can be found `here. <https://www.hpe.com/us/en/product-catalog/servers/proliant-servers/pip.hpe-proliant-dl360-gen10-server.1010007891.html>`_ What is the deployment logical diagram? ------------------------------------------- Datacenter deployment is shown in the diagram below with redundancy, where R1 and R2 are two edge routers that connected to VGW or VPN Gateway over DX. R3 and R4 are two routers connect to the inside of the datacenter. Aviatrix CloudN also runs a BGP session with R3 and R4 to collect datacenter routes. VGW is only used to terminate DX. Aviatrix Gateway and on-prem appliance CloudN run a BGP session to propagate on-prem routes to the Transit VPC/VNet. IPsec tunnels are also built between the two. |insane_datacenter| A logical deployment layout is described as below. |datacenter_layout| How to deploy Insane Mode for hybrid connectivity? ---------------------------------------------------- Follow the `Insane Mode CloudN Deployment Checklist <https://docs.aviatrix.com/HowTos/CloudN_insane_mode.html>`_ to deploy CloudN in your datacenter. Do I need Direct Connect/ExpressRoute/FastConnect/InterConnect to use Insane Mode for On-prem? -------------------------------------------------------------------------------------------------------------------------------- Our Insane Mode high speed encryption feature works on top of your existing WAN link, and it is agnostic to the type of connection used. As long as you have a pipe that's large enough to allow for high throughput data transfer, using Insane Mode will offer superior performance to regular IPsec. How to configure Insane Mode for Transit VPC/VNet? ---------------------------------------------- Navigate to `Step 1 Transit Network workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-an-aviatrix-transit-gateway>`_ and mark the **Insane Mode Encryption** checkbox. Can one CloudN appliance connect to multiple connections of Direct Connect/Express Route/FastConnect/InterConnect? ------------------------------------------------------------------------------------------------------------------------------------------------------- Yes. A CloudN appliance can build multiple Insane Mode tunnels to different Aviatrix Transit Gateways over multiple DX/Express Route/FastConnect/InterConnect, as shown in the diagram below. |cloudn_multi_conn| What are the supported gateway sizes for GCP High-performance encryption (Insane Mode)? --------------------------------------------------------------------------------------- There are total 4 sizes: n1-highcpu-4, n1-highcpu-8, n1-highcpu-16, and n1-highcpu-32 What is the subnet prefix length for GCP High-performance encryption (Insane Mode)? ----------------------------------------------------------------------------------- Gateway subnet prefix length cannot be greater than /24. Moreover, Aviatrix highly suggests that customers utilize a subnet exclusively for deploying insane mode gateway without any other instances in the subnet. What ActiveMesh version does GCP High-performance encryption (Insane Mode) support? ----------------------------------------------------------------------------------- GCP Insane Mode supports only Transit Solution ActiveMesh 2.0. What is the MTU and MSS size for GCP High-performance encryption (Insane Mode)? -------------------------------------------------------------------------------- MTU is 1460 and MSS is 1330 bytes What are the features supported with GCP Insane Mode? ------------------------------------------------------------------------------- Because GCP network infrastructure/concept is different than AWS/Azure, Aviatrix GCP Insane Mode behavior differs from AWS/Azure support in the following ways: - Only Spoke and Transit Gateway types are supported. - Only Multi-Cloud Transit functionality is supported with Insane Mode gateways; `encrypted peering <https://docs.aviatrix.com/HowTos/Quick_Tour.html#encrypted-peering>`_ is not supported. - The Advertise Transit VPC Network CIDR(s) feature is not supported with an Insane Mode Gateway. - Aviatrix will support Managed CloudN connecting to Aviatrix Transit Gateway in GCP soon; Standalone/unmanaged CloudN connecting to Aviatrix Transit Gateway is not supported in GCP. .. |tunnel_diagram| image:: insane_mode_media/tunnel_diagram.png :scale: 30% .. |insane_tunnel_diagram| image:: insane_mode_media/insane_tunnel_diagram.png :scale: 30% .. |insane_transit| image:: insane_mode_media/insane_transit.png :scale: 30% .. |insane_datacenter| image:: insane_mode_media/insane_datacenter.png :scale: 30% .. |datacenter_layout| image:: insane_mode_media/datacenter_layout.png :scale: 30% .. |deployment| image:: insane_mode_media/deployment.png :scale: 30% .. |deployment_ha| image:: insane_mode_media/deployment_ha.png :scale: 30% .. |deployment_dual_dx| image:: insane_mode_media/deployment_dual_dx.png :scale: 30% .. |ISR-sample-config| image:: insane_mode_media/ISR-sample-config.png :scale: 30% .. |insane_routing| image:: insane_mode_media/insane_routing.png :scale: 30% .. |cloudn_multi_conn| image:: insane_mode_media/cloudn_multi_conn.png :scale: 30% .. |image1| image:: transitvpc_designs_media/multiRegions.png :width: 5.55625in :height: 3.265480in .. |InsaneBeta| image:: insane_mode_media/InsaneBeta.png :width: 5.55625in :height: 3.265480in .. disqus:: <file_sep> ================================================================== Add an AWS access account to Azure Controller ================================================================== Overview -------- If you have installed your Controller in Azure, you will not be able to use IAM roles to grant the Controller access to the account. The Controller must be installed in AWS with an AWS EC2 role attached for this to work. This guide outlines the steps to set up access to your AWS account using the Access Key ID and Secret Key. Onboarding Steps ---------------- .. note:: These steps apply to users who have an Aviatrix Controller installed in Azure and wish to add an AWS account. Create an AWS User ++++++++++++++++++ Since you cannot use IAM roles to grant access to an Azure Controller, you must create a new AWS user and obtain the Access Key ID and Secret Key. #. Login to the `AWS IAM console <https://console.aws.amazon.com/iam/home#/users>`__ #. Create a new user by clicking on the **Add user** button |imageAddUserStep1| #. In the `User name` field, enter something like `aviatrix-azure-controller-access-account` #. Select **Programmatic access** only (leave `AWS Management Console access` unchecked) #. Click **Next::Permissions** #. Select **Attach existing policies directly** #. Click **Create policy** #. In the new window, click on **JSON** |imageCreatePolicyEnterJSON| #. In the JSON editor, delete the default value and paste in the contents of `this <https://s3-us-west-2.amazonaws.com/aviatrix-download/IAM_access_policy_for_CloudN.txt>` document #. Click **Review policy** |imageCreatePolicyReview| #. Enter a `Name` like `aviatrix-azure-controller-access-account-policy` #. Enter a `Description` like `This policy grants access to the Aviatrix Controller, installed in Azure, to automate Cloud Networking tasks for this AWS account` #. Click **Create policy** #. Close the IAM policy window and return to the IAM user console #. Click **Refresh** to show the newly created policy #. Search for the policy you just created and select it #. Click **Next: Review** |imageAddUserAttachPolicy| #. Click **Create user** |imageAddUserReview| #. On the following screen, you will be given an `Access key ID` and `Secret access key`. |imageAddUserGetCredentials| Add Access Account to Aviatrix Controller +++++++++++++++++++++++++++++++++++++++++ #. Login to your Aviatrix Controller #. Go to the **Access Accounts** navigation item below **Accounts** #. Click **+ New Account** #. Enter a new Account Name and select **AWS** #. Uncheck the **IAM role-based** checkbox .. important:: You will receive an error ('The controller is not role-based enabled.') if you attempt to use role-based access to your AWS account. #. Enter the `AWS Access Key ID` and `AWS Secret Key` from the user created earlier #. Enter the `AWS Account Number` #. Click **OK** |imageAviatrixAddAccount| .. |imageAddUserStep1| image:: AddAWSAccountToAzure_media/aws_add_user_1.png .. |imageCreatePolicyReview| image:: AddAWSAccountToAzure_media/aws_create_policy_review.png .. |imageCreatePolicyEnterJSON| image:: AddAWSAccountToAzure_media/aws_create_policy_json.png .. |imageAddUserAttachPolicy| image:: AddAWSAccountToAzure_media/aws_add_user_attach_policy.png .. |imageAddUserReview| image:: AddAWSAccountToAzure_media/aws_add_user_review.png .. |imageAddUserGetCredentials| image:: AddAWSAccountToAzure_media/aws_add_user_credentials.png .. |imageAviatrixAddAccount| image:: AddAWSAccountToAzure_media/aviatrix_new_account_creation.png <file_sep> .. raw:: html <style> /* override table no-wrap */ .wy-table-responsive table td, .wy-table-responsive table th { white-space: normal !important; } </style> ================================= Site2Cloud IPsec VPN Instructions ================================= Overview ======== The Aviatrix Site2Cloud feature supports connectivity between its Gateways in the cloud and on-premise routers, as shown below. This document outlines how to establish connectivity between an Aviatrix Gateway in AWS, Azure, or GCP and your on-premise router or firewall. |site2cloud_new| .. note:: If you are planning to use certificate-based authentication for your Site2Cloud connection, ensure that you have already generated and exported the external device CA certificate `as described here <https://docs.aviatrix.com/HowTos/site2cloud-cacert.html>`_. Configuration Workflow ========================= Create Site2Cloud Connection ---------------------------- #. Log in to your Aviatrix Controller. #. Select Site2Cloud in the left navigation bar. #. Click **+ Add New** near the top of the Site2Cloud tab. #. Under Add a new connection, select the VPC ID where this tunnel will terminate in the cloud. #. See the below sections for information on configuring the connection. Connection Type ^^^^^^^^^^^^^^^ Select Mapped or Unmapped as the Connection Type. You should select Unmapped unless the Local Subnet and the Remote Subnet overlap. If you select the Mapped option in conjunction with the `Forward Traffic to Transit Gateway option <#forward-traffic-to-transit-gateway>`_ (possible after you configure your Site2Cloud connection, under the Edit options), bi-directional traffic flow occurs. Mapped ++++++ If you select Mapped, configure the following: - remote Subnet (real): specify a list of the destination network CIDRs, separated by comma, that will be encrypted (for example, 10.10.1.0/24, 10.10.2.0/24). - Remote Subnet (virtual): specify a list of virtual remote network CIDRs that are mapped to the real remote subnet (for example, for the real CIDRs listed above, you can have these virtual remote subnets: 192.168.1.0/24, 192.168.2.0/24). - Local Subnet (real): specify a list of the source network CIDRs, separated by comma, that will be encrypted. If left blank, the full CIDR is used. If you enter a value, make sure you include the VPC/VNet as well. These Local Subnets are advertised to Remote Subnets that the Site2Cloud connection can reach. Examples of real local subnets are 172.16.1.0/24, 172.16.2.0/24. - Local Subnet (virtual): specify a list of virtual local network CIDRs that are mapped to the real local subnet (for example, for the real CIDRs listed above for the real local subnet, you can have these virtual local subnets: 192.168.7.0/24, 192.168.8.0/24). .. important:: If the Local Subnet field is outside of gateway VPC/VNet, you need to open the gateway inbound security groups to allow the Local Subnet network CIDR ranges. .. note:: If you enter multiple real subnets, you must configure an equal number of virtual subnets. One-to-one mapping is supported if both sides are configured properly. The Remote and Local Subnet fields can contain multiple values. Use a comma to separate the values. If the Local Subnet field is outside the gateway VPC/VNet, you must open the gateway inbound security groups to allow the Local Subnet network CIDR ranges. Here is an example of one-to-one mapping: | Remote Subnet(Real): 10.1.7.10/32 | Remote Subnet(Virtual): 172.16.7.10/32 | | Local Subnet(Real): 10.1.7.15/32 | Local Subnet(Virtual): 192.168.7.45/32 Enter the Connection Name and click **OK**. Custom Mapping ++++++++++++++ If you select the Custom Mapped checkbox after selecting the Mapped option, more complex Site2Cloud configurations are possible. You can have locally initiated traffic flows only, remotely initiated traffic flows only, and differing NAT translation based on these local/remote initiated flows. Remote Gateway Type ^^^^^^^^^^^^^^^^^^^ +-------------------------------+------------------------------------------+ | Type | Description | +===============================+==========================================+ | Generic | Use this option for most third-party | | | routers and firewalls. | +-------------------------------+------------------------------------------+ | AWS VGW | For terminating on an AWS Virtual Private| | | Gateway, select this option. | +-------------------------------+------------------------------------------+ | Azure VPN | For terminating on Azure VPN Services | +-------------------------------+------------------------------------------+ | Aviatrix | When terminating on an Aviatrix CloudN | | | on-premise gateway. | +-------------------------------+------------------------------------------+ | SonicWall | | +-------------------------------+------------------------------------------+ Authentication Type ^^^^^^^^^^^^^^^^^^^ You can authenticate the connection using PSK or certificate-based authentication. PSK-Based +++++++++ If you select PSK-based authentication, you can provide the Pre-shared Key when prompted (this is optional). This key comes from your firewall UI. Certificate-Based +++++++++++++++++ If you select Cert-based authentication: - In the Remote CA Certificate field select the certificate you uploaded from your Palo Alto VM-Series firewall as per `these instructions <https://docs.aviatrix.com/HowTos/site2cloud-cacert.html>`_. - Enter the SAN/Remote Identifier. The format depends on the device you are connecting to. For example, for an on-prem Aviatrix gateway the format will be the DNS from the server certificate (such as gw-54-210-118-19). See `here <https://docs.aviatrix.com/HowTos/site2cloud-cacert.html>`_ for more details on Site2Cloud certificate-based authentication. Tunnel Type ^^^^^^^^^^^ Select Policy-based or Route-based. If you select the latter, you must enter the local and remote tunnel IP. If you selected the Mapped Connection Type, only Route-based is supported. Algorithms ^^^^^^^^^^ If the Algorithms checkbox is unmarked, the default values will be used. If it is checked, you can set any of the fields defined below. +-------------------------------+ | Field | +===============================+ | Phase 1 Authentication | +-------------------------------+ | Phase 1 DH Groups | +-------------------------------+ | Phase 1 Encryption | +-------------------------------+ | Phase 2 Authentication | +-------------------------------+ | Phase 2 DH Groups | +-------------------------------+ | Phase 2 Encryption | +-------------------------------+ IKEv2 ^^^^^ Select the option to connect to the remote site using IKEv2 protocol. This is the recommended protocol. .. note:: If you configure IKEv1 in a Site2Cloud connection that uses certificate-based authentication and is connecting to another Aviatrix device, you must add the intermediate CA's in addition to the root CA. When an intermediate CA is renewed and re-authentication is attempted, the Site2Cloud connection will go down until you add the new certificate. Enabling HA ^^^^^^^^^^^ Select this option to to create a backup/failover connection in case the primary connection fails. If you select this option you can also select the Enable Single IP HA check box, which allows you to use the same EIP to bring up the backup tunnel (supported for AWS and Azure only). If mapped NAT is enabled, HA in Site2Cloud is not supported. If you have the following configuration you can select the Same Pre-shared Key as primary check box, which means the backup tunnel uses the same pre-shared key as the primary. - Enable HA check box selected - Enable Single IP HA checkbox not selected - PSK-based authentication selected If the Enable HA checkbox is selected, you can enter a Pre-shared Key for the back-up (HA) gateway. Also if this checkbox is selected, you must enter the Remote Gateway IP address of the backup gateway (.hagw). Enable Single IP HA ^^^^^^^^^^^^^^^^^^^ When you select the Enable Single IP HA check box, you also need to select the Backup Gateway. The backup gateway should be the .hagw created at Gateway > Edit > Gateway for High Availability Peering. Over Private Network ^^^^^^^^^^^^^^^^^^^^ Select this option if your underlying infrastructure is a private network, such as AWS Direct Connect or Azure Express Route. When this option is selected, BGP and IPSEC run over private IP addresses. Primary Cloud Gateway ^^^^^^^^^^^^^^^^^^^^^ Select the Gateway where the tunnel will terminate in this VPC. Remote Gateway IP address ^^^^^^^^^^^^^^^^^^^^^^^^^ Enter the IP address of the device. Editing the Site2Cloud Connection ================================= Once a connection is created, you can download the configuration or edit parameters. To do this, select Site2Cloud in the left pane and select the connection you just created. Local Identifier --------------------- By default, Aviatrix configures gateway's public IP as the Local Identifier. User can adjust these settings to the gateway's private IP. Remote Identifier ------------------------- Aviatrix only supports IP_ADDRESS and KEY_ID as the IKE identity type for the remote identifier in the pre-shared key authentication. The IP_ADDRESS must be a valid IPv4 IP address. The KEY_ID is a remote device ID during the key authentication. By default, Aviatrix configures the public IPv4 address of the peer device as the Remote Identifier for pre-shared key authentication. You can adjust this setting to the private IPv4 address of the peer device. If you enter string(s) other than an IPv4 address or empty string(""), the string(s) you entered is treated as Key_ID. If KEY_ID value is not correct, this field validation will fail. If you are unsure about this field's value, enter an empty string("") to skip the validation of this field. Download Configuration ------------------------ You can generate a remote site configuration template. This template file contains the gateway public IP address, VPC CIDR, pre-shared secret and encryption algorithm. You can import the information to your remote router/firewall configuration. .. note:: If the remote gateway is an Aviatrix CloudN, go to the Site2Cloud Setup page in the Controller, import the downloaded configuration file, and click OK. To download a configuration: 1. After creating a Site2Cloud connection, select the remote site device from the table on the Setup Site2Cloud Connection page and click **Edit**. #. In the Download Configuration area, select your remote site device from the Vendor menu, or use the Generic/Vendor Independent template (you select Generic for anything that is not an Aviatrix gateway. If you are connecting two Aviatrix gateways, you select Aviatrix as the vendor). - If you select a Generic vendor, the Platform field is populated as Generic, and the Software field is populated with Vendor Independent. - If you select the Aviatrix vendor, the Platform is populated with UCC, and the Software version is 1.0. - If you select a specific hardware vendor (such as Cisco), available platforms belonging to that vendor are displayed in the Platform field, and the Software field is populated with related software versions. How to use this downloaded configuration: - If connecting two Aviatrix gateways, you import the downloaded configuration when creating the other side of the tunnel. Gateways can be in different Controllers or the same Controller). See `here <https://docs.aviatrix.com/HowTos/site2cloud_aviatrix.html#configure-tunnel-from-gateway-a-to-gateway-b>`_ for more information. - If connecting an Aviatrix gateway to a firewall or other on-prem vendor, use the downloaded configuration information to populate the necessary information in your firewall UI. Dead Peer Detection --------------------- This field is not applicable to a Site2Cloud connection established by `Transit Network workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_. Dead Peer Detection (DPD) is a standard mechanism (RFC 3706) between IPsec tunnels to send periodic messages to ensure the remote site is up. By default, DPD detection is enabled. ================ =============== =============== Field Value Description ================ =============== =============== Delay >= 1 Keepalive timer (in seconds) Retry Delay >= 1 How long should the tunnel wait before declaring keep alive failed. (in seconds) Maxfail >= 1 Number of tries before considering the peer is dead. ================ =============== =============== Active Active HA ------------------- Allow Site2Cloud gateways to support Active-Active mode where both tunnels are up and packets are routed to both gateways via respective VPC/VNet route tables. To enable this, go to Site2Cloud, edit the connection on the Setup page, scroll down to Active Active HA, and click **Enable**. Forward Traffic to Transit Gateway ----------------------------------- Typically you enable the **Forward Traffic to Transit Gateway** option when you have a Site2Cloud connection that has overlapping CIDRs. This forwarding ensures that traffic is sent between on-prem routers and local Spoke and Transit gateways. In most cases customers will enable this so that their on premise traffic is forwarded. For more information view the explanation `in this scenario <https://docs.aviatrix.com/HowTos/overlapping_network_solutions.html#scenario-4-multi-sites-overlap-in-aviatrix-transit-deployment>`_. This option is only available for route-based IPSec paired with Mapped NAT. Event Triggered HA ------------------- Event Trigger HA is a new mechanism to reduce the convergence time. To configure, go to Site2Cloud > select a connection, click **Edit**. Scroll down to Event Triggered HA and click **Enable**. Jumbo Frame ------------- Jumbo Frame improves the performance between an Aviatrix Transit gateway and CloudN or an Aviatrix Edge Gateway. .. note:: - Jumbo Frame feature is only supported on private connections that support Jumbo Frame. - Jumbo Frame is not supported for Transit Gateway connections to other devices such as, firewalls and routers. - Jumbo Frame is supported with High Performance Encryption and BGP over IPsec and BGP over GRE connections only. High Performance Encryption must be enabled on all gateways in the end-to-end path of the traffic flow. - Jumbo Frame is supported for AWS and OCI only; it is not supported for Azure and GCP. To configure: 1. Navigate to Site2Cloud > select a connection and click **Edit**. #. Scroll down to Jumbo Frame and click **Enable**. Clear Sessions ------------------- Clear Session allows to reset all the active sessions on a selected Site2Cloud connection: 1. Navigate to Site2Cloud > select a connection and click **Edit**. #. Scroll down to Clear Sessions and click **Clear**. Periodic Ping -------------------- In very rare cases Site2Cloud tunnels may fail to pass traffic if the tunnel is dormant for a long period of time. This is not an issue with the Aviatrix Gateways and can usually be traced to misconfigurations on the remote device. To compensate for this Periodic Ping was developed to maintain a steady flow of traffic across the tunnel. For configuration steps read the full article here: `Periodic Ping <https://docs.aviatrix.com/HowTos/periodic_ping.html>`_ Network Device Support ====================== Aviatrix Site2Cloud supports all types of on-prem firewall and router devices that terminate VPN connection. Below are configuration examples to specific devices. - `Azure VPN Gateway <./avxgw_azurevpngw_site2cloud.html>`_ - `AWS VGW <./site2cloud_awsvgw.html>`_ - `pfSense IPsec VPN <./CloudToPfSense.html>`__ - `Palo Alto Next-Gen Firewall (PAN) <./S2C_GW_PAN.html>`__ - `Check Point Firewall <./S2C_GW_CP.html>`__ - `Cisco ASA <./S2C_GW_ASA.html>`__ - `FortiGate <./site2cloud_fortigate.html>`__ - `Cisco Meraki MX64 <./site2cloud_meraki.html>`__ - `Cisco ISR <./S2C_GW_IOS.html>`__ - `Cisco Meraki vMX100 <./site2cloud_meraki_vmx100.html>`_ - `Aviatrix Gateway <./site2cloud_aviatrix.html>`_ Additional Use Cases ===================== Real-world use cases sometimes require a combination of Site2Cloud and other features, such as `SNAT <https://docs.aviatrix.com/HowTos/gateway.html#source-nat>`_ and `DNAT <https://docs.aviatrix.com/HowTos/gateway.html#destination-nat>`_. Here are a few documents in the Tech Notes session that demonstrate how you can solve some of them. - `Site2Cloud with customized SNAT <https://docs.aviatrix.com/HowTos/s2c_vgw_snat.html>`_. - `Site2Cloud for overlapping IP addresses <https://docs.aviatrix.com/HowTos/s2c_overlapping_subnets.html>`_. - `Site2Cloud to public IP addresses <https://docs.aviatrix.com/HowTos/s2c_for_publicIP.html>`_. - `How to build site to site connection <https://docs.aviatrix.com/HowTos/site_to_site_vpn.html>`_ - `Connecting offices to multiple VPCs using AWS Peering <https://docs.aviatrix.com/HowTos/simpletransit.html>`_ - `Connect Networks with Overlap CIDRs <https://docs.aviatrix.com/HowTos/connect_overlap_cidrs.html>`_ - `Connect Overlapping VPC to On-prem <https://docs.aviatrix.com/HowTos/connect_overlap_vpc_via_VGW.html>`_ Troubleshooting =============== To check a tunnel state, go to Site2Cloud. The tunnel status appears next to the connection. Diagnostics and troubleshooting options are available in the **Diagnostics** tab. You must first select the connection, and then select an **Action**, followed by **OK**. .. |site2cloud| image:: site2cloud_media/site2cloud.png :scale: 50% .. |site2cloud_new| image:: site2cloud_media/site2cloud_new.png :scale: 50% .. disqus:: <file_sep> ==================================== Aviatrix OpenVPN® Feature Highlights ==================================== This document highlights Aviatrix OpenVPN® features. For how to instructions, consult `this link <http://docs.aviatrix.com/HowTos/uservpn.html>`_. VPN Management -------------------------- - **Centrally Managed** A single pane of glass allows you to manage all VPN users, VPN certificates, and VPN user visibility. - **OpenVPN® Compatible** Built on OpenVPN® and is compatible with all OpenVPN® client software. - **Split Tunnel** Supports split tunnel mode where only specified CIDRs ranges go through the VPN tunnel. - **Full Tunnel** Supports full tunnel mode where all user IP sessions including Internet browsing go through the VPN tunnel. - **PKI Management** Supports Bring Your Own (BYO) PKI management system. - **Force Disconnect** Any admin can force disconnect a VPN user from the Controller. - **Dashboard** View all active VPN users and their connection history from the Controller dashboard. - **API** Support API for all management activities. Authentication Options ------------------------------------------- - **LDAP/AD Integration** Authenticates VPN user from Aviatrix Gateways in addition to VPN certificate authentication. - **DUO Integration** Authenticates VPN user from Aviatrix Gateways in addition to VPN cert authentication. - **OKTA Integration** Authenticates VPN user from Aviatrix Gateways in addition to VPN cert authentication. - **MFA Integration** Combines LDAP and DUO for multi-factor authentication. - **Shared Certificate** Supports a shared certificate arrangement among VPN users. (When this option is is selected, you should enable additional authentication options to ensure secure access.) - **Client SAML Integration** Authenticates a VPN user directly from the Aviatrix VPN client to any IDP via SAML protocol. Authorization -------------- - **Profile-Based Access Control** Each VPN user can be assigned to a profile that is defined by access privileges to network, host, protocol and ports. The access control is dynamically enforced when a VPN user connects to the public cloud via an Aviatrix VPN Gateway. For more description, refer to `this link <https://docs.aviatrix.com/HowTos/openvpn_faq.html#what-is-user-profile-based-security-policy>`_. For how to create user profiles and access policies, refer to `this link <https://docs.aviatrix.com/HowTos/openvpn_faq.html#how-do-i-setup-profile-based-security-policies>`_. For how to assign VPN users to profiles, refer to `this link <https://docs.aviatrix.com/HowTos/openvpn_faq.html#how-do-i-assign-a-user-to-a-profile>`_. Scale Out Performance ------------------------------------- - **TCP-based VPN** For a universal/no firewall/no fuss user VPN solution, use an Aviatrix-integrated NLB to load balance multiple Aviatrix VPN gateways. When NLB is used, OpenVPN® client software runs on TCP port 443. TCP-based VPN requires no special corporate firewall rules when VPN client is on-prem. - **UDP-based VPN** For a high performance user VPN solution, use Aviatrix-integrated AWS Route53 round robin routing to load balance multiple Aviatrix VPN gateways. When Route53 round robin routing is used, OpenVPN® client software runs on UDP port 1193. UDP-based VPN has improved file transfer performance. - **Geo VPN** For TCP-based VPN, you can use Aviatrix-integrated AWS Route53 latency-based routing to load balance clients residing in different geographic locations. Logging Integration ------------------- - **VPN User** VPN user connection history and bandwidth usage can be logged to Splunk, SumoLogic, ELK, Remote Syslog and DataDog. - **User Activity** Each VPN user TCP/UDP session can be logged to Splunk, SumoLogic, ELK, Remote Syslog and DataDog. Client Software --------------------------- - **OpenVPN® Client Software** All OpenVPN® client software is supported. The supported clients are macOS, Windows, iOS, Android, Chromebook, Linux and BSD. - **Aviatrix VPN Client** Aviatrix VPN Client supports macOS, Windows and Linux Debian distribution and BSD distribution. Choose Aviatrix VPN Client if you require SAML authentication directly from VPN client software. To download and install Aviatrix VPN Client, refer to `this link <https://docs.aviatrix.com/Downloads/samlclient.html>`_. OpenVPN® is a registered trademark of OpenVPN Inc. .. disqus:: <file_sep> ================= General Glossary ================= This Glossary provides definitions for terms related to common software, networking, cloud computing, or the Internet. For words and phrases directly associated with Aviatrix products, features, or terminology, please see the `Aviatrix Glossary <https://docs.aviatrix.com/HowTos/aviatrix_glossary.html>`_. Abstraction ^^^^^^^^^^^^^^^^^^^^^ The practice of simplifying the experience of a software product for the user by hiding unnecessary details and complexity. Abstraction makes software more accessible and attractive by enabling users to configure the product further without needing to work with programming languages or other technical information. Architecture ^^^^^^^^^^^^^^^^^^^^^ The design or organization of a system, including its components, processes, environment, and general principles. Anomaly Detection ^^^^^^^^^^^^^^^^^^^^^ A method of data mining/monitoring that examines behavior or incidents that differ from normal patterns. In network security, Anomaly Detection can help search for malware, viruses, hackers, or network failures or errors. API (Application Programming Interface) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ APIs enable systems and applications to exchange data – for example, for a data analysis tool to extract salary data from an accounting program. This data exchange is designed to automate large and complex data transfers securely. APIs often work two ways (each system sending and receiving information). See `webhook <https://docs.aviatrix.com/HowTos/general_glossary.html#id30>`_. Availability Zone (AZ) ^^^^^^^^^^^^^^^^^^^^^ (Used by `AWS <https://docs.aviatrix.com/HowTos/general_glossary.html#aws-amazon-web-services>`_ and `Azure <https://docs.aviatrix.com/HowTos/general_glossary.html#id1>`_): Highly available data centers within each AWS/Azure region. AZs are locations in different regions that can sustain local failures. AWS (Amazon Web Services) ^^^^^^^^^^^^^^^^^^^^^^^^^ Amazon’s `Cloud Service Provider (CSP) <https://docs.aviatrix.com/HowTos/general_glossary.html#id3>`_ offering, the industry leader for cloud platform providers. AWS provides on-demand cloud computing platforms and `APIs <https://docs.aviatrix.com/HowTos/general_glossary.html#api-application-programming-interface>`_. Automation ^^^^^^^^^^^^^^^^^^^^^ The practice of designing technology and systems that require minimal work for human beings – for example, automating report creation can simplify accountants’ jobs by removing a simple, repetitive task from their workloads. Cloud automation enables IT teams and developers to create, modify, and tear down resources on the cloud automatically. Azure ^^^^^^^^^^^^^^^^^^^^^ Microsoft Azure is Microsoft’s `CSP (Cloud Service Provider) <https://docs.aviatrix.com/HowTos/general_glossary.html#id3>`_ offering, a cloud computing service operated by Microsoft for application management via Microsoft-managed data center. Azure is behind Amazon’s service, `AWS <https://docs.aviatrix.com/HowTos/general_glossary.html#aws-amazon-web-services>`_, in terms of industry leadership, but is increasing its market share. BGP (Border Gateway Protocol) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ The dynamic routing protocol, or set of rules for directing traffic, for the Internet. BGP maximizes efficiency. It acts as the postal service of the Internet. Blast Radius ^^^^^^^^^^^^^^^^^^^^^ In computer networking, the Blast Radius is the area affected by an error, security failure, disruption, or other major problem; the maximum impact that might be sustained in the event of a system failure. Companies try to minimize the Blast Radius of each system or program to minimize damage per incident. Brownfield ^^^^^^^^^^^^^^^^^^^^^ In software, brownfield development is building new systems or software where there are already existing codes or legacy components. See `greenfield <https://docs.aviatrix.com/HowTos/general_glossary.html#id8>`_. CIDR (Classless Inter-Domain Routing) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Also known as supernetting. CIDR allocates `Internet Protocol (IP) <https://docs.aviatrix.com/HowTos/general_glossary.html#ip-internet-protocol-address>`_ addresses by creating unique and detailed addresses for networks and devices. A CIDR is the range of IP addresses a network uses. CIDR’s class system improves the efficiency of allocating IP (Internet Protocol) Addresses by using prefixes of varying lengths (variable-length subnet masking (VLSM)). Classless Inter-Domain Routing (CIDR) is a range of IP addresses a network uses. A CIDR address looks like a normal IP address, except that it ends with a slash followed by a number. The number after the slash represents the number of addresses in the range. Cloud ^^^^^^^^^^^^^^^^^^^^^ Cloud computing is the delivery of computing services—including servers, storage, databases, networking, software, analytics, and intelligence—you can access over the Internet, instead of managing a physical server yourself. Construct ^^^^^^^^^^^^^^^^^^^^^ Software components such as folders, websites, and files that exist virtually, not physically. CPU (Central Processing Unit) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The “brain” of almost any device, from a computer to a thermostat. CPUs process and execute instructions to make these devices work. CSP (Cloud Service Provider) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A company that sells cloud services: servers, components, platforms, and infrastructure. `Amazon Web Services (AWS) <https://docs.aviatrix.com/HowTos/general_glossary.html#aws-amazon-web-services>`_, `Azure <https://docs.aviatrix.com/HowTos/general_glossary.html#id1>`_, `Google Cloud Platform (GCP) <https://docs.aviatrix.com/HowTos/general_glossary.html#gcp-google-cloud-platform>`_, and `Oracle Cloud Infrastructure (OCI) <https://docs.aviatrix.com/HowTos/general_glossary.html#oci-oracle-cloud-infrastructure>`_ are all examples of CSPs. Data center ^^^^^^^^^^^^^^^^^^^^^ A physical location where companies store important data and applications. These centers are designed to network these resources to customers. Data centers can include switches, routers, firewalls, storage systems, servers, and controllers. Each data center creates its own `Availability Zone <https://docs.aviatrix.com/HowTos/general_glossary.html#availability-zone-az>`_. Day 2 Operations ^^^^^^^^^^^^^^^^^^^^^ (For IT personnel or `DevOps Engineers <https://docs.aviatrix.com/HowTos/general_glossary.html#devops>`_): The ability to observe the state of cloud networks across providers and respond to change without disruption, or maintaining the overall stability and health of your platform in production. Deploy/deployment ^^^^^^^^^^^^^^^^^^^^^ Software engineers “deploy” software systems or updates to make them available to users. A single “deployment” is usually smaller and less significant than a full product release: it implements updates and improvements. DevOps ^^^^^^^^^^^^^^^^^^^^^ A software engineer whose role includes development (creating, updating, and improving software) and operations (the processes, steps, and methods required to run software cycles). DevOps Engineers improve the efficiency and effectiveness of the release cycle. In some companies, they are known as “IT for engineers,” or highly-qualified IT personnel who have the expertise to address complex coding and networking issues. Duo ^^^^^^^^^^^^^^^^^^^^^ A two-factor authentication service that provides extra security for user accounts. DNS (Domain Name System) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The Domain Name System translates the domain names that are easier for human to remember, such as www.example.com, to the `IP (Internet Protocol) addresses <https://docs.aviatrix.com/HowTos/general_glossary.html#ip-internet-protocol-address>`_ that distinguish devices, websites, and other Internet entities from each other. DNS removes the need for people to remember complex numeric or alphanumeric IP addresses such as 314.837.1.2. Some websites compare DNS to a phonebook for the Internet. DPI (Deep Packet Inspection) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A type of network packet filtering in which a firewall examines the content of data packets to search for potential security threats. DPI differs from conventional packet filtering in that conventional filtering only examined the header information of each packet, not the contents (like reading the Subject line of an email but not the body). nDPI is an open-source library for DPI. ECMP (Equal Cost Multiple Path) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A networking feature that enables firewalls to use up to four routes to the same destination that have the same cost. ECMP improves the efficiency and flexibility of a network. Edge (in networking) ^^^^^^^^^^^^^^^^^^^^^ The security boundary where a local or private network connects to a third-party network. Egress ^^^^^^^^^^^^^^^^^^^^^ The exit of an entity or network boundary; outbound communication from instances in your VPC to the Internet. See `ingress <https://docs.aviatrix.com/HowTos/general_glossary.html#id11>`_. In `AWS <https://docs.aviatrix.com/HowTos/general_glossary.html#aws-amazon-web-services>`_, an egress can be centralized or distributed. A centralized egress ensures all traffic that is destined for a particular `IP address <https://docs.aviatrix.com/HowTos/general_glossary.html#ip-internet-protocol-address>`_ goes through a single VPC in which egress policy enforcement can take place before a connection is allowed to exit. A distributed egress means there would be a gateway in every VPC, and each of those gateways needs egress control. EIP (Enterprise Integration Patterns OR Enterprise Information Portal) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Enterprise Integration Patterns are a catalog of design patterns for integrating both new and existing software. * These design patterns provide solutions to known problems that recur in software. * Enterprise Information Portal is a knowledge base or resource and networking platform for enterprise employees, partners, or vendors. Encryption ^^^^^^^^^^^^^^^^^^^^^ Encryption is a process that uses digital keys to encode various components—text, files, databases, passwords, applications, or network packets. Encrypted data needs to be decrypted before it can be read. ESNI (Encrypted Server Name Indication) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A tool that keeps your software browsing private by masking the websites you are visiting. ESNI is a part of the TLS (Transport Layer Security) protocol. See `TLS <https://docs.aviatrix.com/HowTos/general_glossary.html#id28>`_. Firewall ^^^^^^^^^^^^^^^^^^^^^ A hardware or software device that acts as a wall or barrier between an internal network (such as a personal home’s system) and the Internet. Firewalls examine traffic in and out of the system and determine whether to allow it or not. More sophisticated firewalls examine the traffic and its source to detect malware, viruses, hackers, or unsafe destinations. There are four types of firewalls: * Stateless – A stateless firewall examines the header of each data packet, the destination address, and the source to determine whether to let traffic through via preset rules. * Stateful – A stateful firewall closely examines all data packets and their characteristics to determine whether to let traffic through. * Next-generation (Next-gen or NG) – A next-generation firewall uses the scrutiny of a stateful firewall with additional features such as integrated intrusion prevention, leveraging threat intelligence feeds, advanced malware detection, and application and user control. * L4-Layer – Works at the transport level and examines traffic without inspecting or decrypting data packets. * L7-Layer – Works at the application level and examines the contents of traffic. Full Mesh ^^^^^^^^^^ A type of networking design in which each node in the system has a circuit that connects it to every other node. While full mesh does make multiple redundant connections, this design keeps traffic going even if one node fails. Full-mesh design is useful in systems which are intransitive: A connects to B and B connects to C, but A cannot interact with C. FQDN (Fully Qualified Domain Name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The full domain name for a website, including the hostname, second-level domain name and TLD (Top-Level Domain) name, separated with periods and ending with a period, such as www.aviatrix.com. FTP (File Transfer Protocol) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The protocol, set of rules, or language that computers on a network use to transfer files. In FTP, files are transferred through an FTP server or site. Gateway (in cloud networking) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A hardware or software appliance that acts as a bridge or tunnel between local networks and cloud networks. A gateway connects and translates between these systems to enable them to communicate. GCP (Google Cloud Platform) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Google’s cloud computing service platform, a competitor of `Amazon Web Services (AWS) <https://docs.aviatrix.com/HowTos/general_glossary.html#aws-amazon-web-services>`_, `Microsoft Azure <https://docs.aviatrix.com/HowTos/general_glossary.html#id1>`_, `Oracle Cloud Infrastructure (OCI) <https://docs.aviatrix.com/HowTos/general_glossary.html#oci-oracle-cloud-infrastructure>`_, and other platforms. GRE (Generic Routing Encapsulation) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A tunneling protocol that enables data packets that are incompatible with the protocols of a network to travel through the network. GRE enables these data packets to travel through the network by encapsulating them in protocols that do fit the network’s settings. GRE is an alternative to `IPSec tunneling <https://docs.aviatrix.com/HowTos/general_glossary.html#ipsec-internal-protocol-security>`_. Greenfield ^^^^^^^^^^^^^^^^^^^^^ In software, greenfield development is building new, with no pre-existing structures or code. See `brownfield <https://docs.aviatrix.com/HowTos/general_glossary.html#brownfield>`_. HA (High Availability) ^^^^^^^^^^^^^^^^^^^^^ A network, server array, or other system designed to provide uninterrupted service by managing service failures and planned downtime. Hub and Spoke Distribution Model ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A network distribution model shaped like a hub with spokes, like a bicycle wheel. This topology includes a hub or central network zone that manages ingress and egress (entrances and exits) between spokes, on-premise networks, and the Internet. A Hub and Spoke Distribution Model can help companies save costs, but it does have a risk: if the hub fails, so does the entire system. IaaS (Infrastructure as a Service) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A cloud computing service that includes compute, storage, and networking services that customers can access. Users can rent virtual machines of different configurations, on demand, for the time required. IaaS is often on-demand and pay-as-you-go. IaaS is one of the cloud computing service types along with `PaaS (Platform as a Service) <https://docs.aviatrix.com/HowTos/general_glossary.html#id20>`_ and `SaaS (Software as a Service) <https://docs.aviatrix.com/HowTos/general_glossary.html#id22>`_. IAM (Identity and Access Management) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Processes, policy, and technologies to help manage digital identities. IAM frameworks enable IT personnel to make sure users in their organizations can safely and securely access systems and data they should be able to access and unauthorized users cannot access the system. ICMP (Internet Control Message Protocol) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Network devices such as routers uses this protocol to communicate problems with data transmission ― whether data travels fast enough in a network. IDA (Intrusion Detection System) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A system that monitors a network for suspicious activity or malware. IDaaS (Identity as a Service) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A subscription service for `IAM (Identity and Access Management) <https://docs.aviatrix.com/HowTos/general_glossary.html#iam-identity-and-access-management>`_. IDaaS helps ensure that authorized users can access systems while still keeping those systems secure. Okta and OneLogin are examples of IDaaS companies. In-Band Management ^^^^^^^^^^^^^^^^^^^^^ In-Band Management is the ability to administer a network via the LAN. See `Out of Band (OOB) <https://docs.aviatrix.com/HowTos/general_glossary.html#oob-out-of-band>`_. Infrastructure ^^^^^^^^^^^^^^^^^^^^^ The components or assets that make up a system. Architecture is the actual design of the system. Ingress ^^^^^^^^^^^^^^^^^^^^^ Traffic that enters a network. See `egress <https://docs.aviatrix.com/HowTos/general_glossary.html#egress>`_. Firewalls examine ingress traffic for potential malware or other unauthorized access. A firewall permits instances to receive traffic from the Internet or specified IPv4/IPV6 `CIDR <https://docs.aviatrix.com/HowTos/general_glossary.html#cidr-classless-inter-domain-routing>`_ ranges. Investment Cost (in cloud networking) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The time, expertise, opportunity cost, and engineering effort required to adopt cloud. IOS (iPhone Operating System) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The operating system for Apple devices such as the iPhone and Apple TV. IoT (Internet of Things) ^^^^^^^^^^^^^^^^^^^^^ Physical objects or “things” that have software and other technology that connects them to the Internet. Internet of Things (IoT) connects and manages billions of devices. IP (Internet Protocol) Address ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A numeric or alphanumeric address assigned to every device connected to the Internet, from smartphones to computers. See `CIDR <https://docs.aviatrix.com/HowTos/general_glossary.html#cidr-classless-inter-domain-routing>`_ to learn about how IP addresses are allocated or DNS to learn more about how IP addresses are translated to more-memorable domain names. As the Internet grows bigger and more and more devices, systems, and machines become a part of it, more versions of assigning IP addresses appear. The Internet Engineering Task Force (IETF) created the sixth version, IPv6, in 1998. IP can be used with several transport protocols, including `TCP <https://docs.aviatrix.com/HowTos/general_glossary.html#tcp-transmission-control-protocol>`_ and `UDP <https://docs.aviatrix.com/HowTos/general_glossary.html#udp-user-datagram-protocol>`_. IPS (Intrusion Prevention System) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A network security tool that blocks, reports, or blocks threats or intruders in a system. IPsec (Internal Protocol Security) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A set of security protocols for `IP (Internet Protocol) <https://docs.aviatrix.com/HowTos/general_glossary.html#ip-internet-protocol-address>`_ networks that are used together to set up encrypted connections between devices. LAN (Local Area Network) ^^^^^^^^^^^^^^^^^^^^^^^ A group of two or more connected computers in one small geographic area, usually within the same building or campus. LANs can be connected across larger distances by `WANs (Wide Area Networks) <https://docs.aviatrix.com/HowTos/general_glossary.html#wan-wide-area-network>`_. Latency ^^^^^^^^^^^^^^^^^^^^^ The time it takes for a data packet to transfer across a network. Network administrators and IT personnel try to minimize latency as much as possible. LDAP (Lightweight Direct Access Protocol) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A standard communications protocol used to read and write data to and from an Active Directory. Line rate Gbps ^^^^^^^^^^^^^^^^^^^^^ The speed at which your router communicates with equipment at the other end of the line, measured in gigabytes per second. MCNA (Multi-Cloud Networking Architecture) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Architecture that stores and supports multiple cloud computing and storage systems, both public (like `Amazon Web Services (AWS) <https://aws.amazon.com/free/?trk=fce796e8-4ceb-48e0-9767-89f7873fac3d&sc_channel=ps&sc_campaign=acquisition&sc_medium=ACQ-P|PS-GO|Brand|Desktop|SU|Core-Main|Core|US|EN|Text&s_kwcid=AL!4422!3!423740514695!e!!g!!amazon%20web%20services&ef_id=CjwKCAiAyPyQBhB6EiwAFUuakhrje2kPR-HnjqbEQ4hlh7IkPdr0wVwk0IV3BD5LYqeumvQ32lNmMhoCYMAQAvD_BwE:G:s&s_kwcid=AL!4422!3!423740514695!e!!g!!amazon%20web%20services&all-free-tier.sort-by=item.additionalFields.SortRank&all-free-tier.sort-order=asc&awsf.Free%20Tier%20Types=*all&awsf.Free%20Tier%20Categories=*all>`_) and private. Multi-Cloud Networking Architecture gives companies greater security, flexibility, and opportunity to use multiple cloud systems instead of being dependent on one or trying to manage data and users across multiple separate systems. Multi-Cloud Agility ^^^^^^^^^^^^^^^^^^^^^ The ability to treat the many network capabilities provided by `Cloud Service Providers (CSPs) <https://docs.aviatrix.com/HowTos/general_glossary.html#id3>`_ as one. A `Multi-Cloud Networking <https://docs.aviatrix.com/HowTos/general_glossary.html#mcna-multi-cloud-networking-architecture>`_ solution achieves agility when it replaces the unique language of each individual cloud with more general terminology. MFA (Multi-Factor Authentication) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ An identification method that requires users to provide at least two “factors” (such as a username & password and a phone number) to log into a system or account. MFA increases the overall security of a system. See `IAM <https://docs.aviatrix.com/HowTos/general_glossary.html#iam-identity-and-access-management>`_. NAT (Network Address Translation) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A security process that enables a local or private network to connect to the Internet but prevents Internet entities from connecting with the local network. * NAT translates the IP addresses of the local network to their `IP (Internet Protocol) addresses <https://docs.aviatrix.com/HowTos/general_glossary.html#ip-internet-protocol-address>`_ that enable them to connect with resources on the Internet. * NAT can also mask a group of resources in the private network behind a single IP address so they cannot be distinguished from each other, providing extra security. This second function is sometimes called “NAT-ing” or “natting.” See `SNAT <https://docs.aviatrix.com/HowTos/general_glossary.html#snat-source-network-address-translation>`_. NACL (Networking and Cryptography Library OR Network Access Control List) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The acronym NACL has two possible meanings in networking software: #. NaCL (“salt”) is a software library of resources for building cryptographic tools. #. NACL (Network Access Control List) is part of the security layer for `AWS (Amazon Web Services) <https://docs.aviatrix.com/HowTos/general_glossary.html#aws-amazon-web-services>`_. This NACL is a layer of security that acts as a firewall for controlling traffic in and out of a subnet. Native (in software) Software or data formats designed to run on a specific operating system, such as an iPhone or Android. Companies have to decide whether to build native apps and software for each platform (which are more expensive to create and maintain) or use cross-platform software (which is easier to create and maintain but may not have the same quality or speed in each platform). Network ^^^^^^^^^^^^^^^^^^^^^ A collection of connected devices and software than share data. The biggest network is the Internet itself. Network Ossification ^^^^^^^^^^^^^^^^^^^^^ The danger of assuming that something in software, networking, or the Internet in general cannot change because it has not changed. For example, in the Y2K scare of the 1990s, engineers worried that the Internet would stop working when the date changed from “19__” to “20__.” Ossification prevents software from upgrading, adapting, or improving over time. Network Visibility ^^^^^^^^^^^^^^^^^^^^^ A holistic view of Cloud Network assets and Key Performance Indicators (KPIs) or important metrics. Network visibility technology provides deep insights into everything within and moving through customer’s enterprise network. NLB (Network Load Balancing) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A technique that shares a resource over multiple network channels to divide a sending payload over components or segments. There are two types of Load Balancing: Layer 4 or Layer 7. On-prem or on-premise ^^^^^^^^^^^^^^^^^^^^^ Software that is deployed or delivered on-premise: the servers, network connections, and other components are on the company’s property. Off-promise software such as cloud networking software can be accessed remotely. On-premise software gives companies complete control over their software resources, but they are far more expensive to maintain. OCI (Oracle Cloud Infrastructure) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Oracle’s CSP (Cloud Service Provider) offering. Oracle is behind `AWS <https://docs.aviatrix.com/HowTos/general_glossary.html#aws-amazon-web-services>`_, `Azure <https://docs.aviatrix.com/HowTos/general_glossary.html#id1>`_, and `GCP <https://docs.aviatrix.com/HowTos/general_glossary.html#gcp-google-cloud-platform>`_ in the market. OOB (Out of Band) ^^^^^^^^^^^^^^^^^^^^^ Activity outside a defined telecommunications frequency band, or, metaphorically, outside some other kind of activity. OOB provides a secure dedicated alternate access method into an IT network infrastructure to administer connected devices and IT assets without using the corporate `LAN <https://docs.aviatrix.com/HowTos/general_glossary.html#lan-local-area-network>`_. See `In-Band Management <https://docs.aviatrix.com/HowTos/general_glossary.html#in-band-management>`_. PaaS (Platform as a Service) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ One of the options for cloud computing services. With PaaS, the company owns the applications and data but pays for the use of servers from a cloud services provider. See `IaaS <https://docs.aviatrix.com/HowTos/general_glossary.html#iaas-infrastructure-as-a-service>`_ and `SaaS <https://docs.aviatrix.com/HowTos/general_glossary.html#id22>`_. PBR (Policy-Based Routing) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A technique used in computer networks for forwarding and routing data according to pre-written policies or filter. PBR improves the efficiency of a network. Peering ^^^^^^^^^^^^^^^^^^^^^ The process of free data sharing between two providers, services, or other Internet entities. Peering is one option other than transit or customer network traffic, where one network pays for access. Ping ^^^^^^^^^^^^^^^^^^^^^ Ping is a program that helps you test the connectivity and speed between `IP (Internet Protocol) <https://docs.aviatrix.com/HowTos/general_glossary.html#ip-internet-protocol-address>`_-networked devices, such as your computer and the Internet. You can “ping” a website or device to test the latency or speed of the connection. Protocol ^^^^^^^^^^^^^^^^^^^^^ A set of rules for formatting and processing data in networking. Protocols enable computers to communicate with one another. Router ^^^^^^^^^^^^^^^^^^^^^ A hardware or software device that connects a local network to the Internet. Routers can combine the functions of hubs, modems, or switches. Route/Routing Table ^^^^^^^^^^^^^^^^^^^^^ In computer networking, a routing table is a data file often formatted as a table. A routing table contains a set of rules that determines where data packets from an `Internet Protocol (IP) address <https://docs.aviatrix.com/HowTos/general_glossary.html#ip-internet-protocol-address>`_ should be routed. SaaS (Software as a Service) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ One of the cloud computing service offerings. In SaaS, a company pays another company for use of a software service. SaaS vendors own the servers, applications, and data. See `IaaS <https://docs.aviatrix.com/HowTos/general_glossary.html#iaas-infrastructure-as-a-service>`_ and `PaaS <https://docs.aviatrix.com/HowTos/general_glossary.html#id20>`_. SAML (Security Assertion Markup Language) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ SAML enables SSO (Single Sign-On), which enables a user to access multiple web applications using a single set of login credentials. SAML exchanges information between an identity provider (idP) who verifies the user’s identity, and each web application they can access. See `SSO <https://docs.aviatrix.com/HowTos/general_glossary.html#sso-single-sign-on>`_. SD-WAN (Software-Defined Wide Area Network) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ (Software-defined `Wide Area Network <https://docs.aviatrix.com/HowTos/general_glossary.html#wan-wide-area-network>`_) A software-defined wide area network (SD-WAN) connects local area networks (LANs) across large distances using controlling software that works with a variety of networking hardware.= and it is more flexible WAN architecture that can take advantage of multiple hardware platforms and connectivity option. See `LAN (Local Area Network) <https://docs.aviatrix.com/HowTos/general_glossary.html#lan-local-area-network>`_. Segmentation ^^^^^^^^^^^^^^^^^^^^^ A method of structuring software architecture that separates certain subnets into mini-networks that work independently of each other. Segmentation is important for performance, monitoring, and security. Single pane of glass ^^^^^^^^^^^^^^^^^^^^^ A software term that refers to a management tool that creates a single, unified view out of multiple data sources or interfaces. A single pane of glass gives you a comprehensive view and ability to manage complex and multi-layered systems. SNAT (Source Network Address Translation) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A networking feature that translates a virtual machine's private `IP <https://docs.aviatrix.com/HowTos/general_glossary.html#ip-internet-protocol-address>`_ into Load Balancer's public IP address. SNAT helps keep the private network secure. See `NAT <https://docs.aviatrix.com/HowTos/general_glossary.html#nat-network-address-translation>`_. SNI (Server Name Indication) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ An extension of the `TLS (Transport Layer Security) <https://docs.aviatrix.com/HowTos/general_glossary.html#id28>`_ protocol that helps clients reach the correct website. SNI allows the server to safely host multiple TLS Certificates for multiple sites, all under a single `IP address <https://docs.aviatrix.com/HowTos/general_glossary.html#ip-internet-protocol-address>`_. SSH (Secure Shell or Secure Socket Shell) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A method for secure remote login from one computer to another. SSL (Secure Sockets Layer) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A protocol that provides privacy, authentication, and integrity to Internet communications. SSL eventually evolved into `Transport Layer Security (TLS) <https://docs.aviatrix.com/HowTos/general_glossary.html#id28>`_. SSO (Single Sign-On) ^^^^^^^^^^^^^^^^^^^^^ Single Sign-On, a method of access and authentication which enables one user to access multiple web applications through one set of login credentials. SSO is a compromise between security (ensuring that both the user’s profile and each web account is password-protected) and ease-of-use (removing the requirement for users to memorize dozens of individual usernames and passwords). Subnet ^^^^^^^^^^^^^^^^^^^^^ A division of an `Internet Protocol (IP) <https://docs.aviatrix.com/HowTos/general_glossary.html#ip-internet-protocol-address>`_ network into segments. Dividing networks into subnets helps each smaller network run more efficiently and be more secure. The simplest subnet is a point-to-point subnet which connects two devices. Suricata ^^^^^^^^^^^^^^^^^^^^^ The leading open-source threat detection engine. Suricata combines Intrusion Detection (IDS), `Intrusion Prevention (IPS) <https://docs.aviatrix.com/HowTos/general_glossary.html#ips-intrusion-prevention-system>`_, and other tools to prevent attacks. Terminate ^^^^^^^^^^^^^^^^^^^^^ In networking, to “terminate” can mean to end or break a connection or to provide an endpoint for the connection. Terraform ^^^^^^^^^^^^^^^^^^^^^ An Infrastructure as Code (IaC) tool that enables you to build, maintain, change, and replicate infrastructure. Turn-key ^^^^^^^^^ A type of computer system that is full set up and ready to use. A user should be able to metaphorically turn a key to start using the system’s hardware and software. TCP (Transmission Control Protocol) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A standard for establishing and continuing network conversations or data exchanges between applications. TCP works with Internet Protocol (IP). See `Internet Protocol (IP) Address <https://docs.aviatrix.com/HowTos/general_glossary.html#ip-internet-protocol-address>`_. TLS (Transport Layer Security) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A cryptographic protocol that provides end-to-end security for exchanging data over the Internet. TLS is the successor to `SSL <https://docs.aviatrix.com/HowTos/general_glossary.html#ssl-secure-sockets-layer>`_. UDP (User Datagram Protocol) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A communications protocol that helps minimize latency (the time it takes to exchange data) and secure connections between Internet applications. UDP is a very common protocol for voice and video traffic. Velocity ^^^^^^^^^^^^^^^^^^^^^ Rate of innovation and ability to deliver new products to market. VM (Virtual Machine) ^^^^^^^^^^^^^^^^^^^^^ A computer resource with its own operating system and functions that can run alongside similar resources (other Virtual Machines) on the same physical host machine. Computer networks connect Virtual Machines to other devices and Internet resources. VPN (Virtual Private Network) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A network that creates a secure connection between multiple devices and the Internet using encryption. Companies will often have their own VPNs that act as sheltered spaces for their employees and contractors to work in. See `VPN Tunnel <https://docs.aviatrix.com/HowTos/general_glossary.html#vpn-virtual-private-network-tunnel>`_. VPN (Virtual Private Network) Tunnel ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ An encrypted link between your personal device(s) such as laptops or phones and an outside network. VPN Tunnels are secure connections. See `VPN <https://docs.aviatrix.com/HowTos/general_glossary.html#vpn-virtual-private-network>`_. Walled garden ^^^^^^^^^^^^^^^^^^^^^ A software construct (such as a suite) which provides its services only for its own users. `AWS <https://docs.aviatrix.com/HowTos/general_glossary.html#aws-amazon-web-services>`_ is an example of a walled garden service: you must subscribe in order to use its resources. WAN (Wide Area Network) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A network that connects devices and resources over a large geographic area. A WAN can connect multiple `LANs (Local Area Networks) <https://docs.aviatrix.com/HowTos/general_glossary.html#lan-local-area-network>`_. Note that now, Aviatrix uses the term “CloudN” instead of “CloudWAN.” Webhook ^^^^^^^^^^^^^^ A lightweight API (Application Program Interface) that enables a one-way connection to share data. See `API <https://docs.aviatrix.com/HowTos/general_glossary.html#api-application-programming-interface>`_. Zero Trust Model ^^^^^^^^^^^^^^^^^^^^^ A security framework that assumes there is no traditional network edge and requires all users to be authenticated and validated to enter a system. “Zero trust” means that this framework does not assume any user or application is automatically trustworthy. ZTP (Zero-Touch Provisioning) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ZTP automates repetitive tasks, reduce human touch points, reduce errors and scale the deployment process to any size. ZTP can be found in switches, wireless access points, (`SD-WAN <https://docs.aviatrix.com/HowTos/general_glossary.html#sd-wan-software-defined-wide-area-network>`_) routers, NFV (Network Functions Virtualization) platform, and firewalls. .. disqus:: <file_sep> ################################### Tag Based Security Policy ################################### Aviatrix Gateway security policies are implemented at each gateway. Key features are: * It is a L4 stateful firewall that filters on CIDR, protocol and port. * Each policy is associated with an Allow or Deny action. * A Base policy for "Allow" or "Deny" for the gateway can be used as a catch-all rule. * All security policy events as well as packets can be logged to Splunk, SumoLogic, Syslog, ELK, and Datadog. Starting with release 3.0, a tag mechanism has been introduced to make the security policy specification more user-friendly. You can associate an IP address or a subnet with a name tag and use it as a shorthand to specify the source and destination for your security rules. Defining a Tag -------------------- You give a tag a name and a list of one or more network addresses. The network address can be a subnet or a host IP address. Navigate to Security > Stateful Firewall > Tag Management > Add New. A tag is a global resource to the Aviatrix Controller and can be applied to any gateway. Editing a Tag ------------------ Once a tag is created, you can edit the tag. Editing is about adding a name to a CIDR address (network address or host address). Multiple Name<->CIDR pair can be added. When you are done editing, click **Update** to implement your changes. Applying Policy --------------------- Navigate to Security > Stateful Firewall > Policy. You should see a list of gateways that the Controller manages. Highlight a gateway and click **Edit**. To configure security policies, select a Base Policy. A Base Policy is always attached as the last rule as a catch-all policy. Select **Enable Packet Logging** if you want to forward logs to well known log management systems, such as Splunk, Sumo Logic, Elastic Search, and remote syslog. If you click **Add New**, you can specify Source by manually entering a specific CIDR. You can also click the table icon to select one of the tags you created earlier. Both Source and Destination can be configured either manually or by using tags. Once a rule is saved, you must remember to click **Update** for the policy to take effect. Note: For the Destination field, if a host name is specified either manually or with a tag, the IP address of the host name will be resolved when programming the security policy. A host name is not suitable if it is a public web site, such as www.google.com. To filter on public host names, refer to `FQDN Whitelists. <http://docs.aviatrix.com/HowTos/FQDN_Whitelists_Ref_Design.html>`__ Viewing Policy and Tags ------------------------------ To view the names in a tag, select **Tag Management**, highlight a tag and click **Edit**. To view the policies of gateway, select **Policy**, highlight a gateway, and click **Edit**. Example Use Case -------------------------- Say you have a group of virtual machine (EC2/GCE) instances or a group of AWS Workspace instances. You would like to set up policies to allow them to access a database which itself consists of a group of nodes. You can create a tag, name it my-app, and configure the list of IP addresses associated with each instance with a name. You can then create a second tag, name it my-database, and configure the list of IP addresses associated with each instance with a name. You then can simply apply one policy at the gateway that says my-app to my-database is allowed. The Controller will automatically push the policies to the gateway. .. disqus:: <file_sep> Quick Tour =========== Scaling Out a Remote User VPN Solution ---------------------------------------------------- No more bastion stations and jump hosts. Provide your employees with the ability to seamlessly access instances with private IP addresses by using our user VPN capability. To configure a Cloud VPN: 1. At the Gateway menu, create a gateway with VPN access enabled. 2. Repeat the step above for multiple gateways if ELB is enabled to create a scale out VPN solution. 3. (Optional) At OpenVPN® > Profiles, define VPN user profiles and access policies for each profile that will be dynamically enforced as user connects to the cloud at the network perimeter. 4. Navigate to OpenVPN® > VPN Users and add VPN users. 5. For a single VPC/VNet user VPN solution, open `this link. <http://docs.aviatrix.com/HowTos/uservpn.html>`__ 6. For a multi-VPC/VNet user VPN solution, open this `reference design <http://docs.aviatrix.com/HowTos/Cloud_Networking_Ref_Des.html>`__ Geo VPN -------------------- If you have a global workforce and would like to give your employees the best user experience in accessing the services in the cloud, Geo VPN is the right solution for you. Go to Open VPN > Geo VPN to enable Geo VPN. See this `reference design <http://docs.aviatrix.com/HowTos/GeoVPN.html>`__. Developer’s Sandbox ------------------------------- If keeping your production environment secure while giving your developers an isolated environment to learn and experiment with new technologies is a challenge for you, see the `Developer’s Sandbox <http://docs.aviatrix.com/HowTos/DevSandbox.html>`__ feature. AWS Global Transit Network ------------------------------------ Follow `these instructions <http://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ to build an AWS Global Transit Network. Site2Cloud Solution ---------------------------- If you need to connect to your partner or customer sites to a VPC/VNet but do not want to replace the edge routers or firewalls that is already deployed at these sites, check out our `Site2Cloud reference design <http://docs.aviatrix.com/HowTos/site2cloud.html>`__. Help ----------------- Under the Help menu, check out FAQs and additional implementation guides. Please open a support ticket at the `Aviatrix Support Portal <https://support.aviatrix.com>`_ to get immediate support. OpenVPN is a registered trademark of OpenVPN Inc. .. disqus:: <file_sep> ========================================================================================== Azure Multi-Cloud Transit BGP over LAN Workflow ========================================================================================== Introduction ============ Transit BGP to LAN allows Aviatrix Transit Gateways to communicate with a pair of instances in different VNets in Azure without running any tunneling protocol such as IPsec or GRE. One use case is to interoperate with third-party virtual appliances such as SD-WAN cloud instances that do not have the capability to support BGP over any tunneling protocols. For example, integrating with SD-WAN gateways can be deployed as below, |sd_wan_inte_azure| where an Aviatrix Multi-Cloud Transit Gateway connects to a third-party cloud instance in different VNets in Azure. This document describes a step-by-step instruction on how to build Aviatrix Transit Gateway to External Device using BGP over LAN in Azure. In this Tech Note, you learn the following: #. Workflow on `deploying Aviatrix Transit Solution <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_azure_workflow.html#deploy-aviatrix-multi-cloud-transit-solution>`_ #. Workflow on `launching third-party cloud instances <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_azure_workflow.html#launch-third-party-cloud-instances>`_ #. Workflow on `building BGP over LAN <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_azure_workflow.html#build-bgp-over-lan>`_ For other BGP over LAN workflows, please check out the below documents: - `AWS Multi-cloud Transit BGP over LAN Workflow <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_workflow.html>`_ - `Aviatrix BGP over LAN with Cisco Meraki in AWS <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_with_aws_meraki_workflow.html>`_ For more information about Multi-Cloud Transit Network and External Device, please check out the below documents: - `Multi Cloud Global Transit FAQ <https://docs.aviatrix.com/HowTos/transitvpc_faq.html#multi-cloud-global-transit-faq>`_ - `Global Transit Network Workflow Instructions (AWS/Azure/GCP/OCI) <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ - `Aviatrix Transit Gateway to External Devices <https://docs.aviatrix.com/HowTos/transitgw_external.html>`_ - `Transit Network Design Patterns <https://docs.aviatrix.com/HowTos/transitvpc_designs.html>`_ .. important:: - This solution supports only `ActiveMesh 2.0 <https://docs.aviatrix.com/HowTos/activemesh_faq.html#what-is-activemesh-2-0>`_, please check this doc `How to migrate to ActiveMesh 2.0 <https://docs.aviatrix.com/HowTos/activemesh_faq.html#how-to-migrate-to-activemesh-2-0>`_ for migration detail. - This solution is available to AWS and Azure. To configure this solution for AWS, see `AWS Multi-Cloud Transit BGP over LAN Workflow <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_workflow.html>`_. Please adjust the topology depending on your requirements. - LAN interfaces for Aviatrix Transit Primary and third-party cloud instance must be in the different VNets. - One BGP over LAN connection per gateway is supported. The key ideas for this solution are: ---------------------------------------- - A BGP session establishes between a third-party cloud instance and Aviatrix Transit Gateway via each LAN interface in different VNets. - Data plane traffic also runs between a third-party cloud instance and Aviatrix Transit Gateway via each LAN interface without a tunnel protocol such as IPsec and GRE. Prerequisites ==================== - This feature is available for 6.3 and later. `Upgrade <https://docs.aviatrix.com/HowTos/inline_upgrade.html>`_ Aviatrix Controller to at least version 6.3. - In this example, we are going to deploy the below VNets in Azure: - Transit VNets (i.e. 10.1.0.0/16 and 10.2.0.0/16) by utilizing Aviatrix feature `Create a VNet <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ with Aviatrix FireNet VNet option enabled - Spoke VNets (i.e. 192.168.11.0/24 and 192.168.21.0/24) by utilizing Aviatrix feature `Create a VNet <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ as the previous step or manually deploying it in each cloud portal. Moreover, feel free to use your existing cloud network. - Third-party cloud instance has high throughput supported. Deploying Aviatrix Multi-Cloud Transit Solution ================================================= Refer to `Global Transit Network Workflow Instructions <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ for the below steps. Please adjust the topology depending on your requirements. 1. Deploy `Aviatrix Multi-Cloud Transit Gateway and HA <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html#step-2-deploy-the-transit-aviatrix-gateway>`_ with Insane Mode enabled in Transit VNet. .. Important:: Mark the **BGP Over LAN** checkbox to enable that function. See `this document <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_azure_workflow.html#performance-benchmark>`_ for more information about Gateway size and benchmark performance. 2. Deploy `Spoke Gateway and HA <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html#step-3-deploy-spoke-gateways>`_ to launch Aviatrix Spoke gateway and enable HA with insane mode enabled in Spoke VNet. 3. Attach `Spoke Gateways to Transit Network <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html#step-4-attach-spoke-gateways-to-transit-network>`_. 4. (Optional) Attach `Azure ARM Spoke VNet via native peering <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#b-attach-azure-arm-spoke-vnet-via-native-peering>`_ if users prefer not to encrypt the traffic between the Transit VNet and the Spoke VNet. In this example, this approach is selected to benchmark `performance <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_azure_workflow.html#performance-benchmark>`_. 2. Launch Third-Party Cloud Instances ================================================================================ Deploy third-party cloud instances in a separate Transit VNet. #. Create a third-party cloud instance and put MGMT interface in public gateway subnet. #. Create a new public WAN subnet and a dedicated routing table for WAN interface if needed. #. Create a new private LAN subnet and a dedicated routing table for LAN interface. #. Make sure the function IP forwarding function on third-party cloud instance's interfaces is enabled. .. important:: An Aviatrix Transit Gateway and third-party cloud instance CANNOT be deployed in the same Transit VNet. Building BGP over LAN ================================================ Creating Azure VNet Peering Between Aviatrix Transit VNet and Third-Party Cloud Instance Transit VNet ---------------------------------------------------------------------------------------------------------------------------------- See `Azure VNET Peering doc <https://docs.aviatrix.com/HowTos/peering.html#azure-vnet-peering>`_ for more info. #. Log in to the Aviatrix Controller and go to Peering > Azure. #. Click **+ NEW PEERING**. #. Select VNet where Aviatrix Transit gateway locates as Peer1. #. Select VNet where third-party cloud instance locates as Peer2. #. Click **OK**. Configuring BGP over LAN on Aviatrix Transit Gateway --------------------------------------------------------------------- 1. Log in to the Aviatrix Controller. 2. Go to Multi-Cloud Transit > Setup > External Connection. 3. Select option External Device > BGP > LAN. 4. Enter the following information in the fields provided. +----------------------------------+-----------------------------------------------------------------------------------------------------------------------------+ | Transit VPC Name | Select the Transit VPC ID where Transit GW was launched | +----------------------------------+-----------------------------------------------------------------------------------------------------------------------------+ | Connection Name | Provide a unique name to identify the connection to external device | +----------------------------------+-----------------------------------------------------------------------------------------------------------------------------+ | Aviatrix Transit Gateway BGP ASN | Configure a BGP AS number that the Transit GW will use to exchange routes with external device | +----------------------------------+-----------------------------------------------------------------------------------------------------------------------------+ | Primary Aviatrix Transit Gateway | Select the Transit GW | +----------------------------------+-----------------------------------------------------------------------------------------------------------------------------+ | Enable Remote Gateway HA | Check this option in this example to connect two external devices | +----------------------------------+-----------------------------------------------------------------------------------------------------------------------------+ | Remote BGP AS Number | Configure a BGP AS number that third-party cloud primary instance will use to exchange routes with Aviatrix Transit Primary | +----------------------------------+-----------------------------------------------------------------------------------------------------------------------------+ | Remote VNet Name | Select the Transit VNet where third-party cloud instance locates | +----------------------------------+-----------------------------------------------------------------------------------------------------------------------------+ | Remote LAN IP | Use the private IP of the LAN interface of the third-party cloud primary instance | +----------------------------------+-----------------------------------------------------------------------------------------------------------------------------+ | Local LAN IP | Aviatrix detects the Local LAN IP automatically | +----------------------------------+-----------------------------------------------------------------------------------------------------------------------------+ | Remote BGP AS Number (Backup) | Configure a BGP AS number that third-party cloud HA instance will use to exchange routes with Aviatrix Transit HA | +----------------------------------+-----------------------------------------------------------------------------------------------------------------------------+ | Remote LAN IP (Backup) | Use the private IP of the LAN interface of the third-party cloud HA instance | +----------------------------------+-----------------------------------------------------------------------------------------------------------------------------+ | Local LAN IP (Backup) | Aviatrix detects the Local LAN IP automatically | +----------------------------------+-----------------------------------------------------------------------------------------------------------------------------+ 4. To generate BGP session over LAN, click **Connect**. S(Optional) Downloading the BGP over LAN configuration sample from Aviatrix Controller -------------------------------------------------------------------------------------------- #. Navigate to Site2Cloud > Setup. #. Select the connection that you created with Connection Name in the previous step. #. Click **Edit**. #. Select Vendor type, Platform, and Software. #. Click Download Configuration. Configuring BGP over LAN on Third-Party Cloud Instance --------------------------------------------------------------- #. Log in to the Azure portal. #. Create a user-defined routing table with default route (0.0.0.0/0) pointing nexthop to Aviatrix Primary Transit's LAN IP for the subnet where third-party cloud primary instance's LAN interface locates. #. Create a user-defined routing table with default route (0.0.0.0/0) pointing nexthop to Aviatrix HA Transit's LAN IP for the subnet where third-party cloud HA instance's LAN interface locates for HA deployment. #. (Optional) Open the downloaded BGP over LAN configuration file. #. Log in third-party cloud instance. #. Program route to send traffic to Aviatrix Transit's LAN IP through third-party cloud instance's LAN interface. #. Configure those related BGP and LAN info on third-party cloud instance. #. Check whether the function 'eBGP multi-hop' is enabled if BGP session is not established. #. Repeat those steps for HA deployment. .. important:: Customer must create a default route 0.0.0.0/0 in the third-party cloud instance's LAN route table to point to Aviatrix Transit's LAN IP over VNET peering in Azure. Verifying LAN status on Aviatrix Controller ---------------------------------------------------------- #. Navigate back to Aviatrix Controller. #. Go to Site2Cloud > Setup. #. Under Create a New Site2Cloud Connection, find the connection that you created with Connection Name in the previous step. #. Check the Tunnel Status. Then: #. Go to Multi-Cloud Transit > List. #. Select the Transit Primary Gateway that was created in the previous step. #. Click **Details/Diag**. #. Scroll down to Connections > On-prem Connections. #. Under On-prem Connections, find the connection that you created with Connection Name in the previous step. #. Check the Tunnel Status in the Status column. Verifying BGP session status on Aviatrix Controller ---------------------------------------------------------- #. Go to Multi-Cloud Transit > BGP. #. In the Connections tab on this page, find the connection that you created with Connection Name in the previous step. #. Check the BGP Status. Ready to Go ================= At this point, run connectivity and performance test to ensure everything is working correctly. Performance Benchmarks =========================== End-to-End traffic via Native Spoke VNet <-> Aviatrix <-> Aviatrix <-> Native Spoke VNet ---------------------------------------------------------------------------------------- The performance test is done with a pair of Aviatrix Transit Gateways as the third-party cloud instances, as shown below. Multiple flows result by using iperf3 tool with TCP 128 connections ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +-----------------------+------------------+ | Aviatrix Gateway size | Throughput (Gbps)| +-----------------------+------------------+ | Standard_D5_v2 | 22 - 23 | +-----------------------+------------------+ 6. Additional Read =========================== Additional read can be found in this short blog, `Need of conventional BGP support in the cloud <https://community.aviatrix.com/t/h7htvvc/need-of-conventional-bgp-support-in-the-cloud>`_ .. |transit_azure_gateway_external_device_bgp_over_lan_diagram| image:: transit_gateway_external_device_bgp_over_lan_simulation_workflow_media/transit_azure_gateway_external_device_bgp_over_lan_diagram.png :scale: 50% .. |aviatrix_azure_transit_externel_device_lan| image:: transit_gateway_external_device_bgp_over_lan_simulation_workflow_media/aviatrix_azure_transit_externel_device_lan.png :scale: 50% .. |aviatrix_azure_bgp_lan_status_1| image:: transit_gateway_external_device_bgp_over_lan_simulation_workflow_media/aviatrix_azure_bgp_lan_status_1.png :scale: 50% .. |aviatrix_azure_bgp_lan_status_2| image:: transit_gateway_external_device_bgp_over_lan_simulation_workflow_media/aviatrix_azure_bgp_lan_status_2.png :scale: 50% .. |aviatrix_azure_bgp_status| image:: transit_gateway_external_device_bgp_over_lan_simulation_workflow_media/aviatrix_azure_bgp_status.png :scale: 50% .. |aviatrix_azure_gateway_creation| image:: transit_gateway_external_device_bgp_over_lan_simulation_workflow_media/aviatrix_azure_gateway_creation.png :scale: 50% .. |sd_wan_integ| image:: transitvpc_designs_media/sd_wan_integ.png :scale: 30% .. |sd_wan_inte_azure| image:: transitvpc_designs_media/sd_wan_inte_azure.png :scale: 30% .. disqus:: <file_sep> ============================================================ Aviatrix CoPilot Overview ============================================================ .. important:: This content has moved. Please see `Aviatrix CoPilot Product Documentation <https://docs.aviatrix.com/copilot/latest/index.html>`_ for CoPilot overview information. <file_sep> ========================================================= Transit FireNet Workflow for OCI ========================================================= Aviatrix Transit FireNet allows you to deploy firewalls functions for the Aviatrix Multi-Cloud Transit architecture. With Transit FireNet feature, the Firewall Network (FireNet) function is integrated into the Aviatrix Transit gateway. To learn more about Transit FireNet, check out `Transit FireNet FAQ. <https://docs.aviatrix.com/HowTos/transit_firenet_faq.html>`_ In this example, three VCNs with Aviatrix gateways will be deployed, one Aviatrix transit gateway and two Spoke Gateways (DEV and PROD) will be attached to it. The transit VCN will have a firewall of supported vendors (Check Point, Palo Alto Networks and Fortinet etc.) deployed in it. Please see the diagram below for more details. Once the infra is in-place then the policy will be created to inspect the east-west and north-south traffic. |avx_tr_firenet_topology_az| Step 1 : Create Transit VCN ******************************* VCNs can be created manually on OCI or directly from Aviatrix Controller. Aviatrix controller has set of useful tools available for users and in this example, VCNs are created following the Useful Tools `Create a VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ guidelines. 1. Login to the Aviatrix Controller with username and password #. Navigate to **Useful Tools -> Create A VPC** #. Add one VCN for Transit FireNet Gateway and select **Aviatrix FireNet VPC** option as shown below. #. Create two more VCNs with **no option/checkbox** selected for Spoke Gateways. |create_vpc| Step 2: Deploy the Transit Aviatrix Gateway *************************************************** Transit Aviatrix Gateway can be deployed using the `Transit Gateway Workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-a-transit-gateway>`_ Prerequisite for OCI ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Transit FireNet builds on the Aviatrix Transit Network solution where Aviatrix gateways are deployed in Transit VCN and/or in Spoke VCN in OCI. Make sure the deployment meets the following specifications: 1. ActiveMesh must be enabled when launching the Aviatrix Transit Gateway. 2. Select the option “Enable Transit FireNet” when launching the Aviatrix Transit Gateway. 3. Aviatrix Transit Gateway minimum instance size should be VM.Standard2.4 or more .. Note:: Transit FireNet Insane mode is not supported in Release 6.4. Procedure ~~~~~~~~~~~~~~~~~~~~~ 1. Navigate to **MULTI-CLOUD TRANSIT -> Setup -> #1 Launch an Aviatrix Transit Gateway** #. Choose virtual machine size **VM.Standard2.4** #. Enable **ActiveMesh Mode (Mandatory)** #. Enable InsaneMode for higher throughput (optional) #. Enable Transit Gateway HA by navigating to **MULTI-CLOUD TRANSIT -> Setup -> #2 (Optional) Enable HA to an Aviatrix Transit Gateway** Please see an example below for Transit FireNet GW: |tr_firenet_gw| Step 3: Deploy Spoke Gateways ************************************* Now that we have Aviatrix Transit Gateway, we can deploy Aviatrix Spoke Gateways in the spoke VCN using `Aviatrix Spoke Gateway Workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-a-spoke-gateway>`_. 1. Navigate to **MULTI-CLOUD TRANSIT -> Setup -> #4 Launch an Aviatrix Spoke Gateway** #. Deploy a Spoke Gateway (GW) in each of the spoke VCNs using defaults while choose correct Account and VCN info #. Choose the Public Subnet #. Enable Spoke Gateway HA by navigating to Transit network -> Setup -> #5 (Optional) Enable/Disable HA at Spoke GW |launch_spk_gw| Step 4: Attach Spoke Gateways to Transit Network ******************************************************* Transit and spoke gateways are deployed, next step is to connect them. 1. Navigate to **MULTI-CLOUD TRANSIT -> Setup -> #6a Attach Spoke Gateway to Transit Network** #. Select one spoke at a time and attach to the Transit Gateway. |attach_spk_trgw| .. note:: By default, Transit Gateway will not route traffic between Spoke Gateways. Step 5: Enable Connected Transit ************************************** By default, spoke VCNs are in isolated mode where the Transit will not route traffic between them. To allow the Spoke VCNs to communicate with each other, we need to enable Connected Transit 1. Navigate to **MULTI-CLOUD TRANSIT -> Advanced Config**, select the right Transit Gateway and enable **“Connected Transit”** |connected_transit| Step 6: Configure Transit Firewall Network ************************************************** Transit and Spoke Gateways have now been deployed, next step is to deploy and enable the Firewall for traffic inspection. Let’s start with enabling the firewall function and configure the FireNet policy. 1. Navigate to **MULTI-CLOUD TRANSIT -> Transit FireNet -> #1 Enable Transit FireNet on Aviatrix Transit Gateway** #. Choose the Aviatrix Transit Gateway and Click **“Enable”** |en_tr_firenet| 3. Navigate to **MULTI-CLOUD TRANSIT -> Transit FireNet -> #2 Manage FireNet Policy** #. Add spokes to the Inspected box for traffic inspection .. note:: By default, FireNet inspects ingress (INET to VCN) and east-west traffic (VCN to VCN) only. |tr_firenet_policy| Step 7a: Launch and Associate Firewall Instance ***************************************************************** This approach is recommended if this is the first Firewall instance to be attached to the gateway. This step launches a Firewall instance and associates it with one of the FireNet gateways. .. important:: The Firewall instance and the associated Aviatrix FireNet gateway above must be in the same AZ, and, we recommend that the Management Interface Subnet and Egress (untrust dataplane) Interface Subnet should not be in the same subnet. 7a.1 Launch and Attach ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Go to Aviatrix Controller's console and navigate to **Firewall Network -> Setup -> Step 7a** and provide all the required input as shown in a table and click **"Launch"** button. .. important:: Vendor's firewall may take some time after launch to be available. ========================================== ========== **Setting** **Value** ========================================== ========== VPC ID The Security VNET created in Step 1. Gateway Name The primary FireNet gateway. Firewall Instance Name The name that will be displayed on Azure Console. Firewall Image The OCI Image that you have subscribed. Firewall Image Version Firewall supported software versions. Firewall Instance Size Firewall virtual machine size. Management Interface Subnet. Select the subnet whose name contains "gateway and firewall management" Egress Interface Subnet Select the subnet whose name contains "FW-ingress-egress". Username Applicable to Azure deployment only. "admin" as a username is not accepted. Authentication Method SSH Public Key Key Pair Name (Optional) The .pem file name for SSH access to the firewall instance. Attach (Optional) By selecting this option, the firewall instance is inserted in the data path to receive packet. If this is the second firewall instance for the same gateway and you have an operational FireNet deployment, you should not select this option as the firewall is not configured yet. You can attach the firewall instance later at Firewall Network -> Advanced page. Advanced (Optional) Click this selection to allow Palo Alto firewall bootstrap files to be specified. ========================================== ========== 1. Check Point Specification ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Check Point support for OCI is coming in future release 2. Palo Alto VM-Series Specifications ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Palo instance has 3 interfaces as described below. ======================================================== =============================== ================================ **Palo Alto VM interfaces** **Description** **Inbound Security Group Rule** ======================================================== =============================== ================================ eth0 (on subnet -Public-gateway-and-firewall-mgmt) Management interface Allow SSH, HTTPS, ICMP, TCP 3978 eth1 (on subnet -Public-FW-ingress-egress) Egress or Untrusted interface Allow ALL eth2 (on subnet -dmz-firewall) LAN or Trusted interface Allow ALL (Do not change) ======================================================== =============================== ================================ Note that firewall instance eth2 is on the same subnet as FireNet gateway eth2 interface. Launch VM Series from Aviatrix Controller automatically set it up the Palo Alto Network VM-Series firewall. User should be able to login to the VM-Series console with given username and password during launch. .. important:: For Panorama managed firewalls, you need to prepare Panorama first and then launch a firewall. Check out `Setup Panorama <https://docs.aviatrix.com/HowTos/paloalto_API_setup.html#managing-vm-series-by-panorama>`_. When a VM-Series instance is launched and connected with Panorama, you need to apply a one time "commit and push" from the Panorama console to sync the firewall instance and Panorama. .. Tip:: If VM-Series are individually managed and integrated with the Controller, you can still use Bootstrap to save initial configuration time. Export the first firewall's configuration to bootstrap.xml, create an IAM role and Bootstrap bucket structure as indicated above, then launch additional firewalls with IAM role and the S3 bucket name to save the time of the firewall manual initial configuration. 3. Fortinet Specifications ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Fortinet support for OCI is coming in future release Step 7b: Associate an Existing Firewall Instance ******************************************************* This step is the alternative step to Step 7a. If you already launched the firewall (Check Point, Palo Alto Network or Fortinet) instance from Azure Console, you can still associate it with the FireNet gateway. Go to Aviatrix Controller's console and navigate to **Firewall Network -> Setup -> Step 7b** and associate a firewall with right FireNet Gateway. Step 8: Configure Firewall Interfaces ***************************************************** 1. Check Point ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Check Point support for OCI is coming in future release 2. Palo Alto VM-Series ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Follow `Configure PaloAlto VM-Series Example in OCI <https://docs.aviatrix.com/HowTos/config_paloaltoVM.html>`_ to properly configure PAN VM-Series. Step 9: Vendor Firewall Integration ***************************************************** Vendor integration dynamically updates firewall route tables. The use case is for networks with RFC 1918 and non-RFC 1918 routes that require specific route table programming on the firewall appliance 1. Go to Firewall Network -> Vendor Integration -> Select Firewall, fill in the details of your Firewall instance. 2. Click Save, Show and Sync. Step 10: Enable Health Check Policy in Firewall *************************************************** Aviatrix Controller uses ICMP or ping to check the health of firewall every 5 seconds. User needs to enable this port in firewall as per given instruction. Check Point ~~~~~~~~~~~~~~ Check Point support for OCI is coming in future release Palo Alto Network (PAN) ~~~~~~~~~~~~~~~~~~~~~~~~~ By default, VM-Series do not allow ICMP or ping. Pleas follow the given steps to enable it: 1. Login to VM-Series with username and password. #. Go to Network -> Interface Mgmt under Network Profiles and click "Add". #. Give any name in "Interface Management Profile", check ping checkbox under Administrative Management Service and click "OK". #. Attach Profile with LAN interface. Network -> Interfaces -> Select LAN Ethernet Interface -> Advanced -> Management Profile -> Select appropriate profile. Fortinet ~~~~~~~~~~~~~~~ Fortigate support for OCI is coming in future release Step 11: Example Setup for "Allow All" Policy *************************************************** After a firewall instance is launched, wait for 5 to 15 minutes for it to come up. Time varies for each firewall vendor. In addition, please follow example configuration guides as below to build a simple policy on the firewall instance for a test validation that traffic is indeed being routed to firewall instance. Palo Alto Network (PAN) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For basic configuration,`Follow PaloAlto VM-Series Example Step 8 <https://docs.aviatrix.com/HowTos/config_paloaltoVMOCI.html>`_ to add Allow-all policy. FortiGate (Fortinet) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Fortigate support for OCI is coming in future release Check Point ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Check Point support for OCI is coming in future release Step 12: Verification *************************** There are multiple ways to verify if Transit FireNet is configured properly: 1. Aviatrix Flightpath - Control-plane Test #. Ping/Traceroute Test between Spoke VCNs (East-West) - Data-plane Test Flight Path Test for FireNet Control-Plane Verification: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Flight Path is a very powerful troubleshooting Aviatrix tool which allows users to validate the control-plane and gives visibility of end to end packet flow. 1. Navigate to **Troubleshoot-> Flight Path** #. Provide the Source and Destination Region and VCN information #. Select ICMP and Private subnet, and Run the test .. note:: VM instance will be required in OCI, and ICMP should be allowed in security group. Ping/Traceroute Test for FireNet Data-Plane Verification: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Once control-plane is established and no problem found in security and routing polices. Data-plane validation needs to be verified to make sure traffic is flowing and not blocking anywhere. There are multiple ways to check data-plane: 1. One way is to SSH to Spoke instance (e.g. DEV1-VM) and ping other Spoke instance (e.g PROD1-VM) to make sure no traffic loss in the path. 2. Ping/traceroute capture can also be performed from Aviatrix Controller. Go to **TROUBLESHOOT -> Diagnostics** and perform the test. .. |avx_tr_firenet_topology_az| image:: transit_firenet_workflow_media/transit_firenet_oci_workflow_media/avx_tr_firenet_topology_az.png :scale: 35% .. |insane_mode_tp| image:: transit_firenet_workflow_media/transit_firenet_oci_workflow_media/insane_mode_tp.png :scale: 30% .. |create_vpc| image:: transit_firenet_workflow_media/transit_firenet_oci_workflow_media/create_vpc.png :scale: 40% .. |tr_firenet_gw| image:: transit_firenet_workflow_media/transit_firenet_oci_workflow_media/tr_firenet_gw.png :scale: 35% .. |launch_spk_gw| image:: transit_firenet_workflow_media/transit_firenet_oci_workflow_media/launch_spk_gw.png :scale: 35% .. |attach_spk_trgw| image:: transit_firenet_workflow_media/transit_firenet_oci_workflow_media/attach_spk_trgw.png :scale: 35% .. |en_tr_firenet| image:: transit_firenet_workflow_media/transit_firenet_oci_workflow_media/en_tr_firenet.png :scale: 35% .. |tr_firenet_policy| image:: transit_firenet_workflow_media/transit_firenet_oci_workflow_media/tr_firenet_policy.png :scale: 35% .. |avx_tr_firenet_topology| image:: transit_firenet_workflow_media/transit_firenet_oci_workflow_media/avx_tr_firenet_topology.png :scale: 35% .. |connected_transit| image:: transit_firenet_workflow_media/transit_firenet_oci_workflow_media/connected_transit.png :scale: 40% .. disqus:: <file_sep> ============================================ Aviatrix Gateway to Cisco ASA ============================================ This document describes how to build an IPsec tunnel based Site2Cloud connection between an Aviatrix Gateway and Cisco ASA Firewall. The network setup is as follows: **VPC/VNet-AVX (with Aviatrix Gateway)** *VPC/VNet CIDR: 10.0.0.0/16* *VPC/VNet Public Subnet CIDR: 10.0.1.0/24* *VPC/VNet Private Subnet CIDR: 10.0.2.0/24* **On-Prem (with Cisco ASA Firewall)** *On-Prem Network CIDR: 10.10.0.0/16* Creating a Site2Cloud Connection at the Aviatrix Controller ====================================================== 1. Go to Gateway > New Gateway to launch an Aviatrix Gateway at the subnet (public subnet for AWS, GCP, or OCI) of VPC/VNet-AVX. Collect Gateway's public IP addresses (172.16.17.32 in this example). 2. Go to the **Site2Cloud** page and click **Add New** to create a Site2Cloud connection. =============================== ================================================================= **Field** **Value** =============================== ================================================================= VPC ID/VNet Name Choose VPC/VNet ID of VPC-AVX Connection Type Unmapped Connection Name Arbitrary (e.g. avx-asa-s2c) Remote Gateway Type Generic Tunnel Type UDP Algorithms Uncheck this box Encryption over Direct Connect Uncheck this box Enable HA Uncheck this box Primary Cloud Gateway Select Aviatrix Gateway created above Remote Gateway IP Address Public IP of ASA WAN port (192.168.3.11 in this example) Pre-shared Key Optional (auto-generated if not entered) Remote Subnet 10.10.0.0/16 (On-Prem Network CIDR) Local Subnet 10.0.2.0/24 (VPC-AVX private subnet) =============================== ================================================================= 3. Go to the **Site2Cloud** page. From Site2Cloud connection table, select the connection created above (e.g. avx-asa-s2c). - Select **Cisco** from the **Vendor** dropdown menu. - Select **ASA 5500 Series** from the **Platform** dropdown menu. - Select the proper ASA Software versin from **Software** drop down list depending on your ASA running OS. - Click **Download Configuration** button to download the ASA site2cloud configuration. - Save the configuration file as a reference for configuring your ASA. The following is an ASA sample configuration based on the Site2Cloud configuration above. |image0| Configuring Cisco ASA ======================= 1. Either SSH into the ASA or connect to it directly through its console port. 2. Issue the **configure terminal** command in privileged **EXEC** mode to start global configuration mode. The prompt changes to the following : hostname(config)# 3. Enter the CLIs in ASA site2cloud configuration guide downloaded before. Note that you may need to modify these CLIs to fit your ASA configuration. Troubleshooting and Verifying at Aviatrix Controller ======================================================== 1. At the Aviatrix Controller, go to the Site2Cloud page. Verify that the status of the Site2Cloud connection is up. 2. At the Site2Cloud - Diagnostics page, run various diagnostics commands. =============================== ================================================================= **Field** **Value** =============================== ================================================================= VPC ID/VNet Name VPC/VNet-AVX (Aviatrix Gateway VPC/VNet) ID Connection Name of Site2Cloud connection created at Step 2 Gateway Name of Aviatrix Gateway Action One of the supported diagnostics commands =============================== ================================================================= For support, please open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_ .. |image0| image:: s2c_gw_asa_media/Doc1.png :width: 5.55625in :height: 3.26548in .. disqus:: <file_sep> .. toctree:: :numbered: ============================================================================== Google IdP for SAML Integration ============================================================================== Overview ------------ This guide provides an example on how to configure Aviatrix to authenticate against a Google IdP. When SAML client is used, your Aviatrix controller acts as the Identity Service Provider (ISP) that redirects browser traffic from client to IdP (e.g., Google) for authentication. Before configuring SAML integration between Aviatrix and Google, make sure you have a valid Google account with administrator access. Configuration Steps ------------------- Follow these steps to configure Aviatrix to authenticate against your Google IdP: Step 1. Create a `temporary Aviatrix SP Endpoint <#aviatrix-endpoint>`__ in the Aviatrix Controller Step 2. Create a `Google SAML Application <#google-saml-app1>`__ for Aviatrix Step 3. Retrieve `Google IdP metadata <#google-idp-metadata>`__ Step 4. Update `Aviatrix SP Endpoint <#google-update-saml-endpoint>`__ in the Aviatrix Controller Step 5. `Test the Integration <#google-test-integration>`__ is Set Up Correctly .. _aviatrix_endpoint: Step 1. Create an Aviatrix SP Endpoint ######################################## Visit one of the following links based on your use case and follow step1 (Create temporary Aviatrix SP Endpoint for Aviatrix) from the link's Configuration section: If integrating Google IdP with `Controller Login SAML Config <https://docs.aviatrix.com/HowTos/Controller_Login_SAML_Config.html#config-31>`_ If integrating Google IdP with `OpenVPN with SAML Authentication <https://docs.aviatrix.com/HowTos/VPN_SAML.html#config-31>`_ This step will ask you to pick a short name to be used for the SAML application name ``[Endpoint Name]``. In the notes below we will refer to this as **aviatrix_google**. It can be any string that will identify the SAML application you create in the IdP. We will use the string you select for the SAML application name to generate a URL for Google IdP to connect with Aviatrix. This URL is defined below as **SP_ACS_URL**. This URL should be constructed as: ``https://<<<your controller ip or host name>>>/flask/saml/sso/<<<aviatrix_google>>>`` .. tip:: Replace **<<<your controller ip or host name>>>** with the actual host name or IP address of your controller and **<<<aviatrix_google>>>** with the ``[Endpoint Name]`` you chose to refer to the SAML application. .. _google_saml_app1: Step 2. Create a Google SAML App for Aviatrix ############################################### .. note:: This step is usually done by the Google Admin. #. Login to the Google Admin portal #. Follow `Google documentation <https://support.google.com/a/answer/6087519?hl=en>`__ to create a new **custom** application. Click on the `Setup My Own Custom App` |imageStep1| #. Basic Information +-------------------+-----------------+-------------------------------------+ | Field | Value | Description | +===================+=================+=====================================+ | Application Name | Aviatrix | This can be any value. It will be | | | | displayed in Google only. | +-------------------+-----------------+-------------------------------------+ | Description | | This can be any value. | +-------------------+-----------------+-------------------------------------+ | | Aviatrix logo: | Aviatrix logo (optional) | | | | | | Upload logo | | |logoAlias1|_ | | | | | |logoAlias2|_ | | +-------------------+-----------------+-------------------------------------+ |imageStep3| #. Service Provider Details +----------------------+----------------------------------------------------+ | Field | Value | +======================+====================================================+ | ACS URL | ``https://[host]/flask/saml/sso/[Endpoint Name]`` | +----------------------+----------------------------------------------------+ | Entity ID | ``https://[host]/`` | +----------------------+----------------------------------------------------+ | Start URL | ``https://[host]/flask/saml/sso/[Endpoint Name]`` | +----------------------+----------------------------------------------------+ | Signed Response | Checked | +----------------------+----------------------------------------------------+ | Name ID | Basic Information / Primary Email (Default) | +----------------------+----------------------------------------------------+ | Name ID Format | UNSPECIFIED | +----------------------+----------------------------------------------------+ ``[host]`` is the hostname or IP of your Aviatrix controller. For example, ``https://controller.demo.aviatrix.live`` ``[Endpoint Name]`` is an arbitrary identifier. This same value should be used when configuring SAML in the Aviatrix controller. |imageStep4| #. Attribute Mapping +----------------+-----------------+--------------------------------------+ | Attribute | Category | User field | +================+=================+======================================+ | FirstName | Basic | First Name | +----------------+-----------------+--------------------------------------+ | LastName | Basic | Last Name | +----------------+-----------------+--------------------------------------+ | Email | Basic | Primary Email | +----------------+-----------------+--------------------------------------+ |imageStep5| #. Disable "Signed Response" #. Open the Service Provider Details for the SAML application just created. Uncheck `Signed Response`. #. Click `Save` .. _google_idp_metadata: Step 3. Retrieve Google IdP metadata ##################################### Scroll down to `Option 2`. Click the `Download` button next to the `IdP metadata` label. |imageStep2| The IdP metadata text will be used to configure the Aviatrix SP Endpoint. .. _google_update_saml_endpoint: Step 4. Update Aviatrix SP Endpoint ################################### .. note:: This step is usually completed by the Aviatrix admin. Google IdP provides IdP Metadata through text obtained in `Retrieve Google IdP metadata (Step 3) <google-idp-metadata>`_. Continue with updating Aviatrix SAML Endpoint by visiting one of the following links based on your use case: #. If integrating Google IdP with `Controller Login SAML Config <https://docs.aviatrix.com/HowTos/Controller_Login_SAML_Config.html#config-34>`_ #. If integrating Google IdP with `OpenVPN with SAML Authentication <https://docs.aviatrix.com/HowTos/VPN_SAML.html#config-34>`_ |imageControllerNavOpenVPNAdvanced| +-------------------------+-------------------------------------------------+ | Field | Value | +=========================+=================================================+ | Endpoint Name | ``Endpoint Name`` (Use the same name you entered | | | in the Google Application previously) | +-------------------------+-------------------------------------------------+ | IdP Metadata Type | Text | +-------------------------+-------------------------------------------------+ | IdP Metadata Text | ``Value Copied from Google`` (Paste the value | | | from `Google IdP Metadata file <#google-idp-metadata>`_`) | +-------------------------+-------------------------------------------------+ | Entity ID | Hostname | +-------------------------+-------------------------------------------------+ | Access | Select admin or read-only access | +-------------------------+-------------------------------------------------+ | Custom SAML Request | Unchecked | | Template | | +-------------------------+-------------------------------------------------+ .. note:: Each endpoint only supports one type of access. If you need admin and read-only access, create two separate SAML apps. `Hostname` is the default for Entity ID, but if you have other apps using the same hostname, use a custom Entity ID. #. Click `OK` .. _google_test_integration: Step 5. Test the Integration ############################ .. tip:: Be sure to assign users to the new application in Google prior to validating. If you do not assign your test user to the Aviatrix SAML application, you will receive an error. Continue with testing the integration by visiting one of the following links based on your use case: 1. If integrating Google IdP with `Controller Login SAML Config <https://docs.aviatrix.com/HowTos/Controller_Login_SAML_Config.html#config-35>`_ #. Click `Settings` in the left navigation menu #. Select `Controller` #. Click on the `SAML Login` tab 2. If integrating Google IdP with `OpenVPN with SAML Authentication <https://docs.aviatrix.com/HowTos/VPN_SAML.html#config-35>`_ #. Expand `OpenVPN®` in the navigation menu and click `Advanced` #. Stay on the `SAML` tab You can quickly validate that the configuration is complete by clicking on the **Test** button next to the SAML endpoint. .. |logoAlias1| replace:: Aviatrix logo with red background .. _logoAlias1: https://www.aviatrix.com/news/press-kit/logo-aviatrix.png .. |logoAlias2| replace:: Aviatrix logo with transparent background .. _logoAlias2: https://www.aviatrix.com/images/logo-reverse.png .. |imageStep1| image:: SSL_VPN_Google_SAML_media/gsaml_step1.png :scale: 25% .. |imageStep2| image:: SSL_VPN_Google_SAML_media/gsaml_step2.png :scale: 25% .. |imageStep3| image:: SSL_VPN_Google_SAML_media/gsaml_step3.png :scale: 25% .. |imageStep4| image:: SSL_VPN_Google_SAML_media/gsaml_step4.png :scale: 25% .. |imageStep5| image:: SSL_VPN_Google_SAML_media/gsaml_step5.png :scale: 25% .. |imageGwVPNSAML| image:: SSL_VPN_Google_SAML_media/gw_vpn_saml.png .. |imageControllerNavOpenVPNAdvanced| image:: SSL_VPN_Google_SAML_media/OpenVPN_Advanced_SAML_AddNew.png :scale: 50% .. disqus:: <file_sep>.. meta:: :description: Rescure PKI Agent Certificate :keywords: PKI, X509, SPIRE, agent, SVID, certificate, attestation, re-attestation, unattested, expiring, expired ================================= Rescure PKI Agent Certificate ================================= How To Rescure The Expiring Certificate of a PKI Agent ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1. Make sure the machine is powered on. If it is not, please turn it on. 2. Login Aviatrix Controller. 3. Navigate to Troubleshoot->Diagnostics->Gateway->Service Actions. 4. Enter gateway name for the dropdown "Gateway". 5. Select "PKI" for the dropdown "Service". 6. Select "Restart" for the dropdown "Actions and click "OK" button" and click "OK" to confirm. 7. Wait for 30 seoncds. 8. Select "Status" for dropdown "Actions and click "OK" button and confirm. 9. In the "Show Results" box below, make sure the service is active and stably running (look for the line "Active: active (running) since"). 10. If the result indicates the service is active (running) for more than 30 seconds, the problem is solved". If you have any problem with following the steps above, please contact `Aviatrix Support <https://support.aviatrix.com>`_. How to Rescure The Expired Certificate of a PKI Agent ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ * Please contact `Aviatrix Support <https://support.aviatrix.com>`_ as soon as possible. How to Rescure an Unattested PKI Agent ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ * Please contact `Aviatrix Support <https://support.aviatrix.com>`_ as soon as possible.<file_sep> ======== BGP ======== Use the BGP page to review your BGP connections and settings. To open this page, in your Aviatrix Controller, go to MULTI-CLOUD TRANSIT > BGP on the left sidebar. BGP Page: Connections Tab ^^^^^^^^^^^^^^^^^^^^^^^^ If you set up a `Transit Network <http://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_, Transit GWs will be listed on the BGP page in the Connections tab. Select one Transit GW to view its details. - Advertised Networks represents the list of Spoke GW CIDR list. - Learned routes represents the list of on-prem network propagated by VGW. - Local AS Num is the Transit GW AS number you specified at the time of `Step 3 <http://docs.aviatrix.com/HowTos/transitvpc_workflow.html#connect-the-transit-gw-to-aws-vgw>`_ when connecting to VGW. BGP Page: Diagnostics Tab ^^^^^^^^^^^^^^^^^^^^^^^^^ Use the Diagnostics tab on the BGP page to troubleshoot BGP problems. Aviatrix BGP is implemented by using `Quagga <https://www.quagga.net/>`__. You can either type in `Quagga commands <https://www.nongnu.org/quagga/docs/docs-multi/BGP.html#BGP>`__ or use the |imageGrid| to select one of the pre-defined commands. BGP Page: Configuration Tab ^^^^^^^^^^^^^^^^^^^^^^^^^^ Use the Configuration tab on the BGP page to edit your BGP settings if necessary. BGP Overlapping Alert Email ######################## When Aviatrix Controller detects overlapping network CIDRs in the network, it sends out alert emails to the admins. BGP Route Limit Alert Email ############################ AWS VGW BGP supports up to 100 routes. When this limit is reached, VGW BGP goes down and causes outage. This email alert notifies admin when routes approach 90. BGP Maximum AS Limits ####################### The BGP Maximum AS Limit sets the maxium number of BGP hops the Controller allows the route to propagate. This limit determines the scope of a BGP network by setting the maxium BGP AS path length. This setting is disabled by default, meaning that the network size is unlimited. If you wish to limit the size of your network (for example, if you have a complex topology between your on-prem and cloud networks), you can enable this option by entering 1-254 in the field provided. Then, use the up and down arrows to increase or decrease the number. ======= .. disqus:: <file_sep> ===================================== Multi-Cloud Transit Network Design Patterns ===================================== The `Multi-Cloud Transit Network <http://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ provides a workflow to create a Transit VPC/VNet GW with a set of Spoke VPC/VNet GWs. From one Aviatrix Controller, you can set up a Multi-Cloud Transit Network in a single region or across multiple regions. Single Region Transit VPC/VNet Design --------------------------------------------------------- The use case for this design is if you have one connection from an on-prem network to the cloud (Direct Connect/ExpressRoute/InterConnect/FastConnect) or Internet to a VPC/VNet. Aviatrix's Multi-Cloud Transit Network solution provides default network segmentation, a Spoke VPC/VNet has no connectivity to another Spoke VPC/VNet via the Transit GW. For example, you do not need to spin up a Dev Transit Group and a Production Transit Transit Group as none of the Spoke VPC/VNets in either group can communicate with each other. As such, you do not need to spin up multiple Transit Groups for network isolation purpose. See the diagram below. For connectivity between Shared Service VPC/VNet and Spoke VPC/VNets, and between Spoke VPC/VNets, choose `AWS Peering <http://docs.aviatrix.com/HowTos/peering.html#aws-peering>`_ for AWS or `Aviatrix Encrypted Peering <http://docs.aviatrix.com/HowTos/peering.html#encrypted-peering>`_ from the Controller to set up. Notice Transit GW is only used for traffic between on-prem and cloud (Spoke VPC/VNets). Cloud-to-cloud traffic, such as Shared Service VPC/VNet to Spoke VPC/VNets does not go through the Transit GW. Decouple the different traffic streams reduces the performance bottleneck and removes the single failure point. .. Tip:: A Spoke network can be deployed in a different region and different cloud (AWS and Azure). |image0| Multi-Regions Transit VPC Design ------------------------------------------ If you have data centers in multiple regions and its corresponding CSP regions, you build network redundancy to reach cloud by leveraging VPN Gateway (VGW/VPN Connect) termination. In the diagram below, which uses AWS as an example, there are two Transit Groups, one in each region. The VPN Gateway or VGW has an on-premise to the cloud (Direct Connect/ExpressRoute/InterConnect/FastConnect) or to one datacenter, the same VGW is also used as a backup connectivity over Internet from the second datacenter. In case a data center loses connectivity to the VGW, the backup link can take over and route through the alternate route. Note one Aviatrix Controller manages both Transit Groups. If you need connectivity between any two Spoke VPC/VNets in each region, you can build an AWS Peering or `Aviatrix Encrypted Peering <http://docs.aviatrix.com/HowTos/peering.html#encrypted-peering>`_ from the Controller. |image1| Connected Transit Design ----------------------------------- If you like to build a Transit Network where all Spoke VPC/VNets are connected via Transit GW, you can accomplish that by enabling the Connected Transit property for the Transit GW. When Connected Transit is enabled, you do not need to build additional tunnels between shared service VPC/VNet to other VPC/VNets. See the diagram below: |image2| 10Gbps Transit VPC/VNet Design --------------------------- If you have applications that need 10Gbps bandwidth, you can place these applications in a VPC/VNet that terminates on the VPN Gateway/VGW with the 10Gbps VIF DX. Place the Aviatrix Transit GW in a separate VPC/VNet and connect it to the VPN Gateway/VGW through the normal `Multi-Cloud Transit Network <http://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ |image3| Alternatively, you can place the high bandwidth application in a separate VPC/VNet that terminates directly on a VIF or network interface, as shown below. |image4| Distributed Egress Control with Aviatrix ------------------------------------------------- If you are using a NAT Gateway as your egress control for Internet access, consider using Aviatrix FQDN to improve egress control. Aviatrix provides `L7 FQDN <http://docs.aviatrix.com/HowTos/FQDN_Whitelists_Ref_Design.html>`_ to whitelists and blacklists public sites that applications in a Spoke VPC/VNet need to make API calls. The function is embedded in the Aviatrix Gateway. It is transparent to user instances and requires neither agents nor certs. |image5| Centralized Third-Party Firewall Integration ----------------------------------------------------- If you need a full-fledged firewall device, centralized third party firewall appliances can be deployed via `Aviatrix Transit FireNet <https://docs.aviatrix.com/HowTos/transit_firenet_faq.html>`_ |transit_firenet| Centralized Egress Control with Aviatrix ------------------------------------------- |transit_firenet_aviatrix_egress| SD-WAN Integration -------------------- The Aviatrix Multi-Cloud Transit Network integrates with SD-WAN cloud instances with BGP over LAN where both BGP routes and data packets are exchanged between Aviatrix Transit Gateways and SD-WAN gateways deployed in the same Transit VPC/VNet, as shown in the diagram below. . |sd_wan_integ| .. |image0| image:: transitvpc_designs_media/singleRegion.png :width: 10.0in :height: 4.0in .. |image1| image:: transitvpc_designs_media/multi_region2.png :width: 10.0in :height: 4.0in .. |image2| image:: transitvpc_designs_media/connected_transit.png :width: 10.0in :height: 4.0in .. |image3| image:: transitvpc_designs_media/10Gbpspattern.png :width: 10.0in :height: 4.0in .. |image4| image:: transitvpc_designs_media/10Gbpspattern2.png :width: 10.0in :height: 4.0in .. |image5| image:: transitvpc_designs_media/egress-control2.png :width: 10.0in :height: 4.0in .. |image6| image:: transitvpc_designs_media/Firewallintegration.png :width: 10.0in :height: 4.0in .. |image7| image:: transitvpc_designs_media/Egresstofirewall.png :width: 10.0in :height: 4.0in .. |image8| image:: transitvpc_designs_media/SDWANtransit.png :width: 10.0in :height: 4.0in .. |transit_azure_native_spoke| image:: transitvpc_designs_media/transit_azure_native_spoke.png :scale: 30% .. |multi_cloud_transit_native| image:: transitvpc_designs_media/multi_cloud_transit_native.png :scale: 30% .. |sd_wan_integ| image:: transitvpc_designs_media/sd_wan_integ.png :scale: 30% .. |transit_firenet| image:: transit_firenet_media/transit_firenet.png :scale: 30% .. |transit_firenet_aviatrix_egress| image:: transit_firenet_media/transit_firenet_aviatrix_egress.png :scale: 30% .. disqus:: <file_sep> .. |win| image:: AVPNC_img/Win.png .. |mac| image:: AVPNC_img/Mac.png .. |lux| image:: AVPNC_img/Linux.png .. |bsd| image:: AVPNC_img/BSD.png .. |Client| image:: AVPNC_img/Client.png :width: 500 =================== Aviatrix VPN Client =================== .. important:: To download the latest VPN client, click `here <https://docs.aviatrix.com/documentation/latest/aviatrix-openvpn/download-vpn-client.html>`_. |Client| The Aviatrix VPN solution is the only VPN solution that provides SAML authentication from the client itself. The solution is built on OpenVPN®. The Aviatrix VPN Client provides a seamless user experience when authenticating a VPN user through a SAML IDP. The client also supports password based authentication methods as well. The VPN Client can be installed on desktop platforms and is supported on various operating systems like Windows, Mac and Linux. To set up the VPN Client, see the `User Guide <http://docs.aviatrix.com/Downloads/vpnclientguide.html>`_. Please see the `Release Notes <https://docs.aviatrix.com/documentation/latest/release-notes/vpn-client/vpn-release-notes.html>`_ to find the latest VPN client version. ************* Windows |win| ************* The Windows client can be downloaded from `this link <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/AVPNC_win_x64.exe>`__ The Windows client checksum can be downloaded from `this link <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_win_x64.exe.checksum.txt>`__ At the end of the installation, please install the TUN TAP driver if you haven't done so earlier. Please note that the client uses the default browser, and Microsoft Edge/IE is not supported ********* Mac |mac| ********* The Mac client can be downloaded from `this link <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/AVPNC_mac.pkg>`__. Please make sure that you are running macOS 10.12(Sierra) or higher. The Mac client checksum can be downloaded from `this link <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_mac.pkg.checksum.txt>`__. If you have installed version 1.4.26 or lower, please uninstall before you install the newer version. Please note that the client uses the default browser, and Safari is not supported (will show certificate warnings) *********** Linux |lux| *********** For the .deb files, if opening them using software center does not work, use sudo dpkg -i file.deb; sudo apt-get install -f (Dependencies) to install For the .tar files use tar -xvzf file.tar.gz; cd AVPNC_setup; sudo ./install.sh to install If the icon is missing from the launcher, type AVPNC in the terminal to launch the app Debian/Ubuntu ============= Ubuntu22 LTS - `Debian file <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_linux_JammyJellyfish.deb>`_, `Debian file checksum <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_linux_JammyJellyfish.deb.checksum.txt>`_, `Tar file <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_linux_JammyJellyfish.tar.gz>`_, `Tar file checksum <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_linux_JammyJellyfish.tar.gz.checksum.txt>`_. Ubuntu20.04 LTS - `Debian file <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_linux_FocalFossa.deb>`__, `Tar file <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_linux_FocalFossa.tar.gz>`__, `Debian file checksum <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_linux_FocalFossa.deb.checksum.txt>`__, `Tar file checksum. <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_linux_FocalFossa.tar.gz.checksum.txt>`__ Ubuntu18.04.1 LTS/Generic - `Debian file <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/AVPNC_debian.deb>`__, `Tar file <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/AVPNC_linux.tar.gz>`__, `Debian file checksum <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_debian.deb.checksum.txt>`__, `Tar file checksum. <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_linux.tar.gz.checksum.txt>`__ Ubuntu18.04.3 LTS - `Debian file <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/AVPNC_debian_latest.deb>`__, `Tar file <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/AVPNC_linux_latest.tar.gz>`__, `Debian file checksum <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_debian_latest.deb.checksum.txt>`__, `Tar file checksum. <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_linux_latest.tar.gz.checksum.txt>`__ Note: Currently we do not support Fedora/Arch-Linux. VPN Clients running on Ubuntu 16.04 and older are designated EOL. ************* FreeBSD |bsd| ************* FreeBSD 11 client can be downloaded from- `this link <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/AVPNC_FreeBSD.tar.gz>`__ tar -xvzf file.tar.gz; cd AVPNC_setup; sudo ./install.sh to install ***************** FIPS140-2 version ***************** `Windows <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/fips/AVPNC_win_x64_FIPS.exe>`__, `Checksum <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/fips/AVPNC_win_x64_FIPS.exe.checksum.txt>`__ `Mac <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/fips/AVPNC_mac_FIPS.pkg>`__ , `Checksum <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/fips/AVPNC_mac_FIPS.pkg.checksum.txt>`__ `Ubuntu 22 tar <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/fips/AVPNC_linux_JammyJellyfish_FIPS.tar.gz>`__, `Checksum <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/fips/AVPNC_linux_JammyJellyfish_FIPS.tar.gz.checksum.txt>`__ `Ubuntu 22 deb <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/fips/AVPNC_linux_JammyJellyfish_FIPS.deb>`__, `Checksum <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/fips/AVPNC_linux_JammyJellyfish_FIPS.deb.checksum.txt>`__ `Ubuntu 20 tar <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/fips/AVPNC_linux_FocalFossa_FIPS.tar.gz>`__, `Checksum <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/fips/AVPNC_linux_FocalFossa_FIPS.tar.gz.checksum.txt>`__ `Ubuntu 20 deb <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/dev/fips/AVPNC_debian_FIPS.deb>`__, `Checksum <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/dev/fips/AVPNC_linux_FocalFossa_FIPS.deb.checksum.txt>`__ `Ubuntu 18 tar <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/fips/AVPNC_linux_FIPS.tar.gz>`__, `Checksum <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/fips/AVPNC_linux_FIPS.tar.gz.checksum.txt>`__ `Ubuntu 18 deb <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/dev/fips/AVPNC_debian_FIPS.deb>`__, `Checksum <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/fips/AVPNC_debian_FIPS.deb.checksum.txt>`__ ***************** Archived Clients ***************** Ubuntu14.04 LTS - `Debian file <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/AVPNC_debian_Q4.deb>`__, `Tar file <https://s3-us-west-2.amazonaws.com/avi atrix-download/AviatrixVPNClient/AVPNC_linux_Q4.tar.gz>`__, `Debian file checksum <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_debian_Q4.deb.checksum.txt>`__, `Tar file checksum. <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_linux_Q4.tar.gz.checksum.txt>`__ ******************* Development version ******************* These are preview images for the next release. `Windows <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/dev/AVPNC_win_x64.exe>`__, `MacOS <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/dev/AVPNC_mac.pkg>`__ , `Debian Jammy Jellyfish <https://aviatrix-download.s3.us-west-2.amazonaws.com/AviatrixVPNClient/dev/AVPNC_linux_JammyJellyfish.deb>`__, `Linux Jammy Jellyfish <https://aviatrix-download.s3.us-west-2.amazonaws.com/AviatrixVPNClient/dev/AVPNC_linux_JammyJellyfish.tar.gz>`__, `Debian Focal Fossa <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/dev/AVPNC_linux_FocalFossa.deb>`__, `Linux tar Focal Fossa <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/dev/AVPNC_linux_FocalFossa.tar.gz>`__, `Linux tar <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/dev/AVPNC_linux.tar.gz>`__, `Debian file <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/dev/AVPNC_debian.deb>`__, `Linux tar bionic <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/dev/AVPNC_linux_latest.tar.gz>`__, `Debian bionic <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/dev/AVPNC_debian_latest.deb>`__, `Linux tar xenial <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/dev/AVPNC_xenial.tar.gz>`__, `Debian xenial <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/dev/AVPNC_xenial.deb>`__, `Linux tar trusty <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/dev/AVPNC_linux_Q4.tar.gz>`__, `Debian trusty <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/dev/AVPNC_debian_Q4.deb>`__, `FreeBSD <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/dev/AVPNC_FreeBSD.tar.gz>`__ FIPS140-2 Dev version `Windows <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/dev/fips/AVPNC_win_x64_FIPS.exe>`__, `Mac <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/dev/fips/AVPNC_mac_FIPS.pkg>`__ , `Ubuntu-22 tar <https://aviatrix-download.s3.us-west-2.amazonaws.com/AviatrixVPNClient/dev/fips/AVPNC_linux_JammyJellyfish_FIPS.tar.gz>`__ , `Ubuntu-22 deb <https://aviatrix-download.s3.us-west-2.amazonaws.com/AviatrixVPNClient/dev/fips/AVPNC_linux_JammyJellyfish_FIPS.deb>`__ , `Ubuntu-20 tar <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/dev/fips/AVPNC_linux_FocalFossa_FIPS.tar.gz>`__ , `Ubuntu-20 deb <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/dev/fips/AVPNC_linux_FocalFossa_FIPS.deb>`__ , `Ubuntu-18 tar <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/dev/fips/AVPNC_linux_FIPS.tar.gz>`__, `Ubuntu 18 deb <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/dev/fips/AVPNC_debian_FIPS.deb>`__ OpenVPN is a registered trademark of OpenVPN Inc. .. disqus:: =======  .. |win| image:: AVPNC_img/Win.png .. |mac| image:: AVPNC_img/Mac.png .. |lux| image:: AVPNC_img/Linux.png .. |bsd| image:: AVPNC_img/BSD.png .. |Client| image:: AVPNC_img/Client.png :width: 500 =================== Aviatrix VPN Client =================== .. important:: To download the latest VPN client, click `here <https://docs.aviatrix.com/documentation/latest/aviatrix-openvpn/download-vpn-client.html>`_. |Client| The Aviatrix VPN solution is the only VPN solution that provides SAML authentication from the client itself. The solution is built on OpenVPN®. The Aviatrix VPN Client provides a seamless user experience when authenticating a VPN user through a SAML IDP. The client also supports password based authentication methods as well. The VPN Client can be installed on desktop platforms and is supported on various operating systems like Windows, Mac and Linux. To set up the VPN Client, see the `User Guide <http://docs.aviatrix.com/Downloads/vpnclientguide.html>`_. Please see the `Release Notes <https://docs.aviatrix.com/documentation/latest/release-notes/vpn-client/vpn-release-notes.html>`_ to find the latest VPN client version. ************* Windows |win| ************* The Windows client can be downloaded from `this link <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/AVPNC_win_x64.exe>`__ The Windows client checksum can be downloaded from `this link <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_win_x64.exe.checksum.txt>`__ At the end of the installation, please install the TUN TAP driver if you haven't done so earlier. Please note that the client uses the default browser, and Microsoft Edge/IE is not supported. .. important:: When a Windows client UserVPN search-domain length is > 180 characters, VPN clients may fail to connect to the gateway. ********* Mac |mac| ********* The Mac client can be downloaded from `this link <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/AVPNC_mac.pkg>`__. Please make sure that you are running macOS 10.12(Sierra) or higher. The Mac client checksum can be downloaded from `this link <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_mac.pkg.checksum.txt>`__. If you have installed version 1.4.26 or lower, please uninstall before you install the newer version. Please note that the client uses the default browser, and Safari is not supported (will show certificate warnings) *********** Linux |lux| *********** For the .deb files, if opening them using software center does not work, use sudo dpkg -i file.deb; sudo apt-get install -f (Dependencies) to install For the .tar files use tar -xvzf file.tar.gz; cd AVPNC_setup; sudo ./install.sh to install If the icon is missing from the launcher, type AVPNC in the terminal to launch the app Debian/Ubuntu ============= Ubuntu22 LTS - `Debian file <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_linux_JammyJellyfish.deb>`_, `Debian file checksum <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_linux_JammyJellyfish.deb.checksum.txt>`_, `Tar file <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_linux_JammyJellyfish.tar.gz>`_, `Tar file checksum <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_linux_JammyJellyfish.tar.gz.checksum.txt>`_. Ubuntu20.04 LTS - `Debian file <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_linux_FocalFossa.deb>`__, `Tar file <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_linux_FocalFossa.tar.gz>`__, `Debian file checksum <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_linux_FocalFossa.deb.checksum.txt>`__, `Tar file checksum. <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_linux_FocalFossa.tar.gz.checksum.txt>`__ Ubuntu18.04.1 LTS/Generic - `Debian file <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/AVPNC_debian.deb>`__, `Tar file <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/AVPNC_linux.tar.gz>`__, `Debian file checksum <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_debian.deb.checksum.txt>`__, `Tar file checksum. <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_linux.tar.gz.checksum.txt>`__ Ubuntu18.04.3 LTS - `Debian file <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/AVPNC_debian_latest.deb>`__, `Tar file <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/AVPNC_linux_latest.tar.gz>`__, `Debian file checksum <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_debian_latest.deb.checksum.txt>`__, `Tar file checksum. <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_linux_latest.tar.gz.checksum.txt>`__ Note: Currently we do not support Fedora/Arch-Linux. VPN Clients running on Ubuntu 16.04 and older are designated EOL. ************* FreeBSD |bsd| ************* FreeBSD 11 client can be downloaded from- `this link <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/AVPNC_FreeBSD.tar.gz>`__ tar -xvzf file.tar.gz; cd AVPNC_setup; sudo ./install.sh to install ***************** FIPS140-2 version ***************** `Windows <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/fips/AVPNC_win_x64_FIPS.exe>`__, `Checksum <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/fips/AVPNC_win_x64_FIPS.exe.checksum.txt>`__ `Mac <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/fips/AVPNC_mac_FIPS.pkg>`__ , `Checksum <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/fips/AVPNC_mac_FIPS.pkg.checksum.txt>`__ `Ubuntu 22 tar <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/fips/AVPNC_linux_JammyJellyfish_FIPS.tar.gz>`__, `Checksum <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/fips/AVPNC_linux_JammyJellyfish_FIPS.tar.gz.checksum.txt>`__ `Ubuntu 22 deb <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/fips/AVPNC_linux_JammyJellyfish_FIPS.deb>`__, `Checksum <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/fips/AVPNC_linux_JammyJellyfish_FIPS.deb.checksum.txt>`__ `Ubuntu 20 tar <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/fips/AVPNC_linux_FocalFossa_FIPS.tar.gz>`__, `Checksum <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/fips/AVPNC_linux_FocalFossa_FIPS.tar.gz.checksum.txt>`__ `Ubuntu 20 deb <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/dev/fips/AVPNC_debian_FIPS.deb>`__, `Checksum <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/dev/fips/AVPNC_linux_FocalFossa_FIPS.deb.checksum.txt>`__ `Ubuntu 18 tar <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/fips/AVPNC_linux_FIPS.tar.gz>`__, `Checksum <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/fips/AVPNC_linux_FIPS.tar.gz.checksum.txt>`__ `Ubuntu 18 deb <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/dev/fips/AVPNC_debian_FIPS.deb>`__, `Checksum <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/fips/AVPNC_debian_FIPS.deb.checksum.txt>`__ ***************** Archived Clients ***************** Ubuntu14.04 LTS - `Debian file <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/AVPNC_debian_Q4.deb>`__, `Tar file <https://s3-us-west-2.amazonaws.com/avi atrix-download/AviatrixVPNClient/AVPNC_linux_Q4.tar.gz>`__, `Debian file checksum <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_debian_Q4.deb.checksum.txt>`__, `Tar file checksum. <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/AVPNC_linux_Q4.tar.gz.checksum.txt>`__ ******************* Development version ******************* These are preview images for the next release. `Windows <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/dev/AVPNC_win_x64.exe>`__, `MacOS <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/dev/AVPNC_mac.pkg>`__ , `Debian Jammy Jellyfish <https://aviatrix-download.s3.us-west-2.amazonaws.com/AviatrixVPNClient/dev/AVPNC_linux_JammyJellyfish.deb>`__, `Linux Jammy Jellyfish <https://aviatrix-download.s3.us-west-2.amazonaws.com/AviatrixVPNClient/dev/AVPNC_linux_JammyJellyfish.tar.gz>`__, `Debian Focal Fossa <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/dev/AVPNC_linux_FocalFossa.deb>`__, `Linux tar Focal Fossa <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/dev/AVPNC_linux_FocalFossa.tar.gz>`__, `Linux tar <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/dev/AVPNC_linux.tar.gz>`__, `Debian file <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/dev/AVPNC_debian.deb>`__, `Linux tar bionic <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/dev/AVPNC_linux_latest.tar.gz>`__, `Debian bionic <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/dev/AVPNC_debian_latest.deb>`__, `Linux tar xenial <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/dev/AVPNC_xenial.tar.gz>`__, `Debian xenial <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/dev/AVPNC_xenial.deb>`__, `Linux tar trusty <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/dev/AVPNC_linux_Q4.tar.gz>`__, `Debian trusty <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/dev/AVPNC_debian_Q4.deb>`__, `FreeBSD <https://s3-us-west-2.amazonaws.com/aviatrix-download/AviatrixVPNClient/dev/AVPNC_FreeBSD.tar.gz>`__ FIPS140-2 Dev version `Windows <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/dev/fips/AVPNC_win_x64_FIPS.exe>`__, `Mac <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/dev/fips/AVPNC_mac_FIPS.pkg>`__ , `Ubuntu-22 tar <https://aviatrix-download.s3.us-west-2.amazonaws.com/AviatrixVPNClient/dev/fips/AVPNC_linux_JammyJellyfish_FIPS.tar.gz>`__ , `Ubuntu-22 deb <https://aviatrix-download.s3.us-west-2.amazonaws.com/AviatrixVPNClient/dev/fips/AVPNC_linux_JammyJellyfish_FIPS.deb>`__ , `Ubuntu-20 tar <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/dev/fips/AVPNC_linux_FocalFossa_FIPS.tar.gz>`__ , `Ubuntu-20 deb <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/dev/fips/AVPNC_linux_FocalFossa_FIPS.deb>`__ , `Ubuntu-18 tar <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/dev/fips/AVPNC_linux_FIPS.tar.gz>`__, `Ubuntu 18 deb <https://aviatrix-download.s3-us-west-2.amazonaws.com/AviatrixVPNClient/dev/fips/AVPNC_debian_FIPS.deb>`__ OpenVPN is a registered trademark of OpenVPN Inc. .. disqus:: <file_sep>==================================================================================================================================================================================== Steps to check the version of SumoLogic Collectors on the Sumologic Servers(UI) and also Upgrade/Downgrade the version of the Collectors from the WebUI of Sumologic Servers ==================================================================================================================================================================================== 1: Login to the Sumologic server a. On the left pane Click on manage Data and then Collection b. You will be displayed the Controllers/gateways you are running |image1| 2.Click -> Show ->Running Collectors Note: Upgrade wont work if your Controller/Gateway is not running. |image2| 3. On the top right there is an option to upgrade all the Collectors. It will upgrade the collectors on all the Gateways and Controllers running. |image3| 4. If you want to know the version running on the individual collectors follow the below steps: a. Click on the individual Collector (either gateway or Controller). b. You will be displayed the Version number running on individual Collector. |image4| 5. To change the version or upgrade the version only on one particular Collector click on change version as shown below and then upgrade/downgrade to the version as per your requirement. |image5| .. |image1| image:: ./sumologic_upgrade_media/1.png :width: 7.00000 in :height: 5.00000 in .. |image2| image:: ./sumologic_upgrade_media/2.png :width: 7.00000 in :height: 5.00000 in .. |image3| image:: ./sumologic_upgrade_media/3.png :width: 7.00000 in :height: 5.00000 in .. |image4| image:: ./sumologic_upgrade_media/4.png :width: 7.00000 in :height: 5.00000 in .. |image5| image:: ./sumologic_upgrade_media/5.png :width: 7.00000 in :height: 5.00000 in <file_sep> .. role:: orange .. role:: green .. role:: blue .. raw:: html <style> .orange { color: #FFB366; } .blue { color: #0066CC; } .green { color: #006633; } </style> ================================================================================ Hybrid Network Load Balancing (NLB) ================================================================================ Balance Traffic between AWS and your Datacenter using AWS `Network Load Balancer <https://www.aviatrix.com/learning/glossary/network-load-balancing.php>`_ and Aviatrix Gateway ---------------------------------------------------------------------------------------------------- Problem Description ^^^^^^^^^^^^^^^^^^^ Operations teams are frequently managing infrastructure and services hosted both in the cloud and on-premise. Some common examples include: * DR scenarios, * centrally located shared services, and * application and workload migration to the cloud. Establishing reliable and secure network connectivity for these hybrid use cases presents a challenge to most teams. Imagine one specific example: you have a critical internal web application hosted in remote offices around the globe as well as in AWS. In order to provide fault-tolerance for the application, you would like to setup a central load balancer that balances traffic between the remote sites and AWS. AWS recently released the Network Load Balancer that made this possible by adding the ability to specify an IP address as a load balancer target, in addition to instances. However, using the NLB to forward traffic to a target IP address outside of AWS will only work if you have Direct Connect between the remote site and the AWS region. An IPSEC tunnel built between AWS VGW and on-prem site does not work since in this case traffic is always initiated from the VPC. So, for most users this doesn't help. Aviatrix solves this for AWS customers without Direct Connect. In this document, we will demonstrate how to go from an empty AWS VPC and a remote, on-premise hypervisor to a working demo that balances web traffic between the two sites. Demonstration ^^^^^^^^^^^^^ This demo will involve two web servers hosting a basic website. One server will be located in a remote site and one will be hosted in AWS. We'll set up AWS' NLB service to listen on port 80 and configure both of these servers as targets. This diagram represents the desired configuration: |image1| The webdemo hostname has been registered in DNS pointing to the NLB. When a user accesses the demo site (webdemo.aviatrix.com/index.html) from a browser, that request will be handled by the Network Load Balancer (the :orange:`orange` line in the diagram). The NLB will choose either the :green:`green` route to the remote site or the :blue:`blue` route to the EC2 instance and the selected web server will respond to the user with the contents of the requested file. For the purposes of this demo, the contents of `index.html` will differ slightly on each server to include either "Welcome to the Data Center" or "Welcome to AWS". Prerequisites ^^^^^^^^^^^^^ In order to complete the steps in this guide, you'll need: - An AWS account, - An Aviatrix license key (email to <EMAIL> if you don't have one) Step 1: Create AWS Resources ---------------------------- For AWS, we'll create a new VPC, EC2 instance, and enable the NLB service. Step 1a: Create VPC ^^^^^^^^^^^^^^^^^^^ There are a number of ways to create a VPC in AWS. We'll use the VPC Wizard, available in the `VPC Dashboard <https://console.aws.amazon.com/vpc/home>`_. Click the `Start VPC Wizard` button to launch the wizard. Then, select the `VPC with a Private Subnet Only and Hardware VPN Access` option. |imageAWSVPC1| Finally, fill out the form that follows providing an appropriate CIDR block and VPC name. |imageAWSVPC2| Step 1b: Create EC2 Instance (Web Server) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ We'll create a T2-micro instance running Amazon Linux and Apache to handle the web server role. The steps we used to create the EC2 instance are shown below: |imageAWSEC20| |imageAWSEC21| |imageAWSEC22| Connect to the new instance via SSH. We temporarily associated an Elastic IP with this instance for convenience while configuring it. :: > ssh ec2-user@<EIP> -i ~/aviatrix/demo/aws/aviatrix-demo.pem And, install the Apache package:: > sudo yum install httpd Finally, create a simple `index.html` page in the doc root (`/var/www/html/` for our installation):: <html> <head> <title>Welcome!</title> </head> <body> <h3>Welcome to AWS</h3> </body> </html> Now, if we go directly to the instance EIP in a web browser we should see this: |imageAWSEC25| In the next step, we'll set up the NLB to route traffic to this instance so we will no longer need the EIP associated with this instance. Step 1c: Configure the Network Load Balancer ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ In the `EC2 Dashboard <https://console.aws.amazon.com/ec2/home>`_, select `Load Balancers`, click the `Create Load Balancer` button, and finally select `Network Load Balancer` when prompted for the type: |imageAWSNLB1| On Step 1 of the form that is displayed, give the NLB a name and select `internet-facing` for the Scheme. We'll only need one listener on port 80 for this demo, so the default configuration is sufficient. Under Availability Zones, select the VPC we created in step 1a and then check the only subnet in the table below that. |imageAWSNLB2| On Step 2, select `New target group0 and provide a name. Be sure to change the `Target type` to `ip` instead of `instance` (we'll rely on this configuration later when accessing our remote site). Everything else will remain the default. |imageAWSNLB3| Step 3 requires us to select our target(s). For now, we only have one (our Linux EC2 instance that we created in the previous step. In the `IP` field, type in the private IP address of the EC2 instance that was created earlier. Keep the default port of 80 in the Port field and then click `Add to list`. |imageAWSNLB4| Review the configuration and click `Create`. Give the Load Balancer a few minutes to move out of the `provisioning` state into `active`. Once `active`, open a web browser and go to the public DNS name of the new load balancer. Step 2: Create and Configure Remote Site Web Server --------------------------------------------------- The remote site can be any network not in AWS. For this demo, I've provisioned a VM with Apache on my laptop's VMware Fusion environment. On this VM, I've also added a simple `index.html` file:: <html> <head> <title>Welcome!</title> </head> <body> <h3>Welcome to the Remote Site</h3> </body> </html> Step 3: Set up Aviatrix in the Cloud ------------------------------------ Without a Direct Connect connection between the remote site and AWS, you won't be able to add this new VM to the NLB. However, Aviatrix can overcome this requirement with a few simple steps. Step 3a: Install and configure the Controller ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The Aviatrix Controller provides a single pane of glass to visualize all of your hybrid cloud networking connections. An example dashboard looks like this: |imageAvtxDashboard0| Follow the `installation instructions <http://docs.aviatrix.com/StartUpGuides/aviatrix-cloud-controller-startup-guide.html>`_ to get a Controller up and running in AWS. Once complete, open a browser and connect to the controller over https (https://<controller ec2 public IP>/). Login with the username `admin`. The password is the controller's private IP address. Follow the prompts to enter your email address and click `Run` when prompted to upgrade the Controller to the latest version. When the upgrade is finished, login using admin/<private ip address>. Once you login, you will be prompted to change your password. After that you will see this screen: |imageController4| Select `AWS` to configure your AWS account. And, then enter your Aviatrix customer ID and click `Save`: |imageController5| Finally, create an Aviatrix Controller account. You'll use this to login to the Controller. Aviatrix recommends selecting `IAM role-based` option for AWS access. |imageController6| Step 3b: Create a Gateway ^^^^^^^^^^^^^^^^^^^^^^^^^ Next, follow the `instructions <http://docs.aviatrix.com/HowTos/gateway.html>`_ to install an Aviatrix Gateway in this VPC. This will be where our remote site will connect. Once the Gateway is up, you should see it appear on the Controller's dashboard: |imageGateway2| Step 4: Set up Aviatrix on your remote site ------------------------------------------- Our final step is to add an Aviatrix Gateway at our remote site. Aviatrix provides a virtual appliance that can be downloaded from `here <http://aviatrix.com/download/>`__. Download the appropriate appliance for your environment and spin up a VM. Step 4a: Configure the Appliance ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ At the prompt, enter `help` to see the options available. You'll want to set up a static IP address. The format of the command is:: > setup_interface_static_address <static_ip> <netmask> <default_gateway> <primary_dns> <secondary_dns> proxy {true|false} The configuration we used (on a VMware Fusion instance) looks like this: |imageCloudN0| Once complete, open a browser and browse to the IP address you just configured for your controller. Follow the same initial steps as you did for the cloud (AWS) Controller. Once you get to Step 2 `Datacenter Extension or Site2Cloud`, stop and click on the `Site2Cloud` icon on the left. |imageCloudN1| Step 4b: Connect Remote Site to AWS ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ In a separate browser window, log into the Aviatrix Controller hosted in AWS. Click on the `Site2Cloud` icon on the left and click `+ Add New` button at the top. Select the correct VPC, enter a Connection Name, and change the Remote Gateway Type to `Aviatrix`. Finally, provide your edge router IP address for the Remote Gateway IP Address and populate the appropriate Remote Subnet. Then, click `OK`. |imageSite2Cloud0| Once complete, select the connection from the table you just created. Click `Download Configuration` (NOTE: you may need to disable the popup blocker in your browser). |imageSite2Cloud1| Once downloaded, go back to the browser window with the Aviatrix Controller in the remote site. You should be on the `Site2Cloud` page. Click `+ Add New` at the top. Then, scroll to the bottom and select `Import`. |imageSite2Cloud2| In the file open box, select the configuration downloaded in the previous step. Once complete, switch to the Aviatrix Controller hosted in AWS and go to the dashboard. You should see the 2 sites connected but with a red line. |imageSite2Cloud3| Once the link is established and the line representing the link turns green, we are all set. |imageSite2Cloud4| One last step that we'll need to do is to tell the default gateway on the subnet where Aviatrix gateway is deployed that the next hop is the Aviatrix Gateway for traffic in AWS VPC private IP address range. The steps to make this change will depend on your individual router. You'll need to route all traffic destined for the AWS VPC private IP range (10.77.0.0/24 in my example) back to the Aviatrix Gateway. Step 4c: Add Remote Site Web Server to the NLB ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Back in the AWS console, go to the Target Groups in the EC2 Dashboard. Click on the Target Group we created earlier and then click on `Targets`. You should have just one IP in the list right now. Click `Edit` and then click on the `+` icon at the top. |imageTestTG0| Change the `Network` drop down to `Other private IP address` and then enter the private IP address of the Apache VM we set up earlier on the remote side. Click `Add to list` and then `Register`. |imageTestTG1| |imageTestTG2| Once the remote VM is registered, verify that the NLB shows both targets as `healthy`. It may take a few seconds for the newly added IP to move from `initial` to `healthy`. |imageTestTG5| After both target IP addresses are `healthy`, we are ready to test. Step 5: Test ------------ First, let's open a browser window to the NLB's EIP. We should see the welcome message from one of the web servers. On my first attempt, I saw the remote site: |imageTest2| Next, let's turn off the web server on remote VM:: > sudo systemctl status apache2 > sudo systemctl stop apache2 > sudo systemctl status apache2 The NLB target group reports the server as `unhealthy` quickly after: |imageTestTG7| And, the browser, after refresh, shows the welcome message from AWS: |imageTest1| Next, start Apache back up on the remote VM and wait for the target group to show both targets as `healthy`. Once both are healthy, shut down Apache on the AWS (or remove port 80 from the security group's allowed inbound ports): |imageTest3| Wait for the NLB to show the AWS node as `unhealthy`: |imageTestTG8| Now, the browser, after refresh, shows the welcome message from the remote VM: |imageTest2| Start Apache back up on the AWS instance (or add port 80 back to the security group): |imageTest4| Conclusion ---------- Aviatrix makes balancing load between AWS and remote sites easy. But that's just the beginning. Aviatrix makes cloud and hybrid networking as simple, dynamic, and disposable as compute and storage. Read more about Aviatrix `here <http://aviatrix.com/products/>`__. .. |image0| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/Overview.png .. |image1| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/overview_with_aviatrix.png .. |imageAWSVPC1| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/aws_screenshots/create_vpc/screenshot_vpc_step_1.png .. |imageAWSVPC2| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/aws_screenshots/create_vpc/screenshot_vpc_step_2.png .. |imageAWSEC20| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/aws_screenshots/create_web_server/screenshot_EC2_step_1.png .. |imageAWSEC21| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/aws_screenshots/create_web_server/screenshot_EC2_step_3.png .. |imageAWSEC22| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/aws_screenshots/create_web_server/screenshot_EC2_step_5.png .. |imageAWSEC25| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/aws_screenshots/create_web_server/screenshot_web_browser_view_of_aws_httpd.png .. |imageAWSNLB1| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/aws_screenshots/create_nlb/screenshot_nlb_select_load_balancer_type.png .. |imageAWSNLB2| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/aws_screenshots/create_nlb/screenshot_configure_load_balancer_step_1.png .. |imageAWSNLB3| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/aws_screenshots/create_nlb/screenshot_configure_load_balancer_step_2.png .. |imageAWSNLB4| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/aws_screenshots/create_nlb/screenshot_configure_load_balancer_step_3.png .. |imageAvtxDashboard0| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/aviatrix_screenshots/screenshot_aviatrix_dashboard_sample.png .. |imageAWSCF0| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/aws_screenshots/create_aviatrix_using_cf/screenshot_cf_select_template.png .. |imageAWSCF1| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/aws_screenshots/create_aviatrix_using_cf/screenshot_cf_specify_details.png .. |imageAWSCF2| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/aws_screenshots/create_aviatrix_using_cf/screenshot_cf_options.png .. |imageController0| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/controller_setup_screenshots/screenshot_controller_email.png .. |imageController1| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/controller_setup_screenshots/screenshot_controller_run_update.png .. |imageController2| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/controller_setup_screenshots/screenshot_controller_change_password.png .. |imageController3| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/controller_setup_screenshots/screenshot_controller_email.png .. |imageController4| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/controller_setup_screenshots/screenshot_controller_wizard_home.png .. |imageController5| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/controller_setup_screenshots/screenshot_controller_enter_aviatrix_customer_id.png .. |imageController6| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/controller_setup_screenshots/screenshot_controller_create_account.png .. |imageController7| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/controller_setup_screenshots/screenshot_controller_stack_outputs.png .. |imageCloudN0| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/cloudn_screenshots/screenshot_cloudn_setup_address.png .. |imageCloudN1| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/cloudn_screenshots/screenshot_cloudn_site2cloud_icon_navigation.png .. |imageGateway0| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/aws_gateway_screenshots/screenshot_gw_nav_gateway.png .. |imageGateway1| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/aws_gateway_screenshots/screenshot_gw_create_new.png .. |imageGateway2| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/aws_gateway_screenshots/screenshot_gw_dashboard.png .. |imageSite2Cloud0| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/site2cloud_screenshots/screenshot_aws_site2cloud_add_new.png .. |imageSite2Cloud1| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/site2cloud_screenshots/screenshot_site2cloud_aws_download_config.png .. |imageSite2Cloud2| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/site2cloud_screenshots/screenshot_site2cloud_remote_import.png .. |imageSite2Cloud3| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/site2cloud_screenshots/screenshot_site2cloud_link_down.png .. |imageSite2Cloud4| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/site2cloud_screenshots/screenshot_site2cloud_link_up.png .. |imageTestTG0| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/test_screenshots/tg/screenshot_test_tg_plus.png .. |imageTestTG1| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/test_screenshots/tg/screenshot_test_tg_ip_about_to_add.png .. |imageTestTG2| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/test_screenshots/tg/screenshot_test_tg_remote_ip_added.png .. |imageTestTG3| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/test_screenshots/tg/screenshot_test_tg_before_adding_remote.png .. |imageTestTG4| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/test_screenshots/tg/screenshot_test_tg_aws_unhealthy.png .. |imageTestTG5| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/test_screenshots/tg/screenshot_test_tg_both_healthy.png .. |imageTestTG6| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/test_screenshots/tg/screenshot_test_tg_remote_ip_added.png .. |imageTestTG7| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/test_screenshots/tg/screenshot_test_tg_unhealthy_remote.png .. |imageTestTG8| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/test_screenshots/tg/screenshot_test_tg_aws_unhealthy.png .. |imageTest0| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/test_screenshots/screenshot_test_apache_status_then_stop.png .. |imageTest1| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/test_screenshots/screenshot_test_browser_aws_after_remote_unhealthy.png .. |imageTest2| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/test_screenshots/screenshot_test_browser_remote.png .. |imageTest3| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/test_screenshots/screenshot_test_sg_http_removed.png .. |imageTest4| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/test_screenshots/screenshot_test_sg_http_allowed.png .. |imageTest5| image:: AWS_NetworkLoadBalancer_Onsite_And_In_Cloud_media/test_screenshots/screenshot_test_start_apache_remote.png .. disqus:: <file_sep> ========================== Monitoring Your Network ========================== Aviatrix Controller and CoPilot provide alerting, monitoring, and logging capabilities that help you see what is happening across all clouds in your multi-cloud network that are managed by Aviatrix Controller. These capabilities assist you with finding issues, and addressing them as they occur. Visit `this link on the Aviatrix website <https://aviatrix.com/resources/youtube-aviatrix-copilot-cloud-network-operational-visibility>`_ for cloud network operations, visibility and monitoring tutorials. Setting up Alerts for Detected Threat IPs ========================================= The ThreatIQ with ThreatGuard feature enables you to monitor for security threats in your Aviatrix cloud network; set alerts when threats are detected in the network traffic flows; and block traffic that is associated with threats. For more information on how to set up this feature see `Working with Threat IQ <https://docs.aviatrix.com/HowTos/copilot_reference_guide.html#working-with-threatiq>`_. Sending Notifications to External Systems ========================================= You can configure web-hook alerts to send notifications to external (third-party) systems, such as PagerDuty. Click `here for more information <https://docs.aviatrix.com/HowTos/copilot_reference_guide.html#working-with-notifications>`_. Monitoring Status and Resources =============================== The following monitoring capabilities provide visibility into the status and resources (Aviatrix and native cloud networking resources) on your multi-cloud network. This current and accurate snapshot of your data enables you to find and quickly resolve network issues. See below for details on these monitoring capabilities: - Operational status of cloud resources (`dashboard <https://docs.aviatrix.com/HowTos/copilot_reference_guide.html#copilot-dashboard>`_) - Network traffic flows, top talkers/receivers, and geographic origin of traffic (`FlowIQ <https://docs.aviatrix.com/HowTos/copilot_reference_guide.html#working-with-flowiq>`_) - Status of connections for Aviatrix gateways, Site2Cloud (data center connections into the cloud) and BGP (Border Gateway Patrol) connections from on-prem to the cloud (Cloud Routes) - Notifications of changes in your Aviatrix Controller and Aviatrix Gateways based on system or network metrics (Notifications); see below for more details on the Notifications feature. System Notifications Feature ============================ You can configure notifications to be alerted about events (such as performance bottlenecks) and detected anomalies that occur in your networks. If an event or anomaly meets the configured metric or condition, an alert is triggered and sent to the selected destination. How you set a condition threshold to trigger an alert will depend on different factors. For example, for system metrics, the instance size can influence the condition threshold that makes sense. For metrics associated with cloud provider-maintained infrastructure, the desired condition threshold may vary between cloud service providers. Work with your network operations team to determine the metric conditions that will trigger alerts in your environment. The alerts you can set are configured in CoPilot. For more information about setting alerts based on system and network metrics, see `Working with Notifications <https://docs.aviatrix.com/HowTos/copilot_reference_guide.html#working-with-notifications>`_. For more information about configuring anomalies, see `Working with Anomalies <https://docs.aviatrix.com/HowTos/copilot_reference_guide.html#working-with-anomalies>`_. Aviatrix Controller Alert Notifications ======================================= In the Aviatrix Controller, emails are sent when there is a change in gateway or tunnel status. You can configure the status change event email address and email notification interval on the Settings> Controller> Email tab. You can also configure alert notifications (sent via email or web-hook) for the following features. These alerts display when you click the Controller alert bell in the Controller toolbar: - `Overlapping CIDR Check <https://docs.aviatrix.com/HowTos/bgp.html#bgp-overlapping-alert-email>`_: an email is sent when BGP routes overlap in Site2Cloud. - GuardDuty Check: when Amazon GuardDuty detects and blocks malicious IP addresses detected in NetFlow data. - Log Service Check: when a remote syslog server is down. - `Reach of Route Limit Check <https://docs.aviatrix.com/HowTos/bgp.html#bgp-route-limit-alert-email>`_: when VPC and BGP route limits reach a given threshold. - Blackhole Route Entry Check: when a VPC route table has inactive routes. Click `here <https://docs.aviatrix.com/HowTos/alert_and_email.html#how-to-manage-alert-bell-notification>`_ for more information on these alerting features in the Aviatrix Controller. Monitoring Gateways ==================== When heartbeat information from any gateway fails, Aviatrix Controller restarts these gateways and sends an email to the administrator. You can also `monitor gateway subnets <https://docs.aviatrix.com/HowTos/gateway.html#monitor-gateway-subnet>`_ to ensure that no unauthorized virtual machines are being launched. When enabled, Controller periodically monitors the selected subnet where the gateway was launched. An alert mail is sent to admin, and the instance is immediately stopped. Account Audit ============= Aviatrix Controller periodically audits its managed IAM roles and policies to ensure the roles are attached to accounts and that the policies are correct. If any of the audits fail, the Controller sends an email alert and logs the event. The Controller also sends an alert email if any gateways report these audit failures (upon first detection and every 24 hours until the problem is fixed). See `here <https://docs.aviatrix.com/HowTos/account_audit.html#account-audit>`_ for more information. Logging ======= In Aviatrix Controller you can select a logging management system to receive data from the Controller and its managed gateways. Logs sent to these systems can be parsed to display relevant analytics of collected data and to evaluate the trends that help monitor network connectivity and user VPN sessions. You can enable Remote Syslog logging and send the information to CoPilot by entering CoPilot’s IP address and UDP port 5000. If using Remote Syslog to send information to other applications, see `here <https://docs.aviatrix.com/HowTos/AviatrixLogging.html#remote-syslog>`_. Click `here <https://docs.aviatrix.com/HowTos/AviatrixLogging.html>`_ for more information on configuring logging options, and keywords that the logging management system can flag. Background Tasks ================ During background tasks such as software upgrades and gateway deployments, a notification email is sent to the admin email address configured in the Aviatrix Controller under Settings > Controller > Email. .. disqus:: <file_sep> ========================================================= Firewall Network (FireNet) FAQ ========================================================= What is Aviatrix Firewall Network (FireNet)? ------------------------------------------------------------ Aviatrix Firewall Network (FireNet) is a turnkey network solution to deploy firewall instances in the cloud, as shown in the diagram below. |firewall_network| FireNet significantly simplifies firewall instance deployment and allows the firewall instances to inspect VPC/VNet to VPC/VNet (East West) traffic, VPC/VNet to Internet (Egress) traffic, and VPC/VNet to on-prem (North South) traffic. In addition, FireNet allows you to scale firewall deployment to multiple AZs and multiple instances in active/active state. How does Aviatrix FireNet compare with the native deployment in AWS Transit Gateway? --------------------------------------------------------------------------------------------------------------- There are two native deployments: TGW VPN to connect to firewall or TGW VPC attachment to connect to firewall. The three different deployment models are illustrated in the diagram below. |firewall_deploy| If an AWS Transit Gateway connects to a firewall by using its built in VPN function, it must run IPsec and BGP. If you run more than one firewall instances by using ECMP, each firewall instance must configure SNAT function to ensure that both source and destination-initiated traffic lands on the same firewall instance. Furthermore, since native deployment requires an IPsec VPN which limits its performance to 1Gbps, in this scenario a single firewall instance can only perform at 500Mbps since the VPN function is traversed twice. A more detailed functional comparison is described in the table below. ========================================= ================================== ============================== ================================= **Firewall Deployment Functions** **Firewall in VPN deployment** **Firewall in VPC/VNet attachment** **Firewall in Aviatrix FireNet** ========================================= ================================== ============================== ================================= On-prem to VPC/VNet traffic inspection Yes Yes Yes VPC/VNet to VPC/VNet traffic inspection Yes (requires SNAT) Yes Yes Egress traffic inspection Yes Yes Yes Per firewall performance 500Mbps Up to 6Gbps Up to 6Gbps Total FireNet performance > 500Mbps Up to 6Gbps up to 75Gbps Multiple firewalls (scale out) Yes No (Active/Standby) Yes Integrated solution Yes No (requires external script) Yes Solution complexity High Medium Low Centrally managed Yes No (requires external script) Yes Multi-vendor support Yes Yes Yes ========================================= ================================== ============================== ================================= What are the Benefits of FireNet Deployment Model? ---------------------------------------------------------------------------------------- For enterprises that wish to deploy a firewall in any Cloud Service Provider (CSP) including AWS, Azure, GCP, or OCI, Aviatrix’s FireNet deployment model provides the best performance and automation. - **Simplicity** The Aviatrix Firewall Network significantly simplifies firewall deployment in the cloud while providing the maximum performance and scale. - **Full Traffic Inspection** With FireNet, North South (on-prem and cloud), East West (VPC/VNet to VPC/VNet) and Internet bound egress traffic can be inspected by firewall instances. - **No IPsec Tunnels** There are no IPsec tunnels connecting to firewall instances as opposed to ECMP VPN deployment model, maximizing each firewall instance throughput. - **No SNAT** SNAT function is not required to be performed by firewall instances for east west traffic inspection as opposed to the ECMP VPN deployment model, resulting in instances in Spoke VPC/VNets having complete visibility of source traffic. - **No BGP** The Firewall does not need to run BGP. All routes programming is done by the Controller through Palo Alto APIs. - **Scale Out** Multiple firewall instances can be deployed as a group to meet the demand of increasing workload. - **Policy Driven** Policy driven workflow allows you to customize which VPC/VNets traffic should be inspected. - **Vendor Integration** Launch Palo Alto Networks VM-Series from the Aviatrix Controller console to simplify deployment. - **Automation** The Aviatrix Controller automatically updates Palo Alto VM-Series route tables when on-prem route changes or VPC/VNet attachment changes. Does FireNet support other firewalls? -------------------------------------------------------------- The following firewalls are supported: - Palo Alto VM-Series - Check Point CloudGuard - Fortinet FortiGate Is the FireNet solution recommended by Palo Alto Networks? ------------------------------------------------------------------------------------- Yes. Aviatrix is a technology `partner of Palo Alto Networks. <https://www.paloaltonetworks.com/partners/alliance>`_ Palo Alto has published the `joint solution brief. <https://www.paloaltonetworks.com/content/dam/pan/en_US/assets/pdf/technology-solutions-briefs/palo-alto-networks-and-aviatrix.pdf>`_ Does FireNet work with other firewall appliances? ---------------------------------------------------------------- Yes. FireNet solution has been validated to work with `Checkpoint <https://docs.aviatrix.com/HowTos/config_Checkpoint.html>`_, `FortiGate <https://docs.aviatrix.com/HowTos/config_FortiGate.html>`_ and `Barracuda CloudGen Firewall <https://docs.aviatrix.com/HowTos/config_Barracuda.html>`_. How is Firewall Network different from Transit DMZ? -------------------------------------------------------------------- Firewall Network is the new iteration from Transit DMZ. FireNet decouples the firewall deployment from the path between on-prem and Aviatrix Transit VPC/VNet, yet provides the same traffic inspection functions and more scale out capabilities. How Does Aviatrix Security Domains work with FireNet? ------------------------------------------------------------------------- Aviatrix `Security Domain <https://docs.aviatrix.com/HowTos/tgw_faq.html#what-is-a-security-domain>`_ builds on the AWS Transit Gateway (TGW) route domain concepts. It provides isolation and segmentation between VPC/VNets. With Aviatrix Security Domains, you can create a group of VPC/VNets with similar security requirements. There are situations where additional security measures such as packet inspection are required. That is, you need to deploy a firewall for certain VPC/VNets. FireNet provides the network solution that simplifies firewall deployment and scale. 1. Deploy the Aviatrix FireNet in a special Security Domain with a Firewall Domain attribute. #. If a Security Domain has a connection policy to the Firewall Domain, then traffic going in and out of each VPC/VNet member in that Security Domain will first be forwarded to the Firewall for inspection. In other words, the connection policy specifies which domain (or a group of VPC/VNets) will be inspected by the firewall. See `Domain-based inspection <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#a-domain-based-inspection>`_. #. Alternatively, starting in Release 6.3 you can specify inspection based on pairs of Connection Policies. See `Connection-based inspection <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#b-connection-based-inspection>`_. What are the use cases for FireNet? ----------------------------------------------------- Example 1. VPC/VNet with PCI data ############################## If you have a VPC/VNet that deploys applications that host Personal Information or PCI data and your compliance requires packet inspection, you can create a Security Domain where this VPC/VNet is attached. Specify a connection policy for this Security Domain to connect to the Firewall Domain. All packets to and from this VPC/VNet will be inspected. Example 2. Production VPC/VNets ########################### You may decide to inspect all traffic from the production data, which resides in multiple VPC/VNets. In this case you can create a Security Domain that all of these VPC/VNets are attached to. Then use connection policy to connect this domain to the firewall domain. What are the limitations of FireNet? ------------------------------------------------- You can have multiple Firewall Domains. However, a Security Domain cannot be connected to two Firewall Domains except the case when one is for Ingress/Egress and another is for East-West and North-South inspection. How does FireNet compare with ECMP/VPN based firewall deployment? ---------------------------------------------------------------------------------------------- AWS Transit Gateway (TGW) supports VPN with ECMP load balancing. With this capability, you can launch multiple firewall instances in a load balanced fashion for Egress Inspection and VPC/VNet to VPC/VNet traffic inspection. One problem with this deployment is performance. The IPsec tunnel limits each firewall instance to be capped at 1Gbps. When this architecture is deployed for VPC/VNet to VPC/VNet inspection, traffic goes through the VGW (the other end of the IPsec tunnel) twice, further reducing its throughput to 500Mbps. What this implies is that each firewall instance can only operate at 400Mbps throughput. This is much lower than what firewall instances can do without an IPsec tunnel. Another problem is that for east west traffic inspection, the firewall instance must NAT the source address, otherwise the return traffic is not guaranteed to go through the same firewall instance. This is because ECMP makes the independent decision of distributing the traffic of the firewall instances for each direction of the traffic. What is the minimum gateway instance size for FireNet deployment? ------------------------------------------------------------------------------------------ The minimum gateway instance size is C5.xlarge. This is because the FireNet gateway requires 4 network interfaces: - eth0 as a management interface - eth1 as a TGW interface - eth2 as a firewall instance interface - eth3 as the HA FireNet gateway interface The private interfaces on FireNet Gateway are described as below. |private_interfaces| Can TGW send packets to both FireNet Gateways? ------------------------------------------------------------------- Yes. Both primary and HA FireNet Gateways attach its eth1 ENI to TGW. When TGW forwards packets to the FireNet VPC/VNet, it applies AZ affinity in the best effort manner. That is, packets coming from a source VPC/VNet instance in AZ-a will be forwarded to the gateway whose ENI is in AZ-a. For example, two FireNet gateways, gateway-1 and gateway-2, one has eth1 in AZ-a and the other is in AZ-b, respectively. In a healthy state, both gateways receive traffic from TGW. A Spoke VPC/VNet traffic from AZ-a will be forwarded to gateway-1 eth1 ENI for processing. Spoke VPC/VNet traffic from AZ-b will be forwarded to gateway-2 for processing. When gateway-1 goes down, the Controller detects the failure, and then the Controller reprograms the default route entry (0.0.0.0/0) of the route table that is associated with the gateway-1 eth1 subnet (with the name like -gw-tgw-ingress) to point to the ENI of eth1 of the gateway-2 (its subnet should have a name like -gw-hagw-tgw-ingress), thus redirecting all AZ-a source traffic to the gateway in AZ-b. How does FireNet work? ------------------------------------ Take, for example, a VPC/VNet1 to VPC/VNet2 traffic inspection, where VPC/VNet1 and VPC/VNet2 are attached to the same TGW. As a packet from VPC/VNet1 arrives at the FireNet gateway via the TGW, it does a 4-tuple (source IP, destination IP, source port and destination port) hash calculation to decide if it should forward the packet to one of the associated firewall instances or forward to the HA FireNet gateway. If the hash calculation determines the firewall instance is associated with the HA FireNet gateway, it forwards the packet to the HA FireNet gateway through its eth3 interface. When the HA FireNet gateway receives the packet, it performs exactly the same hash calculation and decides which associated firewall instance it should forward the traffic to. The packet flow is illustrated in the diagram below: |firenet_packet_flow| How do I configure FireNet? ---------------------------------------- Follow the `FireNet workflow <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html>`_ to deploy firewall in the cloud. How do I enable Egress inspection on FireNet? ------------------------------------------------------------ By default, FireNet inspects traffic between North South (on-prem and VPC/VNet) and East West (VPC/VNet to VPC/VNet). To enable Egress traffic (Internet bound) inspection: Go to Firewall Network > Advanced. Click the skewer. Scroll down to Egress through Firewall and click **Enable**. Note for GCE instances: Any GCE instance (excluding Controller-created gateways) that needs to participate in egress control (FQDN, SNAT, and FW Egress) have to be tagged as "avx-snat-noip." The GCE network tag "avx-snat-noip" can be associated during GCE instance creation or by editing an existing instance. How do I make Ingress inspection to work on FireNet? ----------------------------------------------------------------------- If the FireNet deployment is for both Egress and Ingress traffic, you need to SNAT on the firewall instance to its LAN or Trusted Interface IP (eth2 interface). The rule is that for a source IP address that comes from NLB or a vendor load balancer such as F5 private IP address, it is translated to firewall interface eth2 private IP address. How to exclude specific CIDRs from being inspected by the firewall? ---------------------------------------------------------------------------------------- By default, FireNet inspects all East-West (VPC/VNet to VPC/VNet) traffic but you may have an instance in the VPC/VNet which you do not want to be inspected. For example, the Aviatrix Controller deployed in the Shared Service VPC/VNet to be excluded from inspection while Shared Service VPC/VNet traffic is inspected. This improves the Controller reachability by not subjecting the Controller access to unintentional firewall policy errors. Go to Firewall Network > Advanced and put the CIDRs in the field **"Network List Excluded From East-West Inspection"** to exclude from being inspected by the firewall. **Note:** 1. Maximum 20 CIDRs coma-separated are supported. 2. CIDRs are excluded from East-West inspections only. 3. In AWS TGW FireNet, if Egress inspection is enabled, Egress traffic originated from an excluded CIDRs will be dropped. If excluded CIDRs needs to be inspected then use a separate FireNet for Egress Traffic and separate FireNet for East-West Traffic. Is there an example guide to setup Palo Alto VM-Series policies? ------------------------------------------------------------------------------- Yes. Follow `Example Config for Palo Alto VM-Series <https://docs.aviatrix.com/HowTos/config_paloaltoVM.html>`_ to setup an "ALLOW ALL" policy for test validation. How do I test FireNet connectivity without deploying firewall instance? ------------------------------------------------------------------------------------------ You can test connectivity without deploying any firewall instances. When the FireNet gateway has no firewall instance attached to it for the data path, the FireNet gateway loops the received packet and forwards it to its destination. Follow the FireNet workflow to complete Steps 1, 2, 3, 4, 5, 6 and 8. If you have an instance in VPC/VNet/Domain and another instance in a different VPC/VNet/Domain, and you specify connection policy between the Domains and one Domain to connect to the Firewall Domain, then you should be able to ping the two instances. What is the maximum performance FireNet can achieve? ---------------------------------------------------------------------- For East-West (VPC/VNet to VPC/VNet) and North-South (on-prem to VPC/VNet) traffic inspection, FireNet achieves 40Gbps throughput with Jumbo frame size in AWS. Note the maximum TGW performance between two attached VPC/VNets is 50Gbps. |firewall_network_perf| Are there any design patterns for Firewall Network deployment? ---------------------------------------------------------------------------------- Yes, please refer to the `Firewall Network Design Patterns. <https://docs.aviatrix.com/HowTos/firewall_network_design_patterns.html>`_ Can VM-Series be launched with Bootstrap integration? ---------------------------------------------------------------------- Yes. When you launch a VM-Series from Aviatrix Controller console, you can select the option to launch the VM-Series instance with `bootstrap information <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#example-configuration-for-bootstrap>`_. Can Firewall Network work with Panorama? ------------------------------------------------------------ Yes. Follow the instructions for `Panorama integration. <https://docs.aviatrix.com/HowTos/paloalto_API_setup.html#managing-vm-series-by-panorama>`_ What is the FireNet gateway failover time? ----------------------------------------------------------- Aviatrix FireNet gateway failure detection time is 8 - 10 seconds. The switch over to alternative gateway (primary or backup) is about the same time. Why does the primary gateway send packets to backup gateway instead of sending to firewall directly? --------------------------------------------------------------------------------------------------------------------------------- If the firewall instance is in the same AZ and on the same subnet with the primary gateway, packets are forwarded directly from the gateway to the firewall instance. However, if the firewall instance is in the different AZ and subnet, forwarding packets directly to the firewall instance requires AWS route table to be programmed with target as the firewall instance, and as a result, there cannot be more than one firewall instance in the different AZ, thus losing the scale out capability. Does Aviatrix Controller communicate with Palo Alto Panorama to its private IP address? --------------------------------------------------------------------------------------------------------------- Yes, if the Panorama is reachable via private IP. Does Aviatrix Controller check the health of Panorama? ---------------------------------------------------------------------- No. Aviatrix Controller only checks the health of VM-Series instances. How does Aviatrix Controller know which Panorama is the primary one if there are two cross sites? --------------------------------------------------------------------------------------------------------------------------- The primary IP address is configured at the `Vendor Integration <https://docs.aviatrix.com/HowTos/paloalto_API_setup.html#managing-vm-series-by-panorama>`_ function. Aviatrix FireNet Security Groups --------------------------------------------- On firewall LAN interface. Eth2 on PAN; or Eth1 on Fortigate and Checkpoint. This interface accepts all data traffic to be inspected or going to the Internet (if egress is enabled). The traffic originates from an internal instance, which is destinated to another internal instance or the Internet. Therefore, it is OK to limit this SG to RFC1918 only. But if there are non-RFC1918 CIDR’s inside your network, those may not work. On a FireNet gateway, there are 4 interfaces. Eth0: this interface is used for all Internet traffic (DNS, NTP, etc), communication with the Controller (TCP, SSH, etc), encrypted tunnels, etc. This interface is under the Aviatrix Controller’s control, it’s SG is already limited to the minimum. User should NOT change it. Even if user changes it, the Aviatrix Controller will always try to change back. Eth1: this interface is used to send/receive traffic to AWS TGW. It accepts data traffic from TGW, so it is OK to limit SG to RFC1918 only. Eth2: this interface is used to send/receive traffic to firewalls (through firewall’s LAN interface), so it expects traffic originated from both internal and external. It might be OK to limit to RFC1918 since AWS SG is stateful. Eth3: this interface is used to exchange traffic between primary and backup gateway, this is part of our uniform hashing algorithm. Like eth2, it expects traffic originated from both internal and external. It might be OK to limit to RFC1918, since AWS SG is stateful. What are the integration points with Fortinet firewall? --------------------------------------------------------------------- 1. Managing Life Cycle of Fortinet firewall instances a. Aviatrix Controller launches and deletes Fortinet firewall instances. #. Supports `Fortinet Bootstrap mechanism <https://docs.aviatrix.com/HowTos/fortigate_bootstrap_example.html>`_ to simplifying firewall instance launching and preload any firewall configurations. 2. Managing Fortinet firewall instances pool a. The Aviatrix Controller monitors individual firewall health by periodically pining the LAN interface of each firewall instances. Ping period is every 5 second with a 20ms ping time out. The failure detection is maximum 5 seconds and 40ms. The Aviatrix Controller automatically detaches a unhealthy firewall instance. When the firewall instance is reachable again, it automatically attaches it back to the pool. #. You can initiate a new firewall instance to be launched and attached to pool at any given time. #. You can initiate to remove a firewall instance from the pool at any given time. 3. Static Route Configuration Currently there is no API integration to automatically populate Fortinet route table entries. Customer needs to configure these entries. We recommend configuring the 3 RFC 1918 routes to point to the firewall LAN interface. For FireNet deployment, the RFC 1918 routes should point to the LAN interface subnet cloud provider's default gateways. For Transit FireNet deployment, the RFC 1918 routes should point to the FireNet Gateway LAN interface IP, as shown in this `example. <https://docs.aviatrix.com/HowTos/config_FortiGateVM.html#configure-fortigate-next-generation-firewall-port1-with-wan>`_. What is Intra Domain inspection? --------------------------------- Intra Domain inspection allows traffic between VPC/VNets in the same Security Domain to be redirected to Firewall Domain for inspection before reaching to the destination. How to migrate from FireNet to FireNet with AWS GWLB or vice versa? --------------------------------------------------------------------------------- Starting from Release 6.3, Multi-Cloud Transit FireNet added support for AWS Gateway Load Balancer (GWLB). The key advantage of this integration is to allow firewalls to be scaled up and down without affecting established sessions (except sessions associated with the failed firewalls). 1. Save firewall configuration. #. Disassociate firewall instance > Go to Aviatrix Controller > Firewall Network > Setup > Step 10. #. Delete firewall instance > Go to Aviatrix Controller > Firewall Network > Setup > Step 7a. #. Disable FireNet function > Go to Aviatrix Controller > Firewall Network > Step 11a to disable Aviatrix Gateway FireNet Function. #. Enable Transit FireNet function > Go to Aviatrix Controller > Firewall Network > Step 5a to enable the Aviatrix Gateway for FireNet Function. Mark the **Use AWS GWLB** checkbox if migrating from Aviatrix FireNet to FireNet with AWS GWLB. #. Launch and associate firewall > Go to Aviatrix Controller > Firewall Network > Step 7a. #. Restore firewall configuration. Can we migrate from FireNet solution to Native FireNet with GWLB solution ? ---------------------------------------------------------------------------------------------------------------- Native FireNet refers to a deployment scenario where Aviatrix FireNet gateways are not deployed. To migrate, use the following steps for migration: 1. Save the firewall configuration. #. Disassociate firewall instance > Go to Aviatrix Controller > Firewall Network > Setup > Step 10. #. Delete firewall instance > Go to Aviatrix Controller > Firewall Network > Setup > Step 7a. #. Disable FireNet function > Go to Aviatrix Controller > Firewall Network > Step 11a to disable Aviatrix Gateway FireNet Function. #. Delete Transit FireNet Gateway. #. Enable Transit FireNet function > Go to Aviatrix Controller > Firewall Network > Step 5b to enable the Native AWS GWLB for FireNet Function. #. Launch and associate firewall > Go to Aviatrix Controller > Firewall Network > Step 7a. #. Restore firewall configuration. .. |firewall_network| image:: firewall_network_faq_media/firewall_network.png :scale: 30% .. |firewall_deploy| image:: firewall_network_faq_media/firewall_deploy.png :scale: 30% .. |multi_region_firewall| image:: firewall_network_faq_media/multi_region_firewall.png :scale: 30% .. |multi_region_aviatrix_edge| image:: firewall_network_faq_media/multi_region_aviatrix_edge.png :scale: 30% .. |firewall_network_perf| image:: firewall_network_faq_media/firewall_network_perf.png :scale: 30% .. |firewall_network_perf_new| image:: firewall_network_faq_media/firewall_network_perf_new.png :scale: 30% .. |multi_firewall| image:: firewall_network_faq_media/multi_firewall.png :scale: 30% .. |firenet| image:: firewall_network_media/firenet.png :scale: 30% .. |firenet_transit| image:: firewall_network_media/firenet_transit.png :scale: 30% .. |firenet_insane| image:: firewall_network_media/firenet_insane.png :scale: 30% .. |private_interfaces| image:: firewall_network_workflow_media/private_interfaces.png :scale: 30% .. |firenet_packet_flow| image:: firewall_network_faq_media/firenet_packet_flow.png :scale: 30% .. disqus:: <file_sep> ============================================================= Migrating a CSR Transit Solution to Aviatrix Transit Solution ============================================================= This document assumes that you have deployed a `CSR Transit solution <https://aws.amazon.com/answers/networking/aws-global-transit-network/>`_ with Transit hub CSR instances and VGWs in Spoke VPCs. The steps below provide instructions to migrate a live CSR deployment to Aviatrix deployment. The objectives here are: - No change to any on-prem network. - No change to the connectivity between AWS VGW and on-prem. (either over DX or over Internet or both) - Re-use AWS VGW deployed in Transit hub VPC. - No change to existing VPC infrastructure. - Minimum operation downtime. .. Note:: This document assumes you have already `launched an Aviatrix Controller <http://docs.aviatrix.com/StartUpGuides/aviatrix-cloud-controller-startup-guide.html>`_. .. The migrating process starts with launching an Aviatrix Transit GW in the Transit hub VPC, connecting it to VGW, then moving Spoke VPC one at a time to Aviatrix Transit GW. During the process of moving Spoke VPC, traffic should continue to flow to on-prem for both moved and not-yet-moved VPCs. Aviatrix supports multiple Transit GW groups from one Controller. The below steps describe migration from one CSR Transit group. The migration process assumes there is a Transit Network tag on Spoke VPC and VGW that connects to CSR. This tag is used to identify a Transit Network. 1. **Launch Aviatrix Transit GW** `Follow Step 1 and Step 2 <http://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-a-transit-gateway>`_ to launch an Aviatrix Transit GW and enable HA in the Transit hub VPC. You can consider using a new Transit hub VPC in case the existing Transit hub VPC does not have enough IP addresses to launch new instances. (The Aviatrix Transit GW pair) 2. **Connect Aviatrix Transit GW to VGW** `Follow Step 3. <http://docs.aviatrix.com/HowTos/transitvpc_workflow.html#connect-the-transit-gw-to-aws-vgw>`_ At this point, VGW starts to advertise to Aviatrix Transit GW. Make sure you specifiy a different "AS" number for the BGP session of Aviatrix Transit GW connection to VGW. Also note that if Transit GW and VGW are in the same account and same VPC, VGW must be detached from the VPC. 3. **Remove a Spoke VPC** Select one Spoke VPC that has VGW deployed. Remove the VPC Transit Network tag. This will effectively detach the Spoke VPC from the CSR Transit Network. Make sure the above Spoke VPC CIDR route entry has been removed from the Transit Network. 4. **Attach Spoke VPC to Aviatrix Transit GW** `Follow Step 4, Step 5 and Step 6 <http://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-a-spoke-gateway>`_ to launch an Aviatrix GW in this Spoke VPC (with HA as an option) and attach to the Aviatrix Transit GW. Test connectivity to make sure this Spoke VPC can communicate with on-prem. Note this step is reversable if Spoke VPC fail to connect to on-prem after a period of time (depending on how many routes are being propagated, this could take minutes.) To reverse the step, detach the Spoke VPC from the Aviatrix Transit GW; add the Transit Network tag back to the Spoke VPC will move the Spoke VPC back to CSR solution. Once a Spoke is moved to Aviatrix Transit GW group, the Spoke VPC CIDR will be advertised to from Aviatrix Transit GW to VGW and to on-prem. 5. **Repeat the abovev step 3 and 4** Repeat the above 2 steps for the remaining Spoke VPCs. 6. **Remove Transit hub VGW CSR tag** After all Spoke VPCs have been migrated to Aviatrix Transit GW, remove the VGW Transit Network tag. This effectively detach VGW from CSR. The effective operation downtime for each Spoke VPC is the time between Transit Network tag being removed for the Spoke VPC and the Spoke VPC being attached to Aviatrix Transit GW. It should be a few minutes. Note in Aviatrix solution, Spoke VPCs have no connectivities to each other by default. If a Spoke VPC needs connectivity to another Spoke VPC, for example, the shared service VPC, configure `AWS Peering <http://docs.aviatrix.com/HowTos/peering.html#aws-peering>`_ or `Aviatrix Encrypted Peering <http://docs.aviatrix.com/HowTos/peering.html#encrypted-peering>`_ from the Controller console. Another note is Aviatrix GW runs on instances EIP, make sure you have sufficient quota for EIP. You can contact AWS support to request for more EIPs. .. |image1| image:: FAQ_media/image1.png .. disqus:: <file_sep> =================================== Aviatrix in China Regions Overview =================================== This document provides an overview of the Aviatrix features that are supported and the requirements for implementing Aviatrix in the China regions. It also provides various options and design patterns for interconnecting Aviatrix in the China regions and Global regions. Features Supported in AWS China, Azure China, and Alibaba China Regions ======================================================================= +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | **Feature** | **AWS China** | **Azure China** | **Alibaba Cloud China** | | | | | **and Global** | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | Controller Marketplace Launch | Yes | Yes | No | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | CoPilot Marketplace Launch | Yes | No | No | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | Controller Security Group Management | Yes | No | No | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | Multi Accounts | Yes | Yes | Yes | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | Launch Controller with CloudFormation | Yes | N/A | N/A | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | VPC Tool | Yes | Yes | Yes | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | FlightPath | Yes | Yes | Yes | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | Transit Network Spoke and Transit Gateways | Yes | Yes | Yes | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | Aviatrix Transit Gateway Peering | Yes | Yes | Yes | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | Transit to External IPsec Devices | Yes | Yes | Yes | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | Site2Cloud VPN for All Gateways | Yes | Yes | Yes | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | BGP over LAN | No | No | No | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | BGP over GRE | No | No | No | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | Native Peering | Yes | Yes | No | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | Network Segmentation | Yes | Yes | Yes | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | Firewall Network | Yes | No | No | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | Insane Mode Encryption | Yes | Yes | No | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | Managed CloudN | Private | Private | No | | | Preview | Preview | | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | Aviatrix Edge | No | No | No | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | FQDN Egress Control | No | No | No | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | Stateful Firewall | No | No | No | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | Advanced NAT | No | No | No | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | ThreatIQ and ThreatGuard | No | No | No | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | Micro-Segmentation | No | No | No | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | Remote Access User VPN (OpenVPN) | No | No | No | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | PrivateS3 | No | N/A | N/A | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | Transit to AWS VGW | No | N/A | N/A | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | AWS Transit Gateway Orchestration | No | N/A | N/A | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | Controller Migrate | No | No | No | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | Terraform | Yes | Yes | Yes | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | Backup and Restore | Yes | Yes | Yes | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ | Logging Service Integration (Rsyslog, Netflow, and CloudWatch) | Yes | Yes | Yes | +------------------------------------------------------------------------+---------------+-----------------+---------------------------+ Requirements to Implement Aviatrix in China Regions ==================================================== The following are the requirements to implement Aviatrix in AWS China, Azure China, and Alibaba China regions. - The Aviatrix Controller must be deployed in the China region, for example, AWS China Ningxia region. Currently, an Aviatrix Controller in the Global region (non-China) does not support Aviatrix Gateways deployment and management in the China region. Similarly, an Aviatrix Controller in the China region does not support Aviatrix Gateways deployment and management in the Global region. See `Unsupported Topologies`_. - You must have an Internet Content Provider (ICP) license. An ICP license is required for opening a CSP account in the China region. For more information, see `Acquiring a China ICP License`_. Unsupported Topologies ====================== The following topologies are not supported. An Aviatrix Controller launched in the Global region does not support Aviatrix Gateways deployment and management in the China region. |aviatrix_china_unsupported_global_manage_china| An Aviatrix Controller launched in the China region does not support Aviatrix Gateways deployment and management in the Global region. |aviatrix_china_unsupported_china_manage_global| Acquiring a China ICP License ============================== Regulations in China require you to acquire an Internet Content Provider (ICP) license from the government and register the license with your CSP to provide Internet services in China. In China, an ICP license is required to establish SSL connections between different regions, ISPs, CSPs, or to cross national borders. Aviatrix supports transit gateways using AWS China, Azure China, and Alibaba multi-cloud networks in the China region. Obtaining and implementing an ICP is a process, and you should follow the directions of your compliance experts. Here are some general guidelines Aviatrix recommends to implement a multi-cloud network in the China region: - Create or use a Legal Entity in China to apply for the ICP license. - Apply for a Legal Domain Name in the China Registration. - Acquire the ICP Certificate from the China Ministry of Industry and Information Technology (MIIT). - Register the ICP Certificate with your CSP in the China region. - Use dedicated lines from certified telecom carries for connections between China and the rest of the world. .. Tip:: Slow connection speeds and high-latency associated with the China region can be overcome by using a dedicated line to create Aviatrix transit connections and deploying services close to the China region. - Deploy the Aviatrix Controller, CoPilot (for AWS China only). - Enter the certificate domain that was submitted during the ICP application in Aviatrix Controller (see `What is Certificate Domain? <https://docs.aviatrix.com/HowTos/onboarding_faq.html#what-is-certificate-domain?>`_. - Deploy Aviatrix Secure Multi-Cloud Network in China. Consequences of Non-Compliance with the Chinese Government Regulations ====================================================================== The following consequences can result for non-compliance of the Chinese Government Regulations. - The company is not permitted to open an account with a CSP in China region. - Aviatrix Controller is unable to deploy and manage Aviatrix Gateways. - The connection between Aviatrix Gateways is intermittent or becomes disconnected from time to time. Interconnecting Aviatrix in the China region and the Global region =================================================================== Site2Cloud can be established between Aviatrix Transit Gateways in the China region and the Global region. The following options are available for the underlying network of Site2Cloud: 1. Public Internet .. Note:: Public Internet connections maybe unstable due to additional network traffic processing by the Chinese government. |aviatrix_china_site2cloud_internet| 2. Private connectivity through certified telecom carriers such as China Telecom, China Unicom, and China Mobile |aviatrix_china_site2cloud_telecoms| 3. Alibaba Cloud Network using VPC Peering or Alibaba Cloud Enterprise Network (Alibaba CEN) https://www.alibabacloud.com/product/cen |aviatrix_china_site2cloud_alicloud| To create a global multi-cloud network with low-latency connectivity between the China region and the global region, we recommend that you use private connectivity provided by certified telecom carriers or through the Alibaba Cloud network. For a description of the design patterns for these underlying networks, see `Design Patterns for China Region`_. Launching Aviatrix Controller in AWS China ========================================== To launch Aviatrix Controller in AWS China, do the following: 1. Log in to the AWS China Portal. 2. Navigate to the AWS Marketplace for the Ningxia and Beijing Region. 3. Search for the keyword "Aviatrix." |aviatrix_aws_china_marketplace| .. Note:: The Aviatrix Controller is available on both the AWS China and Azure China Marketplaces. Aviatrix CoPilot is available on AWS China Marketplace only. .. Use the following URLs to find the Controller and CoPilot on the AWS China Marketplace: - `Aviatrix Secure Networking Platform - BYOL <https://awsmarketplace.amazonaws.cn/marketplace/pp/prodview-tr55yz2zpuzlo>`_ - `Aviatrix CoPilot - BYOL <https://awsmarketplace.amazonaws.cn/marketplace/pp/prodview-m73cvirso7uu6>`_ Use the following URL to launch the Aviatrix Controller from the AWS CloudFormation in AWS China: - `AWS China Cloudformation Aviatrix Controller and IAM Setup-BYOL <https://cn-northwest-1.console.amazonaws.cn/cloudformation/home?region=cn-northwest-1#/stacks/new?stackName=AviatrixController&templateURL=https://aviatrix-public-download.s3.cn-north-1.amazonaws.com.cn/aws-china/cloudformation-templates/aviatrix-controller-and-IAM-setup-CFT/aviatrix-controller-and-IAM-setup-cft-BYOL.template>`_ Launching Aviatrix Controller in Azure China ============================================ To launch Aviatrix Controller in Azure China, do the following: 1. Log in to the Azure China Portal. 2. Navigate to the Azure Marketplace for the China North region. 3. Search for the keyword "Aviatrix." |aviatrix_azure_china_marketplace| .. Note:: The Aviatrix Controller is available on both the AWS China and Azure China Marketplaces. Aviatrix CoPilot is available on AWS China Marketplace only. You can launch CoPilot only from AWS China. .. Use the following URL to find the Controller on the Azure China Marketplace: - `Aviatrix Secure Networking Platform - BYOL <https://market.azure.cn/>`_ Design Patterns for China region ================================ China region only |aviatrix_china_design_china_only| Cross-border connectivity through certified telecom carriers |aviatrix_china_design_cross_border_telecom| Cross-border connectivity through Alibaba Cloud Enterprise Network (Alibaba CEN) |aviatrix_china_design_cross_border_alicloud| .. |aviatrix_china_unsupported_global_manage_china| image:: aviatrix_china_overview_media/aviatrix_china_unsupported_global_manage_china.png :scale: 50% .. |aviatrix_china_unsupported_china_manage_global| image:: aviatrix_china_overview_media/aviatrix_china_unsupported_china_manage_global.png :scale: 50% .. |aviatrix_china_site2cloud_internet| image:: aviatrix_china_overview_media/aviatrix_china_site2cloud_internet.png :scale: 40% .. |aviatrix_china_site2cloud_telecoms| image:: aviatrix_china_overview_media/aviatrix_china_site2cloud_telecoms.png :scale: 40% .. |aviatrix_china_site2cloud_alicloud| image:: aviatrix_china_overview_media/aviatrix_china_site2cloud_alicloud.png :scale: 40% .. |aviatrix_aws_china_marketplace| image:: aviatrix_china_overview_media/aviatrix_aws_china_marketplace.png :scale: 50% .. |aviatrix_azure_china_marketplace| image:: aviatrix_china_overview_media/aviatrix_azure_china_marketplace.png :scale: 50% .. |aviatrix_china_design_china_only| image:: aviatrix_china_overview_media/aviatrix_china_design_china_only.png :scale: 50% .. |aviatrix_china_design_cross_border_telecom| image:: aviatrix_china_overview_media/aviatrix_china_design_cross_border_telecom.png :scale: 50% .. |aviatrix_china_design_cross_border_alicloud| image:: aviatrix_china_overview_media/aviatrix_china_design_cross_border_alicloud.png :scale: 50% .. disqus:: <file_sep> ============================================ Aviatrix Transit Architecture for Azure ============================================ Azure Native Transit --------------------------------------------------------------- The most common design topology within Azure is the Hub and Spoke model. The hub is a virtual network (VNet) in Azure that acts as a central point of connectivity to your on-premises network. The spokes are VNets that peer with the HUB and can be used to isolate workloads, departments, subscriptions, etc... Traffic flows between the on-premises datacenter and the hub through an ExpressRoute or VPN gateway connection. It is common in these environments for spoke to spoke communication to be desired both within and across regions. To facilitate spoke to spoke communication, Azure natively provides three methods for performing this functionality. Each of these options has advantages and disadvantages however, these options can be used simultaneously for customers to apply the right transit method for the desired outcome. |hub-spoke| Intra-Region Transitive Options: ################################ 1. **Leveraging ExpressRoute** - the most common transitive method is for customers to leverage their ExpressRoute circuits to provide spoke to spoke communication. This method requires a default (0.0.0.0/0) or summary route to be advertised from on-prem to allow spoke to spoke traffic to hairpin off the Microsoft Edge Routers. The advantage to this method is that this traffic will not incur VNET peering charges and this provides any to any spoke connectivity. The disadvantage to this approach is that bandwidth is limited by the ExpressRoute gateway SKU, traffic takes a longer path from spoke to spoke, a lack of granular control as this method provides any to any communication, and the fact that this is not a recommended approach as there is no dedicated bandwidth allocation on the Microsoft Edge Routers for this configuration. |S2SER| 2. **Leveraging a HUB Network Virtual Appliance (NVA)** - in this option, an NVA is deployed in the HUB VNET and User Defined Routes (UDRs) are created in each spoke to route traffic from spoke to spoke. The advantage to this approach is that traffic takes a more ideal path, does not require any route advertisements from on-prem, and potentially provides additional security functionality depending upon the NVA being leveraged. The disadvantage to this approach comes with the management of UDRs at scale, potential bandwidth limits of the NVA itself, and the configuration of NVA high availability (HA) to ensure redundancy in case of failure. |S2SNVA| 3. **VNET Peering** - the recommended approach for spoke to spoke communication is VNET peering as this leverages the MSFT backbone directly and always takes the preferred path. This option provides the lowest latency possible and has no bandwidth restrictions as opposed to the options previously discussed. The disadvantage of this model is this connectivity is a 1 to 1 mapping. Each spoke much be peered directly with another spoke in order to facilitate communication which at scale becomes a web of interconnected fully meshed VNETS. As such, customers often have challenges in managing the scale of VNET peers. |S2SPeer| Inter-Region Transitive Options: ################################ The options for spoke to spoke communication across regions follow the same patterns above with a few notable nuances. 1. **Leveraging ExpressRoute** - this method is similar to what was described in Intra-Region however, as ExpressRoute circuits are terminated across regions the routes are propagated automatically. To facilitate cross region spoke to spoke communication, no summary or default route is required. The same advantages and disadvantages apply. 2. **Leveraging a HUB Network Virtual Appliance (NVA)** - this method is also similar to what was previously described however, the number of UDRs increases as additional routes must be defined in the HUB VNETs to facilitate routing across regions to another HUB. Additionally, a VNET peer must be leveraged between the HUB to facilitate this HUB to HUB transit path. 3. **VNET Peering** - the only change in VNET peering across regions is in naming convention. Microsoft refers to this as Global VNET Peering but still has the same advantages and disadvantages previously discussed. .. Note:: Azure Virtual WAN is another native architectural approach which can also provide transitive functionality. Aviatrix Transit can integrate with Azure Virtual WAN and is not covered in detail here. Aviatrix Transit for Azure --------------------------------------------------------------- Aviatrix Transit for Azure is an architecture to interconnect multiple VNets and on-prem leveraging the hub and spoke deployment model while adding additional functionality and features. This deployment is shown in the diagram below. |nextgentransit_for_azure| In the above diagram, the Aviatrix Controller is a VM that manages all networking connections from VNETs to on-prem as well as between VNETs themselves. It deploys one Aviatrix gateway (two for redundancy) in each VNet. The Transit gateway is deployed in the transit VNet and connects to on-prem over Express Route or Internet. The Transit Gateway is then peered to each spoke VNET gateway to provide end to end communication. Communication can be granularly controlled to provide any to any communication between the spokes and to/from on-prem however, the transit gateway can also block certain traffic to keep spokes isolated. Additionally, all Spoke UDRs are orchestrated from the controller based on desired traffic flows. For cross region communication, multiple Transit Gateways can also be interconnected. Spoke VNets can communicate to remote Spoke VNets through the two connected Transit Gateways with the same granular controls mentioned previously. Additionally, route advertisements between the two transit gateways can be controlled to provide additional functionality like summarization, route exclusion, etc. This topology is depicted below. |multiregion_azure| Another important advantage of using Aviatrix Transit is that all communications are encrypted by default providing additional levels of security. Azure does not provide any native encryption across the Microsoft Backbone and depends upon third party NVAs to provide this functionality should customers require it. The Aviatrix controller also has the ability to orchestrate native VNET peering for Azure VNETs should customers not wish to deploy gateways within spoke VNETs. While customers will lose the encryption and visibility benefits across these links, all appropriate UDRs will be orchestrated to facilitate transitive communication as desired. It is also important to note that certain native limitations may apply as to the number of peerings allowed as well as restricitions to overlapping IP space when native peering is leveraged. |native_peering| Why do I need Aviatrix Transit for Azure? ------------------------------------------------------ Transit architecture is about building connectivity between cloud and on-prem in the most agile manner possible. In the Transit architecture, there is one connection (not including the backup) between on-prem and a Transit Hub VNet. Everything else (the Spoke VNet to on-prem traffic) is routed through the Transit Hub VNet. The alternative to Transit architecture is to leverage the native options already mentioned or is to build one connection (often referred to as "flat" architecture), either IPSEC over Internet or Express Route, each time you spin up a new VNet in Azure. This requires changes at the on-prem edge, which requires a change control process that takes from days to weeks. Additionally, this method often facilitates the default any to any connectivity which may require additional configuration to prevent. The Benefits of Aviatrix Transit for Azure ------------------------------------------------------------------- - **Simplicity** The Aviatrix Controller provides an abstraction layer and workflow to build the Transit network. You do not need to program any Azure route tables, manage the route entries or understand the significant details about Azure networking. - **Multi Subscriptions Support** The Controller provides a single pane of glass to manage the entire cloud network of multiple Azure subscriptions. - **Logging Service Integration** Out-of-the-box integration with Splunk, Sumo Logic, DataDog, ELK, remote syslog and Netflow. - **Visibility** View connectivity status, network latency and traffic statistics from a central dashboard. - **Granular Routing Control** Route redistribution can be controlled to selectively allow specific route propagation and/or summarization. - **Advanced Networking Features** Support for Network Address Translation, NGFW Insertion, FQDN filtering, etc. - **No Route Limits** The Aviatrix solution auto summarizes the on-prem and Spoke VNet routes so that Spoke VNet route entries do not exceed the route limits. - **End-to-End Encryption** All traffic in flight, between Spoke VNets and between Spoke to on-prem, is encrypted. How does it work? ------------------------------------------------------------------------------------------------- Aviatrix Transit Network is a Duo Mode architecture. While the Transit Gateway runs BGP protocol, advertising Spoke VNets CIDRs to an on-prem network and learning the on-prem network CIDRs, Spoke VNets do not run dynamic routing protocols. Learned routes by the Transit Gateway are reported to the Controller which in turn propagate to the Spoke VNets. By minimizing dynamic protocol running in the network, operations and troubleshooting become simple. CloudOps engineers without extensive networking background are able to build and manage the network. How do I deploy it? -------------------------------------------------------------------- The Aviatrix Controller is available in the Azure Marketplace. 1. Follow the `Azure Startup Guide <https://docs.aviatrix.com/StartUpGuides/azure-aviatrix-cloud-controller-startup-guide.html>`_ to launch the Controller. #. Follow the onboarding steps to setup Azure API credentials so that the Controller can launch gateways on behalf of the Azure account. #. Select the use case Next-Gen Transit Network and follow the `workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ to start building the transit network. .. |nextgentransit_for_azure| image:: nextgentransit_for_azure_media/nextgentransit_for_azure.png :scale: 30% .. |multiregion_azure| image:: nextgentransit_for_azure_media/multiregion_azure.png :scale: 30% .. |hub-spoke| image:: nextgentransit_for_azure_media/hub-spoke.png :scale: 30% .. |S2SER| image:: nextgentransit_for_azure_media/S2SER.png :scale: 30% .. |S2SNVA| image:: nextgentransit_for_azure_media/S2SNVA.png :scale: 30% .. |S2SPeer| image:: nextgentransit_for_azure_media/S2SPeer.png :scale: 30% .. |native_peering| image:: nextgentransit_for_azure_media/native-peering-updated-resized-2.png :scale: 30% .. disqus:: <file_sep> ================================================================================================== Migrating from Classic Aviatrix Encrypted Transit Network to Aviatrix ActiveMesh Transit Network ================================================================================================== This document describes the steps to migrate an existing non-ActiveMesh Aviatrix Encrypted Transit Network to the new ActiveMesh Transit Network. If your Transit Network is built prior to Aviatrix software release 5.1, it’s very likely that the Transit Network is non-ActiveMesh deployment where the IPSec tunnels between Spoke GWs and Transit GWs are in Active/Standby mode (i.e. only one IPSec tunnel is carrying the data traffic). You can confirm it by checking in the Gateway page if your Transit GW is ActiveMesh Enabled=yes. We recommend that you create a new transit and transit-ha gateway with active mesh enabled, detach the spokes from the current transit and transit-ha gateways, enable active-mesh on the spokes and then connect them to the new active-mesh enabled transit and transit-ha gateways. The steps are documented in detail below. 1. Go to Useful Tools -> Create a VPC page. Select or enter all the necessary information and check the Aviatrix Transit VPC box. This is the recommended approach from Aviatrix but you can always create the VPC from AWS console. 2. Go to Transit Network -> Setup - Step 1 Launch a Transit VPC GW to create a new Active Mesh Transit Gateway. Make sure the Enable ActiveMesh Mode is checked (default) prior to clicking the Create button. |image1| 3. Go to Step 2 to Enable HA on the newly created Transit GW. Typically you will select another AZ (depends on your HA Gateway Subnet created in the VPC). on this created gateway by going to transit network -> setup -> step2 |image2| 4. Proceed to Step 3 to Connect this newly created Transit gateway GW to same VGW/external device that is already connected to the non ActiveMesh Transit Network. This allows the new ActiveMesh Transit GW to learn the same and make sure that its learning routes from the on-premises/datacenter. You can validate it by going to Transit Network -> Aadvanced -> Diagnostics page, select the new ActiveMesh Transit GW, Commands = “show ip bgp” and click OK to display the learned routes from the VGW/Externaldevice. |image3| 5. Go to Transit Network > Setup > Step 7a and detach the Spoke GW from the old non-ActiveMesh Transit gateway. 6. Go to Gateway page and select the Spoke GW that was detached in the previous step. Click Edit and scroll down to ActiveMesh Mode section to enable the ActiveMesh on this gateway |image4| 7. Go to Step 6a to attach the ActiveMesh enabled Spoke GW to the ActiveMesh Transit GW. 8. Go to Transit Network -> Advanced -> Diagnostics page, select the new ActiveMesh Transit GW, Commands = “show ip bgp” and click OK to confirm that the Spoke GW VPC CIDR is advertised to the VGW 9. Repeat steps 5 through 8 for all spokes 10. Prior to Deleteing the old gateways please go to Multi Cloud Network >> Advanced and select the old gateway from the drop down. Make sure that the option Advertise Transit VPC CIDR is disabled. Once this is verified you can go to "Controller/Gateway" and select your old Transit and Transit-HA gateways and delete them. 11. Please check your network routes and connectivity and open a ticket on `Aviatrix Support Portal <https://support.aviatrix.com>`_ if you run into any issues .. |image1| image:: ./activemesh_migration_media/image1.png :width: 100% .. |image2| image:: ./activemesh_migration_media/image2.png :width: 100% .. |image3| image:: ./activemesh_migration_media/image3.png :width: 100% .. |image4| image:: ./activemesh_migration_media/image4.png :width: 100% <file_sep> :redirect: https://docs.aviatrix.com/HowTos/Controller_and_Software_Release_Notes.html ========= Redirect ========= .. important:: This content has moved. Please see `Aviatrix Controller and Gateway Release Notes <https://docs.aviatrix.com/HowTos/Controller_and_Software_Release_Notes.html>`_ for the latest Aviatrix release notes. <file_sep> ===================================================== Connecting Meraki Network to Aviatrix Transit Network ===================================================== This document assumes that you have deployed a Meraki vMX100 in AWS that has full meshed to all your branch offices using Meraki MX products. In this technical note, we will outline the steps to have end to end connectivity from your Meraki network to your AWS Global Transit Network using Aviatrix solution. At the end of configuration, your on-prem client will be able to access an EC2 instance in a Spoke VPC. |meraki_avxtransit01| In this configuration guide, we will summarize the Meraki on-prem subnets (10.28.144.0/24 and 10.28.145.0/24) into a single 10.28.0.0/16. We will also summarize Aviatrix Spoke subnets (10.32.0.0/16, 10.50.0.0/16, 10.63.0.0/16) into 10.32.0.0/11. With good planning of on-prem subnets and VPC subnets, we can use summarized subnets in the Site2Cloud connection and avoid configuring AWS route tables and security groups when we add a new Meraki on-prem subnet or a new Aviatrix Spoke. The objectives here are: - Build an Aviatrix Transit Network with multiple spokes. - Launch an Aviatrix gateway in the same VPC as vMX100. - Create a Site2Cloud connection from the Aviatrix gateway to the same VGW used in Aviatrix Transit Network. - Adjust security groups on both vMX100 and the Aviatrix gateway and update AWS route tables accordingly. .. Note:: This document assumes you have already `launched an Aviatrix Controller <http://docs.aviatrix.com/StartUpGuides/aviatrix-cloud-controller-startup-guide.html>`_. An Aviatrix GW uses an EIP, so make sure you have sufficient quota space for an EIP. You can contact AWS support to request more EIPs. Aviatrix supports multiple Transit GW groups from one Controller. In this example, we will only use one Transit GW group with HA enabled. .. Build an Aviatrix Transit Network with multiple spokes ------------------------------------------------------ 1. **Launch Aviatrix Transit GW** `Follow Step 1 and Step 2 <http://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-a-transit-gateway>`_ to launch an Aviatrix Transit GW and enable HA in the Transit hub VPC. You can consider using a new Transit hub VPC in case the existing Transit hub VPC does not have enough IP addresses to launch new instances (The Aviatrix Transit GW pair). 2. **Connect Aviatrix Transit GW to VGW** `Follow Step 3. <http://docs.aviatrix.com/HowTos/transitvpc_workflow.html#connect-the-transit-gw-to-aws-vgw>`_ At this point, VGW starts to advertise to Aviatrix Transit GW. Make sure you specify a different "AS" number for the BGP session of Aviatrix Transit GW connection to VGW. 3. **Attach Spoke VPC to Aviatrix Transit GW** `Follow Step 4, Step 5 and Step 6 <http://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-a-spoke-gateway>`_ to launch an Aviatrix GW in this Spoke VPC (with HA as an option) and attach to the Aviatrix Transit GW. 4. **Repeat the above step 3 and 4** Repeat the above 2 steps for the remaining Spoke VPCs. .. Note:: In the Aviatrix solution, Spoke VPCs have no connectivity to each other by default. If a Spoke VPC needs connectivity to another Spoke VPC, for example, the shared service VPC, configure `AWS Peering <http://docs.aviatrix.com/HowTos/peering.html#aws-peering>`_ or `Aviatrix Encrypted Peering <http://docs.aviatrix.com/HowTos/peering.html#encrypted-peering>`_ from the Controller console. .. In this example, the Meraki vMX100 is already deployed in the us-west-2 (Oregon) region in a VPC with a CIDR of 10.10.0.0/16. The following is the configuration for vMX100 in AWS VPC. |meraki_avxtransit02| Here is the configuration for the MX64 at on-prem. |meraki_avxtransit03| Launch an Aviatrix gateway in the same VPC as vMX100 ---------------------------------------------------- 1. Login to the Aviatrix Controller UI and click Gateway at the navigation panel. 2. Click New to launch a gateway with the following settings: - Gateway Name = vMX-AvxGW - Access Account Name = Select the same AWS account where the vMX100 is deployed - Region = us-west-2 (Oregon) - VPC ID = Select the same VPC where vMX100 is deployed - Public Subnet = Select the same subnet where vMX100 is deployed 3. Click OK to create the gateway. Create a Site2Cloud connection between an Aviatrix GW and a VGW ---------------------------------------------------------- 1. Go to the AWS console in the us-west-2 (Oregon) region. Click on Services and go to VPC Dashboard. 2. Click on VPN Connections at the left panel. 3. Click "Create VPN Connection" to create an IPsec tunnel to Aviatrix GW. |meraki_avxtransit04| 4. Select the VPN connection that you just created and click "Download Configuration" to download the "Generic" configuration. 5. At the Aviatrix Controller UI, click Site2Cloud at the navigation panel. 6. Click "Add New" to configure the Site2Cloud connection to the same VGW that is already connected to Aviatrix Transit Networks. |meraki_avxtransit05| 7. Click on the Site2Cloud > Diagnostics page and verify that the IPsec tunnel is established between Aviatrix GW and the VGW. |meraki_avxtransit06| Adjust security groups and update AWS route tables -------------------------------------------------- 1. Go to AWS console and select us-west-2 (Oregon) region. 2. Go to EC2 Dashboard and click on the vMX100 instance. 3. Click on the Security Group for the vMX100 and add Allow Inbound traffic from 10.10.0.0/16, 10.28.0.0/16 and 10.32.0.0/11. Let the default Outbound Allow All. |meraki_avxtransit07| 4. Select EC2 Aviatrix GW instance and click on its Security Group. 5. Add Allow Inbound traffic from 10.10.0.0/16, 10.28.0.0/16 and 10.32.0.0/11. Let the default Outbound Allow All. |meraki_avxtransit08| 6. Go to AWS VPC Dashboard and edit the route table of the VPC where vMX100 and Aviatrix GW are deployed. Configure both the public and private route tables such that 10.28.0.0/16 is pointed to vMX100 eni. The 10.32.0.0/11 and 10.254.0.0/26 are automatically added when we create the Site2Cloud connection to the VGW in the previous section. |meraki_avxtransit09| Validate connectivity --------------------- 1. At the Aviatrix Controller UI, click Site2Cloud at navigation panel. 2. Select Site2Cloud connection for the Aviatrix Transit Network. You should observe that both IPsec tunnels to VGW are UP. There will be 2 learned routes from VGW (10.10.0.0/16, 10.28.0.0/16) and 3 advertised networks from spokes (10.32.0.0/16, 10.50.0.0/16, 10.63.0.0/16). |meraki_avxtransit10| |meraki_avxtransit11| 3. In this example here, I have 3 EC2 instances in each Spoke VPC (10.32.102.81 in private subnet, 10.50.0.5 in public subnet, 10.63.100.97 in private subnet). My on-prem client is 10.28.144.19. The following screenshot shows the end to end connectivity from on-prem to each spoke. |meraki_avxtransit12| 4. Here is a logical view of the networks from Aviatrix Controller UI. |meraki_avxtransit13| 5. If you have a high number of spokes in your deployment, we recommend that you enable `Manual Summarization <https://docs.aviatrix.com/HowTos/site2cloud.html#manual-bgp-advertised-network-list>`_ to reduce the number of advertised networks. This is needed due to an AWS BGP route limitation. Please see `How do I troubleshoot BGP connection issues over VPN? <https://aws.amazon.com/premiumsupport/knowledge-center/troubleshoot-bgp-vpn/>`_ for more details. 6. In order to summarize Spoke CDIRs, please go to Transit Network -> Advanced Config -> Edit Transit, select the Transit GW. Enter the summarized route in the "Manual BGP Advertised Network Lis" and click "Change BGP Manual Spoke Advertisement". You can then go to Site2Cloud page, and select the connection to check out summarized advertised networks. |meraki_avxtransit14| In summary, we can connect an existing Meraki network to Aviatrix Transit Network to leverage the agility, automation and other benefits of using Aviatrix solution. .. |meraki_avxtransit01| image:: meraki_to_transit_media/meraki_avxtransit01.png .. |meraki_avxtransit02| image:: meraki_to_transit_media/meraki_avxtransit02.png .. |meraki_avxtransit03| image:: meraki_to_transit_media/meraki_avxtransit03.png .. |meraki_avxtransit04| image:: meraki_to_transit_media/meraki_avxtransit04.png .. |meraki_avxtransit05| image:: meraki_to_transit_media/meraki_avxtransit05.png .. |meraki_avxtransit06| image:: meraki_to_transit_media/meraki_avxtransit06.png .. |meraki_avxtransit07| image:: meraki_to_transit_media/meraki_avxtransit07.png .. |meraki_avxtransit08| image:: meraki_to_transit_media/meraki_avxtransit08.png .. |meraki_avxtransit09| image:: meraki_to_transit_media/meraki_avxtransit09.png .. |meraki_avxtransit10| image:: meraki_to_transit_media/meraki_avxtransit10.png .. |meraki_avxtransit11| image:: meraki_to_transit_media/meraki_avxtransit11.png .. |meraki_avxtransit12| image:: meraki_to_transit_media/meraki_avxtransit12.png .. |meraki_avxtransit13| image:: meraki_to_transit_media/meraki_avxtransit13.png .. |meraki_avxtransit14| image:: meraki_to_transit_media/meraki_avxtransit14.png .. disqus:: <file_sep> ===================================================================================== Aviatrix Controller and Gateway Deployment Guide in Discrete Regions ===================================================================================== The Aviatrix Secure Networking Platform consists of two components: Aviatrix Controller and Gateway. The Aviatrix Controller manages the Aviatrix Gateway and orchestrates all connectivities. Launch Aviatrix Controller =========================== These instructions apply when deploying in discrete regions in AWS. This guide takes you through the 3 steps to launch the Controller instance. Step 1. Subscribe to Aviatrix Secure Networking Platform - BYOL on AWS ICMP ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ If you have already subscribed the Aviatrix Secure Networking Platform - BYOL on AWS ICMP, skip this step and proceed to Step 2. Step 2. Launch the Controller ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Two options to search and deploy Aviatrix Controller: - (Option 1) Search the product “Aviatrix Secure Networking Platform - BYOL” on ICMP website - (Option 2) Log in to AWS ICMP console and navigate to EC2 dashboard page - (Option 2) Click the button “Launch Instances” and select the product “Aviatrix Secure Networking Platform - BYOL” on AWS ICMP - Follow EC2 configuration workflow to deploy Aviatrix Controller - Select the instance size “t3.large” of 8GB of memory, which is the recommended instance type - Select the VPC where the controller will be launched - Make sure the subnet you select is a public subnet with IGW as its default gateway, otherwise the controller will not be accessible as it won’t have a public IP address. - Edit security groups to allow inbound TCP port 443 open to anywhere - Assign an Elastic Public IP address to Aviatrix Controller - After launching the instance, note down the instance’s Private IP and Public IP. You can find that info by going to AWS EC2 console, clicking the Controller instance, and locating its private IP and public IP address Step 3. Onboarding ^^^^^^^^^^^^^^^^^^^ Now that Aviatrix Controller instance has been launched, let’s login and go through the onboarding process. - Access the Controller console by going to https://[*Controller_Public_IP*] on a browser - Log in with the username "admin" and the default password of your *Controller_Private_IP* - Enter your email address - Change password - Click the button Run to upgrade software version with latest .. tip:: The Controller upgrade takes about 3-5 minutes. Once complete, the login prompt will appear. Use the username `admin` and your new password to login. Launch Aviatrix Gateway =========================== To deploy Aviatrix Secure Companion Gateway from AWS ICMP successfully, make sure you follow the instructions as follows. When complete, you'll be ready to deploy use cases. Step 1. Follow the step Launch Aviatrix Controller above ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Step 2. Subscribe to Aviatrix Secure Companion Gateway on AWS ICMP ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Step 3. Start a Use Case ^^^^^^^^^^^^^^^^^^^^^^^^^ Congratulations! You are now ready to deploy use cases. - `Build Aviatrix Transit Network Solution <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`__ .. disqus:: <file_sep> ========================================================= Aviatrix in AWS Outposts ========================================================= AWS Outposts is a fully managed service that offers the same AWS infrastructure, AWS services, APIs, and tools to virtually any datacenter, co-location space, or on-premises facility for a truly consistent hybrid experience. AWS Outposts is ideal for workloads that require low latency access to on-premises systems, local data processing, data residency, and migration of applications with local system interdependencies. AWS compute, storage, database, and other services run locally on Outposts, and you can access the full range of AWS services available in the Region to build, manage, and scale your on-premises applications using familiar AWS services and tools. The Aviatrix platform runs on Outposts. This brings the repeatable multi-cloud network architecture to Outposts with the common control plane that supports native cloud APIs and advanced networking and security capabilities needed to form a common data plane with visibility and control required for an enterprise-class multi-cloud network. 1. Architecture ================ The Aviatrix controller remains in the public region of any cloud. It deploys, manages and monitors Aviatrix gateways that physically reside in Outposts. An ActiveMesh Aviatrix transit network is built using those gateways in Outposts. This allows Aviatrix to provide networking and security in the following use cases: - Intra-Outposts. - Inter-Outposts. - Outposts to non-Outposts on-prem data center. - Outposts to public AWS regions. - Outposts to Azure. - Outposts to GCP. |architecture| 2. Intra-Outposts =================== Using Aviatrix inside Outposts brings the following benefits: - Complete automation of Outposts networking. - Simplified network management at the application layer. - Higher scalability. - Easy-to-use segmentation domains. - Consistent operations, control plane, and data plane with the public cloud. An Aviatrix controller is already deployed in a public AWS region. Using the Aviatrix controller, an Aviatrix ActiveMesh network can be deployed in Outposts: - Redundant pairs of Aviatrix spoke gateways are launched in the spoke VPCs. - A redundant pair of Aviatrix transit gateways is launched in the transit VPC. - Redundant ActiveMesh peerings are established between the spoke gateways and the transit gateways. |intra-outposts| An Aviatrix controller is already deployed in a public AWS region. Using the Aviatrix controller, an Aviatrix ActiveMesh network can be deployed in Outposts: - Redundant pairs of Aviatrix spoke gateways are launched in the spoke VPCs. - A redundant pair of Aviatrix transit gateways are launched in the transit VPC. - Redundant ActiveMesh peerings are established between the spoke gateways and the transit gateways. The Aviatrix control plane is learning and propagating the routes to the spoke gateways accordingly per Aviatrix segmentation domains. This enables encrypted, high-speed connectivity between workloads in Outposts-Spoke1-VPC and workloads in Outposts-Spoke2-VPC. Currently the ActiveMesh tunnels between the Aviatrix spoke gateways and transit gateways are established over public IPs. Support for private IP ActiveMesh tunnels in Outposts is under development. 3. Inter-Outposts =================== The same Aviatrix ActiveMesh transit network can be deployed in multiple Outposts racks. Then, an encrypted transit peering can be established between Aviatrix transit gateways across different Outpost racks. The Aviatrix control plane propagates the VPC CIDRs across the Outposts racks, enabling inter-Outposts connectivity. Data plane traffic goes over the Outposts Local Gateways (LGWs). |inter-outposts| 4. Outposts to non-Outposts on-prem data center ================================================== Aviatrix provides a NAT gateway functionality for traffic going from Outposts to on-prem, which brings the following benefits: - No need to allocate customer-owned IPs to instances. - Scalability advantage. - Operational advantage. The Aviatrix control plane automates the propagation of on-prem subnets to Outposts spoke VPCs. This can optionally be controlled by Aviatrix segmentation domains. Redundant Site2Cloud connections are established between the Aviatrix transit gateways and the on-prem router. BGP runs on top to exchange the routes in both directions. |outposts_to_non-outposts_dc| 5. Outposts to Public AWS regions ======================================= Aviatrix enables Outposts connectivity to public AWS regions. It offers the following benefits: - Repeatable architecture. - Outposts connectivity to public AWS region with extreme simplicity: 1-click peering. - Encrypted peering over Direct Connect or over the public Internet. - Same user experience and feature-set. - Consistent, end-to-end automated control plane. Using the Aviatrix controller, the same Aviatrix network architecture can be deployed in any public AWS region. An Aviatrix encrypted transit peering can be established between Aviatrix transit gateways across Outposts and the public region. The Aviatrix control plane propagates the VPC CIDRs across the Outposts racks and the region, enabling end-to-end connectivity. Data plane traffic can go over Direct Connect or over the public Internet. |outposts_to_public_aws| 6. Outposts to Azure ======================== Aviatrix enables Outposts connectivity to Azure with the following benefits: - Repeatable architecture - Outpost connectivity to Azure with extreme simplicity: 1-click peering. - Encrypted peering over private or public connections. - Same user experience and feature-set. - Consistent, end-to-end automated control plane. Using the Aviatrix controller, the same Aviatrix network architecture can be deployed in any public Azure region. An Aviatrix encrypted transit peering can be established between Aviatrix transit gateways across Outposts and the public Azure region. The Aviatrix control plane propagates the VPC and VNet CIDRs across the Outposts racks and Azure, enabling Outposts multi-cloud connectivity. Data plane traffic can go the public Internet, or over private peering on AWS Direct Connect and Azure Express Route connected in a colocation facility. |outposts_to_azure| 7. Outposts to GCP ==================== Aviatrix enables Outposts connectivity to GCP with the following benefits: - Repeatable architecture - Outpost connectivity to GCP with extreme simplicity: 1-click peering. - Encrypted peering over private or public connections. - Same user experience and feature-set. - Consistent, end-to-end automated control plane. Using the Aviatrix controller, the same Aviatrix network architecture can be deployed in any public GCP region. An Aviatrix encrypted transit peering can be established between Aviatrix transit gateways across Outposts and the public GCP region. The Aviatrix control plane propagates the VPC and VNet CIDRs across the Outposts racks and GCP, enabling Outposts multi-cloud connectivity. Data plane traffic can go the public Internet, or over private peering on AWS Direct Connect and GCP Cloud Interconnect connected in a colocation facility |outposts_to_gcp| 8. Visibility and Troubleshooting =================================== Aviatrix provides deep visibility and troubleshooting into the Outposts network. Aviatrix CoPilot is supported for Aviatrix networking in Outposts and offers the following functionalities for Outposts: - Network Health Monitor – Real-time cloud network resource inventory and status. - Dynamic Topology Map – Accurate, multi-cloud network topology, layout control and search. - FlowIQ – Detailed application traffic flow analysis, global heat map and trends. - CloudRoutes – Detailed searchable routing tables. - Notifications – Alert on resources status/utilization. .. |architecture| image:: aws_outposts_media/architecture.png :scale: 30% .. |intra-outposts| image:: aws_outposts_media/intra-outposts.png :scale: 70% .. |inter-outposts| image:: aws_outposts_media/inter-outposts.png :scale: 70% .. |outposts_to_non-outposts_dc| image:: aws_outposts_media/outposts_to_non-outposts_dc.png :scale: 70% .. |outposts_to_public_aws| image:: aws_outposts_media/outposts_to_public_aws.png :scale: 70% .. |outposts_to_azure| image:: aws_outposts_media/outposts_to_azure.png :scale: 70% .. |outposts_to_gcp| image:: aws_outposts_media/outposts_to_gcp.png :scale: 70% .. disqus:: <file_sep>(function () { var s = document.createElement('script'); s.setAttribute('src', 'https://consent.cookiebot.com/uc.js'); s.setAttribute('data-cbid', '3388fa8f-8e22-4f82-8467-26c12b59b9ac'); s.setAttribute('data-blockingmode', 'auto'); s.setAttribute('type', 'text/javascript'); document.head.appendChild(s); })(); <file_sep> ============================ Aviatrix Release 3.1 Preview ============================ The instructions below outline steps to deploy the Aviatrix Transit Network solution with release 3.1-preview. 1. **Launch the Controller** Follow `the startup guide <http://docs.aviatrix.com/StartUpGuides/aviatrix-cloud-controller-startup-guide.html>`_ to launch the controller and go through the onboarding process. #. **Custom Upgrade** Go to Settings -> Maintenance -> Upgrade to Custom Release. Enter 3.1-preview for the Release Version field. #. **Start Transit Network Workflow** Click Transit Network on the main navigation bar to get started! .. |image1| image:: FAQ_media/image1.png .. disqus:: <file_sep> =========================================== User VPN Performance Guide for Deployment =========================================== Aviatrix Gateway OpenVPN® throughput -------------------------------------------------------- Aviatrix VPN Gateways are deployed behind cloud provider's native load balancer, the deployment scales to unlimited number of VPN Gateways capable of supporting unlimited number of simultaneous VPN client connections. OpenVPN® is a single process application running on a gateway. The best measured throughput is 1.1Gbps. t3.medium, c5.large, and c5.xlarge have similar performance. .. note:: AWS classic Load Balancers are not supported with UserVPN gateways. Instead, `migrate <https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/migrate-classic-load-balancer.html>`_ to Network Load Balancers in your AWS account. VPN Client throughput benchmark ---------------------------------------------------------------- Aviatrix VPN solution supports both UDP and TCP mode VPN deployments. They have similar performance characteristics. The chart below benchmarks a VPN client's single session download and upload speed on one VPN gateway in TCP mode. The benchmark provides a reference information on selecting VPN gateway instance size. Note actual VPN client performance also depends on client's Internet ISP speed, packet loss ratio and other factors. The chart below is measured on a Windows client. |windows_client| The chart below is measured on a Linux client. |linux_client| Simultaneous Clients on a Given VPN Gateway ------------------------------------------------------------------------------ There are several factors to consider when determining the number of clients to support on a given VPN Gateway. 1. `VPN virtual address space <https://docs.aviatrix.com/HowTos/gateway.html#vpn-cidr-block>`_. The default is 192.168.43.0/24 which can support 64 simultaneous VPN connection. For large deployment, you should configure this to a /20 network so that address spacing is not an issue. #. `Maximum VPN Connections <https://docs.aviatrix.com/HowTos/gateway.html#max-connections>`_. The default is 100. When the connection number exceeds the configuration, the VPN gateway rejects new connections. The VPN client should auto reconnect and the cloud provider's network load balancer forwards the connection to a different VPN Gateway. #. VPN Client performance. If each VPN client sustained average performance is designed to be capped at 1Mbps, then a VPN Gateway can support 1000 VPN clients (i.e. connections). Accordingly, if each VPN client sustained average throughput is designed to be capped at 10Mbps, then a VPN gateway can support 100 clients. In most cases, using VPN gateway of t3.medium instance size is a good option. Launching a few of them behind an ELB provides redundancy and scaling. OpenVPN® is a registered trademark of OpenVPN Inc. .. |image1| image:: FAQ_media/image1.png .. |imageIdleTimeout| image:: FAQ_media/idle_timeout.png .. |imageClientLog| image:: FAQ_media/aviatrix_client_get_log.png .. |imageRenegotiationInterval| image:: FAQ_media/renegotiation_interval.png .. |full_tunnel| image:: FAQ_media/full_tunnel.png :scale: 30% .. |profile_config| image:: FAQ_media/profile_config.png :scale: 30% .. |assign_user_to_profile| image:: FAQ_media/assign_user_to_profile.png :scale: 30% .. |windows_client| image:: openvpn_faq_media/windows_client.png :scale: 30% .. |linux_client| image:: openvpn_faq_media/linux_client.png :scale: 30% .. disqus:: <file_sep> ========================================================= Transit FireNet FAQ ========================================================= What is the Aviatrix Transit FireNet for AWS & Azure? --------------------------------------------------------------------------- Aviatrix Transit FireNet allows you to deploy firewalls functions for the Aviatrix Encrypted Transit architecture. With Transit FireNet feature, the FireNet function is integrated into the Aviatrix Transit Gateway. If you are looking for firewall functions deployment in AWS Transit Gateway environment, your starting point is `here. <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html>`_ The use case is to deploy firewalls in the `encrypted transit architecture <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ for both AWS and Azure, as shown below. |transit_firenet| When deployed in Azure, Transit FireNet also works when using Native Azure VNet Spokes, as shown below. |transit_firenet_vnet| When deployed in Azure, only two firewall instances are supported. Can multiple firewalls be supported in Transit FireNet? -------------------------------------------------------------------------------------- Yes. Multiple firewall instances can be attached to each Transit Gateway. The Transit Gateway load balances and forwards packets to the firewalls. How does Transit FireNet work? ------------------------------------------------ Transit FireNet works the same way as the Firewall Network where traffic in and out of the specified Spoke is forwarded to the firewall instances for inspection or policy application. What is the minimum gateway instance size for Transit FireNet deployment? ------------------------------------------------------------------------------------------------ The minimum gateway instance size is C5.xlarge. This is because the FireNet gateway requires 4 network interfaces: - eth0 is a management interface - eth1 is not used - eth2 is the interface to the firewall instances - eth3 is the interface to the HA FireNet Gateway What is the Transit FireNet performance? -------------------------------------------------------- With a pair of c5n.18xlarge Aviatrix Transit Gateway, Transit FireNet achieves 70Gbps throughput with iperf3 benchmark, as shown in the diagram below. Note if a single c5n.18xlarge Aviatrix Transit Gateway is deployed, the throughput is about 40Gbps. This is because Aviatrix Encrypted Transit solution runs with ActiveMesh where both Transit Gateways do the packet forwarding. |transit_firenet_perf| Which option should I choose for the Create a VPC tool? -------------------------------------------------------------------- When using the Useful Tool to create the transit VPC/VNet for Transit FireNet deployment, select the Aviatrix FireNet VPC option to create 4 public subnets. How do I configure FireNet? ---------------------------------------- Follow the `FireNet workflow <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html>`_ to deploy firewall in the cloud. For a complete end-to-end example, refer to `The Example Step by Step Guide for Transit FireNet in AWS <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html>`_. How do I enable egress inspection on Transit FireNet? ----------------------------------------------------------------------- By default, FireNet inspects traffic between North South (on-prem and VPC/VNet) and East West (VPC/VNet to VPC/VNet). To enable Egress traffic (Internet bound) inspection: Go to Firewall Network > Advanced. Click the skewer. Scroll down to Egress through Firewall and click **Enable**. .. Important:: When Egress through Firewall is enabled, it applies to all Spoke VPC/VNets. You do not need to configure individual VPC/VNet inspection policy. Is Ingress Inspection supported on Transit FireNet? ----------------------------------------------------------------- Yes. You need to enable source NAT on the LAN Interface of the VM-Series. How to exclude specific CIDRs from being inspected by the firewall? ------------------------------------------------------------------------------------- By default, FireNet inspects all East-West (VPC/VNet to VPC/VNet) traffic but you may have an instance in the VPC/VNet which you do not want to be inspected. For example, the Aviatrix Controller deployed in the Shared Service VPC/VNet to be excluded from inspection while Shared Service VPC/VNet traffic is inspected. This improves the Controller reachability by not subjecting the Controller access to unintentional firewall policy errors. Go to **Firewall Network > Advanced** and put the CIDRs in the field **"Network List Excluded From East-West Inspection"** to exclude from being inspected by the firewall. .. Note:: 1. Maximum 20 CIDRs coma-separated are supported. 2. CIDRs are excluded from East-West inspections only. 3. In Transit FireNet, if Egress inspection is enabled, all the Egress traffic will get inspected by the firewall even for the CIDRs excluded for East-West inspection. Can I deploy an Aviatrix Egress Control FQDN Gateway on Transit FireNet? ------------------------------------------------------------------------------------------------ Yes. Deploy Aviatrix FQDN Gateway as shown in the diagram below. |transit_firenet_aviatrix_egress| The instructions are described as the following. 1. `Enable Aviatrix Transit Gateway for Transit FireNet <https://docs.aviatrix.com/HowTos/transit_firenet_workflow.html#enable-transit-firenet-function>`_. 2. `Launch and associate Aviatrix FQDN gateway <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#c-launch-associate-aviatrix-fqdn-gateway>`_. What is the performance of Aviatrix Egress FQDN gateway on Transit FireNet? ------------------------------------------------------------------------------------------------ Preliminary test results are as follows. ============================== ========================= # of FQDN gateways Throughput (Gbps) ============================== ========================= 4 27 6 30 ============================== ========================= Is there an example guide to setup Palo Alto VM-Series policies? ------------------------------------------------------------------ Yes. Follow `Example Config for Palo Alto VM-Series <https://docs.aviatrix.com/HowTos/config_paloaltoVM.html>`_ to setup an "ALLOW ALL" policy for test validation. How do I test FireNet connectivity without deploying firewall instance? ----------------------------------------------------------------------------------------- You can test connectivity without deploying any firewall instances. When the FireNet Gateway has no firewall instance attached to it for the data path, the FireNet Gateway loops the received packet and forwards it to its destination. Can VM-Series be launched with Bootstrap integration? ------------------------------------------------------------------------- Yes. When you launch a VM-Series from the Aviatrix Controller, you can select the option to launch the VM-Series instance with `bootstrap information. <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#example-configuration-for-bootstrap>`_ Can Firewall Network work with Panorama? --------------------------------------------------------- Yes. Follow the instructions for `Panorama integration <https://docs.aviatrix.com/HowTos/paloalto_API_setup.html#managing-vm-series-by-panorama>`_. How does the Controller check Firewall instance health? ------------------------------------------------------------------------ When vendor integration is enabled, for Palo Alto Networks VM-Series, the Controller pings the individual firewall management interface every 10 seconds. If two consecutive ping fails, the firewall is declared down and is moved to "down" state. The Controller continues to ping the management interface, if consecutive pings become successful, the firewall instance is attached back to the FireNet Gateway pool. For Check Point CloudGuard and Fortinet Fortigate, the Controller uses AWS API to check instance health. Starting in Release 6.0 and later, Controller can also `check firewall instance health on its LAN interface <https://docs.aviatrix.com/HowTos/firewall_advanced.html#firewall-health-check-and-failover-detection-using-lan-interface>`_. What is the firewall instance state Inaccessible mean? --------------------------------------------------------------------- The Controller periodically issues Palo Alto API calls to find out if API can be issued successfully. This is used for route updating purposes, as firewall route updates requires API to work. If Palo Alto API fails for two consecutive times, the Controller declares the firewall is in Inaccessible state, but the firewall should still be attached and be forwarded traffic as long as its health check pass. How does Transit FireNet load balance traffic between different firewalls? ---------------------------------------------------------------------------------------------- AWS ======== In AWS, Transit FireNet Load Balance the traffic across different firewall using five-tuple hash. The tuple is composed of the: Source IP Source port Destination IP Destination port Protocol type The algorithm provides stickiness only within a transport session. Packets that are in the same session are directed to the same firewall. When the client starts a new session from the same source IP, the source port changes and causes the traffic to go to a different firewall. Azure ====== Aviatrix Transit FireNet supports different hashing algorithms available in Azure cloud to load balance the traffic across different firewalls which includes `Hash-based distribution mode (five-tuple hash) <https://docs.microsoft.com/en-us/azure/load-balancer/load-balancer-distribution-mode#hash-based-distribution-mode>`_ and `Source IP affinity mode (three-tuple or two-tuple hash) <https://docs.microsoft.com/en-us/azure/load-balancer/load-balancer-distribution-mode#source-ip-affinity-mode>`_. By default, Transit FireNet use 5-tuple hashing algorithm but that can be changed using Azure's portal. 1. Log in to Microsoft Azure's Portal and Go to Load balancer under Azure services. #. Click the Transit FireNet where Load balancing algorithm needs to be changed. #. Go to Load Balancing rules under Settings and click **LBRule**. #. Select hashing algorithm under Session persistence. 1. None > Default five-tuple (source IP, source port, destination IP, destination port and protocol type) hashing algorithm. 2. Client IP > This mode uses a two-tuple (source IP and destination IP). 3. Client IP and protocol > three-tuple uses source IP, destination IP, and protocol type. |lb-rule-azure| How do I migrate from Aviatrix Transit FireNet to Transit FireNet with AWS GWLB? ------------------------------------------------------------------------------------------------------ Starting from Release 6.3, Multi-Cloud Transit FireNet added support for AWS Gateway Load Balancer (GWLB). The key advantage of this integration is to allow firewalls to be scaled up and down without affecting established sessions (except sessions associated with the failed firewalls). To migrate from Transit FireNet to Transit FireNet with AWS GWLB and vice versa. Follow the steps below: 1. Save the firewall configuration. #. Disassociate firewall instance . Go to Aviatrix Controller > Firewall Network > Setup > Step 10. #. Delete firewall instances > Go to Aviatrix Controller > Firewall Network > Setup > Step 7a. #. Disable Transit FireNet function > Go to Aviatrix Controller > Multi-Cloud Transit > Transit FireNet > Step 5a to disable Transit FireNet Function for Aviatrix Transit Gateway. #. Enable Transit FireNet function > Go to Aviatrix Controller > Multi-Cloud Transit > Transit FireNet > Step 1a to enable Transit FireNet Function on Aviatrix Transit Gateway. Mark the **Use AWS GWLB** if migrating from Transit FireNet to Transit FireNet with AWS GWLB. #. Launch & associate Firewall > Go to Aviatrix Controller > Firewall Network > Step 7a. #. Restore firewall configuration. .. |transit_firenet| image:: transit_firenet_media/transit_firenet.png :scale: 30% .. |transit_firenet_perf| image:: transit_firenet_media/transit_firenet_perf.png :scale: 30% .. |transit_firenet_vnet| image:: transit_firenet_media/transit_firenet_vnet.png :scale: 30% .. |transit_firenet_aviatrix_egress| image:: transit_firenet_media/transit_firenet_aviatrix_egress.png :scale: 30% .. |lb-rule-azure| image:: transit_firenet_media/lb-rule-azure.png :scale: 30% .. disqus:: <file_sep> =========================================================================================== Site2Cloud with NAT to fix overlapping VPC subnets =========================================================================================== This document provides a reference design for solving issues in reaching VMs in two overlapping subnets within two different VPCs. | Environment Description --------------------------------------------------------- There are three VPCs as illustrated in the diagram below. + **VPC1**: VPC CIDR - 10.3.0.0/16 + **VPC2**: VPC CIDR - 172.29.0.0/16 + **VPC3**: VPC CIDR - 10.3.0.0/16 |image1| Both VPC1 and VPC2 have a subnet with the same CIDR (10.3.3.0/24). VPC2 VMs need to access both VPC1 and VPC3 VMs in their 10.3.3.0/24 subnets. Since VPC1 VMs may change their private IP addresses after some unplanned reboots, VPC2 VMs have to access them through DNS. In addition, VPC2 VMs need to access VPC3 VMs through their private IP addresses. To solve this overlapping subnet issue, we need to create two Site2Cloud connections: + **Site2Cloud connection 1**: Unmapped Site2Cloud connection between VPC1 and VPC2 + **Site2Cloud connection 2**: Mapped Site2Cloud connection between VPC2 and VPC3 Detailed configuration steps are illustrated below. | Steps to Configure Site2Cloud Connections --------------------------------------------------------- + **Step 1: Install Aviatrix gateways in VPC1, VPC2 and VPC3.** Install the Aviatrix Gateways by following the instructions in this `document <http://docs.aviatrix.com/HowTos/gateway.html>`__ Don't select "Enable SNAT" when creating the new gateways in these VPCs. + **Step 2: Create an unmapped Site2Cloud connection at the Aviatrix Gateway in VPC2 for the connection to VPC1** Go to the **Site2Cloud** page and click the **Add New** button. Enter the following fields. =========================================== ====================================================== **Field** **Value** =========================================== ====================================================== VPC ID/VNet Name Enter VPC2 VPC ID Connection Type Select **Unmapped** Connection Name Enter any name here Remote Gateway Type Select **Aviatrix** Tunnel Type Select **UDP** Algorithms Leave it blank Encryption over ExpressRoute/DirectConnect Leave it blank Registered Leave it blank Enable HA Leave it blank Primary Cloud Gateway Select Aviatrix Gateway in VPC2 Remote Gateway IP Address Enter the public IP of Aviatrix Gateway in VPC1 Pre-shared Key Leave it blank (Pre-shared key will be auto-generated) Remote Subnet Enter VPC1 CIDR (10.3.0.0/16 in this case) Local Subnet Leave it blank (VPC2 CIDR will be used by default) =========================================== ====================================================== + **Step 3: Download the sample configuration from the Site2Cloud created in Step 2** After the Site2Cloud connection is created in Step 2, select this connection at the **Site2Cloud** page. Enter the following fields and click **Download Configuration** button ========================= ============================================ **Field** **Value** ========================= ============================================ Vendor Select **Aviatrix** Platform Select **UCC** Software Select **1.0** ========================= ============================================ Save the downloaded sample configuration locally at your PC. + **Step 4: Import the sample configuration downloaded from Step 3** Go to **Site2Cloud** page and click the **Add New** button. Select VPC1 VPC ID from **VPC ID/VNet Name** and click the **Import** button. Import the sample configuration downloaded from Step 3. + **Step 5: Create a mapped Site2Cloud at Aviatrix Gateway in VPC2 for the connection to VPC3** Go to the **Site2Cloud** page and click the **Add New** button. Enter the following fields. ========================================== ====================================================== **Field** **Value** ========================================== ====================================================== VPC ID/VNet Name Enter VPC2 VPC ID Connection Type Select **Mapped** Connection Name Enter any name here Remote Gateway Type Select **Aviatrix** Tunnel Type Select **UDP** Algorithms Leave it blank Encryption over ExpressRoute/DirectConnect Leave it blank Registered Leave it blank Enable HA Leave it blank Primary Cloud Gateway Select Aviatrix Gateway in VPC2 Remote Gateway IP Address Enter the public IP of Aviatrix Gateway in VPC3 Pre-shared Key Leave it blank (Pre-shared key will be auto-generated) Remote Subnet(Real) Enter VPC3 CIDR (10.3.0.0/16 in this case) Remote Subnet(Virtual) Enter the virtual CIDR (10.49.0.0/16 in this example) Local Subnet(Real) Enter VPC2 CIDR (172.29.0.0/16 in this case) Local Subnet(Virtual) Enter VPC2 CIDR again (172.29.0.0/16 in this case) ========================================== ====================================================== .. note:: **a.** For Remote Subnet, we want to map the real subnet CIDR (10.3.0.0/16) to the virtual subnet CIDR (10.49.0.0/16). The masks of both real and virtual subnets have to be the same (/16 in this case). The IP addresses in real and virtual subnets are one-to-one mapping by translating 10.3.x.y to 10.49.x.y. For example, for VPC2 VM to reach 10.3.1.100 in VPC3, VPC2 VM needs to use IP address 10.49.1.100. **b.** For Local Subnet, we don't need to map the real subnet CIDR (172.29.0.0/16) to a different virtual subnet CIDR because 172.29.0.0/16 in VPC2 doesn't conflict with any subnet in VPC1 and VPC3. So we use 172.29.0.0/16 for both Real Local Subnet and Virtual Local Subnet. + **Step 6: Download the sample configuration from the Site2Cloud created in Step 5** After the Site2Cloud connection is created in Step 5, select this connection at the **Site2Cloud** page. Enter the following fields and click the **Download Configuration** button ========================= ============================================ **Field** **Value** ========================= ============================================ Vendor Select **Aviatrix** Platform Select **UCC** Software Select **1.0** ========================= ============================================ Save the downloaded sample configuration locally at your PC. + **Step 7: Import the sample configuration downloaded from Step 6** Go to **Site2Cloud** page and click the **Add New** button. Select VPC3 VPC ID from **VPC ID/VNet Name** and click the **Import** button. Import the sample configuration downloaded from Step 6. + **Step 8: Verify that the Site2Cloud connections are up** Go to **Site2Cloud** page and verify that **Status** of all four Site2Cloud connections are **Up**. It may take several minutes for **Status** to be updated to **Up**. To troubleshoot the connections, please go to **Site2Cloud->Diagnostics** page. .. |image1| image:: s2c_overlapping_media/s2c_overlapping.png :scale: 100% .. disqus:: <file_sep> =========================================================================================== Multi Cloud Region Affinity and Latency =========================================================================================== AWS, Azure and GCP all are available in many regions. If you need to expand your cloud deployment to a different cloud, you should consider region affinity, that is, selecting a region of the second cloud that is closest to your current region deployment. This is a good idea even if you do not need inter cloud connectivity at the moment, because you may need it later and nothing beats minimum latency when it comes to networking and application performance. For example, if your AWS deployment is in us-east-2 (Ohio), you may think Azure Central US (Illinois) is a good region to deploy. It turns out that Azure East US 1 has better latency, at 12ms. The next best region is Azure East US 2, with 16ms latency. Below is a table that suggests the two best regions in Azure or GCP for a few given AWS regions. The way to read the table is for a given region, say AWS us-east-1, the best Azure affinity region is Azure East US 1 with a 1.87ms latency to AWS us-east-1. The second best Azure affinity region is Azure East US 2 with a 6.01ms latency to AWS us-east-1. +--------------------------+------------------------------------+---------------------------------------+ | **AWS Region** | **Azure Affinity Region Latency** | **GCP Affinity Regions Latency** | +--------------------------+------------------------------------+---------------------------------------+ | us-east-1 (Virginia) | East US 1 (Virginia), 1.87ms | us-east4 (Northern Virginia), 1.91ms | +--------------------------+------------------------------------+---------------------------------------+ | | East US 2 (Virginia), 6.01ms | us-east1 (South Carolina), 14.14ms | +--------------------------+------------------------------------+---------------------------------------+ | us-east-2 (Ohio) | East US 1 (Virginia), 11.84ms | us-east4 (Northern Virginia), 11.51ms | +--------------------------+------------------------------------+---------------------------------------+ | | East US 2 (Virginia), 16.52ms | us-east1 (South Carolina), 22.98ms | +--------------------------+------------------------------------+---------------------------------------+ | us-west-1 (California) | West US 1 (California), 2.17ms | us-west2 (California), 8.79ms | +--------------------------+------------------------------------+---------------------------------------+ | | West US 2 (Washington), 24.26ms | us-west1 (Oregon), 24.06ms | +--------------------------+------------------------------------+---------------------------------------+ | us-west-2 (Oregon) | West US 1 (California), 22.93ms | us-west1 (Oregon), 13.22ms | +--------------------------+------------------------------------+---------------------------------------+ | | West US 2 (Washington), 10.78ms | us-west2 (California), 27.71ms | +--------------------------+------------------------------------+---------------------------------------+ | eu-central-1 (Frankfurt) | West Europe (Netherlands), 10.67ms | europe-west3 (Frankfurt), 1.19ms | +--------------------------+------------------------------------+---------------------------------------+ References: ------------- * `AWS Region and Location Mapping <https://docs.aws.amazon.com/general/latest/gr/rande.html>`__ * `ARM Region and Location Mapping <https://azure.microsoft.com/en-us/global-infrastructure/locations/>`__ * `GCP Region and Location Mapping <https://cloud.google.com/compute/docs/regions-zones/>`__ .. |gcp_inter_region_latency| image:: gcp_inter_region_latency_media/gcp_inter_region_latency.png :scale: 30% .. disqus:: <file_sep> **Some notes before deployment:** 1. This document complements the existing deployment guide that was designed to help you to associate a Palo Alto VM-Series. We are going to assume that you have completed all the steps up to `launching and associating a firewall instance <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#launching-and-associating-firewall-instance>`_ before launching this firewall instance. Launching and associating a firewall instance is not necessary as it is Palo Alto VM-Series specific. 2. Currently, we do not have full integration between the Aviatrix dashboard and the Barracuda CloudGen Firewall, which means that you will not be able to update the firewall routing table via API, as it is currently possible with the Palo Alto VM-Series. ============================================================= Deploying a Barracuda CloudGen Firewall for use with the Aviatrix FireNet ============================================================== The goal of this document is to provide a step-by-step guide to launch and configure one or more Barracuda CloudGen Firewall instances to be integrated with the Aviatrix Firewall Network. This setup will include basic “allow-all” policies to serve as initial configuration to validate intended traffic is passing through the firewall instance. Setting up Firewall Network (FireNet) ------------------------------------------------- Complete all the steps of the Firewall Network Workflow in the Aviatrix Controller up to `"Attaching Aviatrix FireNet Gateway to TGW Firewall Domain" <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#attaching-aviatrix-firenet-gateway-to-tgw-firewall-domain>`_ to prepare your Firewall VPC (FireNet VPC). This will also set up the subnets that you will need later for launching a Barracuda Firewall instance. Deploying the Barracuda CloudGen Firewall Instance from the AWS Marketplace --------------------------------------------------------------------------------------------------- The Barracuda CloudGen Firewall is available as a Pay-As-You-Go(PAYG) or Bring-Your-Own-License(BYOL) model. For ease of use, we will use the PAYG model in this example. 1. Select the **Launch Instance** link in the AWS console from the Region your Firenet has been deployed in. * Choose the AWS Marketplace link and search for Barracuda. * Choose the Barracuda CloudGen Firewall for AWS - PAYG. |image1| 2. Click **Continue** when prompted. |image2| 3. Choose an instance size. A t2.small can be used for the Demo. Click **Next: Configure Instance Details**. |image3| 4. Choose the VPC created for the Aviatrix FireNet from the dropdown. Click the Public-FW-ingress-egress-us-east-1b subnet. In this example, we are using the US-East region. |image4| 5. Scroll down to adjust the network interfaces. Click **Add Device** to add another Network Interface. On the Subnet dropdown for eth1, choose the aviatrix-fireGW-DMZ-firewall subnet. |image5| 6.. Click **Next: Add Storage**, then **Next: Add Tags**. Add any necessary tags then click **Next: Configure Security Group**. No changes need to be made to the Security Group now. Click **Review and Launch**, the Launch on the next screen. You will be prompted for a key pair. None will be needed for the Firewall. Choose **Launch Instances**. 7. You'll need to configure an Elastic IP in the AWS Console to connect to the Barracuda management interface. `This <https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html>`_ link will guide you through setting up an Elastic IP. Once allocated, it will need to be associated to the private IP address of the Barracuda on eth0. Logging in to Firewall and Configuring Interfaces ----------------------------------------------------------------- 1. Barracuda recommends configuring its instances with the Firewall Admin, a stand-alone Windows application. Directions on downloading and using it can be found `here <https://campus.barracuda.com/product/cloudgenfirewall/doc/79463207/barracuda-firewall-admin/>`_ 2. Open the Admin Client and use the Elastic IP, root as the Username, and the instance id from the AWS console as the initial password. |image6| 3. You will be prompted to change the password upon first logging in. Once prompted to log in again, you will be asked to choose how you will administer the Firewall. Choose Manage via Firewall Admin and confirm. |image7| 4. These steps will be following the `Barracuda Documentation <https://campus.barracuda.com/product/cloudgenfirewall/doc/79462723/how-to-add-aws-elastic-network-interfaces-to-a-firewall-instance/>`_ for adding an additional interface. Once logged in you will need to configure the second(eth1) interface on the Barracuda. Go to Configuration > Configuration Tree > Box > Network. |image8| 5. Click **Lock**. 6. In the left menu, click **Interfaces**. 7. In the Network Interface Cards table, double-click the 10dynmod entry. The window will open. |image9| 8. From the Number of Interfaces, select the number of network interfaces attached to the firewall instance, in this case 2. Click **Ok**. |image10| 9. Click **Send Changes** and **Activate**. Now, add a Direct Attached Route for the second Network Interface. 1. Go to Configuration > Configuration Tree > Box > Network. 2. Click **Lock**. 3. In the left menu, click **Routing**. 4. Click **+ **in the IPv4 Routing Table to add an attached route. 5. Target Network address will be the subnet you put on eth1, the aviatrix-fireGW-DMZ-firewall subnet. * For the Route Type, select direct attached network. * Interface Name, select eth1. * Trust Level, select Trusted. |image11| 6. Click **OK**. 7. Click **Send Changes** and **Activate**. The Network Configuration will need to be activated now. 1. Go to Control > Box. 2. In the Network section of the left menu, click **Activate new network configuration**. The Network Activation window opens. 3. Click Failsafe. The route is now pending in Control > Network. |image12| A virtual IP needs to be added to the Virtual Server. It will be the private IP assigned to your eth1 interface from the AWS console. 1. Go to Configuration > Configuration Tree > Box > Virtual Servers > your virtual server > Server Properties. 2. Click **Lock**. 3. Click **+** in the Additional IP table. The Additional IP window opens. * In Additional IP, add the private IP address configured for the network interface in step 1. * Reply to Ping, select **Yes**. |image13| 4. Click **OK**. 5. Click **Send Changes** and **Activate**. Creating Static Routes for Routing of Traffic VPC-to-VPC ------------------------------------------------------------------------ The next step is to update the route table. For the purpose of this guide, we suggest adding three routes, each for a RFC1918 address pointing to the private IP of the eth2/ENI of the Aviatrix gateway in question (whether you are attaching the instance to the main or to the backup gateway). 1. Go to Configuration > Configuration Tree > Box > Network. 2. Click **Lock**. 3. In the left menu, click **Routing**. 4. Click **+** in the IPv4 Routing Table to add a gateway route. * Target Network address will be a summary of your VPCs or all private addresses. * Route Type, select gateway. * Gateway, add the private IP of the eth2 interface of your primary Aviatrix FireNet Gateway. * Trust Level, select **Trusted**. |image14| 5. Click **OK**. 6. Click **Send Changes** and **Activate**. The Network Configuration will need to be activated now. 1. Go to Control > Box. 2. In the Network section of the left menu, click **Activate new network configuration**. The Network Activation window opens. 3. Click **Failsafe**. For the second interface to become available to the Barracuda the instance will need to be rebooted from the AWS console. If it hasn't already been done, Source/Dest. Check will also need to be disabled for both of the ENIs associated to the Barracuda. |image15| Configuring Basic Traffic Policy to Allow Traffic ----------------------------------------------------------- Security Groups in AWS for the Barracuda ENIs will need to be adjusted as necessary to allow the traffic from the various VPCs to hit the interface. Building rules to allow VPC-to-VPC traffic, and Egress traffic if needed is next. There are two pre-built rules, CLOUD-NET-2-INTERNET and CLOUD-NET-2-CLOUD-NET, that we can adjust to match your VPCs within AWS. 1. Go to Configuration > Configuration Tree > Virtual Servers > your virtual server > NGFW(Firewall) > Forwarding Rules. 2. Click **Lock**. 3. Open the CLOUD-NET-2-INTERNET rule and add your VPCs CIDR ranges to the Source field. |image16| 4. Click OK. 5. Click Send Changes and Activate. Do the same for the CLOUD-NET-2-CLOUD-NET rule, adding your VPCs to the Source and Destination fields. Leaving the Connection Method as Original Source IP will help in any future troubleshooting or logging. |image17| Ready to Go ----------------------- Now your firewall instance is ready to receive packets. The next step is specifying which Security Domain needs packet inspection by defining a connection policy that connects to the firewall domain. This is done by `this step <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#launching-and-associating-firewall-instance>`_ in the Firewall Network workflow. For example, deploy Spoke-1 VPC in Security_Domain_1 and Spoke-2 VPC in Security_Domain_2. Build a connection policy between the two domains. Build a connection between Security_Domain_2 to Firewall Domain. Launch one instance in Spoke-1 VPC and Spoke-2 VPC. From one instance, ping the other instance. The ping should go through. Viewing the Traffic Log ---------------------------------- Traffic can be viewed on the Firewall section of the Firewall Admin. The two most useful views are Live and History. History will show you any expired sessions and any traffic blocked by the firewall, while the Live view will show any active sessions. |image18| Scaling Out ---------------------- Additional Firewall instances can be added to the FireNet as needed, and load balanced using the Aviatrix Gateways. .. |image1| image:: ./barracuda_images/image1.png :width: 100% .. |image2| image:: ./barracuda_images/image2.png :width: 100% .. |image3| image:: ./barracuda_images/image3.png :width: 100% .. |image4| image:: ./barracuda_images/image4.png :width: 100% .. |image5| image:: ./barracuda_images/image5.png :width: 100% .. |image6| image:: ./barracuda_images/image6.png :width: 100% .. |image7| image:: ./barracuda_images/image7.png :width: 100% .. |image8| image:: ./barracuda_images/image8.png :width: 100% .. |image9| image:: ./barracuda_images/image9.png :width: 100% .. |image10| image:: ./barracuda_images/image10.png :width: 100% .. |image11| image:: ./barracuda_images/image11.png :width: 100% .. |image12| image:: ./barracuda_images/image12.png :width: 100% .. |image13| image:: ./barracuda_images/image13.png :width: 100% .. |image14| image:: ./barracuda_images/image14.png :width: 100% .. |image15| image:: ./barracuda_images/image15.png :width: 100% .. |image16| image:: ./barracuda_images/image16.png :width: 100% .. |image17| image:: ./barracuda_images/image17.png :width: 100% .. |image18| image:: ./barracuda_images/image18.png :width: 100% <file_sep> =========================== Peering FAQ =========================== What does Aviatrix encrypted peering do? ----------------------------------------------------- Aviatrix encrypted peering builds an encrypted tunnel between two VPC/VNets with a single click. In addition to building the encrypted connection, the Controller also programs the cloud infrastructure routing table so that you don't have to. The VPC and/or VNet can be across regions and across the cloud. The solution enables you to build an encrypted network. You can enable stateful firewalls on each VPC/VNet to add additional security measures. When should I consider using Aviatrix encrypted peering? ------------------------------------------------------------------------ See `this document <http://docs.aviatrix.com/StartUpGuides/aviatrix_overview.html#cloud-to-cloud-peering>`_. How do I configure encrypted peering? --------------------------------------- 1. Navigate to Gateway > **+New Gateway** in one existing VPC/VNet. VPN access may be disabled. 2. Repeat Step 1 with a different VPC ID or VNet Name. 3. At Peering > Encrypted Peering > **+New Peering**. Select the two gateway names and click **OK**. Is native AWS Peering supported? ------------------------------------------ Yes, you can configure AWS intra region peering and inter-region peering where it is available from the Controller. Go to Peering > AWS Peering. Cross accounts are supported. How do I configure encrypted peering with ActiveMesh and Insane Mode both enabled? ------------------------------------------------------------------------------------ You can configure an encrypted peering with ActiveMesh and Insane Mode by going through the `Transit Network workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_, as described in the following steps. 1. Go to Transit Network > Setup > Step 4, Launch a Spoke Gateway to launch the primary Spoke Gateway. Select ActiveMesh. Select Insane Encryption. #. Go to Transit Network > Setup > Step 5, Enable HA to launch the HA gateway for the Spoke Gateway created in the above step. #. Repeat the above two steps for the peering VPC/VNet. #. Go to Peering > Encrypted Peering, +Add New. Select the two primary gateways created in the above steps. Select HA. Click **OK**. Note that both primary gateway and backup gateway forward traffic. The VPC/VNet route tables are divided so that half of the route tables point the peered VPC/VNet CIDR to the primary gateway and the other half of the route tables point the peered VPC/VNet CIDR to the HA gateway. This division is best effort. Each gateway runs ECMP to the peered gateways. What is the encryption algorithm for encrypted peering? --------------------------------------------------------- Phase 1: - Authentication: SHA-256 - DH group: 14 - Encryption: AES-256-CBC Phase 2: - Authentication: AES-128-GCM-96 - Encryption: AES-128-GCM-96 .. |image1| image:: FAQ_media/image1.png .. disqus:: <file_sep> ===================================================================== Aviatrix Gateway to Meraki MX64 ===================================================================== Overview ----------------- This document describes how to create an IPsec tunnel between an Aviatrix Gateway and a Meraki MX64 using Aviatrix Site2Cloud. The network setup is as follows: **VPC/VNet1 (with Aviatrix Gateway)** *VPC/VNet1 CIDR: 10.10.0.0/16* *VPC/VNet1 Subnet CIDR (public subnet for AWS, GCP, or OCI): 10.10.0.0/24* **On-prem (with Meraki MX64)** *On-prem CIDR: 10.28.144.0/24* Adding a Site2Cloud Tunnel in Aviatrix Controller ------------------------------------------------------------ 1. Log in to your Aviatrix Controller. 2. Select Site2Cloud on the left navigation bar. 3. Click on **+ Add New** near the top of the Site2Cloud tab. 4. Under Add a New Connection, enter the following: +-------------------------------+------------------------------------------+ | Field | Expected Value | +===============================+==========================================+ | VPC ID / VNet Name | Select the VPC/VNet where this tunnel | | | will terminate in the cloud. | +-------------------------------+------------------------------------------+ | Connection Type | Unmapped unless there is an | | | overlapping CIDR block. | +-------------------------------+------------------------------------------+ | Connection Name | Name this connection. This connection | | | represents the connectivity to the | | | edge device. | +-------------------------------+------------------------------------------+ | Remote Gateway Type | Generic | +-------------------------------+------------------------------------------+ | Tunnel Type | UDP | +-------------------------------+------------------------------------------+ | Algorithms | Unmark this checkbox | +-------------------------------+------------------------------------------+ | Encryption over ExpressRoute/ | Unmark this checkbox | | Direct Connect | | +-------------------------------+------------------------------------------+ | Enable HA | Unmark this checkbox | +-------------------------------+------------------------------------------+ | Primary Cloud Gateway | Select the Gateway where the tunnel will | | | terminate in this VPC/VNet. | +-------------------------------+------------------------------------------+ | Remote Gateway IP Address | IP address of the Meraki M64 device. | +-------------------------------+------------------------------------------+ | Pre-shared Key | Optional. Enter the pre-shared key for | | | this connection. If nothing is entered | | | one will be generated for you. | +-------------------------------+------------------------------------------+ | Remote Subnet | Enter the CIDR representing the network | | | behind the Meraki MX64 that this tunnel | | | supports. | +-------------------------------+------------------------------------------+ | Local Subnet | The CIDR block that should be advertised | | | on Meraki M64 for the cloud network | | | (will default to the VPC/VNet CIDR block)| +-------------------------------+------------------------------------------+ 5. Click **OK**, 6. Click on this newly created Site2Cloud connection and select Vendor **Aviatrix** to **Download Configuration** so that you can copy and paste the pre-shared key into your Meraki configuration later. Configuring Site-to-site VPN in Meraki MX64 --------------------------------------------------------- 1. Log in to your Meraki dashboard. 2. In the Security appliance menu, select **Site-to-site VPN** under the Configure section. |meraki01| 3. Configure your Meraki MX64 and add a peer according to the screenshot below. |meraki02| 4. Click **Custom** in the IPsec Policies to create a custom policy that matches the Aviatrix Site2Cloud configuration that was previously downloaded. |meraki03| 5. Click **Update** to save the Custom policy. 6. Click **Save Changes**. 7. In the Security appliance menu, click **VPN Status** under the Monitor section. |meraki04| 8. Send traffic from the on-prem Meraki MX64 internal network to the Aviatrix Gateway VPC/VNet. Verify that VPN Status is green under the Non-Meraki peer tab. |meraki05| .. |meraki01| image:: site2cloud_meraki_media/meraki01.png .. |meraki02| image:: site2cloud_meraki_media/meraki02.png .. |meraki03| image:: site2cloud_meraki_media/meraki03.png .. |meraki04| image:: site2cloud_meraki_media/meraki04.png .. |meraki05| image:: site2cloud_meraki_media/meraki05.png .. disqus:: <file_sep>========================================================= Transit Connection to JuniperSRX over the internet. ========================================================= 1. From the Controller go to Transit Network -> Setup -> Launch a Transit VPC GW. |image1| 2. Connect the transit VPC GW to the JuniperSRX. Go to Transit Network -> Setup -> Connect to VGW/External Device. select External Device and input the following parameters. a. BGP Local AS number: ASN of the transit VPC GW b. BGP Remote AS number: ASN of the JuniperSRX c. Remote Gateway IP Address: JuniperSRX WAN Public IP. |image2| 3. Download the configuration by going to Site2Cloud -> Click on the Connection. select generic and Download Configuration and configure on the JuniperSRX accordingly. |image3| The following is a sample configuration based on the site2cloud configuration above. |image4| 4. Apply the following configuration to your SRX: .. raw:: html <iframe src="https://s3-us-west-2.amazonaws.com/aviatrix-download/docs/JuniperSRX+(1).txt" height="300px" width="100%"></iframe> Note: The tunnel IP addresses are configured accordingly with the configuration file downloaded from above. 5. After configuring the SRX the tunnel should change the status from down to up. 6. Go to Transit Network -> Advanced Config on the Controller and Click on Diagnostics and select the GW name from the dropdown list and select Show Ip bgp Command from the predefined Show list to verify the BGP Routes. |image7| |image8| .. |image1| image:: ./Transit_ExternalDevice_JuniperSRX_media/juniper1.png :width: 7.00000 in :height: 5.00000 in .. |image2| image:: ./Transit_ExternalDevice_JuniperSRX_media/juniper2.png :width: 7.00000 in :height: 5.00000 in .. |image3| image:: ./Transit_ExternalDevice_JuniperSRX_media/juniper3.png :width: 12.00000 in :height: 5.00000 in .. |image4| image:: ./Transit_ExternalDevice_JuniperSRX_media/juniper4.png :width: 7.00000 in :height: 5.00000 in .. |image5| image:: ./Transit_ExternalDevice_JuniperSRX_media/juniper5.png :width: 100% .. |image6| image:: ./Transit_ExternalDevice_JuniperSRX_media/juniper6.png :width: 100% .. |image7| image:: ./Transit_ExternalDevice_JuniperSRX_media/juniper7.png :width: 100% .. |image8| image:: ./Transit_ExternalDevice_JuniperSRX_media/juniper8.png :width: 12.00000 in :height: 5.00000 in .. disqus:: <file_sep> ################################### Certificate Management Overview ################################### You can use the Aviatrix certificate created at the time of installation for the Controller and gateway, or you can customize the Aviatrix Controller and gateway certificate to use an organization-specific certificate. Both types are certificates are issued locally through the Controller's automated processes. All keys and certificates are in PEM format. To customize the Controller or gateway certificate, see below. .. note:: Please make sure there are no special characters (including space) in the file name. ################################### Controller Certificate Management ################################### The Aviatrix Controller uses a self-signed certificate by default. That is why you see "Not Secure" in the browser. You can make the Controller more secure by importing a signed certificate. There are two methods to accomplish this: - Import a Certificate with Key: this is the preferred approach and is described `here <https://docs.aviatrix.com/HowTos/import_cert_with_key.html>`_. In this method, the private key file server.key must match the server.crt. - Generate CSR and Import a Certificate: these steps are provided below. Generate CSR and Import Certificate ------------------------------------- In this approach, you generate a .csr file, ensure it is signed, and then import it to the Aviatrix Controller. Generate the CSR File ^^^^^^^^^^^^^^^^^^^^^ 1. In the left pane of the Aviatrix Controller, select Settings > Controller, and then click the Certificate tab. #. Under Controller Certificate Management, select the **Generate CSR and Import Certificate** option. |gen_csr| 3. Enter the Fully Qualified Domain Name (FQDN) of the Controller. #. Click **Generate Certificate Signing Request**. The CSR is downloaded to your local host. #. After ensuring that the CSR is signed by a Sign Authority, you receive two files: a CA certificate and a Server certificate. #. In the CA Certificate field, select the signed CA certificate and click **Import CA Certificate**. #. In the Server Public Certificate field, select the Server certificate from step 3. #. Click **Import Server Public Certificate**. Import CA Certificate and Server Certificate ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ After you obtain the CA certificate and Server Public Certificate, click the **Import Certificate with Key** option to import/upload the files to the Controller. |ca.crt| ################################### Gateway Certificate Management ################################### .. note:: Setting up your custom gateway certificate only works in versions 6.0 or higher. Earlier versions will cause the custom certificate deployment to fail. You must update all existing gateways to at least version 6.0 before applying a custom certificate. Also, if any of your GCP gateways are version 14.04, using a custom gateway certificate is not supported. The gateway certificate is created when each gateway is launched via the Aviatrix Controller. At the time of gateway launch, an Aviatrix self-signed certificate is issued to the gateway to make sure all data transmission to and from the gateway is authenticated. If you don't customize the certificate, your gateway will continue to operate with the default certificate. If you choose to customize the certificate with your organization credentials, you must apply the below steps to customize all existing and new gateways. In addition, you can confirm and monitor each gateway certificate type in the Aviatrix Controller Console > Gateway > reference column Cert Type. Setting up the Custom Gateway Certificate ----------------------------------------- Make sure that all gateways are green/running before you proceed. 1. In the left pane of the Aviatrix Controller, select Settings > Advanced and click the Gateway tab. #. Under Gateway Certificate Management, the **Import CA Certificate with Key** option is selected by default. Click **Choose File** and navigate to the locations of the CA Certificate and the CA Private Key. #. Click **OK**. Step 3. Check the Gateway Certificate Type to Confirm Deployment ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ When the deployment completes, go to your Gateway list and display the column name Cert Type. Check to make sure each of the Cert Types is Custom. |gateway_cert| .. |gateway_cert| image:: controller_certificate_media/gateway_cert.png :scale: 30% .. |gen_csr| image:: controller_certificate_media/gen_csr.png :scale: 30% .. |ca.crt| image:: controller_certificate_media/ca.crt.png :scale: 30% .. |server_crt| image:: controller_certificate_media/server_crt.png :scale: 30% .. |imageRestoreAWS| image:: controller_backup_media/backup_restore_restore_aws.png .. |S3Create| image:: controller_backup_media/S3Create.png .. |S3Properties| image:: controller_backup_media/S3Properties.png :scale: 30% .. |S3SelectDefaultEncryption| image:: controller_backup_media/S3SelectDefaultEncryption.png :scale: 25% .. |S3SelectEncryption| image:: controller_backup_media/S3SelectEncryption.png :scale: 25% .. |KMSKeyCreate| image:: controller_backup_media/KMSKeyCreate.png :scale: 30% :align: middle .. |KMSKeyAddUser| image:: controller_backup_media/KMSKeyAddUser.png :scale: 30% :align: middle .. disqus:: <file_sep> ========================================================= Firewall Network Design Patterns ========================================================= 1. Hybrid with TGW --------------------------------------------------- FireNet supports AWS Transit Gateway (TGW), as shown below. |firenet_transit| 2. Hybrid with Insane Mode -------------------------------------------------------- FireNet supports AWS Transit (TGW) with Insane Mode, |firenet_insane| 3. Native TGW integration ------------------------------------------------------------------ In the Release 4.6, the hybrid deployment can be using native AWS Direct Connect Gateway. |firenet| 4. Multi Region Transit with Native TGW integration --------------------------------------------------------------------------------- Connect to on-prem with AWS DXGW and use Aviatrix Edge gateway to connect to multiple regions. |multi_region_firewall| 5. Multi-Region Transit with Aviatrix Edge ------------------------------------------------------------------------ Connect to on-prem with an Aviatrix Edge gateway for both hybrid and multi-regions. |multi_region_aviatrix_edge| 6. Two Firewall Networks -------------------------------------------------------- You can deploy two Firewall Networks, one dedicated for VPC-to-VPC traffic inspection and another for egress inspection. Note you must follow the configuration sequence below: 1. Disable the Traffic Inspection of the FireNet domain intended for Egress control. #. Enable Egress Control for FireNet domain intended for Egress control. #. Build connection policies. |multi_firewall| 7. Ingress Traffic Inspection ----------------------------------------------------------------- Follow the `Ingress firewall instructions <https://docs.aviatrix.com/HowTos/ingress_firewall_example.html>`_ to deploy the solution for Ingress traffic inspection. |ingress_firewall| 8. Aviatrix FQDN in FireNet for Egress Control ------------------------------------------------- When Aviatrix FQDN gateway is deployed in a VPC, it uses a public IP address to perform both whitelisting and NAT function for Internet bound traffic. Sometimes these Internet bound traffic are partner API calls and these partners require to limit the number of IP addresses for each customer of theirs. In such situation, you can deploy FQDN in a centralized manner as shown in the diagram below. |fqdn_in_firenet| 9. Ingress Directly through Firewall --------------------------------------- Another often configured Ingress Egress design pattern is to have the traffic forward to firewall instances directly as shown in the diagram below. In this design pattern, each firewall instance must configure SNAT on its LAN interface that connects to the Aviatrix FireNet gateway. The draw back of this design is source IP address is not preserved when traffic reaches the application. If you need to preserve source IP address, refer to `this recommended design for Ingress <https://docs.aviatrix.com/HowTos/firewall_network_design_patterns.html#ingress-traffic-inspection>`_. |firenet_ingress_egress| For more information, follow the `FireNet workflow <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#firewall-network-firenet-workflow>`_. 10. Central Egress in a Multi-Region Deployment -------------------------------------------------------- Since the default routes are propagated over the Aviatrix Transit Gateway peering, you can consolidate the Internet bound egress traffic to the firewalls in one region, as shown in the diagram below. |central_egress| 11. Distributed Egress in a Multi Region Deployment ------------------------------------------------------ If you need to have a distributed egress for each region, make sure you filter out the default route 0.0.0.0/0 when you build the Aviatrix Transit Gateway peering, as shown in the diagram below. |multi_egress| 12. Ingress Protection via Aviatrix Transit FireNet ------------------------------------------------------ This Ingress Protection design pattern is to have the traffic forward to firewall instances directly in Aviatrix Transit FireNet VPC as shown in the diagram below. In this design pattern, each firewall instance must configure (1) SNAT on its LAN interface that connects to the Aviatrix FireNet gateway and (2) DNAT to the IP of application server/load balancer. The draw back of this design is source IP address is not preserved when traffic reaches the application. For an example configuration workflow, check out `Ingress Protection via Aviatrix Transit FireNet with Fortigate <https://docs.aviatrix.com/HowTos/Ingress_Protection_Transit_FireNet_Fortigate.html>`_. |transit_firenet_ingress| .. |firewall_network| image:: firewall_network_faq_media/firewall_network.png :scale: 30% .. |firewall_deploy| image:: firewall_network_faq_media/firewall_deploy.png :scale: 30% .. |multi_region_firewall| image:: firewall_network_faq_media/multi_region_firewall.png :scale: 30% .. |multi_region_aviatrix_edge| image:: firewall_network_faq_media/multi_region_aviatrix_edge.png :scale: 30% .. |firewall_network_perf| image:: firewall_network_faq_media/firewall_network_perf.png :scale: 30% .. |multi_firewall| image:: firewall_network_faq_media/multi_firewall.png :scale: 30% .. |firenet_ingress_egress| image:: firewall_network_faq_media/firenet_ingress_egress.png :scale: 30% .. |firenet| image:: firewall_network_media/firenet.png :scale: 30% .. |firenet_transit| image:: firewall_network_media/firenet_transit.png :scale: 30% .. |firenet_insane| image:: firewall_network_media/firenet_insane.png :scale: 30% .. |central_egress| image:: firewall_network_media/central_egress.png :scale: 30% .. |multi_egress| image:: firewall_network_media/multi_egress.png :scale: 30% .. |private_interfaces| image:: firewall_network_workflow_media/private_interfaces.png :scale: 30% .. |fqdn_in_firenet| image:: firewall_network_workflow_media/fqdn_in_firenet.png :scale: 30% .. |ingress_firewall| image:: ingress_firewall_example_media/ingress_firewall.png :scale: 30% .. |transit_firenet_ingress| image:: ingress_firewall_example_media/Ingress_Aviatrix_Transit_FireNet_topology.png :scale: 30% .. disqus:: <file_sep> =================================== Aviatrix ActiveMesh Workflow =================================== Aviatrix ActiveMesh is officially available in Release 5.1. ActiveMesh leverages both primary gateway and backup gateway for packet forwarding. The architecture statistically doubles the network throughput. In addition, in ActiveMesh mode, multiple remotes sites can be connected to the Aviatrix Transit gateways. The workflow follows the `Transit Network workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ with one additional step. 1. After `Step 1 Launch a Transit Gateway <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-an-aviatrix-transit-gateway>`_ is completed, go to the Gateway page, highlight the just-created Transit gateway, and click **Edit**. At the Gateway Edit page, click **Enable for ActiveMesh Mode**. #. If you like a Spoke Gateway to run in ActiveMesh mode, enable ActiveMesh after `Step 1 Launch a Spoke Gateway <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-an-aviatrix-spoke-gateway>`_. .. |secondary_account| image:: adminusers_media/secondary_account.png :scale: 50% .. |account_structure| image:: adminusers_media/account_structure.png :scale: 50% .. |access_account_35| image:: adminusers_media/access_account_35.png :scale: 50% .. disqus:: <file_sep> ================================= AWS CloudWatch Integration ================================= Starting in release 4.0, Aviatrix Controller and gateway syslog can be exported to AWS `CloudWatch <https://aws.amazon.com/cloudwatch/features/>`_ Logs. .. Note:: * Only AWS gateways and Controllers are supported. Other cloud types are not supported. * AWS gateways created from an access account with AWS secret key and access key are not supported. .. | Step 1: Prepare on the Collector account for Aviatrix logs --------------------------------------------------------------------------------------- In order for Aviatrix controllers and gateways in different AWS accounts to send/update logs to the collector's AWS account, follow the instructions below to setup IAM role and policies on the collector's AWS account. 1. Go to AWS console, create an IAM role with a name aviatrix-role-cloudwatch. 2. Add Trust-Relationships for Aviatrix Controllers' and all gateways' AWS accounts. If you are already using CloudWatch for logs from all your AWS accounts, you may have already built the trust relationship between accounts. If this is the case, skip this step. 3. Attach AWS IAM Cloudwatch policy to the role aviatrix-role-cloudwatch. **a: Create an IAM role aviatrix-role-cloudwatch**, make sure the role name is "aviatrix-role-cloudwatch". |image10| |image11| |image12| |image1| **b: Add Trust-Relationships for controllers and gateways AWS accounts** |image2| |image3| **c: Attach AWS IAM policy for "CloudWatchAgentServerPolicy" to the role** |image4| | **d: Retrieve the ARN of the IAM Role** |image9| | Step 2 Enable CloudWatch log on the Controller ---------------------------------------------------- |image5| .. Note:: * ARN of IAM role: Specify the ARN of the IAM role in the collector's AWS account. * Region: Specify which region you wish to store your logs. .. | Result & Output: -------------------------- In AWS CloudWatch: |image6| |image7| To view Aviatrix Controller's and Gateways' CloudWatch Service Status: |image8| .. |image1| image:: ./cloudwatch_media/img_01_aviatrix_cloudwatch_iam_role_V2.PNG :width: 7.00000 in :height: 5.00000 in .. |image2| image:: ./cloudwatch_media/img_02_start_adding_trust_relationships_to_role_V2.PNG :width: 7.00000 in :height: 5.50000 in .. |image3| image:: ./cloudwatch_media/img_03_trust_relationships_syntax_example_V2.PNG :width: 7.00000 in :height: 5.50000 in .. |image4| image:: ./cloudwatch_media/img_04_attach_aws_iam_policy_to_the_iam_role_V2.png :width: 7.00000 in :height: 5.50000 in .. |image5| image:: ./cloudwatch_media/img_05_enable_aviatrix_cloudwatch_V3.PNG :width: 7.00000 in :height: 5.50000 in .. |image6| image:: ./cloudwatch_media/img_06_aws_cloudwatch_result_01.png :width: 7.00000 in :height: 5.50000 in .. |image7| image:: ./cloudwatch_media/img_07_aws_cloudwatch_result_02_V2.PNG :width: 7.00000 in :height: 5.50000 in .. |image8| image:: ./cloudwatch_media/img_08_troubleshoot_V2.png :width: 7.00000 in :height: 3.50000 in .. |image9| image:: ./cloudwatch_media/img_09_copy_role_ARN.png :width: 7.00000 in :height: 5.00000 in .. |image10| image:: ./cloudwatch_media/img_create_cloudwatch_role_01.png :width: 7.00000 in :height: 5.50000 in .. |image11| image:: ./cloudwatch_media/img_create_cloudwatch_role_02.png :width: 7.00000 in :height: 3.50000 in .. |image12| image:: ./cloudwatch_media/img_create_cloudwatch_role_03.png :width: 7.00000 in :height: 5.00000 in **Note:** Logs from CloudWatch can be exported to S3 buckets. Please follow `AWS Documentation <https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/S3Export.html>`_ .. add in the disqus tag .. disqus:: <file_sep> ========================================================= Firewall Network (FireNet) Workflow ========================================================= FireNet is a solution for integrating firewalls in the Transit Gateway (TGW) deployment for any Cloud Service Provider CSP): AWS, Azure, GCP, or OCI. If you are looking for firewall integration solution on Azure or in Aviatrix Multi-Cloud transit architecture, your starting point is `here <https://docs.aviatrix.com/HowTos/transit_firenet_workflow.html>`_. For questions about FireNet, see the `FireNet FAQ <https://docs.aviatrix.com/HowTos/firewall_network_faq.html>`_. Creating a Security VPC/VNet ------------------------------------------------ We recommend that you use the Aviatrix Useful Tools to create a VPC/VNet for a FireNet deployment. Select the **Aviatrix FireNet VPC** option when creating a security VPC/VNet. ========================================== ================= **Aviatrix FireNet VPC Public Subnet** **Description** ========================================== ================= -Public-gateway-and-firewall-mgmt-AZ-a A /28 subnet (public in AWS/GCP/OCI) in AZ a for FireNet Gateway and firewall instance management interface. -Public-gateway-and-firewall-mgmt-AZ-b A /28 subnet (public in AWS/GCP/OCI) in AZ b for FireNet HA Gateway and firewall instance management interface. -Public-FW-ingress-egress-AZ-a A /28 subnet (public in AWS/GCP/OCI) in AZ a for firewall instance's egress interface. -Public-FW-ingress-egress-AZ-b A /28 subnet (public in AWS/GCP/OCI) in AZ b for firewall instance's egress interface. ========================================== ================= Subscribing to a Firewall Instance (AWS Only) ---------------------------------------------------------- Before setting up Aviatrix FireNet, AWS customers need to subscribe to a firewall instance from a specific vendor on the AWS Marketplace. .. note:: This document section applies to AWS customers **only**. Azure, GCP, and OCI customers can launch firewall instances directly from the Aviatrix Controller without subscriptions. To subscribe to a firewall instance from AWS, use the following steps. 1. In your AWS account, search for **AWS Marketplace Subscriptions**. 2. On the AWS Marketplace Subscriptions page, select **Discover products**. 3. In the search bar, enter the type of firewall instance you wish to subscribe to: * Enter “VM-series” to search for a Palo Alto firewall instance. * Enter “CloudGuard” to search for a Check Point firewall instance. * Enter “Fortigate” to search for a Fortinet firewall instance. 4. From the results, select a bundle and/or license option for the firewall instance you wish to subscribe to. There are different bundle/license options for each instance type that represent different costs and performance offerings. 5. On the next page, click **Continue to subscribe** to subscribe to the instance. 6. On the next page, click **Accept terms** to accept the license terms. After you subscribe to the firewall instance, wait for the Effective date column to change from “Pending” to today’s date. Then, return to the Aviatrix Controller to launch the firewall instance from there. .. note :: Do not launch a firewall instance from AWS itself, as you can launch it from the Aviatrix Controller in the following steps. Creating a Firewall Domain --------------------------------------- This step creates a Security Domain with a Firewall Domain option. In your Aviatrix Controller, go to TGW Orchestrator > Plan > Create an AWS Transit Gateway and then a Security Domain by selecting **Aviatrix Firewall Domain**. For more information, refer to `Create a New Security Domain <https://docs.aviatrix.com/HowTos/tgw_plan.html#create-a-new-security-domain>`_. Launching Aviatrix FireNet Gateway ------------------------------------------ This step leverages the Transit Network workflow to launch one Aviatrix Gateway for FireNet deployment. C5x.large is the minimum Aviatrix gateway instance size for FireNet deployment as it requires `4 interfaces. <https://docs.aviatrix.com/HowTos/firewall_network_faq.html#what-is-the-minimum-gateway-instance-size-for-firenet-deployment>`_ If your deployment requires 2-AZ HA, go through Transit Network > Setup to launch one Aviatrix gateway and enable HA which effectively launches a HA gateway (the second gateway) in a different AZ. If you select public subnet "-Public-gateway-and-firewall-mgmt-AZ-a" for the primary FireNet Gateway, you should select public subnet "-Public-gateway-and-firewall-mgmt-AZ-b" for the second AZ FireNet Gateway. Do not mark the **Insane Mode Encryption** checkbox. Enabling Aviatrix FireNet Gateway --------------------------------------------- This step configures the gateway launched in the "Launching an Aviatrix FireNet Gateway" section above or FireNet function. If you have HA enabled, it automatically sets up the HA gateway for FireNet deployment. .. tip :: If you do not see any gateways in the dropdown menu, refresh the browser to load. In this step, the Aviatrix Controller creates 3 more Ethernet interfaces with associated subnets on the FireNet Gateways. |private_interfaces| ========================================== ============================================== ================= **FireNet Gateway instance interfaces** **Inbound Security Group Rule** **Description** ========================================== ============================================== ================= eth0 Allow SSH and HTTPS from Aviatrix Controller Public interface for communication with Controller eth1 Allow ALL (Do not change) Private interface for traffic to/from TGW eth2 Allow ALL (Do not change) Private interface for traffic to firewall instances eth3 Allow ALL (Do not change) Private interface for traffic to FireNet HA gateway ========================================== ============================================== ================= .. important:: Please do not change the security group inbound and outbound rules on eth1, eth2, and eth3 of a FireNet Gateway. If FireNet Gateway HA is enabled, the HA gateway shares the same route table as the primary for its eth1 interface. The new subnets created by the Controller at these steps are listed below. ========================================== ============================ **Aviatrix FireNet VPC/VNet Private Subnet** **Description** ========================================== ============================ -tgw-egress for FireNet Gateway eth1 to TGW -hagw-tgw-egress for FireNet HA Gateway eth1 to TGW -tgw-ingress for TGW to the ENI of eth1 of FireNet Gateway -hagw-tgw-ingress for TGW to the ENI of eth1 of the FireNet HA Gateway -dmz-firewall for FireNet Gateway eth2 -hagw-dmz-firewall for FireNet HA Gateway eth2 -dmz-exchange for FireNet Gateway eth3 -hagw-dmz-exchange for FireNet HA Gateway eth3 ========================================== ============================ Enabling the Aviatrix Gateway for FireNet Function ############################################################# This step configures the gateway launched in the "Launching Aviatrix FireNet Gateway" section above for FireNet function with AWS Gateway Load Balancer (GWLB). If you have HA enabled, it automatically sets up the HA gateway for FireNet deployment. In the dropdown menu, select one Aviatrix Transit Gateway, mark the **Use AWS GWLB** checkbox and click **Enable**. In this step, the Aviatrix Controller creates 2 more Ethernet interfaces with associated subnets on the FireNet Gateways. ========================================== ============================================== ================= **FireNet Gateway instance interfaces** **Inbound Security Group Rule** **Description** ========================================== ============================================== ================= eth0 Allow SSH and HTTPS from Aviatrix Controller Public interface for communication with Controller eth1 Allow ALL (Do not change) Private interface for traffic to/from TGW eth2 Allow ALL (Do not change) Private interface for traffic to firewall instances ========================================== ============================================== ================= .. important:: Please do not change the security group inbound and outbound rules on eth1 and eth2 of a FireNet Gateway. If FireNet Gateway HA is enabled, the HA gateway shares the same route table as the primary for its eth1 interface. The new subnets created by the Controller at these steps are listed below. ========================================== ============================ **Aviatrix FireNet VPC/VNet Private Subnet** **Description** ========================================== ============================ -tgw-egress for FireNet Gateway eth1 to TGW -hagw-tgw-egress for FireNet HA Gateway eth1 to TGW -tgw-ingress for TGW to the ENI of eth1 of FireNet Gateway -hagw-tgw-ingress for TGW to the ENI of eth1 of the FireNet HA Gateway -dmz-firewall for FireNet Gateway eth2 -hagw-dmz-firewall for FireNet HA Gateway eth2 -gwlb-pool for GWLB and Firewalls -gwlb-pool-ha for GWLB and Firewalls in different AZ -gwlb-egress for FireNet Gateway (if egress inspection is enabled) -gwlb-egress-ha for FireNet HA Gateway (if egress inspection is enabled) ========================================== ============================ |gwlb_tgw_avxgw| .. note:: HTTPS needs to be opened on firewall appliance for health check. See `firewall health check <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_azure.html#step-9-enable-health-check-policy-in-firewall>`_ for more information. Enabling Native AWS GWLB for FireNet Function ############################################################# This step integrates the AWS Transit Gateway (TGW) with AWS Gateway Load Balancer (GWLB) for native FireNet solution. In the dropdown menu, select the right AWS Account and region, provide the right security VPC/VNet and click **Enable**. The Aviatrix Controller will automatically create the new subnets, GWLB and GWLBe. The new subnets created by the Controller at these steps are listed below. ========================================== ============================ **Aviatrix FireNet VPC/VNet Private Subnet** **Description** ========================================== ============================ -tgw-ingress for TGW ENI to the GWLBe -hagw-tgw-ingress for TGW ENI to the GWLBe in different AZ -dmz-firewall for GWLBe -hagw-dmz-firewall for GWLBe in different AZ -gwlb-pool for GWLB and Firewalls -gwlb-pool-ha for GWLB and Firewalls in different AZ -gwlb-egress for NATGW gateway (if egress inspection is enabled) -gwlb-egress-ha for NATGW HA gateway (if egress inspection is enabled) ========================================== ============================ |gwlb_native| .. note:: HTTPS needs to be opened on firewall appliance for health check. Check `Firewall Health Check <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_azure.html#step-9-enable-health-check-policy-in-firewall>`_ for more information. Attaching Aviatrix FireNet Gateway to TGW Firewall Domain --------------------------------------------------------------------------------- This step requires you have already created a Security Domain with Firewall attribute enabled. When this step is completed, you have built the network infrastructure for FireNet deployment. This step may take a few minutes. |gw_launch| This step programs the relative route tables, described as below. ========================================== ===================== ================= **Aviatrix FireNet VPC/VNet route table** **key route entry** **Description** ========================================== ===================== ================= -tgw-egress 0.0.0.0/0 -> tgw for FireNet Gateway eth1 to TGW -hagw-tgw-egress 0.0.0.0/0 -> tgw for FireNet HA gateway eth1 to TGW -tgw-ingress 0.0.0.0/0 -> eth1 for TGW to eth1 of FireNet Gateway -hagw-tgw-ingress 0.0.0.0/0 -> eth1. for TGW to eth1 of FireNet HA gateway -dmz-firewall 0.0.0.0/0 -> tgw for firewall instance LAN interface to TGW -hagw-dmz-firewall 0.0.0.0/0 -> tgw for firewall instance LAN interface to TGW -dmz-exchange 0.0.0.0/0 -> eth3 for eth3 of FireNet Gateway to eth3 of HA gateway -hagw-dmz-exchange 0.0.0.0/0 -> eth3 for eth3 of FireNet HA gateway to eth3 of primary gateway ========================================== ===================== ================= Launching and Associating Firewall Instance ---------------------------------------------------------- This approach is recommended if this is the first Firewall instance to be attached to the gateway. This step launches a Firewall instance and associates it with one of the FireNet Gateways. .. important:: The Firewall instance and the associated Aviatrix FireNet Gateway above must be in the same AZ, and, we recommend that the Management Interface Subnet and Egress (untrust dataplane) Interface Subnet should not be in the same subnet. Launching and Attaching ########################## ========================================== ========== **Setting** **Value** ========================================== ========== VPC ID The Security VPC/VNet created above. Gateway Name The primary FireNet Gateway. Firewall Instance Name The name that will be displayed on the AWS Console. Firewall Image The AWS AMI that subscribed to above. Firewall Image Version Firewall instance current supported software versions. Firewall Instance Size Firewall instance type. Management Interface Subnet. Select the subnet whose name contains "gateway and firewall management" Egress Interface Subnet Select the subnet whose name contains "FW-ingress-egress". Username Applicable to Azure deployment only. "admin" as a username is not accepted. Password Applicable to Azure deployment only. Key Pair Name (Optional) The .pem file name for SSH access to the firewall instance. Attach (Optional) By selecting this option, the firewall instance is inserted in the data path to receive packet. If this is the second firewall instance for the same gateway and you have an operational FireNet deployment, you should not select this option as the firewall is not configured yet. You can attach the firewall instance later at Firewall Network > Advanced page. Advanced (Optional) Click this selection to allow Palo Alto firewall bootstrap files to be specified. IAM Role In advanced mode, create an IAM Role on the AWS account that launched the FireNet Gateway. Create a policy to attach to the role. The policy is to allow access to "Bootstrap Bucket". This option is not supported on Check Point. Bootstrap Bucket Name In advanced mode, specify a bootstrap bucket name where the initial configuration and policy file is stored. This option is not supported on Check Point. User Data In advanced mode and applicable to Check Point and FortiGate. For FortiGate in Azure, refer to `FortiGate User Data in Azure <https://docs.aviatrix.com/HowTos/fortigate_bootstrap_example_azure.html#method-1-configure-fortigate-firewall-via-user-data>`_. For Check Point in Azure, refer to `Check Point User Data in Azure <https://docs.aviatrix.com/HowTos/checkpoint_bootstrap_azure.html#configure-check-point-security-gateway-using-custom-data>`_. ========================================== ========== 1. Palo Alto VM-Series Specifications ************************************** Palo instance has 3 interfaces as described below. ======================================================== =============================== ================================ **Palo Alto VM instance interfaces** **Description** **Inbound Security Group Rule** ======================================================== =============================== ================================ eth0 (on subnet -Public-FW-ingress-egress-AZ-a) Egress or Untrusted interface Allow ALL eth1 (on subnet -Public-gateway-and-firewall-mgmt-AZ-a) Management interface Allow SSH, HTTPS, ICMP, TCP 3978 eth2 (on subnet -dmz-firewall) LAN or Trusted interface Allow ALL (Do not change) ======================================================== =============================== ================================ Note that firewall instance eth2 is on the same subnet as FireNet Gateway eth2 interface. .. important:: For Panorama managed firewalls, you need to prepare Panorama first and then launch a firewall. Check out `Setup Panorama <https://docs.aviatrix.com/HowTos/paloalto_API_setup.html#managing-vm-series-by-panorama>`_. When a VM-Series instance is launched and connected with Panorama, you need to apply a one time "commit and push" from the Panorama console to sync the firewall instance and Panorama. .. Tip:: If VM-Series are individually managed and integrated with the Controller, you can still use Bootstrap to save initial configuration time. Export the first firewall's configuration to bootstrap.xml, create an IAM role and Bootstrap bucket structure as indicated above, then launch additional firewalls with IAM role and the S3 bucket name to save the time of the firewall manual initial configuration. 2. Fortigate Specifications ******************************* Fortigate Next Generation Firewall instance has 2 interfaces as described below. ======================================================== =============================== ================================ **Fortigate VM instance interfaces** **Description** **Inbound Security Group Rule** ======================================================== =============================== ================================ eth0 (on subnet -Public-FW-ingress-egress-AZ-a) Egress or Untrusted interface Allow ALL eth1 (on subnet -dmz-firewall) LAN or Trusted interface Allow ALL (Do not change) ======================================================== =============================== ================================ Note that firewall instance eth1 is on the same subnet as FireNet Gateway eth2 interface. .. Tip:: Starting from Release 5.4, Fortigate bootstrap configuration is supported. 3. CheckPoint Specification ****************************** CheckPoint Firewall instance has 2 interfaces as described below. ======================================================== =============================== ================================ **CheckPoint VM instance interfaces** **Description** **Inbound Security Group Rule** ======================================================== =============================== ================================ eth0 (on subnet -Public-FW-ingress-egress-AZ-a) Egress or Untrusted interface Allow ALL eth1 (on subnet -dmz-firewall) LAN or Trusted interface Allow ALL (Do not change) ======================================================== =============================== ================================ Note that firewall instance eth1 is on the same subnet as FireNet Gateway eth2 interface. .. important:: Starting from Release 5.4, launching CheckPoint firewall instances from the Aviatrix Controller automatically initiates its onboarding process. For initial login information, go to `Credentials for Checkpoint Initial Login <https://aviatrix.zendesk.com/hc/en-us/articles/4417552852109>`_. You must be registered to access the Aviatrix Customer Support website. If you are not already registered, you can sign-up at https://support.aviatrix.com. Launch and Associate More ################################# Repeat the previous step to launch the second firewall instance to associate with the HA FireNet Gateway. Or repeat this step to launch more firewall instances to associate with the same FireNet Gateway. Example Setup for "Allow All" Policy ########################################### After a firewall instance is launched, wait for 15 minutes for it to come up. In addition, please follow example configuration guides as below to build a simple policy on the firewall instance for a test validation that traffic is indeed being routed to firewall instance. Palo Alto ********** For basic configuration, please refer to `this example configuration guide <https://docs.aviatrix.com/HowTos/config_paloaltoVM.html>`_. For implementation details on using Bootstrap to launch and initiate VM-Series, refer to `Bootstrap Configuration Example <https://docs.aviatrix.com/HowTos/bootstrap_example.html>`_. FortiGate ********** For basic configuration, please refer to `this example configuration guide <https://docs.aviatrix.com/HowTos/config_FortiGateVM.html>`_. CheckPoint ********** For basic configuration, please refer to `this example configuration guide <https://docs.aviatrix.com/HowTos/config_CheckPointVM.html>`_ Associate an Existing Firewall Instance -------------------------------------------- This step is the alternative step to the previous step. If you already launched VM-Series from the AWS Console, you can still associate it with the FireNet Gateway. If the firewall instance is by a vendor other than Palo Alto Network, for example, Checkpoint or Fortinet, you should launch the firewall instances from the AWS Console and associate them to the Aviatrix FireNet Gateway. The Management Interface Subnet may be the same as the Egress Interface Subnet. Launching & Associating Aviatrix FQDN Gateway ------------------------------------------------------------------ If you perform one of the previous two steps, then you must be using a third party firewall instance. Skip this step. This option is to deploy `Aviatrix FQDN gateway <https://docs.aviatrix.com/HowTos/fqdn_faq.html>`_ in a FireNet environment for a centralized scale out egress whitelist solution, as shown below. .. important:: If a deployed Aviatrix FQDN gateway has no FQDN whitelist attached to it, the FQDN gateway acts as a NAT gateway and it will pass all traffic to all destination sites. To add whitelist policies, follow `how to configure FQDN instructions <https://docs.aviatrix.com/HowTos/FQDN_Whitelists_Ref_Design.html>`_. This option is available in AWS and Azure. It applies to multi-cloud transit, Azure native Spoke transit, and TGW based transit. |fqdn_egress| |fqdn_in_firenet| ========================================== ========== **Setting** **Value** ========================================== ========== VPC ID The Security VPC/VNet created in Step 1. Gateway Name The primary FireNet Gateway. FQDN Gateway Subnet The public subnet on which Aviatrix FQDN gateway will be launched. FQDN Gateway Size The Aviatrix FQDN gateway instance size, starting from t2.micro. FQDN Gateway Name The Aviatrix FQDN gateway name. Note you cannot change the name once the gateway instance is launched. Attach Attach this FQDN gateway to the primary FireNet Gateway. ========================================== ========== Specify Security Domain for Firewall Inspection ------------------------------------------------------------------- There are two inspection modes. One is Domain-based inspection, which is the default. The other is Connection Policy based inspection. The Connection Policy based inspection mode (connection based inspection) is available in Release 6.3 and later. Domain-based inspection ############################### In domain-based inspection, to specify a Spoke VPC/VNet that needs inspection is to define a connection policy of the Security Domain, where the Spoke VPC/VNet is a member, to the Firewall Domain. For example, if you wish to inspect traffic between on-prem to VPC/VNet, connect Aviatrix Edge Domain to the Firewall Domain. This means on-prem traffic to any Spoke VPC/VNet is routed to the firewall first and then it is forwarded to the destination Spoke VPC/VNet. Conversely, any Spoke VPC/VNet traffic destined to on-prem is routed to the firewall first and then forwarded to on-prem. Connection-based inspection ################################# Connection-based inspection only applies to TGW-based Transit solution. Connection-based inspection is available from Release 6.3 and later. Connection-based inspection allows you to inspect traffic going across a specific pair of Security Domains. For example, Domain A has connection policy to Domain B and Domain C, you can specify to inspect traffic between Domain A and Domain B, but not Domain A and Domain C. This inspection mode reduces the amount of traffic being inspected and reduces the instances size requirements on both FireNet Gateways and firewalls. .. note:: Connection-based inspection is not applicable to `intra-domain inspection <https://docs.aviatrix.com/HowTos/tgw_list.html#edit-intra-domain-inspection>`_ where all VPC/VNet to VPC/VNet traffic in the same domain is inspected. Here are the steps to enable and configure connection-based inspection. Enabling Connection-Based Inspection ********************************************* #. Go to Controller > TGW Orchestrator > List. #. Click TGW, select one TGW, click Action > Edit Inspection Mode. #. Select **Connection-based** and click **Update**. Configuring East-West Inspection ****************************************** `A firewall security domain <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#create-a-firewall-domain>`_ must be created first before configuring east-west inspection. #. Go to Controller > TGW Orchestrator > List. #. Click **Connection** to display all Connection Policies in rows. #. Select **Connection Policy** and click Action > Enable Inspection. #. In the popup dropdown menu, select a firewall domain to associate the Connection Policy with. #. Click **Update**. Repeat these steps for other Connection Policies. Configuring Egress Inspection ************************************* The Firewall Domain must have `Egress Inspection <https://docs.aviatrix.com/HowTos/firewall_advanced.html#egress-through-firewall>`_ enabled before configuring Egress Inspection. #. Go to Controller > TGW Orchestrator > List. #. Click Security Domains which displays all Security Domains configured on the TGW. #. Select one domain and click Action > Enable Egress Inspection. #. In the popup dropdown menu, select a firewall domain to associate the domain with. #. Click **Update**. .. |firewall_domain| image:: firewall_network_workflow_media/firewall_domain.png :scale: 30% .. |gw_launch| image:: firewall_network_workflow_media/gw_launch.png :scale: 30% .. |private_interfaces| image:: firewall_network_workflow_media/private_interfaces.png :scale: 30% .. |panvm_bucket| image:: firewall_network_workflow_media/panvm_bucket.png :scale: 30% .. |fqdn_in_firenet| image:: firewall_network_workflow_media/fqdn_in_firenet.png :scale: 30% .. |fqdn_egress| image:: transit_firenet_design_patterns_media/fqdn_egress.png :scale: 30% .. |gwlb_tgw_avxgw| image:: firewall_network_workflow_media/gwlb_tgw_avxgw.png :scale: 40% .. |gwlb_native| image:: firewall_network_workflow_media/gwlb_native.png :scale: 40% .. disqus:: <file_sep> =========================================================================================== Tuning For Sub-10 Seconds Failover Time in Overlapping Networks =========================================================================================== Introduction -------------- The purpose of this document is to provide the instructions for tuning network configurations for sub-10 seconds failover time when network address ranges on-prem and cloud are overlapping. The scenario is described in the following diagram: |s2c_overlapping_cidr_topology| In the above diagram, Client-1 and Client-2 need to communicate with on-prem network. However, both Client-1 and Client-2 network address ranges overlap with each other, and worse yet, they both overlap with on-prem network address range (10.0.0.0/16). Such scenarios happen when Client-1, Client-2 and the on-prem networks belong to three different organizations. The traditional solution is to build IPSEC tunnel between the two networks and use SNAT/DNAT rules to translate each addresses, as demonstrated in this `example. <https://docs.aviatrix.com/HowTos/connect_overlap_cidrs.html>`_. Such solution requires a potentially large number of SNAT/DNAT rules which is difficult to configure and maintain. With the introduction of `Mapped Site2Cloud for address overlapping networks <https://docs.aviatrix.com/HowTos/overlapping_network_solutions.html>`_ , you no longer need to wrestle with the individual SNAT/DNAT rules. Configuration Steps ---------------------------- .. note:: This example uses Aviatrix Gateway on client site to simulate fast convergence environment Step 1: Follow the Multi-Cloud Transit workflow to launch gateways ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Log in to the Controller console, go to Multi-CLOUD TRANSIT. Follow step 1, step 4 and step 6 respectively to launch transit and spoke gateways, and attach spoke gateways to transit. Create VPN tunnel between Transit Gateway and On-prem. Step 2: Create a Site2Cloud tunnel between Spoke Gateway and Client-1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 2.1 Configure S2C from Spoke Gateway to Client-1 ################################################## Go to Controller Console -> Site2Cloud -> Setup. Click "+Add New". Fill the form and click OK. Select "Mapped" for the Connection Type field. ================================================== ======================================================================= **Field** **Value** ================================================== ======================================================================= VPC ID/VNet Name Choose VPC ID (Select Spoke Gateway VPC) Connection Type Mapped Connection Name Arbitrary (e.g. S2C-SPK-to-Client1) Remote Gateway Type Aviatrix Tunnel Type Route-based Algorithms Uncheck this box IKEv2 Uncheck this box Over Private Network Uncheck this box Enable HA Check this box Primary Cloud Gateway Select the Aviatrix Gateway created above Backup Gateway Select the Aviatrix Gateway HA Remote Gateway IP Address Public IP of Client-1 Primary Gateway Remote Gateway IP Address (Backup) Public IP of Client-1 Backup Gateway Pre-shared Key Optional (auto-generated if not entered) Same Pre-shared Key as Primary Check this box Custom Mapped Uncheck this box Remote Subnet (Real) 10.10.0.0/16 (Client-1 Real CIDR) Remote Subnet (Virtual) 172.16.31.10/16 (Client-1 Virtual CIDR) Local Subnet (Real) 10.10.0.0/16 (On-Prem Network CIDR) Local Subnet (Virtual) 192.168.0.0/16 (On-Prem Virtual CIDR) ================================================== ======================================================================= 2.2 Configure S2C from Client Side ################################################## Go to Controller Console -> Site2Cloud -> Setup. Click "+Add New". Fill the form and click OK. Select "unmapped" for the Connection Type field. ================================================== ======================================================================= **Field** **Value** ================================================== ======================================================================= VPC ID/VNet Name Choose VPC ID (Select Client-1 VPC) Connection Type Unmapped Connection Name Arbitrary (e.g. S2C-Client1-to-SPK-GW) Remote Gateway Type Aviatrix Tunnel Type Route-based Algorithms Uncheck this box IKEv2 Uncheck this box Over Private Network Uncheck this box Enable HA Check this box Primary Cloud Gateway Select the Aviatrix Gateway created above Backup Gateway Select the Aviatrix Gateway HA Remote Gateway IP Address Public IP of Spoke Primary Gateway Remote Gateway IP Address (Backup) Public IP of Spoke Backup Gateway Pre-shared Key Optional (auto-generated if not entered) Same Pre-shared Key as Primary Check this box Remote Subnet 192.168.0.0/16 (On-Prem Virtual CIDR) Local Subnet 10.10.0.0/16 (Client-1 Local Network CIDR) ================================================== ======================================================================= Step 3: Configure global parameters ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Go to Controller Console -> Settings -> Advanced 1) Click on "Tunnel" tab and change "Status Change Detection Time" and save settings. ================================================== ======================================================================= **Field** **Value** ================================================== ======================================================================= Aviatrix Entity Choose Controller Detecion time (secs) 20 ================================================== ======================================================================= 2) Click on "Keepalive" tab and modify Keepalive Template Configuration ================================================== ======================================================================= **Field** **Value** ================================================== ======================================================================= Keep Alive Speed fast ================================================== ======================================================================= Step 4: Configure site2cloud parameters ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Go to Aviatrix Controller's Console -> Site2Cloud -> Setup. 4.1 Spoke Gateway Side ######################## Select Spoke Gateway VPC, spoke gateway to client site2cloud connection and click "Edit" 1) Make sure only one tunnel is UP and HA status Active-Standby 2) DPD Timer is enabled, configure DPD timers as shown below and click "Save and Apply". ================================================== ======================================================================= **Field** **Value** ================================================== ======================================================================= Initial Delay 1 Retry 1 Maxfail 1 ================================================== ======================================================================= 3) Forward Traffic to Transit Gateway is enabled 4) Event Triggered HA is enabled 4.2 Client Side ######################## Select Client VPC, client to spoke site2cloud connection and click "Edit" 1) Make sure only one tunnel is UP and HA status Active-Standby 2) DPD Timer is enabled, configure DPD timers as shown below and click "Save and Apply". ================================================== ======================================================================= **Field** **Value** ================================================== ======================================================================= Initial Delay 1 Retry 1 Maxfail 1 ================================================== ======================================================================= 3) Active Active HA is disabled 4) Event Triggered HA is enabled Test site2cloud fast convergence ------------------------------------ Bring down IPSec primary tunnel and measure convergence. Done. .. |s2c_overlapping_cidr_topology| image:: connect_overlap_cidrs_media/s2c_overlapping_cidr_topology.png :scale: 40% .. disqus:: <file_sep> ========================================================= TGW List ========================================================= TGW List page provides the list of TGW Attachments and TGW Security Domains. It also allows you to make modular changes on attachments and Security Domains. For background information, refer to the `TGW Orchestrator FAQ <https://docs.aviatrix.com/HowTos/tgw_faq.html>`_. Before you show list, you must have at least completed some `TGW Build <https://docs.aviatrix.com/HowTos/tgw_build.html>`_ in Build page. TGW ------ TGW lists the TGWs created by the Controller. TGW lists also allows you to select a FireNet Inspection Mode. TGW Attachments ------------------------------------------- Showing Details ~~~~~~~~~~~~~~~ Show Details display routing details of TGW attachments, Spoke VPC, or TGW VPN/DXGW. The routing details include Spoke VPC's VPC route table entries, its attached TGW route table entries and Edge Domain VPC route table entries and its TGW route tables entries. The visibility helps to verify the correctness of route entries. To view, go to TGW Orchestrator > List > TGW Attachment. Select the attachment, click **Actions** > **Show Details**. Showing Attachment Reachability ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Show Attachment Reachability displays the selected attachment's connectivity configuration graphically. Auditing Routes ~~~~~~~~~~~~~~ Audit Routes verify route correctness by scanning the attachment's VPC route table, its attached TGW route table and connected TGW route tables. Use this to detect missing routes deleted by mistake or through programming errors. Updating VPC CIDR ~~~~~~~~~~~~~~~~~ If a new Spoke VPC CIDR is added/deleted or a new VPC route is added/deleted, clicking this option updates VPC attachments without having to detach the VPC first. Update VPC CIDR automatically makes routing adjustment when there is VPC CIDR change, for example, a new VPC CIDR has been added to the VPC. It also makes routing adjustment when a new route table is added or deleted. To configure, go to TGW Orchestrator > List > TGW Attachment. Select the attachment, click **Actions** > **Update VPC CIDR**. Editing Spoke VPC Customized Routes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ By default, RFC 1918 summarized routes and learned non-RFC 1918 specific routes are dynamically programmed into each Spoke VPC's VPC route table. This feature allows you to statically program specific routes whose target is TGW. .. Note:: When Edit Spoke VPC Customized Routes is enabled, all dynamically learned routes by the Spoke VPC are not programmed into the Spoke VPC route tables. To configure, go to TGW Orchestrator > List > TGW Attachment. Select the attachment, click **Actions** > **Edit Spoke VPC Customized Routes**. Enter a list of network CIDRs separated by comma. Editing Spoke VPC Advertised Routes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ By default, Spoke VPC advertises its VPC CIDR to TGW route table. This feature allows you to advertise different network CIDRs. There are environments where all Spoke VPCs have one identical CIDR, attaching these Spoke VPCs to a TGW will result in error. For example, Spoke VPC CIDR is 10.10.0.0/16, 192.168.127.12/16 where 192.168.127.12/16 is common across all Spoke VPCs. By using this feature, the Spoke VPC only advertises 10.10.0.0/16. To configure, go to TGW Orchestrator > List > TGW Attachment. Select the attachment, click Actives > Customize Spoke VPC Advertised Routes. Enter a list of network CIDRs separated by comma. Editing Spoke VPC Local Route Propagation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This feature changes an attached Spoke VPC local route propagation attribute without detaching the VPC. To configure, go to TGW Orchestrator > List > TGW Attachment. Select one attachment, click **Actions** > **Edit Spoke VPC** Local Route Propagation. Switching Security Domain ~~~~~~~~~~~~~~~~~~~~~~~~~ This feature allows you to switch a Spoke VPC's Security Domains without having to detach the Spoke VPC first. To configure, go to TGW Orchestrator > List > TGW Attachment. Select one attachment, click **Actions** > **Switch Security Domain**. In the dropdown menu, select the desired Security Domain, click **Update**. FireNet Management ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To allow access to the private IP of the MGMT interface of the Firewalls, enable Management Access From Onprem. This feature advertises the Firewalls private MGMT subnet to your Edge domain. This allows administrators and Firewall MGMT servers to connect to the Firewall without having to go over the internet. To enable, navigate to TGW Orchestrator > List and highlight the FireNet VPC. Then choose **Actions** > **FireNet Management**. TGW Security Domains ------------------------------ Showing Details ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Show Details display the TGW route table entries. Editing Intra Domain Inspection ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ By default, traffic between VPCs in the same Security Domain does not get inspected by firewalls in the FireNet deployment. This feature allows you to enable firewall inspection for traffic within one Security Domain. Enabling Edge Inspection ~~~~~~~~~~~~~~~~~~~~~~~~ This option applies to connection-based inspection mode. When connection-based inspection is enabled, use this option to enable Egress inspection for a specific domain. TGW Connection ----------------------- TGW > List > Connection lists all Connection Policies. Each Connection Policy is represented by two rows. Each row represents one Connection Policy in one direction. Enabling Inspection ~~~~~~~~~~~~~~~~~~~ This configuration is to specify an inspection rule for connection-based mode. Select one Connection Policy row by clicking on the row. Then click **Actions** > **Enable Inspection**. In the popup dropdown menu, select the firewall domain to associate. Click **Update**. The reverse direction is automatically configured. Disabling Inspection ~~~~~~~~~~~~~~~~~~~ This configuration is to disable an inspection rule for connection-based mode. Disable Inspection is only available for an inspection rule if it is already enabled. Select one Connection Policy row by clicking on the row. Then click **Actions** > **Disable Inspection**. In the popup dropdown menu, select the firewall domain to disassociate. Click **Update**. The reverse direction is automatically configured. .. |firewall_launch| image:: tgw_list_media/firewall_launch.png :scale: 30% .. disqus:: <file_sep> ================================================================== Multi-cloud Transit Gateway Peering over Private Network Workflow ================================================================== Introduction ============ Aviatrix Transit Gateway Peering over Private Network feature expands Transit Gateway peering to across multi-clouds where there is a private network connectivity between the cloud providers via on-prem or a co-location. This enables customers to build high performance data networks while ensuring data privacy by encrypting data in motion. The solution applies to AWS Direct Connect, Azure ExpressRoute, and Google Cloud Interconnect for the cloud to on-prem connectivity. This document describes a step-by-step instruction on how to build Aviatrix Transit Gateway Peering with Private Network over AWS Direct Connect and Azure ExpressRoute for R6.2 and later releases. In this note, you learn the following: #. Workflow on building underlay connectivity for private network with AWS Direct Connect #. Workflow on building underlay connectivity for private network with Azure ExpressRoute #. Workflow on Aviatrix Transit Gateway Peering with private network For more information about Multi-Cloud Transit Network, please check out the below documents: `Multi Cloud Global Transit FAQ <https://docs.aviatrix.com/HowTos/transitvpc_faq.html#multi-cloud-global-transit-faq>`_ `Global Transit Network Workflow Instructions (AWS/Azure/GCP/OCI) <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ `Aviatrix Transit Gateway Encrypted Peering <https://docs.aviatrix.com/HowTos/transit_gateway_peering.html>`_ `Transit Network Design Patterns <https://docs.aviatrix.com/HowTos/transitvpc_designs.html>`_ .. important:: - Aviatrix Transit Gateway Peering over Private Network solution supports only High-Performance Encryption (Insane) mode where Aviatrix Transit Gateways have Insane Mode Encryption option enabled at the gateway launch time. - This solution supports only `ActiveMesh 2.0 <https://docs.aviatrix.com/HowTos/activemesh_faq.html#what-is-activemesh-2-0>`_, please check this doc `How to migrate to ActiveMesh 2.0 <https://docs.aviatrix.com/HowTos/activemesh_faq.html#how-to-migrate-to-activemesh-2-0>`_ for migration detail. - Private subnets reachability between two Transit CIDRs is customers' responsibility which is typically done by Colo providers. - Workflow on building underlay connectivity for private network with AWS Direct Connect/Azure ExpressRoute here is just an example. Please adjust the topology depending on your requirements. Topology ==================== |transit_gateway_peering_with_private_network_diagram| The key ideas for this solution are: ------------------------------------- - The edge (WAN) router runs a BGP session to AWS VGW via AWS Direct Connect where the edge router advertises the Azure Transit VNET CIDR and the AWS VGW advertises the AWS Transit VPC CIDR. - The edge (WAN) router runs a BGP session to Azure VNG via Azure ExpressRoute where the edge router advertises the AWS Transit VPC CIDR and the Azure VNG advertises the AZURE Transit VNET CIDR. - The edge (WAN) router redistributes AWS Transit VPC CIDR and AZURE Transit VNET CIDR. - Once the reachability between two cloud transits over private network is there, user is able to deploy Aviatrix Multi Cloud Global Transit Gateway Encrypted Peering over Private Network .. important:: - Reachability between two transit networks' private CIDR is the responsibility of customer. Prerequisite ==================== This feature is available for 6.2 and later. `Upgrade <https://docs.aviatrix.com/HowTos/inline_upgrade.html>`_ Aviatrix Controller to at least version 6.2 In this example, we are going to deploy the below VPCs in AWS and Azure - AWS Aviatrix Transit VPC (i.e. 10.1.0.0/16) - AWS Aviatrix Spoke VPC (i.e. 192.168.1.0/24) - Azure Aviatrix Transit VNET (i.e. 10.0.0.0/16) - Azure Aviatrix Spoke VNET (i.e. 192.168.0.0/24) Workflow on building underlay connectivity for private network with AWS Direct Connect ====================================================================================== Building AWS Direct Connect is customer's responsibility. For more information about AWS Direct Connect, please check out the below documents: - Refer to `Connect Your Data Center to AWS <https://aws.amazon.com/getting-started/projects/connect-data-center-to-aws/>`_ Please adjust the topology depending on your requirements. Step 1.1. Build AWS Direct Connect ----------------------------------- - Refer to `Equinix ECX Fabric AWS Direct Connect <https://docs.equinix.com/en-us/Content/Interconnection/ECXF/connections/ECXF-aws-direct-connect.htm>`_ if users select Equinix solution. This is just an example here. Step 1.2. Associate AWS VGW to AWS Transit VPC ----------------------------------------------- - Login AWS VPC Portal - Click the hyperlink "Virtual Private Gateways" under sidebar "VIRTUAL PRIVATE NETWORK (VPN)" - Select the Virtual Private Gateway that you have the private virtual interface to AWS Direct Connect - Click the button "Actions" - Click the hyperlink "Attach to VPC" - Select the AWS Transit VPC and click the button "Yes, Attach" Workflow on building underlay connectivity for private network with Azure ExpressRoute ======================================================================================= Building Azure ExpressRoute is customer's responsibility. For more information about Azure ExpressRoute, please check out the below documents: - Refer to `Azure ExpressRoute <https://azure.microsoft.com/en-us/services/expressroute/>`_ - Refer to `ExpressRoute documentation <https://docs.microsoft.com/en-us/azure/expressroute/>`_ for more info - Refer to `Equinix ECX Fabric Microsoft Azure ExpressRoute <https://docs.equinix.com/en-us/Content/Interconnection/ECXF/connections/ECXF-ms-azure.htm>`_ if users select Equinix solution. This is just an example here. Please adjust the topology depending on your requirements. Step 2.1. Create an ExpressRoute circuit ---------------------------------------- - Refer to `Tutorial: Create and modify an ExpressRoute circuit <https://docs.microsoft.com/en-us/azure/expressroute/expressroute-howto-circuit-portal-resource-manager>`_ Step 2.2. Create Azure private peering for an ExpressRoute circuit ------------------------------------------------------------------- - Refer to `private peering section in Create and modify peering for an ExpressRoute circuit <https://docs.microsoft.com/en-us/azure/expressroute/expressroute-howto-routing-portal-resource-manager>`_ Step 2.3. Create a virtual network gateway for an ExpressRoute circuit ---------------------------------------------------------------------- - Refer to `Configure a virtual network gateway for ExpressRoute using the Azure portal <https://docs.microsoft.com/en-us/azure/expressroute/expressroute-howto-add-gateway-portal-resource-manager>`_ Step 2.4. Connect a virtual network to an ExpressRoute circuit -------------------------------------------------------------- - Refer to `Connect a virtual network to an ExpressRoute circuit using the portal <https://docs.microsoft.com/en-us/azure/expressroute/expressroute-howto-linkvnet-portal-resource-manager>`_ Step 2.5. Check Express Route Circuits - List Routes Table on Azure portal --------------------------------------------------------------------------- - Login Azure Portal - Search for "ExpressRoute circuits" on the search bar - Select the "ExpressRoute circuits" that you created - Select the Azure private peering row - Click on the hyperlink "Get route table" - Check whether AWS Transit VPC's CIDR with the ASN Path of edge router and AWS VGW |express_route_circuits_list_routes| Workflow on Aviatrix Transit Gateway Peering with private network =================================================================== Refer to `Global Transit Network Workflow Instructions <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ and `Aviatrix Transit Gateway Encrypted Peering <https://docs.aviatrix.com/HowTos/transit_gateway_peering.html>`_ for the below steps. Please adjust the topology depending on your requirements. Step 3.1. Deploy VPCs for Transit FireNet ------------------------------------------ - Create AWS Transit VPC and Azure Transit VNET by utilizing Aviatrix feature `Create a VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ with Aviatrix FireNet VPC option enabled - Create AWS Spoke VPC and Azure Spoke VNET by utilizing Aviatrix feature `Create a VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ as the previous step or manually deploying it in each cloud portal. Moreover, feel free to use your existing cloud network. Step 3.2. Deploy Aviatrix Multi-Cloud Transit Gateway and HA in AWS ------------------------------------------------------------------- - Follow this step `Deploy the Transit Aviatrix Gateway <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html#step-2-deploy-the-transit-aviatrix-gateway>`_ to launch Aviatrix Transit gateway and enable HA with insane mode enabled in AWS Transit VPC - Instance size of at least c5.xlarge will be required for `Insane Mode Encryptions <https://docs.aviatrix.com/HowTos/gateway.html#insane-mode-encryption>`_ for higher throughput. Recommended minimum size for Transit in AWS is c5n.4xlarge. Please refer to this `doc <https://docs.aviatrix.com/HowTos/insane_mode_perf.html>`_ for performance detail. Step 3.3. Enable Route Propagation on the subnet route table where Aviatrix Transit Gateway locates on AWS portal ------------------------------------------------------------------------------------------------------------------ - Login AWS VPC portal - Locate the subnet route table where Aviatrix Transit Gateway locates - Select the tab "Route Propagation" - Click the button "Edit route propagation" - Locate the AWS VGW that is associated with this Transit VPC and check the checkbox "Propagate" - Click the button "Save" - Check whether the Propagate status is Yes |aws_route_propagation_status_yes| Step 3.4. Check route propagation info on AWS portal ---------------------------------------------------- - Login AWS VPC portal - Locate the subnet route table where Aviatrix Transit Gateway locates - Select the tab "Routes" - Check whether there is a route entry "Azure Transit VNET's CIDR pointing to AWS VGW" |aws_route_propagation_routing_entry| Step 3.5. Deploy Aviatrix Multi-Cloud Transit Gateway and HA in Azure --------------------------------------------------------------------- - Follow this step `Deploy the Transit Aviatrix Gateway <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html#step-2-deploy-the-transit-aviatrix-gateway>`_ to launch Aviatrix Transit gateway and enable HA with insane mode enabled in Azure Transit VNET - Instance size of at least Standard_D5_v2 will be required for `Insane Mode Encryptions <https://docs.aviatrix.com/HowTos/gateway.html#insane-mode-encryption>`_ for higher throughput. Please refer to this `doc <https://docs.aviatrix.com/HowTos/insane_mode_perf.html>`_ for performance detail. - Enable Transit FireNet Function (optional) Step 3.6. Check Effective routes info on Azure portal ------------------------------------------------------- - Login Azure Portal - Search for "Network interfaces" on the search bar - Select Aviatrix Transit Gateway's interface - Navigate to the page "Effective routes" by clicking the link "Effective routes" under the section "Support + troubleshooting" - Check whether there is a route entry "AWS Transit VPC's CIDR pointing to Next Hop Type Virtual network gateway" |azure_effective_routes_routing_entry| Step 3.7. Establish Transit Gateway Peering over Private Network ------------------------------------------------------------------- - Navigate back to Aviatrix Controller - Go to MULTI-CLOUD TRANSIT -> Transit Peering - Click the button "+ADD NEW" - Select "AWS Transit Gateway" as Transit Gateway1 - Select "Azure Transit Gateway" as Transit Gateway2 - Under Advanced options, check the option "Peering over Private Network" - (Optional) Under Advanced options, check the option `Single-Tunnel mode` if the underlying network is low speed (up to 4Gbps) - Click the button "OK" - Wait for a couple of minutes - Confirm the transit peering status is Up |transit_gateway_peering_status| Step 3.8. Deploy Spoke Gateway and HA -------------------------------------- - Follow this step `Deploy Spoke Gateways <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html#step-3-deploy-spoke-gateways>`_ to launch Aviatrix Spoke gateway and enable HA with insane mode enabled in AWS Spoke VPC - Instance size of at least c5.xlarge will be required for `Insane Mode Encryptions <https://docs.aviatrix.com/HowTos/gateway.html#insane-mode-encryption>`_ for higher throughput. Please refer to this `doc <https://docs.aviatrix.com/HowTos/insane_mode_perf.html>`_ for performance detail. - Follow this step `Deploy Spoke Gateways <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_azure.html#step-3-deploy-spoke-gateways>`_ to launch Aviatrix Spoke gateway and enable HA with insane mode enabled in Azure Spoke VNET - Instance size of at least Standard_D5_v2 will be required for `Insane Mode Encryptions <https://docs.aviatrix.com/HowTos/gateway.html#insane-mode-encryption>`_ for higher throughput. Please refer to this `doc <https://docs.aviatrix.com/HowTos/insane_mode_perf.html>`_ for performance detail. Step 3.9. Attach Spoke Gateways to Transit Network -------------------------------------------------- - Follow this step `Attach Spoke Gateways to Transit Network <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html#step-4-attach-spoke-gateways-to-transit-network>`_ to attach Aviatrix Spoke Gateways to Aviatrix Transit Gateways in AWS - Follow this step `Attach Spoke Gateways to Transit Network <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_azure.html#step-4-attach-spoke-gateways-to-transit-network>`_ to attach Aviatrix Spoke Gateways to Aviatrix Transit Gateways in Azure Ready to go! ============ Now you are able to send traffic over Aviatrix Transit Gateway Peering with Private Network. .. |transit_gateway_peering_with_private_network_diagram| image:: transit_gateway_peering_with_private_network_workflow_media/transit_gateway_peering_with_private_network_diagram.png :scale: 50% .. |express_route_circuits_list_routes| image:: transit_gateway_peering_with_private_network_workflow_media/express_route_circuits_list_routes.png :scale: 50% .. |aws_route_propagation_status_yes| image:: transit_gateway_peering_with_private_network_workflow_media/aws_route_propagation_status_yes.png :scale: 50% .. |aws_route_propagation_routing_entry| image:: transit_gateway_peering_with_private_network_workflow_media/aws_route_propagation_routing_entry.png :scale: 50% .. |azure_effective_routes_routing_entry| image:: transit_gateway_peering_with_private_network_workflow_media/azure_effective_routes_routing_entry.png :scale: 50% .. |transit_gateway_peering_status| image:: transit_gateway_peering_with_private_network_workflow_media/transit_gateway_peering_status.png :scale: 50% .. disqus:: <file_sep> =============================================== Oracle Cloud Infrastructure (OCI) Startup Guide =============================================== The Aviatrix cloud network solution consists of two components, the Controller and Gateways, both of which are cloud VMs (Virtual Machines). Gateways are launched from the Controller console to specific VCNs. This guide helps you to launch the Controller in OCI. * `Preparing Your Account in OCI <https://docs.aviatrix.com/StartUpGuides/oracle-aviatrix-cloud-controller-startup-guide.html#id1>`_ * `Subscribing to the Controller <https://docs.aviatrix.com/StartUpGuides/oracle-aviatrix-cloud-controller-startup-guide.html#id2>`_ * `Accessing the Controller <https://docs.aviatrix.com/StartUpGuides/oracle-aviatrix-cloud-controller-startup-guide.html#id3>`_ * `Onboarding Your OCI Account to your Aviatrix Controller <https://docs.aviatrix.com/StartUpGuides/oracle-aviatrix-cloud-controller-startup-guide.html#id4>`_ .. Important:: The Aviatrix Controller is a secure multi-cloud networking platform. Aviatrix recommends you deploy your controller in clouds that offer metered pricing, then deploy your gateways in any supported cloud. Metered pricing offers you a true pay-as-you-go option without any up-front commitments or contract negotiations. The AWS and Azure clouds offer metered pricing for running the Aviatrix Controller image. The GCP and OCI clouds do not offer metered pricing for running the Aviatrix Controller image. Preparing Your Account in OCI ============================== #. Create an OCI account if you do not already have one. #. Set up your compartment. Although you can use default account and root compartment, it is recommended that you follow this doc to create your own user, group, and compartment with the right policy. For more details, refer to `Setting Up Your Tenancy <https://docs.cloud.oracle.com/iaas/Content/GSG/Concepts/settinguptenancy.htm>`_. #. Create a VCN that has Internet access by navigating to Networking > Virtual Cloud Networks in the OCI console. Then, click **Create Virtual Cloud Network** and select **create virtual cloud network plus related resources**. #. Alternatively, if you want to create a VCN with your own CIDR, select **create virtual cloud network only**. Continue to create a subnet and Internet gateway. Then, add a default route in the VCN default routing table to point to the newly created Internet gateway. This is to grant Internet access to the Controller inside of this VCN. Subscribing to the Controller ============================== 1. Go to `Oracle Cloud Marketplace <https://cloudmarketplace.oracle.com/marketplace/en_US/homePage.jspx>`_ and search for Aviatrix to subscribe to the Aviatrix platform. 2. Click **Get App** at the top of the App page. 3. Select an OCI region and click **Launch Image**. |inst_region| 4. Choose the version and compartment and click **Launch Instance**. |inst_launch| On the "Create Compute Instance" page: 5. Choose name, availability domain, and Virtual Machine as instance type. 6. Choose an Instance Shape. The recommended shape is **Standard2.2**. |inst_flavor| 7. Choose the proper compartment for VCN and subnet. Optional: you could select **Use network security groups to control traffic** if you have one, otherwise leave it as you can create one later. |inst_network| 8. Choose an ssh public key file. 9. Click **Create** to launch the instance. Accessing the Controller ========================= To be able to reach your Controller public IP via https using your browser, you will need to open port 443 in either the Security List or Security Group. Security List (easy to configure) ---------------------------------------- #. From the OCI portal, navigate to Networking > Virtual Cloud Networks > your VCN name > Security Lists > Default Security List. #. Add an ingress rule to allow port 443. You could further limit the source CIDR if you know all your VCN subnets where the gateway will be launched. |inst_seclist| Security Group (recommended) ------------------------------------------ #. From the OCI portal, navigate to Networking > Virtual Cloud Networks > your VCN name > Network Security Groups. #. Create a new Security Group. Add an ingress rule to allow port 443. You could further limit the source CIDR if you know all your VCN subnets where gateway will be launched. |inst_secgroup| #. Navigate to Compute > Instances > Controller VM detail page, select **Edit** besides the Network Security Groups under Primary VNIC Information. #. Associate the Security Group you created to the controller VNIC. |inst_vnic_secgroup| Opening your Aviatrix Controller ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #. After the Aviatrix Controller instance is in a running state, you can access the Controller via a browser by navigating to https://Controller_public_IP, where "Controller_public_IP" is the static public IP address of the Controller. The initial password is the private IP address of the instance. #. Follow the steps in your browser to go through an initial setup phase to download the latest software. Use "latest" as version if you are not asked to use other version number. #. After the latest software is downloaded which takes around 5 mins, UI would redirect you to the login page. You could also try to log in again if browser is closed to go through the account onboarding process. Onboarding Your OCI Account to your Aviatrix Controller ================================================= Follow the `onboarding instructions <https://docs.aviatrix.com/HowTos/oracle-aviatrix-cloud-controller-onboard.html>`_ to create an Aviatrix account that corresponds to your OCI account credential. **Note**: You only need to create a single Aviatrix account that corresponds to many OCI, AWS, Azure and GCloud account credentials. This is a multi-cloud platform. Congratulations on finishing launching your Aviatrix networking platform. Please take a look at our `Documentation website <https://docs.aviatrix.com/>`_. Enjoy! .. |inst_launch| image:: OCIAviatrixCloudControllerStartupGuide_media/inst_launch.png .. |inst_region| image:: OCIAviatrixCloudControllerStartupGuide_media/inst_region.png .. |inst_flavor| image:: OCIAviatrixCloudControllerStartupGuide_media/inst_flavor.png .. |inst_network| image:: OCIAviatrixCloudControllerStartupGuide_media/inst_network.png .. |inst_seclist| image:: OCIAviatrixCloudControllerStartupGuide_media/inst_seclist.png .. |inst_secgroup| image:: OCIAviatrixCloudControllerStartupGuide_media/inst_secgroup.png .. |inst_vnic_secgroup| image:: OCIAviatrixCloudControllerStartupGuide_media/inst_vnic_secgroup.png .. |startup_version| image:: OCIAviatrixCloudControllerStartupGuide_media/startup_version.png .. |startup_first_login| image:: OCIAviatrixCloudControllerStartupGuide_media/startup_first_login.png .. |startup_login| image:: OCIAviatrixCloudControllerStartupGuide_media/startup_login.png <file_sep> ========================================================= Example Config for Palo Alto Network VM-Series in GCP ========================================================= In this document, we provide an example to set up the VM-Series for you to validate that packets are indeed sent to the VM-Series for VPC-to-VPC and from VPC to internet traffic inspection. For using bootstrap method to set up the VM-Series, follow `this document <https://docs.aviatrix.com/HowTos/bootstrap_example.html>`_. VM-Series in AWS can be set up using the guide `Palo Alto Networks VM-Series AWS Example <https://docs.aviatrix.com/HowTos/config_paloaltoVM.html#example-config-for-palo-alto-network-vm-series>`_. VM-Series in Azure can be set up using the guide `Palo Alto Networks VM-Series Azure Example <https://docs.aviatrix.com/HowTos/config_PaloAltoAzure.html#example-config-for-palo-alto-networks-vm-series-in-azure>`_. The Aviatrix Firewall Network (FireNet) workflow launches a VM-Series at `this step <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#launching-and-associating-firewall-instance>`_. After the launch is complete, the console displays the VM-Series instance with its public IP address of management interface and allows you to download the .pem file for SSH access to the instance. Below are the steps for initial setup. Downloading VM-Series Access Key -------------------------------------------------- After `this step <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#launching-and-associating-firewall-instance>`_ in the workflow is completed, click **Download** to download the .pem file. If you get a download error, usually it means the VM-Series is not ready. Wait until it is ready, refresh the browser and then try again. |access_key| Resetting VM-Series Password ------------------------------------------ For Metered AMI, open a terminal and run the following command. .. tip :: Once you download the .pem file, change the file permission to 400. If you are asked to enter a password during the login, the VM-Series is still not ready. Wait and try again. It usually takes up to 15 minutes for the VM-Series to be ready. When the VM-Series is ready, you will not be asked for a password anymore. :: ssh -i <private_key.pem> admin@<public-ip_address> configure set mgt-config users admin password commit For BYOL, open a terminal and run the following command. :: ssh -i <private_key.pem> admin@<public-ip_address> configure set mgt-config users admin password set deviceconfig system dns-setting servers primary <ip_address> commit Terminate the SSH session. Logging in to the VM-Series -------------------------------------- 1. Go back to the Aviatrix Controller. 2. Go to Firewall Network workflow, Step 2a. Click on the Management UI. It takes you the VM-Series you just launched. 3. Login with Username "admin". Password is the password you set at the previous step. Activating VM License -------------------------------- Dynamic Updates ------------------------------ 1. From Device > Dynamic Updates > Click on **Check Now** > download and then install latest versions of a. Applications and Threats b. Wildfire updates. 2. Click on **Check Now** again > download and then install latest version of Antivirus. Configuring VM-Series ethernet1/1 with WAN Zone ---------------------------------------------------------------------- After logging in, select the **Network** tab and you should see a list of ethernet interfaces. Click ethernet1/1 and configure as the following screenshot. 1. Select the **Network** tab. 2. Click **ethernet1/1**. 3. Select **layer3** for Interface Type. 4. Select the **Config** tab in the popup Ethernet Interface window. 5. Select the default for Virtual Router at the Config tab. 6. Click **New Zone for Security Zone** to create a WAN zone. 7. At the next popup screen, name the new zone "WAN" and click **OK**. |new_zone| Continue: 8. Select **IPV4** tab in the popup Ethernet Interface window. 9. Select **DHCP Client**. 10. Unmark the **Automatically create default route pointing to default gateway provided by server**, as shown below. |ipv4| 11. Click **Commit**. Once Commit is complete, you should see the Link State turn green at the Network page for ethernet1/1. Configuring VM-Series ethernet1/2 with LAN Zone -------------------------------------------------------------------- 1. Repeat the steps in the "Configuring VM-Series ethernet1/1 with WAN Zone" section above for ethernet1/2. Name the new zone LAN. 2. Click **Commit**. Once Commit is complete, you should see the Link State turn green at the Network page for ethernet1/2. GCP VM-Series Health Check ------------------------------------------- First, configure DNAT rule for Health Check is a mandatory required in GCP. Go to Polices > NAT > Add NAT. See example below for NAT configurations. |health_check_dnat| Also, follow `VM-Series Health Check Steps <https://docs.aviatrix.com/HowTos/config_PaloAltoAzure.html#enable-vm-series-health-check-policy>`_ to allow Google Load Balancer to check firewall instance health at regular intervals. Configure Basic Allow-all Policy -------------------------------------------------- In this step, we will configure a basic traffic security policy that allows traffic to pass through the VM-Series firewall. 1. Select the **Policies** tab. #. Select the **+Add** at the bottom-left corner to create a new policy. #. Select the **General** tab. Name the policy Allow-all. #. Select the **Source** tab. Select **Any** for both panels. #. Select the **Destination** tab. Select **Any** for both panels. #. Select the **Application** tab. Select **Any**. #. Click **OK**. #. Click **Commit** to install the Allow-all policy. Configuring NAT for Egress -------------------------------------- If you would also like to enable NAT to test egress, follow these steps. 1. Policies > NAT > Click **Add** > Select the **General** tab, give it a name > Click Original Packet. 2. At Source Zone, click **Add**, select "LAN". 3. At Destination Zone, select WAN. 4. At Destination Interface, select Ethernet1/1, as shown below. |nat_original_packet| 5. Click **Translated Packet**. At Translation Type, select **Dynamic IP And Port**. At Address Type, select **Interface Address**. 6. At Interface, select **ethernet1/1**, as shown below. |nat_translated_packet| Ready to Go -------------------------- Now your firewall instance is ready to receive packets. Next step is to validate your configurations and polices using FlightPath and Diagnostic Tools (ping, traceroute etc.). 12. View Traffic Log ----------------------------- You can view if traffic is forwarded to the firewall instance by logging in to the VM-Series console. 1. Click **Monitor**. 2. Start ping packets from one Spoke VPC to another Spoke VPC where one or both of Security Domains are connected to Firewall Network Security Domain .. |access_key| image:: config_paloaltoVM_media/gcp/access_key.png :scale: 45% .. |health_check_dnat| image:: config_paloaltoVM_media/gcp/health_check_dnat.png :scale: 45% .. |new_zone| image:: config_paloaltoVM_media/new_zone.png :scale: 30% .. |ipv4| image:: config_paloaltoVM_media/ipv4.png :scale: 30% .. |nat_original_packet| image:: config_paloaltoVM_media/nat_original_packet.png :scale: 30% .. |nat_translated_packet| image:: config_paloaltoVM_media/nat_translated_packet.png :scale: 30% .. disqus:: <file_sep> ================================= NAT for non-tunnel-bound Traffic ================================= If you set up `egress filtering <FQDN_Whitelists_Ref_Design.html>`__, you must enable `SNAT <gateway.html#source-nat>`__ so private instances can access the internet through the AVX gateway. With SNAT enabled, traffic going through the gateway will leave with the private IP of the gateway as its source. This is fine for common use cases; however, it can present a problem if you want the source unchanged for traffic destined for your data center or another VPC, for example. In this guide, we will show you how to set up the SNAT to only change the source IP for traffic headed out of the gateway on the **eth0** interface and not the tunnel interface(s). Steps to Enable SNAT for non-Tunnel Traffic -------------------------------------------- Navigate to Source NAT Configuration ************************************ #. Login to your AVX Controller #. Navigate to **Gateway** #. Select the Gateway and click **Edit** #. Scroll down to the **Source NAT** section Configure ********* |source_nat_fields| #. Select the **Customized SNAT** radio button #. Click the **+ Add New** button #. Enter the values in the fields as follows: +-----------------------+-------------------------------------------------+ | Field | Value | +=======================+=================================================+ | Src CIDR | **<<enter the CIDR for this VPC>>** | +-----------------------+-------------------------------------------------+ | Src Port | <<Leave blank>> | +-----------------------+-------------------------------------------------+ | Dst CIDR | <<Leave blank>> | +-----------------------+-------------------------------------------------+ | Dst Port | <<Leave blank>> | +-----------------------+-------------------------------------------------+ | Protocol | **all** | +-----------------------+-------------------------------------------------+ | Interface | **eth0** | +-----------------------+-------------------------------------------------+ | Mark | <<Leave blank>> | +-----------------------+-------------------------------------------------+ | SNAT IPs | **<<enter the private IP of the gateway>>** | +-----------------------+-------------------------------------------------+ | SNAT Port | <<Leave blank>> | +-----------------------+-------------------------------------------------+ .. tip:: To find the Private IP address of the gateway, scroll to the top and click the three lines next to **Gateway Detail**. |get_private_ip| #. Click **Save** #. Click **Enable SNAT** This enables NAT only for traffic that is leaving the gateway via **eth0**. For traffic going to the data center or to other spokes, the traffic will be leaving via a tunnel interface rather than eth0. .. |source_nat_fields| image:: nat_only_outbound_traffic_media/source_nat_fields.png .. |get_private_ip| image:: nat_only_outbound_traffic_media/get_private_ip.png <file_sep> .. toctree:: :numbered: ============================================================================== OpenVPN® with SAML Authentication on Okta IDP ============================================================================== Overview ------------ This guide provides an example on how to configure Aviatrix to authenticate against an Okta IDP. When SAML client is used, your Aviatrix Controller acts as the Identity Service Provider (ISP) that redirects browser traffic from client to IDP (e.g., Okta) for authentication. Pre-Deployment Checklist ----------------------------- Before configuring SAML integration between Aviatrix and Okta, make sure the following is completed: #. The `Aviatrix Controller <#aviatrix-controller>`__ is set up and running. #. You have a valid `Okta account <#okta-account>`__ with admin access. #. You have downloaded and installed the `Aviatrix SAML VPN client <#aviatrix-client>`__. .. _aviatrix_controller: Aviatrix Controller #################### If you haven’t already deployed the Aviatrix Controller, follow `the Controller Startup Guide <https://docs.aviatrix.com/StartUpGuides/aviatrix-cloud-controller-startup-guide.html>`_. .. _okta_account: Okta Account ############ A valid Okta account with admin access is required to configure the integration. .. _aviatrix_client: Aviatrix VPN Client ################### All users must use the Aviatrix VPN client to connect to the system. Download the client for your OS `here <http://docs.aviatrix.com/Downloads/samlclient.html>`__. Configuration Steps ------------------------- Follow these steps to configure Aviatrix to authenticate against your Okta IDP: #. Create an `Okta SAML App <#okta-saml-app>`__ for Aviatrix. #. Retrieve `Okta IDP metadata <#okta-idp-metadata>`__. #. Launch an `Aviatrix Gateway <#aviatrix-gateway>`__. #. Create Aviatrix `SAML SP Endpoint <#aviatrix-saml-endpoint>`__. #. `Test the Integration <#test-integration>`__ is Set Up Correctly. #. Create `Aviatrix VPN User <#aviatrix-vpn-user>`__. #. `Validate <#validate-entire-process>`__. .. _okta_saml_app: Creating an Okta SAML App for Aviatrix ##################################### .. note:: This step is usually done by the Okta Admin. #. Log in to the Okta Admin portal. #. Follow `Okta documentation <https://developer.okta.com/standards/SAML/setting_up_a_saml_application_in_okta>`__ to create a new application. +----------------+----------------+ | Field | Value | +================+================+ | Platform | Web | +----------------+----------------+ | Sign on method | SAML 2.0 | +----------------+----------------+ |image0| #. General Settings +----------------+-----------------+----------------------------------------+ | Field | Value | Description | +================+=================+========================================+ | App name | Aviatrix | This can be any value. It will be | | | | displayed in Okta only. | +----------------+-----------------+----------------------------------------+ | | Aviatrix logo: | Aviatrix logo (optional) | | | | | | App logo | | |logoAlias1|_ | | | | | |logoAlias2|_ | | +----------------+-----------------+----------------------------------------+ | App visibility | N/A | Leave both options unchecked | +----------------+-----------------+----------------------------------------+ |image1| #. SAML Settings * General +----------------------+----------------------------------------------------+ | Field | Value | +======================+====================================================+ | Single sign on URL | ``https://[host]/flask/saml/sso/[SP Name]`` | +----------------------+----------------------------------------------------+ | Audience URI | ``https://[host]/`` | | (SP Entity ID) | | +----------------------+----------------------------------------------------+ | Default RelayState | | +----------------------+----------------------------------------------------+ | Name ID format | Unspecified | +----------------------+----------------------------------------------------+ | Application username | Okta username | +----------------------+----------------------------------------------------+ ``[host]`` is the hostname or IP of your Aviatrix Controller. For example, "https://controller.demo.aviatrix.live." ``[SP Name]`` is an arbitrary identifier. This same value should be used when configuring SAML in the Aviatrix Controller. |image2| * Attribute Statements +----------------+-----------------+--------------------------------------+ | Name | Name format | Value | +================+=================+======================================+ | FirstName | Unspecified | user.firstName | +----------------+-----------------+--------------------------------------+ | LastName | Unspecified | user.lastName | +----------------+-----------------+--------------------------------------+ | Email | Unspecified | user.email | +----------------+-----------------+--------------------------------------+ |image3| .. _okta_idp_metadata: Retrieving Okta IDP Metadata ##################################### .. note:: This step is usually completed by the Okta admin. After the application is created in Okta, go to the Sign On tab for the application. Then, click **View Setup Instructions**. |image5| Look for the section titled "Provide the following IDP metadata to your SP provider." |idp_metadata| .. important:: Copy the text displayed. This value will be used to configure the SAML "IDP Metadata URL" field on the Aviatrix Controller. You need to assign the application to your account. Please follow steps 11 through 14 at `Okta documentation <https://developer.okta.com/standards/SAML/setting_up_a_saml_application_in_okta>`__. .. _aviatrix_gateway: Launching an Aviatrix VPN Gateway ############################# .. note:: This step is usually completed by the Aviatrix admin. #. Log in to the Aviatrix Controller. #. Click **Gateway** on the left sidebar. #. Click **+ New Gateway**. #. Enter a Gateway Name. #. Select the appropriate Account Name, Region, VPC ID, Public Subnet, and Gateway Size. #. Mark the **VPN Access**. #. Mark the **Enable SAML**. #. For information on the other settings, please refer to `this <./uservpn.html>`__ document. #. Click **OK** to create the Gateway. .. _aviatrix_saml_endpoint: Creating Aviatrix SAML Endpoint ############################# .. note:: This step is usually completed by the Aviatrix admin. #. Login to the Aviatrix Controller. #. Click **OpenVPN®** on the left sidebar. #. Select **Advanced**. #. Select the **SAML** tab. #. Click **+ Add New**. |imageControllerNavOpenVPNAdvanced| +-------------------------+-------------------------------------------------+ | Field | Value | +=========================+=================================================+ | Endpoint Name | ``SP Name`` (Use the same name you entered | | | in the Okta Application previously) | +-------------------------+-------------------------------------------------+ | IDP Metadata Type | Text | +-------------------------+-------------------------------------------------+ | IDP Metadata Text | ``Value Copied from Okta`` (Paste the value | | | copied from Okta SAML configuration) | +-------------------------+-------------------------------------------------+ | Entity ID | Hostname | +-------------------------+-------------------------------------------------+ #. Click **OK**. .. _test_integration: Testing the Integration #################### #. Start the Aviatrix VPN Client. .. note:: If you don't start the client, you will receive a warning from the browser in the last step of this process #. Log in to the Aviatrix Controller. #. Click **OpenVPN®** on the left sidebar. #. Select **Advanced**. #. Select the **SAML** tab. #. Click **Test** next to the "SP Name" created in the previous step. .. tip:: You will need to assign the new Okta application to a test user's Okta account before clicking **Test**. #. You should be redirected to Okta. Log in with your test user credentials. .. important:: If everything is configured correctly, once you have authenticated you will be redirected back to the Controller and the window will close. .. _create_aviatrix_vpn_user: Create a VPN User ################# #. Log in to the Aviatrix Controller. #. Select OpenVPN® > VPN Users on the left sidebar. #. Click **+ Add New**. #. Select the **VPC ID** and **LB/Gateway Name** for your SAML Gateway. #. Enter a name in the User Name field. #. Enter any valid email address in the User Email field (this is where the cert file will be sent). Alternatively, you can download the cert if you do not enter an email address. #. Select the **SAML Endpoint**. #. Click **OK**. .. _validate_entire_process: Validate ######## #. Log in to the Aviatrix Controller. #. Click OpenVPN® > VPN Users on the left sidebar. #. Download the configuration for your test user created in the previous step. #. Open the Aviatrix VPN Client application. #. Click **Load Conf** and select the file downloaded. #. Click **Connect**. .. note:: SAML VPN supports shared certificates. You can share the certificate among VPN users or create more VPN users. Configuring Okta for Multi Factor Authentication (Optional) ######################################################## Once you have successfully configured Okta IDP with Aviatrix SP, you can configure Okta for Multi Factor Authentication. Please read this `article <https://support.okta.com/help/Documentation/Knowledge_Article/Multifactor-Authentication-1320134400>`__ from Okta on Multifactor setup. See this `article <https://support.okta.com/help/Documentation/Knowledge_Article/Configuring-Duo-Security-734413457>`__ if you're interested in using Duo in particular. OpenVPN is a registered trademark of OpenVPN Inc. .. |logoAlias1| replace:: Aviatrix logo with red background .. _logoAlias1: https://aviatrix.com/wp-content/uploads/2020/09/Aviatrix_logo_reverse.png .. |logoAlias2| replace:: Aviatrix logo with transparent background .. _logoAlias2: https://aviatrix.com/wp-content/uploads/2020/09/Aviatrix_logo.png .. |image0| image:: SSL_VPN_Okta_SAML_media/image0.png .. |image1| image:: SSL_VPN_Okta_SAML_media/image1.png .. |image2| image:: SSL_VPN_Okta_SAML_media/image2.png .. |image3| image:: SSL_VPN_Okta_SAML_media/image3.png .. |image4| image:: SSL_VPN_Okta_SAML_media/image4.png .. |image5| image:: SSL_VPN_Okta_SAML_media/image5.png .. |idp_metadata| image:: SSL_VPN_Okta_SAML_media/idp_metadata.png :scale: 30% .. |image6| image:: SSL_VPN_Okta_SAML_media/image6.png .. |image7| image:: SSL_VPN_Okta_SAML_media/image7.png .. |imageControllerNavOpenVPNAdvanced| image:: SSL_VPN_Okta_SAML_media/OpenVPN_Advanced_SAML_AddNew.png :scale: 50% .. disqus:: <file_sep> =============================================================== Setting up PingOne for Customers Web SAML App with Profile Attribute =============================================================== This guide demonstrates the use of the **Profile** attribute in **PingOne for Customers** so each SAML user can be assigned a different VPN profile. How a VPN Profile Works ---------------------------------- The VPN profiles defined at the **Controller/OpenVPN/Profiles** contain egress control policy. They are attached to the VPN users defined at **Controller/OpenVPN/VPN Users** for controlling their VPN egress traffic. Users without a profile is the same as having a profile with an **allow-all** policy, i.e., their egress traffic are unrestricted. For SAML VPN, the SAML user definition at the IDP has a **Profile** attribute for specifying a VPN profile, overriding the corresponding user's VPN profile assigned at the Controller. If unspecified, the corresponding VPN profile assigned at the controller will be used. .. _pingone_for_customers_setup: Setting up PingOne for Customers Profile Attribute ----------------------------------------------------------------- #. `Define a new User attribute <#pingone-for-customers-new-user-attribute>`__ in the PingOne for customers portal for storing the VPN profile name. #. `Define an attribute mapping <#pingone-for-customers-map-attribute>`__ for the new attribute using the name **Profile** so that the web SAML application knows how to compose the **Profile** information in the SAML response. #. `Assign VPN profile <#pingone-for-customers-user-fill-attribute>`__ to each SAML user. #. `Validate <#pingone-for-customers-validation>`__ the setup. .. _pingone_for_customers_new_user_attribute: Defining a New User Attribute ----------------------------------------- .. note:: This step is usually completed by the PingOne for Customers Admin. 1. Log into the PingOne Admin portal. 2. Follow `PingOne documentation <https://docs.pingidentity.com/bundle/p14c/page/zhb1564020491029.html>`__ to add an User attribute. 3. On the top of the page, click **Settings**. 4. On the left, under Directory, click **Attributes**. 5. Click **+ Add Attribute**. |pingone_idp_adding_attribute| 6. Click **Declared**. |pingone_idp_adding_attribute_declared| 7. Click **Next**. 8. Enter the following information to create the custom user attribute: +-----------------------+---------------+---------------------------------------------------------------------------+ | Field | Value | Description | +-----------------------+---------------+---------------------------------------------------------------------------+ | Name | accessprofile | A unique identifier for the attribute. | +-----------------------+---------------+---------------------------------------------------------------------------+ | Display name | accessprofile | The name of the attribute as you want it to appear in the user interface. | +-----------------------+---------------+---------------------------------------------------------------------------+ | Description | (optional) | A brief characterization of the application. | +-----------------------+---------------+---------------------------------------------------------------------------+ | Enforce unique values | Uncheck | Option to require the attribute values be unique across the environment | +-----------------------+---------------+---------------------------------------------------------------------------+ .. note:: In this example, the new user attribute is named **accessprofile**. |pingone_idp_setting_attribute| 9. Click **Save and Close**. .. _pingone_for_customers_map_attribute: Defining an Attribute Mapping ------------------------------------------ .. note:: This step is usually completed by the PingOne for Customers Admin. #. On the top of the page, click **Connections**. #. Click **Applications** on the left. #. Locate the Web SAML application to add this custom User attribute. #. Click the details icon to expand the Web SAML application, and then click the pencil icon. #. Click **Attribute Mappings**. #. For updating attribute mapping, click the button **+Add Attribute** and then select **PingOne Attribute** to map PingOne user attribute to an application attribute as below. +------------------------+-----------------------+ | PingOne Attribute | Application Attribute | +------------------------+-----------------------+ | accessprofile | Profile | +------------------------+-----------------------+ .. note:: The application attribute **Profile** is required to be an exact match so that Aviatrix Controller can process in the SAML response. |pingone_idp_saml_attribute_mapping| .. _pingone_for_customers_user_fill_attribute: Assigning VPN Profile to Each SAML User ---------------------------------------------------------------- .. note:: This step is usually completed by the PingOne for Customers Admin. For each SAML application user, edit the user profile for assigning the VPN profile. #. On the top of the page, click **Identities**. #. Locate the user you want to edit. You can browse or search for users. #. Click the details icon to expand the user you want to edit, and then click the pencil icon. #. On the Profile tab, scroll down to the **Other** section. #. Find the new User attribute "accessprofile" and assign the VPN profile. .. note:: In this example, the VPN profile defined at the Controller is named **access-profile**. |pingone_idp_vpn_profile| .. _pingone_for_customers_validation: Validation ---------- Please refer to this `doc <https://docs.aviatrix.com/HowTos/Setup_Okta_SAML_Profile_Attribute.html#validation>`__ for more validation details. .. |pingone_idp_adding_attribute| image:: Setup_PingOne_SAML_Profile_Attribute_media/pingone_idp_adding_attribute.png .. |pingone_idp_adding_attribute_declared| image:: Setup_PingOne_SAML_Profile_Attribute_media/pingone_idp_adding_attribute_declared.png .. |profile_editor_add| image:: Setup_PingOne_SAML_Profile_Attribute_media/profile_editor_add.png .. |pingone_idp_setting_attribute| image:: Setup_PingOne_SAML_Profile_Attribute_media/pingone_idp_setting_attribute.png .. |pingone_idp_saml_attribute_mapping| image:: Setup_PingOne_SAML_Profile_Attribute_media/pingone_idp_saml_attribute_mapping.png .. |pingone_idp_vpn_profile| image:: Setup_PingOne_SAML_Profile_Attribute_media/pingone_idp_vpn_profile.png .. disqus:: <file_sep> =========================================================================================== Using Aviatrix Site2Cloud tunnels to access VPC Endpoints in different regions =========================================================================================== `VPC Endpoints <https://docs.aws.amazon.com/vpc/latest/userguide/vpce-interface.html>`_ in AWS allow you to expose services to customers and partners over AWS PrivateLink. In situations where allowing resources to be accessed directly from the Internet is undesirable, VPC Endpoints can enable internal VPC connectivity to resources in other accounts. One limitation of Endpoints is that it is a regional construct, meaning you can't use it to provide connectivity to resources across regions. In some cases it's not possible to move these workloads. This is where Aviatrix can help overcome that limitation. The end design will look similar to the diagram below. |image1| | Environment Requirements --------------------------------------------------------- Three VPCs. In this example there are 2 VPCs in US-East-1. One customer/partner VPC(10.10.10.0/24) with an Endpoint, and our VPC(10.10.11.0/24) with an Endpoint Service tied to an internal Load Balancer. There is 1 VPC(10.10.12.0/24) in US-East-2 that hosts our workload. A set of Aviatrix Gateways, 2 in our VPC in US-East-1, and 2 in the workload VPC in US-East-2. Deploying a set of HA Gateways is documented `here <https://docs.aviatrix.com/Solutions/gateway_ha.html>`_ Once deployed, a set of Site2Cloud tunnels will be built. Documentation for building a tunnel between Aviatrix Gateways is `here <https://docs.aviatrix.com/HowTos/site2cloud_aviatrix.html>`_ They should be built in an active-passive manner to avoid asymmetric routing in AWS. Step 1: Deploy an internal Load Balancer in AWS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From the EC2 section in the console, choose Load Balancers. |image2| Choose Network Load Balancer |image3| Give the LB a name, choose internal, program a listening port for your workload(80 for this test), and choose all availability zones in our US-East-1 VPC. |image4| On the Routing section, create a new target group using our workload, port 80. Target type will be instance. Health Checks will be TCP based. |image5| In the Targets section, choose the Aviatrix Gateways in our US-East-1 VPC and move them to Registered Targets. Click Next to review, then Create. Step 2: Attach an Endpoint Service to our new Load Balancer ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From the VPC section of the AWS console, choose Endpoint Services, then Create Endpoint Service. The new Load Balancer will be in the list as an available NLB. |image6| Update these options as needed. Create Service. |image8| That Service ARN will be what our customer uses to register a service in their VPC. |image9| Step 3: Create Endpoint in Customer VPC ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In the Customer VPC console, build a new Endpoint. Enter the ARN from the last step, and choose the Customer VPC to expose an endpoint in. Once built, the Endpoint DNS names can be used to route traffic. |image10| Step 4: Configure Destination NAT rules on Aviatrix Gateway ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A Destination NAT(DNAT) rule sends traffic from our VPC in US-East-1 to the workload VPC in US-East-2. On the controller, highlight the primary gateway deployed in our US-East-1 VPC. Click the Edit link. |image11| Scroll to the Destination NAT section and choose ADD NEW. Ensure Sync to HA Gateway is selected. Source CIDR will be the source of our US-East-1 VPC, 10.10.11.0/24. Destination CIDR will be the private IP of our Primary Gateway. In our example 10.10.11.5/32. Destination port in our example is 80. Protocol TCP. Connection is None. DNAT IPS in our example will be in the workload VPC available across our Site2Cloud tunnel. The server is 10.10.12.69. DNAT PORT is 80. Once filled out, hit SAVE, then UPDATE. Repeat this step in a second rule, updating the Destination CIDR to point to the private IP of the HA Gateway. |image12| |image13| Step 5: Test connections ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Ensure health checks on your Internal Load Balancer are healthy. Network Security Groups on your workload VPC(10.10.12.0/24) allow traffic from our VPC in US-East-1(10.10.11.0/24) Only 1 tunnel will be active in our scenario, and Aviatrix will update the route tables to point to the active tunnel. A simple way to test connectivity is to edit the /etc/hosts file on a linux instance to point to one of the DNS entries from the Endpoint in the Customer VPC. .. |image1| image:: VPCEndpoints/VPCEndpointsDiagram.png :scale: 50% .. |image2| image:: VPCEndpoints/image2.png :scale: 100% .. |image3| image:: VPCEndpoints/image3.png :scale: 75% .. |image4| image:: VPCEndpoints/image4.png :scale: 75% .. |image5| image:: VPCEndpoints/image5.png :scale: 75% .. |image6| image:: VPCEndpoints/image6.png :scale: 50% .. |image7| image:: VPCEndpoints/image7.png :scale: 50% .. |image8| image:: VPCEndpoints/image8.png :scale: 50% .. |image9| image:: VPCEndpoints/image9.png :scale: 100% .. |image10| image:: VPCEndpoints/image10.png :scale: 60% .. |image11| image:: VPCEndpoints/image11.png :scale: 100% .. |image12| image:: VPCEndpoints/image12.png :scale: 50% .. |image13| image:: VPCEndpoints/image13.png :scale: 50% .. disqus:: <file_sep>======================================= Field Notices ======================================= .. Note:: These field notices are provided as a service to our customers to proactively update them on major issues. This service is provided without any changes in our SLA. The information in this field notice will be updated as we learn more. 42. Field Notice ------------------------------------------------ **Date**: 04/13/2023 (The content of this field notice was revised for clarity on 04/17/2023.) **Issue Description**: For all current Controller software versions (all versions earlier than 7.0.1726), Aviatrix gateways are exporting files to a remote log collection entity. Starting in Controller software version 7.0.1726, instead of exporting files to a remote log collection entity, the Aviatrix Controller and gateways will start streaming the log lines being written to “Syslog” and “Auth.log”. When you use the default rsyslog server configuration suggested in `Aviatrix Documentation <https://docs.aviatrix.com/documentation/latest/platform-administration/aviatrix-logging.html#rsyslog-config-on-controller>`_, the logs streamed from the Controller and gateways will now have multiple files. Each file will be named with the application that generated the log. For example: All logs generated by the avx-gw-state-sync application would be re-directed to a file named "avx-gw-state-sync" on the log server. There will be a change in log format. You must change your syslog collectors and any related automation to accept the new log format. **Old format**: Mar 23 19:17:50 GW-UdpGateway-172.16.31.10 syslog 2023-03-05T19:17:50+00:00 GW-UdpGateway-172.16.31.10 avx-gw-state-sync[11249]: warn#011gateway_launcher/gateway_launcher.go:212#011daemon exited **New format**: Mar 23 19:17:50 GW-UdpGateway-172.16.31.10 avx-gw-state-sync[11249]: warn#011gateway_launcher/gateway_launcher.go:212#011daemon exited Prefix of old format: Mar 23 19:17:50 GW-gg-aws-usw2-s127-192.168.127.12 syslog 2023-03-05T19:17:50+00:00 Prefix of new format: Mar 23 19:17:50 GW-gg-aws-usw2-s127-192.168.127.12 41. Field Notice ------------------------------------------------ **Date:** 11/28/2022 **Change in Default Behavior** The latest 7.0 version of Aviatrix controller introduces a token verification to Aviatrix’s private API. Please take notice of a change in behavior beginning with Aviatrix Controller version 7.0. The 7.0 version introduces token-based Controller API operations that binds Aviatrix’s private API usage by Aviatrix API Legal Terms of Use*. To allow time for customers to make necessary changes in their infrastructure to support token-based API operations, we will not enforce a strict check for the token in the 7.0 release. Therefore, Aviatrix’s private API will continue to work for your existing use cases while running 7.0. However, token checking will be enforced in a later release. **Who is impacted?** Direct users of Aviatrix’s private API would be impacted by this change. There is no impact to users of Aviatrix Terraform Provider, Aviatrix CoPilot and Aviatrix Controller UI. Customers who have a Controller HA set up would also be affected. After upgrading to the release with token enforcement enabled, recreate your Controller HA configuration. Use HA script 2.0.1 or above. For details on HA script version, refer to Controller HA. **Recommended Solution:** To insulate customers from our evolving private API, Aviatrix strongly recommends you switch to Aviatrix Terraform Provider for all operations involving automation. If you have special need to still use Aviatrix’s private API, please reach out to Aviatrix Support by opening a ticket at Support Portal at https://support.aviatrix.com for guidance on Aviatrix’s private API token generation. Please mention your Aviatrix private API use case(s) in your ticket for us to better understand your automation needs, thereby enhancing our Terraform Support. **Aviatrix API Legal Terms of Use:** Use of Aviatrix API software (“Developer Software”) is governed by the Customer Terms of Use. We reserve the right to rescind any license to the Developer Software at our sole discretion without prior notice. DEVELOPER SOFTWARE IS MADE AVAILABLE BY US TO YOU ON AN “AS IS” AND “AS AVAILABLE” BASIS, (I) WITHOUT ANY REPRESENTATION OR WARRANTY OF ANY KIND, WHETHER EXPRESS, IMPLIED OR STATUTORY TO THE FULLEST EXTENT PERMITTED BY LAW AND (II) WITHOUT ANY OBLIGATION OF US TO PROVIDE TECHNICAL SUPPORT OR ANY INDEMNITY FOR YOUR ACCESS TO, AND USE OF, THE DEVELOPER SOFTWARE. 40. Field Notice ------------------------------------------------ **Date:** 11/04/2022 **High Priority Product Enhancement: AVX-31334** **Customers affected:** Any customer who: * Has `Encrypted Transitive Peering <https://docs.aviatrix.com/HowTos/TransPeering.html?highlight=encrypted%20transitive#encrypted-transitive-peering>`_ configured in their Aviatrix Controller. This feature was introduced in 2017 and has been superseded by Aviatrix Multi-CloudTransit, a much more advanced and efficient feature set with expanded capabilities. * Upgrades to 6.8.1398, 6.9.221, or future releases. **Issue Description:** The Encrypted Transitive Peering feature is deprecated. Functionality is replaced by `Aviatrix Multi-Cloud Transit <https://docs.aviatrix.com/HowTos/transit_gateway_peering.html>`_. Aviatrix recommends transitioning to Aviatrix Multi-Cloud Transit if you are using Encrypted Transitive Peerings. The process is straightforward we can help you make the transition. 39. Field Notice --------------------------------- **Date**: 08/16/2022 **High Severity Bug Fix: AVX-25425** **Affected Versions:** For customers running version 6.8 of the Aviatrix Controller and an older AMI released in February 2021 or prior. **Issue Description** Performing a dry run in 6.8 and later versions will fail if the CSP gateway’s AMI is based on IKE-type Racoon**, even though the upgrade from version 6.8 to 6.9 will succeed. This particular issue is reported in AVX-25425 and Aviatrix recommends performing an Image upgrade of gateways running IKE-type Racoon before performing the Software Upgrade. An image upgrade will upgrade the Gateway AMI version and thereby change the IKE-type on the gateways from Racoon to Strongswan. Please follow the steps below to perform a `Gateway Image Upgrade <https://docs.aviatrix.com/HowTos/gateway-image-migration.html>`_: Settings > Maintenance > Selective Gateway Upgrade > Select the gateway which lists IKE-type Racoon > click **Image Upgrade**. The Image Upgrade of the Gateway AMIs also includes several Critical security updates. .. note:: Gateways running older AMIs will not be able to upgrade from 6.9 to 7.0 without performing an Image Upgrade of Gateways to switch to IKE-type Strongswan. ** Racoon – Older IKE daemon (to be deprecated starting R7.0) Strongswan – Current IKE daemon and requires all gateways to run Strongswan prior to upgrading to R7.0 38. Field Notice ------------------ **Date** 08/09/2022 **High Severity Bug Fix: AVX-26277** **Affected Versions:** * For customers running 6.5 or older of the Aviatrix Controller **OR**, * For customers running 6.7 of the Aviatrix Controller, with release 6.7.1325 or older OR * For customers running 6.6 of the Aviatrix Controller, with release 6.6.5667 or older **AND** * AWS AMI version released between May 2022 and June 2022 (ver. 05102022). **Remediation:** This bug is fixed in 6.7.1376 or 6.6.5712. Due to the nature of this error, we strongly recommend that customers upgrade their platforms to the latest version, so that they do not face an outage, and are not blocked in their deployments or configuration changes.  **IMPORTANT NOTE FOR CUSTOMERS RUNNING 6.5 OR OLDER VERSIONS:** Customers running 6.5 or older versions of the Aviatrix Controller should refrain from upgrading their AMI image (to ver. 05102022) until they first upgrade their software version on the Controller to 6.6.5712 or 6.7.1376 by following the steps in “Instructions for Upgrade”. These customers also need to follow the `valid upgrade path <https://docs.aviatrix.com/HowTos/selective_upgrade.html#valid-upgrade-paths>`_. Any customers who are running 6.5 or older who have already upgraded their AMI image (to ver. 05102022) but have not yet seen the issue should proactively open a support ticket with Aviatrix Support for remediation.  **Issue Description & Impact** The AMI included a version of a database store that does not include automatic maintenance settings.  This will cause resource exhaustion on the Controller after a period of time depending on the level of activity the Controller sees.   Due to this bug, at least one of the following situations may occur: * Customers may come across an issue that will halt their ability to build environments or make configuration changes; they will see an error stating `StatusCode.RESOURCE_EXHAUSTED` and details will include `tcdserver : mvcc: database space exceeded`. * Gateway deployment or configuration changes are prevented or is not reflected in the data-plane. * Controller may lose connectivity with the Gateways. * Controller may report an incorrect Gateway status or “waiting” status. * When performing backup using *Settings > Maintenance > Backup & Restore > Backup Now*, an error appears `Gateway <name> not found` on the UI. **Instructions for Upgrade** If you have seen this issue already as described in the “*Issue Description & Impact*” section, it is mandatory to open a support ticket with Aviatrix Support first so that they can assist you in preparing for the bug fix and the subsequent upgrade. 1. Take a backup at *Controller > Settings > Maintenance > Backup & Restore > Backup Now*. If you encounter an issue generating the backup please contact Aviatrix Support. 2. Aviatrix requests that you upgrade your Controller and Gateways to the latest build in the release you are running.  * Please go through the release notes.  * Please review the field notices.  * Please go through the relevant upgrade instructions: Releases 6.4 and earlier or Releases 6.5 and later.  * **Make sure that all Gateways are in “UP” state.**  * **PLEASE DO NOT upgrade unless *Settings > Upgrade > Dry Run* is successfully completed for all Gateways.**  If dry run fails, please address the issue, or reach out to Aviatrix Support.  * Please upgrade to the latest build in the current release by entering the release that the Controller is currently running at *Settings > Upgrade > Target Release Version*. For example, if your Controller is running 6.7.1325, please enter “6.7” in the box without quotation marks.  * Attempt the backup again.  If you run into any issues during the upgrade, please reach out to Aviatrix Support by opening a ticket on the Support Portal at https://support.aviatrix.com.  37. Field Notice ------------------ **Date** 03/25/2022 **High Severity Bug Fix: AVX-18796** AVX-18796 fixes an issue with Controller to Gateway control channel recently. The recommended builds with the fix in 6.4, 6.5 and 6.6 releases are 6.4.3015, 6.5.3012, 6.6.5413 or later. Please refer to `Release Notes <https://docs.aviatrix.com/HowTos/Controller_and_Software_Release_Notes.html>`_ for more information on AVX-18796. We have published the following software patches to help identify if your Controller is at risk and address it: * **Detect AVX-18796**: This patch can be run anytime, and a **maintenance window is not required** as no configuration changes are made and there will be no impact to either the control plane or the data plane on the Controller and the Gateways. The patch will generate an email to the Controller’s admin email and provide a recommendation on next steps. * **AVX-18796: Check the SSH connectivity to all gateways**: This patch validates the state of the connection between the Controller and the Gateway. This patch can be run anytime, a **maintenance window is not required**. We recommend that you run this before applying the next patch to fix the issue. * **AVX-18796: Sanitize certificate state on all gateways**: This software patch will extend the lifetime of certificates to give you time to upgrade to address AVX-18796. This patch is **recommended to be run in a maintenance window**. This patch should only be run when "AVX-18796-Detect" software patch reports this message "Your network is being impacted by a known issue AVX-18796. Follow the intructions in the Field Notice". The patch will generate an email to the Controller’s admin email. When you apply any of the above patches, you will see a popup message like the one shown below – please ignore it and click on “OK”. Depending on the number of Gateways in your deployment, each of these patches can take a while to complete and for an email report to be sent out. |imagefn37| Aviatrix recommends the following be done, as soon as possible, to avoid any possibility of an outage due to this issue: - Check the Controller’s admin email address at "Settings/Controller/Email/ChangeAdminEmail" and make sure that it is correct. Please update this address if needed. - First, do a backup on your Controller in "Controller/Settings/Maintenance/Backup&Restore/Backup Now" - Make sure that **all your Gateways are in Up/Green state** - Go to "Controller/Settings/Maintenance/Software Patches" and click on "Update Available Patches" to see the three patches listed above. - Apply **"Detect AVX-18796"** patch first. Check your email for a report. - AVX_SW-PATCH_AVX-18796-FIXED: If the report indicates that your system is NOT impacted, no further actions are needed. We recommend that you stay on the latest supported releases - AVX_SW-PATCH_BEFORE-DANGER-ZONE: If the report informs you that your system IS affected and directs you to upgrade your Controller and Gateways, please proceed to the "Instructions for Upgrade" section below and **complete your upgrade, before the "due date"** as mentioned in the report - AVX_SW-PATCH_IN-DANGER-ZONE: If the report informs you that your system IS impacted and asks you to follow the instructions in the Field Notice, please do the following: - Please apply the software patch **"AVX-18796: Check the SSH connectivity to all gateways"**: If it succeeds, proceed to next step, else reach out to Aviatrix Support - Please apply the software patch **"AVX-18796: Sanitize certificate state on all gateways"** during a maintenance window. If it succeeds, please proceed to the "Instructions for Upgrade" section below and complete an upgrade on your Controller and Gateways and run **"Detect AVX-18796"** software patch again, to validate your network. If it fails, or if you have any questions or need assistance, please open a ticket with Aviatrix Support. - AVX_SW-PATCH_INACCESSIBLE-GW: If the report informs you that some of the Gateways are inaccessible, please try to fix them and apply this patch again. Reach out to Aviatrix Support if you are unable to fix your Gateways - AVX_SW-PATCH_UNEXPECTED-STATE: If the report indicates an error, please follow the directions in the email report and upload your Controller tracelogs and reach out to Aviatrix Support - AVX_SW-PATCH_INAPPLICABLE: If the report says that no additional action is needed. The patch is not applicable to your controller version. We recommend that you stay on the latest supported releases - Take a backup again at "Controller/Settings/Maintenance/Backup&Restore/Backup Now" **Instructions for Upgrade** - Take a backup at "Controller/Settings/Maintenance/Backup&Restore/Backup Now" - We request you to upgrade your Controller and Gateways to the latest build in the release you are running - Please go through the `release notes <https://docs.aviatrix.com/HowTos/Controller_and_Software_Release_Notes.html>`_ - Please review the `field notices <https://docs.aviatrix.com/HowTos/field_notices.html>`_ - Please go through the relevant upgrade instructions: `Releases 6.4 and earlier <https://docs.aviatrix.com/HowTos/inline_upgrade.html>`_ or `Releases 6.5 and later <https://docs.aviatrix.com/HowTos/selective_upgrade.html>`_ - **Make sure that all Gateways are in “Up/Green” state** - **PLEASE DO NOT upgrade, unless “Settings/Upgrade/Dry Run” is successfully completed.** If “Dry Run” fails, please address the issue or reach out to Aviatrix Support - Please upgrade to the latest build in the current release by entering the release that the Controller is currently running at “Settings/Upgrade/TargetReleaseVersion”. _(For example, if your Controller is running 6.4.3008, please enter “6.4” for “Settings/Upgrade/TargetReleaseVersion”)_ - Take a backup again - Please apply **"Detect AVX-18796"** software patch again to confirm that your network is free of AVX-18796 If you run into any issues during upgrade, you can reach out to Aviatrix Support by opening a ticket at Support Portal at https://support.aviatrix.com. 36. Field Notice ------------------ **Date** 01/11/2022 **High and Medium Severity Vulnerability - AVI-2021-0008** A new software release with a fix for this vulnerability was made available on Tuesday, January 11th, 2022. Aviatrix is strongly recommending you to upgrade to the new release at your earliest convenience. This vulnerability was discovered by Aviatrix engineering team and is not known to be exploited. Please refer to `Release Notes <https://docs.aviatrix.com/HowTos/UCC_Release_Notes.html>`_ and `Security Bulletin <https://docs.aviatrix.com/HowTos/security_bulletin_article.html#aviatrix-controller-and-gateways-unauthorized-access>`_ for more information. The upgrade mechanism is described in our documentation: * For 6.4 release, refer to `these instructions <https://docs.aviatrix.com/HowTos/inline_upgrade.html#how-to-upgrade-software>`_ * For 6.5 release, start `here <https://docs.aviatrix.com/HowTos/selective_upgrade.html#performing-a-platform-software-upgrade-dry-run>`_ If you run into any issues during upgrade, you can reach out to Aviatrix Support by opening a ticket at Support Portal at https://support.aviatrix.com 35. Field Notice ------------------ **Date** 10/25/2021 **Critical Vulnerability Security Patch - AVI-2021-0006** This security patch was made available Monday, October 25th, 2021 at 05:00PM PST. The critical vulnerability addressed by this patch was privately disclosed to Aviatrix. It affects services of Controller available on port 443 and would allow an unauthenticated attacker to execute code on the Controller. This could be mitigated by limiting access to the https/port 443 of the Controller, or by running a Web Application Firewall (WAF) in front of it. Please refer to our documentation to `secure the Controller access <https://docs.aviatrix.com/HowTos/FAQ.html#how-do-i-secure-the-controller-access>`_. Aviatrix is strongly recommending you to apply this patch at your earliest convenience. To apply a security patch, please refer to the following steps: * First, do a backup on your Controller in “Controller/Settings/Maintenance/Backup&Restore/Backup Now” * Go to “Controller/Settings/Maintenance/Software Patches” and click on “Update Available Patches” * You should see a new patch called: “AVI-2021-0006 Critical Vulnerability Security Patch” * Apply the patch, by clicking on the icon on the right and selecting “Apply Patch” * Take a backup again at “Controller/Settings/Maintenance/Backup&Restore/Backup Now” **Note:** * The security patch does not impact the data path or control path and can be executed without a maintenance window * This patch can be applied on releases 6.2 and higher * Aviatrix **strongly recommends** you to upgrade to releases 6.4 or higher. Please check out the `release notes <https://docs.aviatrix.com/HowTos/UCC_Release_Notes.html>`_ and follow the `upgrade instructions <https://aviatrix.zendesk.com/hc/en-us/articles/4403944002829-Aviatrix-Controller-Upgrade>`_ 34. Field Notice ------------------ **Date** 10/11/2021 **Security Fixes for 6.2, 6.3, 6.4, and 6.5 versions to improve security** These releases address a Denial-of-Service vulnerability and also improve the security on Controllers by automatically enabling `security group management <https://docs.aviatrix.com/HowTos/FAQ.html#enable-controller-security-group-management>`_ when the first account is added to the Controller, to deal with security updates in CloudFormation when launching new Controllers. Please upgrade to latest release: - 6.2: 6.2.2052 or later - 6.3: 6.3.2526 or later - 6.4: 6.4.2869 or later - 6.5: 6.5.1936 or later Refer to the `Security Alert <https://docs.aviatrix.com/HowTos/UCC_Release_Notes.html#security-note-6-5-1936-6-4-2869-6-3-2526-and-6-2-2052-10-11-2021>`_ for more details on these updates. Please upgrade to these builds, following the `upgrade instructions <https://aviatrix.zendesk.com/hc/en-us/articles/4403944002829-Aviatrix-Controller-Upgrade>`_, as soon possible. 33. Field Notice ------------------ **Date** 10/02/2021 **The latest 6.5, 6.4, 6.3, and 6.2 versions contain fixes for several vulnerabilities in the controller API** **Problem:** Several APIs used to upload configurations of certain services did not verify the authentication of the service or user executing the API call properly. Similar APIs designed to upload files from authenticated users did not properly sanitize their destination input, allowing directory traversal attacks which could eventually allow an authenticated attacker to execute code on the controller. **Recommended Solution:** Please upgrade to latest release: * 6.2: 6.2.2043 or later * 6.3: 6.3.2490 or later * 6.4: 6.4.2838 or later * 6.5: 6.5.1922 or later Credit: Aviatrix would like to thank the team at Tradecraft ( https://www.wearetradecraft.com/ ) for the responsible disclosure of these issues. Release notes also available on: https://docs.aviatrix.com/HowTos/UCC_Release_Notes.html Please upgrade to these builds, following the `upgrade instructions <https://aviatrix.zendesk.com/hc/en-us/articles/4403944002829-Aviatrix-Controller-Upgrade>`_, as soon possible. 32. Field Notice ------------------ **Date** 09/09/2021 **In rare occasions, Controller backup file could get corrupted, resulting in gateways being shown as “down” if used for a Controller restore** **Problem:** We have observed, on one occasion, that the Controller’s backups were corrupt. If the backup file does get corrupt, the size of the backup file will be much larger than expected (in tens of MB or larger - much larger than the typical sizes ≤1 MB). The size would be the only indication of the backup file corruption. This issue is being tracked as AVX-14852 **Recommended Solution:** A fix for this issue is in works and will be released for the supported releases (6.2, 6.3, 6.4, 6.5) on 9/11/2021. Please upgrade to these builds, following the `upgrade instructions <https://aviatrix.zendesk.com/hc/en-us/articles/4403944002829-Aviatrix-Controller-Upgrade>`_, as soon possible. We request that you inspect your backup file size and if it is larger than expected, please go to Controller/Settings/Backup and click on “backup now” while not running any other operation on the Controller - and compare the backup file sizes. * If the new backup file size is as expected, please save a copy. And upgrade to the new builds with fix for AVX-14852 * If the new backup file size continues to be large, please reach out to Aviatrix Support at https://support.aviatrix.com 31. Field Notice ------------------ **Date** 08/06/2021 **After a Gateway Replace operation on version 6.4 or later, the Site2Cloud connections on the Gateway might not come up** **Problem:** If you run a "Gateway Replace" operation from a Controller running version 6.4 or later, on a gateway which was created when this Controller was running on 6.3 or earlier, the Site2Cloud connections on this Gateway might not be able to come up The default IPSec tunnel management software was changed in the `Gateway Images <https://docs.aviatrix.com/HowTos/image_release_notes.html>`_ associated with `version 6.4 <https://docs.aviatrix.com/HowTos/UCC_Release_Notes.html>`_ and later. Any Gateway which might have been created while running version 6.3 or older will be using the older IPSec tunnel management software. While the Controller ported the config from the old Gateway to the new Gateway, one of the field's default setting has changed. This setting could come into play based on the devices that this Gateway has established Site2Cloud tunnels and might result in the Site2Cloud tunnel not coming up. This was `documented in the 6.4.2499 release notes <https://docs.aviatrix.com/HowTos/UCC_Release_Notes.html#behavior-change-notice>`_. You can find `more information <https://aviatrix.zendesk.com/hc/en-us/articles/4406236429581>`_ on our `Support Portal <https://support.aviatrix.com/>`_ about this issue **Recommended Solution:** If the Site2Cloud tunnel(s) does/do not come up on a Gateway after a "Gateway Replace" operation in 6.4, please go to Controller/Site2Cloud, select the tunnel, click on edit and update the "Remote Identifier" field. If you have any issues, please open a ticket on our `Support Portal <https://support.aviatrix.com/>`_. 30. Field Notice ------------------ **Date** 07/19/2021 **Upgrade from 6.3 to 6.4 could cause gateways to be in down/polling state if any of them have more than 44 characters** **Problem:** We had announced in Field Notice 0027(https://docs.aviatrix.com/HowTos/field_notices.html#field-notice-0027-2021-04-29) that gateway names are required to be 50 characters or less. We have noticed that during upgrade operations, from 6.3 to 6.4, we are further limited on the gateway name length to 44 characters due to a new default behavior introduced in 6.4. From 6.4, we started using self-signed certs to authenticate management/control communication between controller and gateways. The default cert domain used is "aviatrixnetwork.com". This ends up using 20 characters from our internal max of 64 characters - leaving only 44 characters for the gateway names(including "-hagw", if the gateway has an HA gateway). If the controller has any gateways with names longer than 44 characters, that gateway and the following gateways in the upgrade process could show up as "down/polling" state on the gateway page. **Recommended Solution:** * If all your gateway names(including ha gateways) have less than 44 characters, you are not impacted by this issue * If the name length of any of your gateways is 45 to 50 characters, you have two options * While in 6.3, you can delete them and recreate them with names shorter than 44 characters (39 chars max, if you plan to have HA gateway, to account for 5 extra characters in "-hagw" which will be appended to the HA gateway name) * Upgrade to 6.4. Some gateways will not be in "green/up". To recover, head to Controller/Onboarding and click in "AWS" icon and enter "av.com". All gateways should come up in "green/up" status. If not, please perform "Troubleshoot/Diagnostics/Gateway/ForceUpgrade" on the affected gateways. * If any of your gateway names have more than 50 characters (including "-hagw") please schedule a downtime, delete them, and create them again with shorter names(<44 chars, <39 chars if you have an HA for them). If you need further support, please head to our support portal at https://support.avaiatrix.com and open a new ticket. 29. Field Notice ------------------ **Date** 05/11/2021 **Do not upgrade Controllers to R6.4.2499 if you have CloudN’s in your network** Due to some unresolved issues in R6.4.2499, we strongly ask that you do not upgrade your Aviatrix Controller or CloudN devices to R6.4.2499. If you upgrade to this build, your CloudNs could fail, impacting your network operations. Please look to our `release notes <https://docs.aviatrix.com/HowTos/UCC_Release_Notes.html>`_ on future 6.4 builds for guidance on upgrading your network when CloudN devices are involved. We apologize for any inconvenience. 28. Field Notice ------------------ **Date** 05/03/2021 **End of Life (EOL) announcement for Gateway AMI's** Gateway AMI's based on old opensource OS versions are designated EOL effective 5/3/2021. Aviatrix is discontinuing support because these operating systems have reached their end of standard support from the provider. What is the impact if you remain on a deprecated release that is designated EOL? * The Aviatrix Support team does not provide assistance on EOL releases. * Patches for known issues and vulnerabilities are no longer provided. **Recommendation** Replace the deprecated gateways and use the new AMIs. To update your Aviatrix gateways, you may need to upgrade your Aviatrix Controller first. The Gateway page lists the AMIs for all your gateways. Go to "Gateway->Column View->Select Gateway Image Name->Apply Columns". For more information, see https://docs.aviatrix.com/HowTos/image_release_notes.html. Discover all deprecated AMIs. Download the "Generate list of Aviatrix Gateways using deprecated AMIs" utility from "Settings->Maintenance->Software Patches->Update Available Patches". Run this utility to send an email to the admin with a list of all gateways running deprecated AMI's. We recommend that you replace gateways running on old opensource OS versions based AMIs before upgrading to 6.4. Upgrade your Aviatrix Controller to the latest 6.3 release following the instructions at https://docs.aviatrix.com/HowTos/inline_upgrade.html and replace these gateways using the procedures at https://docs.aviatrix.com/HowTos/image_release_notes.html#existing-customers-gateway-image-upgrade. You can also use the following Aviatrix API's to replace your gateways programmatically: * Login and generate CID: curl --location -g --request POST 'https://{{controller_hostname}}/v1/api' --form 'action="login"' --form 'username="admin"' --form 'password="{{<PASSWORD>}}"' * Use the CID generated above to resize gateway and wait till it is complete, before running on another gateway : curl --location -g --request POST 'https://{{controller_hostname}}/v1/api' --form 'action="replace_gateway"' --form 'CID="{{CID}}"' --form 'gateway_name="{{gateway_name_in_controller}}"' * Check the Gateway AMI information: curl --location -g --request GET 'https://{{controller_hostname}}/v1/api?action=get_gateway_info&CID={{CID}}&gateway_name={{gateway_name_in_controller}}' Aviatrix strongly recommends that you keep your Aviatrix Network up to date with the latest releases. We also strongly suggest that you periodically check the AMI versions on all your gateways and update them to get the latest fixes for known issues and vulnerabilities. If you have any difficulties in upgrading your Gateways or have any questions about your Aviatrix network, please open a `support ticket <https://aviatrix.zendesk.com>`_. 27. Field Notice ------------------ **Date** 04/29/2021 **Gateway names longer than 50 bytes can cause issues** **Problem** In Version 6.2 and prior, customer may create a spoke or transit gateway name exceeding 50 Bytes. During peer creation a failure may occur if the peering name (concatenation of spoke-to-transit, spoke-to-spoke, etc) exceeds 120 Bytes and throws an error. (example) Error: command create_peer_xx_gw failed due to exception errors fully qualified namespace peering_info.xxxxxxxx is too long (max is 120 bytes) **Recommended Solution** Version 6.2 and prior: If spoke or transit name exceeds 50 Bytes, manually delete and re-create gateway with name limited to 50 Bytes or less. Version 6.3 and higher: Newly created spoke and transit gateway names are checked and limited to 50 Bytes or less. However, if there are any residual gateways (6.2 and prior) with name exceeding 50 Bytes they must be deleted and re-created to avoid this issue. 26. Field Notice ------------------ **Date** 04/28/2021 **End of Life (EOL) announcement for Aviatrix VPN Clients for old opensource OS versions** VPN Clients running on old opensource OS versions are designated EOL effective immediately. VPN Clients running on old opensource OS versions are designated EOL effective 6/1/2021. Aviatrix is discontinuing support because these operating systems have reached their end of standard support from the provider. What is the impact if you remain on a deprecated release that is designated EOL? The Aviatrix Support team does not provide assistance on EOL releases. Patches for known issues and vulnerabilities are not provided. Recommendation Please upgrade to one of the supported `Aviatrix VPN Clients <https://docs.aviatrix.com/Downloads/samlclient.html>`_. If you have any difficulties in upgrading your Aviatrix VPN Client, please contact your Aviatrix Network Admin and have them open a `support ticket <https://aviatrix.zendesk.com/>`_. 25. Field Notice ------------------ **Date** 04/26/2021 **End of Life (EOL) announcement for 5.4, 6.0, 6.1 releases** Following up on Field Notice `0012 <https://docs.aviatrix.com/HowTos/field_notices.html#field-notice-0012-2020-08-07>`_ and `0016 <https://docs.aviatrix.com/HowTos/field_notices.html#field-notice-0016-2020-12-22>`_, we are announcing EOL and End of Support for releases 5.4, 6.0 and 6.1. The R5.4 EOL date is 6/1/2021, the R6.0 EOL date is 6/19/2021 and the R6.1 EOL date is 8/31/2021. What is the impact if you remain on a deprecated release that is designated EOL? * The Aviatrix Support team does not provide assistance on EOL releases. * Patches for known issues and vulnerabilities are not provided. * Enabling the remote SSH support option as well as sending logs and diagnostics to Aviatrix Support may not work. * The default SMTP on the Controller cannot send Alerts. **Recommendation:** Please use the following processes to upgrade your Aviatrix network: * https://docs.aviatrix.com/HowTos/UCC_Release_Notes.html * https://docs.aviatrix.com/Support/support_center_operations.html#pre-op-procedures * https://docs.aviatrix.com/HowTos/inline_upgrade.html If you have any difficulties upgrading your Aviatrix network, please open a `support ticket <https://aviatrix.zendesk.com/>`_. 24. Field Notice ------------------ **Date** 04/25/2021 **Controller HA Code Improvements for release R6.3 and R6.4** Problem: Improved Controller HA process to avoid corner cases related to Controller HA restore failures. What is Impacted? Controllers deployed in AWS with the "Controller HA" process enabled. Recommendation For Controllers running in AWS with the Controller HA process enabled, Aviatrix strongly recommends that you `disable <https://docs.aviatrix.com/HowTos/controller_ha.html#steps-to-disable-controller-ha>`_ and `reenable <https://docs.aviatrix.com/HowTos/controller_ha.html#steps-to-enable-controller-ha>`_ the "Controller HA" process as soon as possible to pick up the latest version of the software. This operation should not impact the Controller that is in operation but we do recommend that you follow our `pre-operation recommendations <https://docs.aviatrix.com/Support/support_center_operations.html#pre-op-procedures>`_. Please see https://docs.aviatrix.com/HowTos/controller_ha.html for more information on Controller HA. Please verify that your `Controller HA <https://docs.aviatrix.com/HowTos/controller_ha.html?#faq>`_ version is 1.6 or higher. Please check `Controller HA release notes <https://docs.aviatrix.com/HowTos/controller_ha.html#changelog>`_. Please note that enabling and disabling the Controller HA process is a prerequisite for upgrading to release R6.4, which is scheduled to be released soon. * https://docs.aviatrix.com/HowTos/UCC_Release_Notes.html * https://docs.aviatrix.com/Support/support_center_operations.html#pre-op-procedures * https://docs.aviatrix.com/HowTos/inline_upgrade.html 23. Field Notice ------------------ **Date** 04/24/2021 **Default SMTP Service Down on releases < 6.2.1955** **Problem:** The default SMTP service used by Aviatrix has been impacted in releases older than 6.2.1955. Alerts generated from the Controller will fail to reach the admin by email. Gateways are not impacted. Password recovery by email and sending OpenVPN profiles via email will also be impacted. **Who is impacted?** Any Controller running versions older than R6.2.1955 that also does not have an SMTP server configured to override the default service. **Recommended Solution:** To resolve this issue, please upgrade your Controller to the latest R6.2(>=6.2.1955) or R6.3 software version following the instructions at https://docs.aviatrix.com/HowTos/inline_upgrade.html, or configure your own SMTP service to override the default SMTP service using the instructions at https://docs.aviatrix.com/HowTos/alert_and_email.html. This issue will not be addressed in 5.4, 6.0 and 6.1 releases so if your Controller is running one of these releases, Aviatrix strongly encourages you to upgrade to the 6.3 release. 22. Field Notice ------------------ **Date** 04/19/2021 **Deprecated build 6.3.2405** Last week, Aviatrix published R6.3.2405 and due to the incorrect handling of a corner case issue we decided to deprecate R6.3.2405. If you upgraded to R6.3.2405 your controller might incorrectly notify you that there is a newer release, since you are not running the current R6.3.2364 release. We request that you ignore this upgrade notification. We will be releasing a new build > R6.3.2405 later today. You can safely upgrade to the new release. **Recommendation:** Please use the following processes to upgrade your Aviatrix network: * https://docs.aviatrix.com/HowTos/UCC_Release_Notes.html * https://docs.aviatrix.com/Support/support_center_operations.html#pre-op-procedures * https://docs.aviatrix.com/HowTos/inline_upgrade.html If you have any questions about your Aviatrix network, please open a `support ticket <https://aviatrix.zendesk.com/>`_. .. |image1404Controller| image:: field_notices_media/1404Controller.png :width: 600 .. |image1804Controller| image:: field_notices_media/1804Controller.png :width: 600 .. |imagefn14| image:: field_notices_media/fn14.png :width: 600 .. |imagefn37| image:: field_notices_media/fn37.png :width: 400 <file_sep> ========================================================================================== GCP Multi-Peer BGP over LAN Workflow ========================================================================================== Introduction ============ Transit BGP to LAN allows Aviatrix Transit Gateways to communicate with multiple instances in the same VPC in GCP without running any tunneling protocol such as IPsec or GRE. One use case is to interoperate with third-party virtual appliances such as SD-WAN cloud instances that do not have the capability to support BGP over any tunneling protocols. For example, integrating with SD-WAN gateways can be deployed as below, where Aviatrix Multi-cloud Transit Gateways connect to third-party cloud instances in the same VPC in GCP: |sd_wan_integ_gcp| This document describes a step-by-step instruction on how to build Aviatrix Transit Gateway to External Device using BGP over LAN. In this Tech Note, you will learn the following: #. Workflow on `deploying Aviatrix Transit Solution <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_workflow.html#deploy-aviatrix-multi-cloud-transit-solution>`_ #. Workflow on `launching third-party cloud instances <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_workflow.html#launch-third-party-cloud-instances>`_ #. Workflow on `building BGP over LAN <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_workflow.html#build-bgp-over-lan>`_ For other BGP over LAN workflows, see the documents below: - `AWS Multi-cloud Transit BGP over LAN Workflow <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_workflow.html>`_ - `Azure Multi-cloud Transit BGP over LAN Workflow <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_azure_workflow.html>`_ - `Aviatrix BGP over LAN with Cisco Meraki in AWS <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_with_aws_meraki_workflow.html>`_ For more information about Multi-Cloud Transit Network and External Device, see the documents below: - `Multi Cloud Global Transit FAQ <https://docs.aviatrix.com/HowTos/transitvpc_faq.html#multi-cloud-global-transit-faq>`_ - `Global Transit Network Workflow Instructions (AWS/Azure/GCP/OCI) <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ - `Aviatrix Transit Gateway to External Devices <https://docs.aviatrix.com/HowTos/transitgw_external.html>`_ - `Transit Network Design Patterns <https://docs.aviatrix.com/HowTos/transitvpc_designs.html>`_ .. important:: - This solution supports only `ActiveMesh 2.0 <https://docs.aviatrix.com/HowTos/activemesh_faq.html#what-is-activemesh-2-0>`_, please check this doc `How to migrate to ActiveMesh 2.0 <https://docs.aviatrix.com/HowTos/activemesh_faq.html#how-to-migrate-to-activemesh-2-0>`_ for migration detail. - This solution is available in Azure when connecting to a single BGP peer. Multi-peer BGP is supported in GCP and AWS. The workflow with GCP here is just an example. Please adjust the topology depending on your requirements. - GCP does not allow interfaces to be added to an instance after deployment. Verify the design before creating the instances to make sure they have all the interfaces required. The key ideas for this solution are: ---------------------------------------- - A BGP session establishes between third-party cloud instances and Aviatrix Transit Gateways via each LAN interface in the same VPC. - Dataplane traffic also runs between third-party cloud instances and Aviatrix Transit Gateways via each LAN interface without a tunnel protocol such as IPsec or GRE. Prerequisite ==================== - This feature is available starting in Aviatrix software version 6.6. `Upgrade <https://docs.aviatrix.com/HowTos/inline_upgrade.html>`_ Aviatrix Controller to at least version 6.6. - Third-party cloud instance has high throughput supported. Deploying Aviatrix Multi-Cloud Transit Solution ================================================= Refer to `Global Transit Network Workflow Instructions <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ for the below steps. Please adjust the topology depending on your requirements. 1. Deploy `Aviatrix Multi-Cloud Transit Gateway and HA <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html#step-2-deploy-the-transit-aviatrix-gateway>`_ with insane mode encryption enabled in Transit VPC. 2. Deploy `Spoke Gateway and HA <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html#step-3-deploy-spoke-gateways>`_ with insane mode encryption enabled in Spoke VPC(s). 3. Attach Spoke Gateways to Transit Network <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html#step-4-attach-spoke-gateways-to-transit-network>`_. Launching Third-Party Cloud Instances ================================================================================ Deploy third-party cloud instances with an interface in the same VPC as the Aviatrix Transit Gateway. #. Create a third-party cloud instance and put MGMT interface in public gateway subnet. #. Create a new WAN subnet and dedicated routing table for WAN interface if needed. #. Create a new LAN subnet and a dedicated routing table for the LAN interface. #. Make sure the IP forwarding function is enabled on the third-party cloud instances. .. important:: GCP allows a maximum of 8 interfaces per instance, and the max limit depends on the number of vCPUs. Due to this limitation, the solution supports 7 BGP peers without FireNet enabled and 6 BGP peers with FireNet enabled. Building BGP over LAN ================================================ Deploy the Aviatrix Transit Gateway with all the required BGP interfaces. #. Log in to the Aviatrix Controller. #. Navigate to Multi-cloud Transit > Setup > Transit tab. #. Set the parameters to deploy the Aviatrix Transit Gateway. +----------------------------------+--------------------------------------------------------------------------------------------------+ | Cloud Type | GCloud | +----------------------------------+--------------------------------------------------------------------------------------------------+ | Gateway Name | Provide a unique name to identify the Transit Gateway | +----------------------------------+--------------------------------------------------------------------------------------------------+ | Access Account Name | Select the appropriate GCP account | +----------------------------------+--------------------------------------------------------------------------------------------------+ | VPC ID | Select the VPC where the Transit Gateway will be deployed | +----------------------------------+--------------------------------------------------------------------------------------------------+ | Public Subnet | Select the subnet the Transit Gateway interface will use | +----------------------------------+--------------------------------------------------------------------------------------------------+ | Zone | Select the Availability Zone where the Transit Gateway will be deployed | +----------------------------------+--------------------------------------------------------------------------------------------------+ | Gateway Size | Select an instance size that allows interfaces to be created for all BGP peers | +----------------------------------+--------------------------------------------------------------------------------------------------+ | Insane Mode Encryption | Check this box to enable high throughput | +----------------------------------+--------------------------------------------------------------------------------------------------+ | BGP over LAN | Check this box and then **Add Interface** for all BGP peers | +----------------------------------+--------------------------------------------------------------------------------------------------+ |transit_bgp_over_lan_gcloud| Enable HA on the Aviatrix Transit Gateway, deploying the HA Gateway in a different Availability Zone. |transit_bgp_over_lan_gcloud_ha| Configuring BGP over LAN on Aviatrix Transit Gateway ------------------------------------------------------------ 1. Log in to the Aviatrix Controller. 2. Navigate to Multi-Cloud Transit > Setup > External Connection tab > Connect to VGW / External Device / Azure VNG section. 3. Select the options External Device > BGP > LAN. 4. Enter the following information in the fields below. +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | VPC Name / Site ID | Select the Transit VPC ID where the Transit Gateway was deployed. | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Connection Name | Provide a unique name to identify the connection to external device. | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Aviatrix Gateway BGP ASN | Configure a BGP AS number that the Transit Gateway will use to exchange routes with the external device. | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Primary Aviatrix Gateway | Select the Transit Gateway. | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Enable Remote Gateway HA | Check this box to connect two external devices. | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | BGP Activemesh | Check this box to enable full mesh BGP connections to the external devices. | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Remote BGP AS Number | Configure the BGP AS number that the third-party cloud instance will use to exchange routes with the Aviatrix Transit Gateway. | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Remote LAN IP | Use the private IP of the LAN interface of the third-party cloud primary instance. | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Local LAN IP | If blank, the controller will assign an IP in the same subnet as the Remote LAN IP. Optionally, configure a specific IP within the same subnet as the Remote LAN IP. | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Remote BGP AS Number (Backup) | Configure the BGP AS number that the third-party HA cloud instance will use to exchange routes with the Aviatrix HA Transit Gateway. | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Remote LAN IP (Backup) | Use the private IP of the LAN interface of the third-party HA cloud instance. | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Local LAN IP (Backup) | If blank, the controller will assign an IP in the same subnet as the Remote LAN IP (Backup). Optionally, configure a specific IP within the same subnet as the Remote LAN IP (Backup). | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ 5. Click **Connect** to generate the BGP sessions. |transit_s2c_conn_bgp_peer_gcloud| 6. Create a Site2Cloud connection for each BGP peer. (Optional) Downloading the BGP over LAN configuration sample from Aviatrix Controller -------------------------------------------------------------------------------------------- #. Navigate to Site2Cloud > Setup. #. Select the previously created connection(s). #. Click **Edit.** #. Select the Vendor, Platform and Software that correspond to the third-party device. #. Click **Download Configuration.** Configuring BGP over LAN on the Third-Party Cloud Instance(s) ----------------------------------------------------------------------------------- #. (Optional) Open the downloaded BGP over LAN configuration file. #. Configure the relevant BGP over LAN information on the third-party cloud instance(s). Verifying the Connection Status on Aviatrix Controller ---------------------------------------------------------------------- 1. Navigate to Site2Cloud > Setup. 2. Find the previously created connection(s). 3. Check the tunnel status. |transit_check_tunnel_gcloud| 4. Navigate to Multi-Cloud Transit -> List. 5. Select the previously created Aviatrix Transit Gateway. 6. Click **Details/Diag**. 7. Scroll down to the Connections > On-prem Connections section. 8. Under On-prem Connections, find the previously created connection(s). 9. Check the tunnel status in the Status column. |transit_verify_bgp_status_onprem_gcloud| Verifying the BGP session status on Aviatrix Controller -------------------------------------------------------------- #. Navigate to Multi-Cloud Transit > BGP. #. Find the previously created connection(s). #. Check the Neighbor status. |transit_verify_bgp_status_gcloud| Ready to Go ================= At this point, run connectivity and performance test to ensure everything is working correctly. .. |transit_bgp_over_lan_gcloud| image:: transit_gateway_external_device_bgp_over_lan_simulation_workflow_media/transit_bgp_over_lan_gcloud.png :scale: 50% .. |transit_bgp_over_lan_gcloud_ha| image:: transit_gateway_external_device_bgp_over_lan_simulation_workflow_media/transit_bgp_over_lan_gcloud_ha.png :scale: 50% .. |transit_s2c_conn_bgp_peer_gcloud| image:: transit_gateway_external_device_bgp_over_lan_simulation_workflow_media/transit_s2c_conn_bgp_peer_gcloud.png :scale: 50% .. |transit_verify_bgp_status_onprem_gcloud| image:: transit_gateway_external_device_bgp_over_lan_simulation_workflow_media/transit_verify_bgp_status_onprem_gcloud.png :scale: 50% .. |transit_check_tunnel_gcloud| image:: transit_gateway_external_device_bgp_over_lan_simulation_workflow_media/transit_check_tunnel_gcloud.png :scale: 50% .. |transit_verify_bgp_status_gcloud| image:: transit_gateway_external_device_bgp_over_lan_simulation_workflow_media/transit_verify_bgp_status_gcloud.png :scale: 50% .. |sd_wan_integ_gcp| image:: transitvpc_designs_media/sd_wan_integ_gcp.png :scale: 30% .. disqus:: <file_sep> ========================================================= Example Config for Palo Alto Network VM-Series in OCI ========================================================= In this document, we provide an example to set up the VM-Series for you to validate that packets are indeed sent to the VM-Series for VCN to VCN and from VCN to internet traffic inspection. VM-Series in AWS can be set up using the guide `Palo Alto Networks VM-Series AWS Example <https://docs.aviatrix.com/HowTos/config_paloaltoVM.html#example-config-for-palo-alto-network-vm-series>`_. VM-Series in Azure can be set up using the guide `Palo Alto Networks VM-Series Azure Example <https://docs.aviatrix.com/HowTos/config_PaloAltoAzure.html#example-config-for-palo-alto-networks-vm-series-in-azure>`_. The Aviatrix Firewall Network (FireNet) workflow launches a VM-Series at `this step <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#launching-and-associating-firewall-instance>`_. After the launch is complete, the console displays the VM-Series instance with its public IP address of management interface and allows you to download the .pem file for SSH access to the instance. Below are the steps for the initial setup. Downloading VM-Series Access Key ------------------------------------------------ After `launching and associating a firewall instance <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#launching-and-associating-firewall-instance>`_, click **Download** to download the .pem file. If you get a download error, usually it means the VM-Series is not ready. Wait until it is ready, refresh the browser and then try again. |access_key| Resetting VM-Series Password ------------------------------------------- For Metered AMI, open a terminal and run the following command. .. tip :: Once you download the .pem file, change the file permission to 600. If you are asked to enter a password during the login, the VM-Series is still not ready. Wait and try again. It usually takes up to 15 minutes for the VM-Series to be ready. When the VM-Series is ready, you will not be asked for a password anymore. :: ssh -i <private_key.pem> admin@<public-ip_address> configure set mgt-config users admin password commit For BYOL, open a terminal and run the following command. :: ssh -i <private_key.pem> admin@<public-ip_address> configure set mgt-config users admin password set deviceconfig system dns-setting servers primary <ip_address> commit Terminate the SSH session. Logging in to VM-Series ------------------------------------ Go back to the Aviatrix Controller. Go to Firewall Network workflow, Step 2a. Click on the `Management UI`. It takes you the VM-Series you just launched. Login with Username "admin." The password is the password you set at the previous step. Activating VM license ------------------------------ Dynamic Updates ---------------------------- 1. From Device > Dynamic Updates > Click on **Check Now** > download and then install latest versions of a. Applications and Threats b. Wildfire updates. 2. Click on **Check Now** again > download and then install latest version of Antivirus. Configuring VM-Series ethernet1/1 with WAN Zone --------------------------------------------------------------------- After logging in, select the **Network** tab and you should see a list of ethernet interfaces. Click ethernet1/1 and configure as the following screenshot. 1. Select the **Network** tab. 2. Click **ethernet1/1**. 3. Select "layer3" for Interface Type. 4. Select the **Config** tab in the popup Ethernet Interface window. 5. Select the default for Virtual Router at Config tab. 6. Click **New Zone for Security Zone** to create a WAN zone. 7. At the next popup screen, name the new zone "WAN" and click **OK**. |new_zone| Continue, 8. Select the **IPV4** tab in the popup Ethernet Interface window. 9. Select **Static**. 10. Add the Private IP of eth1 firewall WAN NIC, as shown below. |ipv4| 11. Click **Commit**. Once Commit is complete, you should see the Link State turn green at the Network page for ethernet1/1. Configuring VM-Series ethernet1/2 with LAN Zone ------------------------------------------------------------------- Repeat the steps in the "Configuring VM-Series ethernet1/1 with WAN Zone" section above for ethernet1/2. Name the new zone LAN. Also, allow ICMP on LAN interface for health check, as shown below. 1. Go to Network > Interface Mgmt under Network Profiles and click **Add**. #. Give any name in Interface Management Profile, check Ping or ICMP checkbox under Administrative Management Service, and click **OK**. #. Attach Profile with LAN interface: go to Network > Interfaces > Select LAN Ethernet Interface > Advanced > Management Profile > Select appropriate profile. |ipv4_2| Click Commit. Once Commit is complete, you should see the Link State turn green at the Network page for ethernet1/2. Configuring Allow All Policies -------------------------------------- Go to Policies > Security. Click **Add**. 1. Name the policy > Allow-All. #. Source tab -> Any. #. Destination tab -> Any. #. Application tab -> Any. #. Click **OK**. Configuring NAT for Egress ---------------------------------- If you would also like to enable NAT to test egress, follow these steps. 1. Policies > NAT > Click **Add** > Select the **General** tab and give it a name > Click **Original Packet**. 2. At Source Zone, click **Add** and select **LAN**. 3. At Destination Zone, select **WAN**. 4. At Destination Interface, select **Ethernet1/1**, as shown below. |nat_original_packet| 5. Click **Translated Packet**. 6. At Translation Type, select **Dynamic IP And Port**. 7. At Address Type, select **Interface Address**. 8. At Interface, select **ethernet1/1**, as shown below. |nat_translated_packet| Setting up API Access ------------------------------ In order for the Aviatrix Controller to automatically update firewall instance route tables, monitor the firewall instance health and manage instance failover, you need to setup API access permissions. Follow `the instructions here <https://docs.aviatrix.com/HowTos/paloalto_API_setup.html>`_ to enable API access. Ready to Go ------------------- Now your firewall instance is ready to receive packets. For example, launch one instance in Spoke-1 VCN and Spoke-2 VCN. From one instance, ping the other instance. The ping should go through. Viewing the Traffic Log --------------------------------- You can view if traffic is forwarded to the firewall instance by logging in to the VM-Series console. 1. Click **Monitor**. 2. Start ping packets from one Spoke VCN to another Spoke VCN. .. |access_key| image:: config_paloaltoVM_media/oci/access_key.png :scale: 40% .. |new_zone| image:: config_paloaltoVM_media/new_zone.png :scale: 30% .. |ipv4| image:: config_paloaltoVM_media/oci/ipv4.png :scale: 40% .. |ipv4_2| image:: config_paloaltoVM_media/oci/ipv4_2.png :scale: 40% .. |nat_original_packet| image:: config_paloaltoVM_media/oci/nat_original_packet.png :scale: 40% .. |nat_translated_packet| image:: config_paloaltoVM_media/oci/nat_translated_packet.png :scale: 40% .. disqus:: <file_sep> ========================================================= TGW Build ========================================================= At the Build stage, you attach VPCs to an AWS Transit Gateway (TGW) and security domain. Each VPC can only be attached to one security domain. The AWS Transit Gateway (TGW) Orchestrator Build workflow is a one-step instruction to attach a VPC to an AWS Transit Gateway and a security domain. For background information, refer to the `TGW Orchestrator FAQ <https://docs.aviatrix.com/HowTos/tgw_faq.html>`_. Before you can attach VPCs, you must have at least completed `Step 1 <https://docs.aviatrix.com/HowTos/tgw_plan.html#create-aws-tgw>`_ in Plan page. Attaching a VPC to a TGW ------------------------------------------- ==================================================== ========== **Setting** **Value** ==================================================== ========== Region Select a region where AWS Transit Gateway resides. VPC Account An `Aviatrix account <http://docs.aviatrix.com/HowTos/aviatrix_account.html#account>`_ that corresponds to an IAM role or account in AWS. VPC Name Select a VPC in the VPC Account. TGW Account Select an access account where AWS Transit Gateway resides. TGW Name The name of the AWS Transit Gateway in the AWS Transit Gateway Account. Security Domain Name Select from a dropdown menu domain. Advanced (Optional) Select Subnets Available in R4.3 and later. When selected, a dropdown menu of VPC subnets appears for you to multi select subnets/AZs should be attached to the VPC. For a MAC keyboard, use Command key and select. For a Window's machine keyboard, use Control key and select. When not selected, Aviatrix Controller automatically select a subnet representing each AZ for the VPC attachment. Advanced (Optional) Customize Spoke VPC Routes Available in R4.7 and later. When you customize the Spoke VPC route entries, no learned routes are programmed into the VPC route table. If you wish no route to be programmed by Aviatrix Orchestrator, enter 0.0.0.0/32. Advanced (Optional) Select Route Tables Available in R5.0 and later. Only the selected route tables will participate in TGW Orchestrator, i.e., learned routes will be propagated to these route tables. Advanced (Optional) Disable Local Route Propagation Available in R5.0 and later. When selected, the Spoke VPC CIDR is not propagated to the TGW route table. ==================================================== ========== For example, you can attach a VPC to prod_domain created at the Plan page, as shown below. |prod_vpc_attach| Detaching a VPC from a TGW -------------------------------------------------- This step detaches a VPC from a AWS Transit Gateway and Domain. ========================================================= Building a TGW Connect Attachment ========================================================= A *TGW Connect attachment* creates a connection between the Connect VPC, Connect Attachment, Transport Attachment, and third-party appliances. Note: Only VPC attachments to a TGW Connect attachment are supported. TGW Connect Components ----------------------------------- **Connect VPC** - Central VPC containing EC2 instances running third-party virtual appliances that connect to the TGW over the Connect attachment. **Connect Attachment** - TGW attachment type that leverages the Transport TGW attachment (existing VPC as transport) for the third-party appliance to connect to the TGW. Generic Routing Encapsulation (GRE) tunneling protocol and Border Gateway Protocol (BGP) are supported over the Connect attachment. **Transport Attachment** - TGW attachment type (VPC attachment) used as the underlying transport by the Connect attachment. **Third-Party Appliances** - Third-party virtual router and gateway appliances running on an EC2 instance, in a Connect VPC that leverages VPC attachment as the transport. It establishes BGP peering with the TGW over a GRE tunnel using the Connect attachment. It is also responsible for exchanging traffic with the TGW over an encapsulation channel. In the following example, TGW CIDR block (1.1.1.0/24) is used as the Connect peer IP (GRE outer IP 1.1.1.1) on the TGW side. |tgw_connect_vpc| Building the TGW Connect --------------------------------------- 1. Attach the Connect VPC to TGW using a VPC attachment. 2. Launch the third-party virtual appliances in the Connect VPC. 3. Configure a TGW CIDR block which will be used as the Connect peer IP (GRE outer IP) on the TGW side. 4. Create a Connect attachment on the TGW using VPC attachment as the Transport attachment. 5. Create a Connect peer (GRE tunnel) specifying the GRE and BGP parameters. 6. Add an additional Connect peer on the TGW attachment page. 7. Create a route in the appropriate VPC/Subnet route table for the third-party virtual appliances to connect with the TGW side Connect peer IP (GRE tunnel IP). You can use the *Edit Spoke VPC Customized Routes* feature to configure the route. 8. Complete the Connect peer configuration (GRE tunnel and BGP peering configuration) on the third-party virtual appliances. .. |prod_vpc_attach| image:: tgw_build_media/prod_vpc_attach.png :scale: 80% .. |tgw_connect_vpc| image:: tgw_build_media/tgw_connect_vpc.png :scale: 80% .. disqus:: <file_sep> ==================================== Encrypted Transitive Peering ==================================== .. note:: The Encrypted Transitive Peering feature is deprecated and not supported from Release 6.8 and onwards. This feature functionality is replaced by `Aviatrix Multi-Cloud Transit <https://docs.aviatrix.com/HowTos/transit_gateway_peering.html>`_. As DevOps and applications can now run in Cloud Service Providers (CSPs) such as AWS, Azure, GCP, and OCI, it makes sense to have your employees access the cloud directly with the following highlighted benefits: - Lower latency. Rather than having your employees connect via VPN to your corporate office first and then access the cloud, you can provide a cloud VPN where they can access the CSP account directly. - Better Security. Traditional VPN servers do not support modern multi-factor authentication methods such as a combination of DUO Security, LDAP, and OKTA. - Few hardware gears to manage. However, your business may require hosting some critical applications in widespread co-locations. As a cloud infrastructure engineer, you need to access these sites to check on the health of your servers and applications. The challenge is to set up a system to enable secure accessing abilities to both the cloud and co-locations. Solution ======== Our solution is to leverage Aviatrix’s encrypted peering and encrypted transitive peering capabilities to set up an end-to-end secure network. In this example, a data center or co-location hosts some critical customer facing applications. It connects to an AWS or GCP VPC/Azure VNet/OCI VCN for additional processing, such as data analytics. The data center connects to a VPN Gateway, such as an AWS VGW, with an IPsec tunnel. Employees and developers access VPC/VNet-1 and VPC/VNet-2 directly via Aviatrix CloudVPN and encrypted peering configuration. The cloud infrastructure engineers need to access the servers in the datacenter or co-location for maintenance and monitoring purposes. They do so via an Aviatrix encrypted tunnel and Aviatrix encrypted transitive tunnel configuration. The solution diagram is shown below. |image0| Configuration Workflow ====================== Before you start, make sure you have the latest software by checking the Dashboard. If an alert message displays, click Upgrade to download the latest software. We assume here that you have created a management VPC/VNet-main 172.31.0.0/16, its corresponding VPN gateways with a load balancer (ELB/ALB/CLB) enabled. For more information for this part of configuration, check out this `reference design <https://s3-us-west-2.amazonaws.com/aviatrix-download/Cloud-Controller/Cloud+Networking+Reference+Design.pdf>`__. If you configure split tunnel mode for VPN gateways, make sure to include the co-location CIDRs in the additional CIDR field. The encrypted transitive peering configuration workflow is as follows, with major steps highlighted. 1. Create a gateway in VPC/VNet-2. Verify the gateway at Gateway > New Gateway. Make sure it has NAT enabled and VPN disabled (as you don’t need to enable VPN capability). 2. Create an encrypted peering between VPC/VNet-main and VPC/VNet-2. Go to Peering > Encrypted Peering > New Peering. Make sure: * At VPC/VNet Name 1's dropdown menu, select the peering gateway launched in VPC/VNet-main (note, this peering gateway is different from the VPN gateway). * At VPC/VNet Name 2's dropdown menu, select the gateway launched in VPC/VNet-2. * Click **Add**. 2. Create an encrypted transitive peering. Go to Peering > Transitive Peering > New Peering. Make sure: * At the Source VPC/VNet drop down menu, select the peering gateway launched in VPC/VNet-main (the same VPC/VNet gateway selected in the previous step). * At Next Hop VPC/VNet drop down menu, select the gateway launched in VPC/VNet-2 (the same gateway for VPC/VNet-2 selected in the previous step). * At Destination CIDR, fill in the destination CIDR of the co-location. For example, 10.12.0.0/24. Note this address should be unique across your network. 3. Repeat step 3 above for more co-locations. For support, please open a support ticket at `Aviatrix Support Portal <https://support.aviatrix.com>`_. For feature requests and feedback, click **Make a wish** at the bottom of each page. .. |image0| image:: TransitivePeering_media/EncryptedTransitivePeering_reference.png .. disqus:: <file_sep> |image0| ################################################### AWS Global Transit Network ################################################### AWS Reference Deployment Guide ============================== This document describes a transit network built with static routes. The solution has been deprecated. For Aviatrix Next-Gen Transit Network, refer to `this document. <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ This document is published by AWS Answers for `AWS Global Transit Network <https://aws.amazon.com/answers/networking/aws-global-transit-network/>`_ as Partner Offering. 1 Overview =========== Aviatrix is a next generation cloud networking solution built from the ground up for the public cloud. For transit VPC design, Aviatrix provides one console for building, managing, monitoring and troubleshooting all aspects of your network connectivity. The console (controller) gives users the ability to implement Transit VPC design with a point-and-click (no CLI) as well as Terraform. This configuration guide provides step by step instruction on how to build a highly available AWS Global Transit Network. Below is an architecture diagram of what a general AWS Transit VPC deployment looks like, where a Hub VPC (or Transit VPC) connects many Spoke VPCs to facilitate communication between the Spoke VPCs and on-prem network. |image1| 2 Pre Configuration Checklist ============================== Before configuring user VPC peering, make sure the following is completed. **Pre Configuration Check List** 1. Deploy the Aviatrix Controller 2. Check VPC Settings These prerequisites are explained in detail below. 2.1 Deploy the Aviatrix Controller ----------------------------------- The Aviatrix Controller must be deployed and setup prior to configuring VPC and site peering. Please reference the Aviatrix Controller getting started guide for AWS on how to deploy the Aviatrix Controller. `Aviatrix Controller Getting Started <http://docs.aviatrix.com/StartUpGuides/aviatrix-cloud-controller-startup-guide.html>`_ Check and make sure you can access the Aviatrix Controller dashboard and login with an administrator account. The default URL for the Aviatrix Controller is: https://<public ip of Aviatrix Controller> 2.2 Check VPC Settings ----------------------- - The VPC must have at least one public subnet to deploy the gateway. This means one subnet must be associated with a route table that has an IGW as its default route. - If your hub VPC and spoke VPC are in the same region and you like to route the traffic over AWS peering, go to AWS console and configure the necessary AWS peering between the two VPCs. 3 Configuration Steps ===================== Make sure the pre-configuration steps in the previous section is completed before proceeding. The instructions in this section will use the following architecture. The CIDR and subnets may vary depending on your VPC setup; however, the general principals will be the same. |image2| In this example we have three VPCs: Transit VPC, spoke VPC in US-WEST1 and spoke VPC in US-EAST1. The corporate data center is located in California. The system will be configured such that all spoke nodes and sites will be able to communicate with each other via the transit VPC. .. tip:: For Spoke VPC to Spoke VPC connectivity, you can simply use `Aviatrix Encrypted Peering feature <http://docs.aviatrix.com/HowTos/peering.html>`_. You do not need to route traffic through a transit VPC. Below instruction is primary useful for Spoke VPC to on-prem datacenter connectivity configuration. For demonstration purpose, we include Spoke VPC to Spoke VPC connectivity configuration going through transit VPC. 3.1 Step 1 – Deploy Gateways ---------------------------- The first step is to deploy Aviatrix gateways in each VPC. **Instructions:** 1. Login to the Aviatrix Controller Console 2. Click on Gateway -> Create ============== ==================== **Setting** **Value** ============== ==================== Cloud Type Choose AWS Account Name Choose the account name Region Choose the region where your VPC is located VPC ID Choose the VPC Gateway Name This name is arbitrary (ex. gw01) Public Subnet Select a public subnet where the gateway will be deployed Gateway Size t2.micro is fine for testing. Enable NAT Uncheck this box VPN Access Uncheck this box ============== ==================== 1. Click “Create”. It will take a few minutes for the gateway to deploy. Do not proceed until the gateway is deployed. 2. Repeat steps 2 and 3 for the additional 2 VPCs in this example. 3. Done 3.2 Step 2 – Connect Spoke VPC to Transit VPC --------------------------------------------------- This step explains how to connect a spoke VPC to the transit VPC. :: For Spoke VPC to Spoke VPC connectivity, you can simply use `Aviatrix Encrypted Peering feature <http://docs.aviatrix.com/HowTos/peering.html>`_. You do not need to route traffic through a transit VPC. Below instruction is primary useful for Spoke VPC to on-prem datacenter connectivity configuration. For demonstration purpose, we include Spoke VPC to Spoke VPC connectivity configuration going through transit VPC. **Instructions:** 1. From the Aviatrix Controller Console 2. Click VPC/VNet -> Encrypted Peering -> Encrypted Peering. 3. Click Add 4. Select the VPC1 (transit) gateway and VPC2 (spoke 1) gateway for the peering Note: If the two VPCs are in the same region, you can check the box “over AWS Peering”. This would allow the encrypted peering to route traffic over native AWS peering, resulting in 10 times bandwidth saving. 5. Click Add 6. Select the VPC1 (transit) gateway and VPC3 (spoke 2) gateway for the peering and then click Add 7. Done 3.3 Step 3 – Connect Corporate Data Center to Transit VPC ---------------------------------------------------------- This step explains how to connect the corporate data center to the transit VPC **Instructions:** 1. From the Aviatrix Controller Console 2. Click VPC/VNet -> Site2Cloud -> Add =============================== =================================================== **Setting** **Value** =============================== =================================================== VPC ID/VNet Name Choose Transit VPC ID Gateway Choose Transit VPC gateway Connection Name This name is arbitrary (ex. corpdatacenter) Customer Gateway IP Address: Public IP address of the terminating device at the corp datacenter Customer Network 10.3.0.0/16 (in this example) Private Route Encryption Uncheck Cloud Subnet 10.0.0.0/16, 10.1.0.0/16, 10.2.0.0/16 (in this example) Null Encryption Uncheck =============================== =================================================== 1. Click Add 2. Click List, select the Transit VPC ID and then click Run 3. Put a check mark next to your “Connection Name” (from above) and then click download 4. If your terminating device is a Cisco ASA, select ASA, otherwise, select Generic. 5. This template file contains the necessary information to configure the terminating device at the corp data center. Once the terminating device is configured, the tunnel will automatically come up. 6. Done 3.4 Step 4 – Configure Transitive Routing ------------------------------------------ This step explains how to configure transitive routing so that every spoke and site node can communicate with each other via the transit VPC. **Instructions:** 1. From the Aviatrix Controller Console 2. Click VPC/VNet -> Encrypted Peering -> Transitive Peering a. For VPC2 (spoke 1) select: i. Click Add ii. Source VPC: VPC2, Next Hop VPC: VPC1 (transit), Destination CIDR: 10.2.0.0/16 iii. Click Add and then Add again iv. Source VPC: VPC2, Next Hop VPC: VPC1 (transit), Destination CIDR: 10.3.0.0/16 v. Click Add b. For VPC3 (spoke 2) select: i. Click Add ii. Source VPC: VPC3, Next Hop VPC: VPC1 (transit), Destination CIDR: 10.1.0.0/16 iii. Click Add and then Add again iv. Source VPC: VPC3, Next Hop VPC: VPC1 (transit), Destination CIDR: 10.3.0.0/16 v. Click Add 3. Done Appendix - Comparing Aviatrix Global Transit Network Solution with CSR1000v Solution ========================================================================================= Aviatrix Solution has the following benefits compared to CSR1000v: **Simplicity** No Cisco CCIE, BGP, VRF and IPSEC domain expertise required. The Aviatrix central controller builds and manages your network with software defined routing and point and click solutions deploying in minutes. **No Double Egress Charge** Aviatrix supports direct Spoke VPC to Spoke VPC connectivity without going through transit VPC which incurs in twice the egress network charges. **Isolation By Design** AWS Transit VPC solution with CSR1000v automatically builds a full mesh network among all Spoke VPCs, which breaks enterprise security posture as different Spoke VPCs can be owned by different business units. With Aviatrix solution no connectivity is established until you specify. **Highly Available** Built-in gateway redundancy supports hot standby and fail over in seconds. **Scalable** No limits on the number of spoke VPCs can be connected to on-prem via hub VPC. Aviatrix Designated Gateway summarizes all routes. Gateways can scale-up, scale-down or scale-out with a few clicks. **Visibility** Central dashboard monitors, displays and alerts link status and link latency. **Additional Benefits** Stateful firewall at the gateway to enforce security policies. OpenVPN® based user access allows end to end cloud network solution. For more details, check out docs.aviatrix.com. OpenVPN is a registered trademark of OpenVPN Inc. .. |image0| image:: media/image1.png :width: 3.5in :height: 0.5in .. |image1| image:: media/Transit.png :scale: 100% .. |image2| image:: media/DocArchitecture.png :scale: 100% .. |image6| image:: media/image6.png :width: 7in :height: 4in :scale: 150% .. add in the disqus tag .. disqus:: <file_sep> .. toctree:: :numbered: ============================================================================== OpenVPN® with SAML Authentication on OneLogin IdP ============================================================================== Overview ----------------- This guide provides an example on how to configure Aviatrix to authenticate against a OneLogin IdP. When SAML client is used, your Aviatrix Controller acts as the Identity Service Provider (ISP) that redirects browser traffic from client to IdP (e.g., OneLogin) for authentication. Pre-Deployment Checklist ----------------------------------- Before configuring SAML integration between Aviatrix and OneLogin, make sure the following is completed: #. `Aviatrix Controller <#aviatrix-controller>`__ is set up and running. #. Have a valid `OneLogin account <#onelogin-account>`__ with admin access. #. Download and install the `Aviatrix SAML VPN client <#aviatrix-client>`__. .. _aviatrix_controller: Aviatrix Controller #################### If you haven’t already deployed the Aviatrix Controller, follow `the Controller Startup Guide <https://docs.aviatrix.com/StartUpGuides/aviatrix-cloud-controller-startup-guide.html>`_. .. _onelogin_account: OneLogin Account ################ A valid OneLogin account with admin access is required to configure the integration. .. _aviatrix_client: Aviatrix VPN Client ################### All users must use the Aviatrix VPN client to connect to the system. Download the client for your OS `here <../Downloads/samlclient.html>`__. Configuration Steps ------------------------------ Follow these steps to configure Aviatrix to authenticate against your OneLogin IDP: #. Create a `OneLogin SAML App <#onelogin-saml-app>`__ for Aviatrix. #. Create a `SAML Endpoint <#onelogin-saml-endpoint>`__ in the Aviatrix Controller. .. _onelogin_saml_app: OneLogin SAML App ################# Before you start, pick a short name to be used for the SAML application name. In the notes below, we will refer to this as **aviatrix_onelogin**, but it can be any string. We will use the string you select for the SAML application name to generate a URL for OneLogin to connect with Aviatrix. This URL is defined below as **SP_ACS_URL**. This URL should be constructed as: "https://<your controller ip or host name>/flask/saml/sso/<aviatrix_onelogin>" .. tip:: Replace **<your Controller IP or host name>** with the actual host name or IP address of your controller and **<aviatrix_onelogin>** with the string you chose to refer to the SAML application. #. Log in to OneLogin as an administrator. #. Add a new App (Apps > Add Apps). |imageOLAddAppsMenu| #. Search for "SAML Test Connector." |imageOLNewAppSearch| #. Select **SAML Test Connector (Advanced)**. #. Enter the Configuration values and click **Save**. |imageOLNewAppStep1| You can download the rectangular image from `here <./onelogin_saml_media/aviatrix-logo-rect.png>`__ and the square image from `here <./onelogin_saml_media/aviatrix-logo-square.png>`__. #. Click on **Configuration** tab. #. Enter the values. +--------------------+------------------------------------------------------+ | Field | Value | +====================+======================================================+ | RelayState | Blank | +--------------------+------------------------------------------------------+ | Audience(Entity ID)| **SP Entity ID** | +--------------------+------------------------------------------------------+ | Recipient | **SP_ACS_URL** | +--------------------+------------------------------------------------------+ | ACS (Consumer) | **SP_ACS_URL** | | URL Validator | | +--------------------+------------------------------------------------------+ | ACS (Consumer) URL | **SP_ACS_URL** | +--------------------+------------------------------------------------------+ | Single Logout URL | Blank | +--------------------+------------------------------------------------------+ | Login URL | **SP Login(Test) URL** | +--------------------+------------------------------------------------------+ | SAML not valid | 3 (default) | | before | | +--------------------+------------------------------------------------------+ | SAML not valid | 3 (default) | | on or after | | +--------------------+------------------------------------------------------+ | SAML initiator | Service Provider | +--------------------+------------------------------------------------------+ | SAML nameID format | Transient | +--------------------+------------------------------------------------------+ | SAML issuer type | Specific (default) | +--------------------+------------------------------------------------------+ | SAML signature | Assertion | | element | | +--------------------+------------------------------------------------------+ | Encrypt assertion | Unmarked checkbox (default) | +--------------------+------------------------------------------------------+ | SAML encryption | TRIPLEDES-CBC (default) | | method | | +--------------------+------------------------------------------------------+ | Sign SLO Response | Unmarked checkbox (default) | +--------------------+------------------------------------------------------+ | SAML | 1440 (default) | | sessionNotOnOrAfter| | +--------------------+------------------------------------------------------+ | Generate | Unmarked checkbox (default) | | AttributeValue tag | | | for empty values | | +--------------------+------------------------------------------------------+ | Sign SLO Request | Unmarked checkbox (default) | +--------------------+------------------------------------------------------+ |imageConfiguration| #. Click **Save**. #. Select the **Parameters** tab. #. Add the following custom parameters (case sensitive). +--------------------+------------+-----------------------------------------+ | Field | Value | Flags | +====================+============+=========================================+ | Email | Email | Include in SAML assertion | +--------------------+------------+-----------------------------------------+ | FirstName | First Name | Include in SAML assertion | +--------------------+------------+-----------------------------------------+ | LastName | Last Name | Include in SAML assertion | +--------------------+------------+-----------------------------------------+ |imageOLNewAppParams| #. Optionally, add a field to map to the profile in Aviatrix. +--------------------+----------------+-------------------------------------+ | Field | Value | Flags | +====================+================+=====================================+ | Profile | (User Defined) | Include in SAML assertion | +--------------------+----------------+-------------------------------------+ #. Click **Save**. #. Click on **More actions** dropdown menu. #. Copy the **Metadata URL**. |imageOLSSOTab| .. _onelogin_saml_endpoint: Aviatrix Controller SAML Endpoint ################################# #. Log in to your Aviatrix Controller. #. Select OpenVPN > Advanced on the left sidebar. #. select the **SAML** tab. #. Click **+ Add New**. #. Follow the table below for details on the fields in the table: +----------------------------+-----------------------------------------+ | Field | Description | +----------------------------+-----------------------------------------+ | Endpoint Name | Pick | +----------------------------+-----------------------------------------+ | IPD Metadata Type | URL | +----------------------------+-----------------------------------------+ | IDP Metadata Text/URL | Paste in the **Metadata URL** obtained | | | from the OneLogin app. | +----------------------------+-----------------------------------------+ | Entity ID | Select `Hostname` | +----------------------------+-----------------------------------------+ | Custom SAML Request | Unmarked checkbox | | Template | | +----------------------------+-----------------------------------------+ |imageAvtxSAMLEndpoint| Testing the Integration ----------------------------- You can quickly validate that the configuration is complete by clicking **Test** next to the SAML endpoint. |imageAvtxTestSAML| .. _create_aviatrix_vpn_user: Creating a VPN User ################# #. Log in to the Aviatrix Controller. #. Select OpenVPN® > VPN Users on the left sidebar. #. Click **+ Add New**. #. Select the **VPC ID** and **LB/Gateway Name** for your SAML Gateway. #. Enter a name in the User Name field. #. Enter any valid email address in the User Email field (this is where the cert file will be sent). Alternatively, you can download the cert if you do not enter an email address. #. Select the **SAML Endpoint**. #. Click **OK**. .. _validate_entire_process: Validating ########## #. Log in to the Aviatrix Controller. #. Select OpenVPN® > VPN Users on the left sidebar. #. Download the configuration for your test user created in the previous step. #. Open the Aviatrix VPN Client application. #. Click **Load Conf** and select the file downloaded. #. Click **Connect**. .. |imageOLNewAppSearch| image:: onelogin_saml_media/onelogin_new_app_search.png .. |imageOLNewAppStep1| image:: onelogin_saml_media/onelogin_new_app_step1.png .. |imageOLNewAppParams| image:: onelogin_saml_media/onelogin_parameters.png .. |imageAvtxTestSAML| image:: onelogin_saml_media/avtx_saml_endpoint_test.png .. |imageAvtxSAMLEndpoint| image:: onelogin_saml_media/avtx_saml_endpoint.png .. |imageOLAddAppsMenu| image:: onelogin_saml_media/onelogin_select_add_apps.png .. |imageConfiguration| image:: onelogin_saml_media/onelogin_configuration.png .. |imageOLSSOTab| image:: onelogin_saml_media/onelogin_issuer_url.png\ <file_sep> =========================================================================================== Connect Overlapping VPC/VNet to On-prem =========================================================================================== The Problem ------------------ Organizations usually plan out their cloud network address ranges. But there are times where a VPC/VNet CIDR overlaps with an on-prem network address range, yet still requires connectivity to on-prem. In this document, the scenario is such that traffic is always initiated from on-prem to VPC/VNet. The constraint is that there should be no source NAT nor destination NAT performed in the on-prem network. As shown in the diagram below, the on-prem network address range is 10.20.0.0/16. All other VPCs connect to on-prem via Aviatrix Transit solution. However, there is one VPC named spoke-vpc with an identical CIDR of 10.20.0.0/16. |overlap_cidr| The Solution ------------------- Since the on-prem network does not perform any NAT functions, NAT must be performed in the cloud network. The key solution steps are: 1. Allocate two 1-1 mapped corresponding virtual address spaces for the on-prem network and spoke-vpc/vnet. For example, allocate the virtual network 172.16.58.3/16 for the on-prem network, and 192.168.127.12/16 for the spoke-vpc/vnet virtual VPC/VNet CIDR. These two virtual address spaces must not overlap with any on-prem or cloud address spaces. #. Launch an Aviatrix Gateway in the spoke-vpc/vnet. #. Build an IPsec tunnel between spoke-vpc/vnet and the VPN Gateway (VGW/VPN Connect): a. Go to the CSP Console (AWS, Azure, GCP, or OCI) for the VPC/VNet service. Use the same VGW that is used for the Aviatrix Transit solution to create an IPsec tunnel to spoke-vpc/vnet with static routes 192.168.127.12/16 configured, as shown below. Then download the VPN configuration file. |vgw_config| b. On the spoke-vpc/vnet side, go to your Aviatrix Controller, click **Site2Cloud** on the left sidebar, and click **Add New**. Make sure the remote subnet list includes 10.20.0.0/16 and 172.16.58.3/16. The local subnet is 192.168.127.12/16, the virtual address of the spoke-vpc/vnet, as shown in the screenshot below. |site2cloud| 4. Perform both SNAT and DNAT functions on the Aviatrix Gateway: a. Go to your Aviatrix Controller and click Gateway. Select the Aviatrix Gateway for spoke-vpc/vnet. Click **Edit** and scroll down to find Destination NAT . b. Translate the cloud virtual destination address to its real address for each instance in the VPC/VNet. c. Mark the session with a number that is easy to remember. In this example, it is 119. d. Scroll up to find Source NAT. Translate the marked session to any on-prem virtual source address, as shown in the screenshot below. |nat_config| e. Repeat the NAT configuration for each cloud instance. Since the VPN Gateway (VGW/VPN Connect) runs a BGP session to on-prem for normal a Transit Network, the spoke-vpc/vnet virtual CIDR 192.168.127.12/16 should be propagated to on-prem. From on-prem, the destination IP address takes the range 192.168.127.12/16. .. |overlap_cidr| image:: connect_overlap_vpc_via_VGW_medium/overlap_cidr.png :scale: 30% .. |vgw_config| image:: connect_overlap_vpc_via_VGW_medium/vgw_config.png :scale: 30% .. |site2cloud| image:: connect_overlap_vpc_via_VGW_medium/site2cloud.png :scale: 30% .. |nat_config| image:: connect_overlap_vpc_via_VGW_medium/nat_config.png :scale: 30% .. disqus:: <file_sep> ############################################## Transit Network with BGP Setup Instructions ############################################## .. Important:: This document is obsolete for release 3.1 and later releases. Follow `Transit Network workflow instructions <http://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`__ to setup a Transit Network. Introduction ============= `Aviatrix Services Architecture <http://aviatrix.com/blog/architectural-evolution-networking-public-cloud/>`_ builds automated and scalable network architecture for the cloud, as shown in the diagram below. Key characteristics in this architecture: - Spoke VPC to Spoke VPC networking is direct without going through the Transit VPC and is orchestrated by the central controller. Spoke VPCs do not run BGP protocol. - BGP runs between the gateway in the Transit VPC and AWS VGW to facilitate communication between Spoke VPC and on-prem. The idea is you need to configure on-prem connectivity to VGW once and there is no need again when new Spoke VPC is stood up. |image0| This guide provides instructions on how to enable BGP for a Transit VPC solution. Aviatrix gateway deployed in Transit VPC exchanges routes with a VGW that connects to on-prem by Direct Connect or Internet. Review the `Best Practice section <http://docs.aviatrix.com/HowTos/bgp_transitive_instructions.html#best-practice>`_ before you proceed. Deployment Steps ================= 1. Establish BGP between Aviatrix Gateway and VGW in Transit VPC ------------------------------------------------------------------- This step launches an Aviatrix gateway in Transit VPC and builds a IPSEC connection to VGW with BGP enabled. a. At AWS Console create a VGW (the VGW is not attached to a VPC) which we will use to connect to on-prem over Direct Connect or Internet. For information on how to connect a VGW to Direct Connect, follow `the steps <http://docs.aws.amazon.com/directconnect/latest/UserGuide/create-vif.html>`_ for details. For IPSEC configuration, refer to `this doc <http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_VPN.html>`__ for IPSEC over Internet configuration guide. #. From Aviatrix Controller console, launch an Aviatrix Gateway in the Transit VPC. This Aviatrix Gateway in the Transit VPC is the Customer Gateway (CGW) from VGW point of view. #. At AWS Console, create Customer Gateway (CGW) in Transit VPC with the following configuration: - Routing: Dynamic - IP Address: Public IP of Aviatrix Gateway in Transit VPC. #. At AWS Console create AWS VPN Connection in Transit VPC with the following configuration: - Virtual Private Gateway: VGW in Transit VPC - Customer Gateway: CGW created above - Routing Options: Dynamic (requires BGP) #. At AWS Console, download configuration template from AWS VPN Connection for "Generic" vendor (Referred as 'Configuration Template' below) . #. At AWS Console, detach VGW from Transit VPC (if it was attached). #. At Aviatrix Controller console, create Site2Cloud tunnel on Aviatrix Gateway to work with AWS VGW with the following configuration: - VPC ID/VNet Name: Transit VPC ID - Connection Type: Unmapped - Connection Name: Any name - Remote Gateway Type: AWS VGW - Tunnel Type: UDP - Algorithms: Deselected - Encryption over ExpressRoute/DirectConnect: Deselected - BGP: Selected - Remote AS Number: "IPSec Tunnel #1"->"Border Gateway Protocol (BGP) Configuration"->"Virtual Private Gateway ASN" from 'Configuration Template' |image1| - CGW Inside IP Address: "IPSec Tunnel #1"->"Tunnel Interface Configuration"->"Inside IP Addresses"->"Customer Gateway" from 'Configuration Template' |image2| - VGW Inside IP Address: "IPSec Tunnel #1"->"Tunnel Interface Configuration"->"Inside IP Addresses"->"Virtual Private Gateway" from 'Configuration Template' |image3| - Advertise Network: Transit VPC CIDR - Enable HA: Deselected - Primary Cloud Gateway: Aviatrix Gateway in Transit VPC - Remote Gateway IP Address: "IPSec Tunnel #1"->"Tunnel Interface Configuration"->"Outside IP Addresses"->"Virtual Private Gateway" from 'Configuration Template' |image4| - Pre-shared Key: "IPSec Tunnel #1"->"Internet Key Exchange Configuration"->"Pre-Shared Key" from 'Configuration Template' |image5| #. At Aviatrix Controller console, open MULTI-CLOUD TRANSIT > BGP: - Edit "Local AS Num" if required - Enable "BGP" #. At Aviatrix Controller's Site2Cloud page: - Make sure site2cloud tunnel is up and working - View “Remote Subnet”, this is on-prem network obtained through route exchange between. 2. Connect Spoke VPC to on-prem --------------------------------- a. At Aviatrix Controller console, launch an Aviatrix Gateway in a spoke VPC. #. At Controller console, Peering -> Encrypted Peering, create peering between Aviatrix Gateways at spoke VPC and Transit VPC. #. At Controller console, Peering -> Transitive Peering, create transitive peering from spoke VPC to on-prem via Transit VPC. Transitive Peering configuration:i - Source Gateway: Spoke VPC Gateway - Nexthop Gateway: Transit VPC Gateway - Destination CIDR: on-prem network displayed at Site2Cloud -> "Remote Subnet" #. At Controller's Site2Cloud page, select the Site2Cloud connection created above by Aviatrix gateway at Transit VPC with BGP. At "BGP Advertised Networks" field, append Spoke VPC's CIDR to the list. #. Repeat the above section for each Spoke VPC connected to Transit VPC. Building HA Transport Links =========================== There are multiple patterns to build HA in the transport link. AWS VGW can be used to create two Direct Connect links, two IPSEC over Internet links and one Direct Connect and one IPSEC over Internet links. Refer to `this doc <https://aws.amazon.com/answers/networking/aws-multiple-data-center-ha-network-connectivity/>`__ for details. Best Practice =============== - **Plan your cloud address space** when designing a Transit VPC network. Best practice is to allocate a network address space from which the spoke VPC CIDRs are created. Make sure this network address space is unique and not overlapping with any on-prem network. For example, allocate 192.168.127.12/16 as your cloud address space. The spoke VPC CIDRs would be 192.168.127.12/24, 172.16.31.10/24, etc. With this approach, you just need advertise one prefix 192.168.127.12/16 once. When a new spoke VPC come up, you do not need to modify advertise network at the site2cloud page. - **Edit BGP Advertise Network** after BGP has learned the on-prem network prefixes. When creating the Site2Cloud connection, leave the "Advertised Networks" blank. After Site2Cloud connection is created, go to MULTI-CLOUD TRANSIT > BGP to enable BGP. Go back to Site2Cloud connection, if you see list of subnets under Remote Subnet, it implies BGP has come up. At this point, click the connection to Edit BGP Advertised Networks. Enter the entire cloud address space as suggested above. This approach helps you see the list of the on-prem network prefixes to make sure you do not enter overlapping addresses. BGP Troubleshooting =================== Aviatrix BGP is implemented based on Quagga open source software. You can get debugging information at Controller console. MULTI-CLOUD TRANSIT > BGP > Diagnostics. Release 3.0 Limitations ======================== You need to edit each Spoke VPC Transitive Peering settings when on-prem network is changed. The changed network can be viewed from the Controller: MULTI-CLOUD TRANSIT > BGP. .. |image0| image:: bgp_media/servicearchitecture.png :width: 5.55625in :height: 3.26548in .. |image1| image:: bgp_media/VGW_ASN.PNG :width: 5.55625in :height: 3.26548in .. |image2| image:: bgp_media/CGW_IP.PNG :width: 5.55625in :height: 3.26548in .. |image3| image:: bgp_media/VGW_IP.PNG :width: 5.55625in :height: 3.26548in .. |image4| image:: bgp_media/VGW_Public_IP.PNG :width: 5.55625in :height: 3.26548in .. |image5| image:: bgp_media/Pre-shared.PNG :width: 5.55625in :height: 3.26548in .. disqus:: <file_sep> ========================================================= Example Config for Check Point VM in AWS ========================================================= In this document, we provide an example to set up the Check Point Security Gateway instance for you to validate that packets are indeed sent to the Check Point Security Gateway for VPC-to-VPC and from VPC to internet traffic inspection. .. note:: Firewall and Security Gateway word will be used interchangeably in this document. Both refers to Check Point Security Gateway product. Prerequisites ---------------- Before you start, make sure you meet the basic requirements: - Basic Check Point Architecture Understanding - Check Point CloudGuard IaaS product is subscribed in AWS Marketplace The following Check Point AMIs and software versions are supported. ========================================================================== ========== **Supported AMI Name** **Software Version** ========================================================================== ========== CloudGuard IaaS Next-Gen Firewall with Threat Prevention & SandBlast BYOL R80.40, R80.30 CloudGuard IaaS Next-Gen Firewall with Thread Prevention R80.40, R80.30 CloudGuard IaaS All-In-One R80.40 R80.40 ========================================================================== ========== Basic Check Point architecture is shown below: |cp_arch_reference| In this document, we provide an example to set up the Check Point Firewall instance for you to validate that packets are indeed sent to the Check Point Firewall for VPC-to-VPC and from VPC to internet traffic inspection. The Aviatrix Firewall Network (FireNet) workflow launches a Check Point Firewall instance at `this step <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#launching-and-associating-firewall-instance>`_. After the launch is complete, the console displays the Check Point Firewall instance with its public IP address of management/egress interface for you to log in to the console. Here is the Firewall information in this example for your reference. Please adjust it depending on your requirements. .. note:: Firewall Image other then Check Point CloudGuard IaaS All-In-One requires a Check Point Security Management to manage firewall polices. See the `Check Point Azure Example <https://docs.aviatrix.com/HowTos/config_CheckPointAzure.html>`_ for more information. ========================================== ========== **Example setting** **Example value** ========================================== ========== Firewall Image Check Point CloudGuard IaaS All-In-One R80.40 Firewall Image Version R80.40-294.581 Firewall Instance Size m5.large Egress Interface Subnet Select the subnet whose name contains "FW-ingress-egress." Key Pair Name (Optional) The .pem file name for SSH access to the firewall instance. Attach Check ========================================== ========== .. note:: Check Point Firewall instance has 2 interfaces as described below. Additionally, firewall instance eth1 is on the same subnet as FireNet Gateway eth2 interface. ======================================================== =============================== ================================ **Check Point VM instance interfaces** **Description** **Inbound Security Group Rule** ======================================================== =============================== ================================ eth0 (on subnet -Public-FW-ingress-egress-AZ-a) Egress or Untrusted interface Allow ALL eth1 (on subnet -dmz-firewall) LAN or Trusted interface Allow ALL (Do not change) ======================================================== =============================== ================================ Below are the steps for initial setup. Downloading Check Point Firewall Access Key ------------------------------------------------------- After `this step <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#launching-and-associating-firewall-instance>`_ in the FireNet workflow is completed, click **Download** to download the .pem file. If you get a download error, usually it means the Check Point Firewall instance is not ready. Wait until it is ready, refresh the browser and then try again. |v2_avx_pem_file_download| Setting up Check Point Gateway (Firewall) SSH login Using Password ----------------------------------------------------------------------------------- For Metered AMI, open a terminal and run the following command. .. tip :: Once you download the .pem file, change the file permission to 600. It usually takes 5 to 10 minutes for the Check Point Gateway to be ready. Once SSH into the Check Point Gateway using the proper keys and the user “admin,” only few commands will be required to enable ssh for user "admin." :: ssh -i <private_key.pem> admin@<public-ip_address> set expert-password Enter new expert password: Enter new expert password (again): gw-358e82> expert Enter expert password: Warning! All configurations should be done through clish You are in expert mode now. [Expert@gw-358e82:0]# sed -i 's/PasswordAuthentication no/PasswordAuthentication yes/' /etc/ssh/sshd_config [Expert@gw-358e82:0]# sed -i 's/PermitRootLogin forced-commands-only/PermitRootLogin yes/' /etc/ssh/sshd_config [Expert@gw-358e82:0]# service sshd reload Reloading sshd: [ OK ] [Expert@gw-358e82:0]# exit Terminate the SSH session. Logging in to the Check Point Firewall Gaia Portal ------------------------------------------------------------- After launch is completed, go back to the Controller, Firewall Network > Setup > `Step 2a <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#launching-and-associating-firewall-instance>`_ and click on the Management UI as shown below. |v2_avx_management_UI| The URL takes you to the Check Point Firewall Gaia Portal you just launched. |v2_cp_login_UI| .. note:: For initial Check Point login information, go to `Credentials for Check Point Initial Login <https://aviatrix.zendesk.com/hc/en-us/articles/4417552852109>`_. You must be registered to access the Aviatrix Customer Support website. If you are not already registered, you can sign-up at https://support.aviatrix.com. Starting from Release 5.4, launching Check Point firewall instances from the Aviatrix Controller automatically initiates its onboarding process. For initial login information, go to `Credentials for Check Point Initial Login <https://aviatrix.zendesk.com/hc/en-us/articles/4417552852109>`_. You must be registered to access the Aviatrix Customer Support website. If you are not already registered, you can sign-up at https://support.aviatrix.com. Initializing and Logging in to the Check Point Firewall via Gaia Portal -------------------------------------------------------------------------------------- First time login shows the **"Check Point First Time Configuration Wizard"** screen as shown below. |v2_CheckPoint_Gaia_Portal_Wizard_01| Click **Next**, **Next** and continue until the **Finish** button, no need to configure anything in the configuration wizard. |v2_CheckPoint_Gaia_Portal_Wizard_02| |v2_CheckPoint_Gaia_Portal_Wizard_12| .. important:: Aviatrix Controller automatically configures the Check Point interfaces and RFC1918 static routes which is required for FireNet feature, so, initialize wizard configurations are no longer required but we need to click **Next** on each window to initialize the firewall properly. After the initialization is completed, users will be navigated to the Check Point Firewall Gaia Portal Overview page as below. |v2_CheckPoint_Gaia_Portal_Overview| Go to the page Network Management > Network Interfaces to review eth0 (WAN) and eth1 (LAN) configuration as shown below. |cp_firewall_interfaces_aws| Review static routes RFC 1918 which is configured on LAN port, the purpose of those static route is to send the packets back to the Gateway (GW). Those static routes could be reviewed on the page Network Management -> IPv4 Static Routes. |cp_firewall_static_routes_aws| Routes can also be reviewed by clicking **Monitoring** on the page Network Management > IPv4 Static Routes. |cp_firewall_routes_monitoring_aws| (Optional) Firewall Vendor Integration ----------------------------------------------- Go to Aviatrix Controller > Firewall Network > Vendor Integration and complete the step as shown below: |v2_vendor_integration_AWS| Click **Save**, **Show** and **Sync** respectively. This automatically set up the non-RFC 1918 routes between Aviatrix Gateway and Vendor’s firewall instance in this case Check Point. This can also be done manually through Cloud Portal and/or Vendor’s Management tool. Downloading and Installing the SmartConsole -------------------------------------------------------- .. important:: Check Point Single Gateway 'All-In-One' image is used in this example which do not require Check Point Security Manager. All other Gateway images require Check Point Security Manager. If you are not using 'All-In-One' image then skip this step and follow the `Step 4 & Step 5 <https://docs.aviatrix.com/HowTos/config_CheckPointAzure.html#download-and-install-the-smartconsole>`_ in a given link. Downloading the Check Point SmartConsole **************************************** Log in to the Check Point Gateway and download the SmartConsole with version R80.40 on Windows-based computer. Option 1: click **Download Now!** with the message "Manage Software Blades using SmartConsole" on the Overview page as shown below. |v2_CheckPoint_Gaia_Portal_SmartConsole_DL| Option 2: download it by using this link `R80.40 <https://supportcenter.checkpoint.com/supportcenter/portal?action=portlets.DCFileAction&eventSubmit_doGetdcdetails=&fileid=101086>`_. Installing and Logging into the SmartConsole **************************************** Install the SmartConsole and login into it with the Gaia Portal username, password and IP Address of Check Point Gateway. |smart_console_login_aws| |smartconsole_gateway_login_aws| Moreover, execute the function "Get Interfaces With Topology" to sync up the settings that we have configured via Gaia Portal. 1. Select **Gateways & Servers** on the left. 2. Double-click on the Check Point Firewall. 3. Select **Network Management** on left. 4. Click **Get Interfaces** to expand options. 5. Click **Get Interfaces With Topology**. 6. Click **Yes**. 7. Review the Get Topology Results which should match to the settings that we have configured via Gaia Portal. 8. Click **Accept**. |v2_CheckPoint_SmartConsole_syncup_01| |v2_CheckPoint_SmartConsole_syncup_02| Go to Security Policies > Access Control > Policy and click **Install Policy** and then **Install** to commit the settings. |install_policy_aws| Configuring the Basic Traffic Policy to Allow Traffic VPC-to-VPC -------------------------------------------------------------------------------- In this step, we will configure a basic traffic security policy that allows traffic to pass through the firewall. From Security Policies > Access Control > Policy, configure a policy by either modifying the default Cleanup rule or Add a new rule above the default rule. ======================= =============================================== **Field** **Value** ======================= =============================================== Name Configure any name for this policy (i.e. allow-all) Source Any Destination Any VPN Any Service & Applications Any Action Accept Track Log ======================= =============================================== |v2_CheckPoint_policy_vpc_to_vpc| Click **Install Policy** and then **Install** to commit the settings. |v2_CheckPoint_policy_vpc_to_vpc_install| [Optional] Configuring the Basic Traffic Policy to Allow Traffic VPC to Internet ----------------------------------------------------------------------------------------------- In this step, we will configure a basic traffic security policy that allows Internet traffic to pass through the firewall. Given that Aviatrix Gateways will only forward traffic from the TGW to the LAN port of the Firewall, we can simply set our policy condition to match any packet that is going in of LAN interface and going out of WAN interface. .. important:: Enable `Egress inspection <https://docs.aviatrix.com/HowTos/firewall_network_faq.html#how-do-i-enable-egress-inspection-on-firenet>`_ feature on FireNet. 1. First, go back to the Aviatrix Controller. Navigate to Firewall Network > Advanced. 2. Click the skewer/three dot button. 3. Scroll down to Egress through Firewall and click **Enable** button. 4. Verify the Egress status on the page Firewall Network > Advanced. |cp_egress_inspection_aws| Second, go back to the Check Point Firewall SmartConsole. Navigate to the page "Gateways & Servers" and then double-click on the gateway itself to enable NAT function as the following screenshot. 5. Click **NAT**. 6. Mark the **Hide internal networks behind the Gateway's external IP** checkbox. 7. Click **OK**. 8. Click **Install Policy**. |v2_CheckPoint_policy_vpc_to_internet_nat_enabled| .. important:: NAT function needs to be enabled on the Check Point FW interface eth0 for this VPC to Internet policy. Please refer to `Check Point's NAT instruction <https://sc1.checkpoint.com/documents/R76/CP_R76_Firewall_WebAdmin/6724.htm>`_ for detail. **[Optional]** If you have default "Cleanup rule", then navigate to Security Policies > Access Control > Policy and inject a new rule for Internet Policy on top of the default Cleanup rule. ======================= =============================================== **Field** **Value** ======================= =============================================== Name Configure any name for this policy (i.e. Internet-Policy) Source Any Destination Select the object with All_internet VPN Any Service & Applications Any Action Accept Track Log ======================= =============================================== Click **Install Policy** and then **Install** to commit the settings. |cp_policy_vpc_to_internet_aws| After validating that your traffic is being routed through your firewall instances, you can customize the security policy to tailor to your requirements. Ready to Go -------------------- Now your firewall instance is configured and ready to receive packets. Next step is to validate your configurations and polices using FlightPath and Diagnostic Tools (ping, traceroute etc.). Viewing Traffic Log ------------------------------ You can view if traffic is forwarded to the firewall instance by logging in to the Check Point Firewall SmartConsole. Go to the Logs & Monitor page. For VPC-to-VPC traffic: *********************** Launch one instance in PROD Spoke VPC and DEV Spoke VPC. Start ping packets from a instance in DEV Spoke VPC to the private IP of another instance in PROD Spoke VPC. The ICMP traffic should go through the firewall and be inspected in firewall. |v2_CheckPoint_view_traffic_log_vpc_to_vpc| [Optional] For VPC to Internet traffic: *************************************** Launch a private instance in the Spoke VPC (i.e. PROD Spoke VPC) and start ping packets from the private instance towards Internet (e.g 8.8.8.8) to verify the egress function. The ICMP traffic should go through, and get inspected on firewall. |v2_CheckPoint_view_traffic_log_vpc_to_internet| .. |cp_arch_reference| image:: config_Checkpoint_media/cp_arch_reference.png :scale: 35% .. |cp_policy_vpc_to_internet_aws| image:: config_Checkpoint_media/cp_policy_vpc_to_internet_aws.png :scale: 30% .. |cp_egress_inspection_aws| image:: config_Checkpoint_media/cp_egress_inspection_aws.png :scale: 40% .. |policy_installed_aws| image:: config_Checkpoint_media/policy_installed_aws.png :scale: 40% .. |smartconsole_gateway_login_aws| image:: config_Checkpoint_media/smartconsole_gateway_login_aws.png :scale: 30% .. |install_policy_aws| image:: config_Checkpoint_media/install_policy_aws.png :scale: 30% .. |smart_console_login_aws| image:: config_Checkpoint_media/smart_console_login_aws.png :scale: 40% .. |v2_avx_pem_file_download| image:: config_Checkpoint_media/v2_avx_pem_file_download.png :scale: 20% .. |v2_vendor_integration_AWS| image:: config_Checkpoint_media/v2_vendor_integration_AWS.png :scale: 30% .. |v2_pem_file_download| image:: config_Checkpoint_media/v2_pem_file_download.png :scale: 40% .. |v2_avx_management_UI| image:: config_Checkpoint_media/v2_avx_management_UI.png :scale: 30% .. |v2_cp_login_UI| image:: config_Checkpoint_media/v2_cp_login_UI.png :scale: 40% .. |v2_CheckPoint_change_password| image:: config_Checkpoint_media/v2_CheckPoint_change_password.png :scale: 60% .. |v2_CheckPoint_Gaia_Portal_Wizard_01| image:: config_Checkpoint_media/v2_CheckPoint_Gaia_Portal_Wizard_01.png :scale: 40% .. |v2_CheckPoint_Gaia_Portal_Wizard_02| image:: config_Checkpoint_media/v2_CheckPoint_Gaia_Portal_Wizard_02.png :scale: 40% .. |cp_firewall_interfaces_aws| image:: config_Checkpoint_media/cp_firewall_interfaces_aws.png :scale: 40% .. |cp_firewall_static_routes_aws| image:: config_Checkpoint_media/cp_firewall_static_routes_aws.png :scale: 40% .. |cp_firewall_routes_monitoring_aws| image:: config_Checkpoint_media/cp_firewall_routes_monitoring_aws.png :scale: 40% .. |v2_CheckPoint_Gaia_Portal_Wizard_12| image:: config_Checkpoint_media/v2_CheckPoint_Gaia_Portal_Wizard_12.png :scale: 40% .. |v2_CheckPoint_Gaia_Portal_Overview| image:: config_Checkpoint_media/v2_CheckPoint_Gaia_Portal_Overview.png :scale: 40% .. |v2_CheckPoint_Gaia_Portal_Configuration_eth0_WAN| image:: config_Checkpoint_media/v2_CheckPoint_Gaia_Portal_Configuration_eth0_WAN.png :scale: 40% .. |v2_CheckPoint_Gaia_Portal_Configuration_eth1_LAN| image:: config_Checkpoint_media/v2_CheckPoint_Gaia_Portal_Configuration_eth1_LAN.png :scale: 40% .. |v2_CheckPoint_static_routes_01| image:: config_Checkpoint_media/v2_CheckPoint_static_routes_01.png :scale: 40% .. |v2_CheckPoint_static_routes_02| image:: config_Checkpoint_media/v2_CheckPoint_static_routes_02.png :scale: 40% .. |v2_CheckPoint_static_routes_review_01| image:: config_Checkpoint_media/v2_CheckPoint_static_routes_review_01.png :scale: 40% .. |v2_CheckPoint_static_routes_review_02| image:: config_Checkpoint_media/v2_CheckPoint_static_routes_review_02.png :scale: 40% .. |v2_CheckPoint_Gaia_Portal_SmartConsole_DL| image:: config_Checkpoint_media/v2_CheckPoint_Gaia_Portal_SmartConsole_DL.png :scale: 40% .. |v2_CheckPoint_Gaia_Portal_SmartConsole_install| image:: config_Checkpoint_media/v2_CheckPoint_Gaia_Portal_SmartConsole_install.png :scale: 40% .. |v2_CheckPoint_SmartConsole_syncup_01| image:: config_Checkpoint_media/v2_CheckPoint_SmartConsole_syncup_01.png :scale: 40% .. |v2_CheckPoint_SmartConsole_syncup_02| image:: config_Checkpoint_media/v2_CheckPoint_SmartConsole_syncup_02.png :scale: 30% .. |v2_CheckPoint_policy_vpc_to_vpc| image:: config_Checkpoint_media/v2_CheckPoint_policy_vpc_to_vpc.png :scale: 20% .. |v2_CheckPoint_policy_vpc_to_vpc_install| image:: config_Checkpoint_media/v2_CheckPoint_policy_vpc_to_vpc_install.png :scale: 20% .. |v2_avx_egress_inspection| image:: config_FortiGate_media/v2_avx_egress_inspection.png :scale: 20% .. |v2_CheckPoint_policy_vpc_to_internet_nat_enabled| image:: config_Checkpoint_media/v2_CheckPoint_policy_vpc_to_internet_nat_enabled.png :scale: 30% .. |v2_CheckPoint_policy_vpc_to_internet| image:: config_Checkpoint_media/v2_CheckPoint_policy_vpc_to_internet.png :scale: 20% .. |v2_CheckPoint_view_traffic_log_vpc_to_vpc| image:: config_Checkpoint_media/v2_CheckPoint_view_traffic_log_vpc_to_vpc.png :scale: 30% .. |v2_CheckPoint_view_traffic_log_vpc_to_internet| image:: config_Checkpoint_media/v2_CheckPoint_view_traffic_log_vpc_to_internet.png :scale: 30% .. disqus:: <file_sep> ========================================================================================== Aviatrix BGP over LAN with Cisco Meraki in AWS ========================================================================================== Introduction ============ This Tech Note is a step-by-step guide for using `BGP over LAN <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_workflow.html>`_ to interoperate with Cisco Meraki as the third party appliance in AWS. BGP over LAN also works in Azure, make adjustments accordingly when applying to deployment in Azure. Two supported design patterns are described as below: Design Pattern #1 with Aviatrix Multi-cloud Transit ---------------------------------------------------- |cisco_meraki_aviatrix_transit_solution_diag| In this design pattern, Aviatrix Multi-cloud transit is deployed to connect Spoke VPCs to the Transit VPC and Aviatrix Transit Gateway is used to connect to Meraki vMX in the same Transit VPC. Design Pattern #2 with AWS TGW Orchestrator ------------------------------------------- |cisco_meraki_aws_tgw_orchestrator_diag| In the second design pattern, AWS TGW is deployed for connecting to Spoke VPC and Aviatrix Multi-cloud transit is used to connect to Meraki vMX in the same Transit VPC. This Tech Note consists of: #. Workflow on `launching Cisco Meraki vMX in AWS <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_with_aws_meraki_workflow.html#launch-cisco-meraki-vmx-in-aws>`_ #. Workflow on `deploying branch Cisco Meraki device <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_with_aws_meraki_workflow.html#deploy-branch-meraki-device>`_ #. Workflow on `deploying Aviatrix Multi-Cloud Transit Solution <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_with_aws_meraki_workflow.html#deploy-aviatrix-multi-cloud-transit-solution>`_ #. Workflow on `building BGP over LAN <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_with_aws_meraki_workflow.html#build-bgp-over-lan>`_ For more information about how to configure BGP over LAN, please refer to the doc links as follows: - `AWS Multi-cloud Transit BGP over LAN Workflow <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_workflow.html>`_ - `Azure Multi-cloud Transit BGP over LAN Workflow <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_azure_workflow.html>`_ For more information about Multi-Cloud Transit Network, External Device, and AWS TGW Orchestrator, please check out the below documents: - `Multi Cloud Global Transit FAQ <https://docs.aviatrix.com/HowTos/transitvpc_faq.html#multi-cloud-global-transit-faq>`_ - `Global Transit Network Workflow Instructions (AWS/Azure/GCP/OCI) <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ - `Aviatrix Transit Gateway to External Devices <https://docs.aviatrix.com/HowTos/transitgw_external.html>`_ - `Transit Network Design Patterns <https://docs.aviatrix.com/HowTos/transitvpc_designs.html>`_ - `AWS TGW Orchestrator FAQ <https://docs.aviatrix.com/HowTos/tgw_faq.html>`_ - `TGW Design Patterns <https://docs.aviatrix.com/HowTos/tgw_design_patterns.html>`_ .. important:: - The minimum instance sizes of Aviatrix Transit Gateway for `BGP over LAN` are c4.4xlarge, c5.4xlarge, c5n.4xlarge - LAN interfaces for Aviatrix Transit Primary and Meraki vMX must be in the same Availability Zone. Prerequisite ==================== - This feature is available for 6.3 and later. `Upgrade <https://docs.aviatrix.com/HowTos/inline_upgrade.html>`_ Aviatrix Controller to at least version 6.3. - In this Tech Note, the following VPC CIDRs are used for illustration purpose: - Transit VPC (10.1.0.0/16). You can create this VPC by using `Create a VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ with Aviatrix FireNet VPC option enabled. - Spoke VPCs (192.168.1.0/24, 192.168.2.0/24, 192.168.3.0/24). You can create the Spoke VPCs by using `Create a VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ or manually deploying them in AWS console. Use existing Spoke VPCs also works. Illustration for Design Pattern #1 with Aviatrix Transit Solution ------------------------------------------------------------------ |cisco_meraki_aviatrix_transit_solution_illustration_diag| Illustration for Design Pattern #2 with AWS TGW Orchestrator ------------------------------------------------------------ |cisco_meraki_aws_tgw_orchestrator_illustration_diag| 1. Launch Cisco Meraki vMX in AWS ================================================= Step 1.1. Deploy Cisco Meraki vMX in Transit VPC ------------------------------------------------- - Follow the steps in `vMX Setup Guide for Amazon Web Services (AWS) <https://documentation.meraki.com/MX/MX_Installation_Guides/vMX_Setup_Guide_for_Amazon_Web_Services_(AWS)>`_ to launch Cisco Meraki vMX in Transit VPC - Meraki Dashboard Configuration - AWS Setup, Accessing the AMI, and Configuring the EC2 Image - Step "Additional VPC Configuration" in `vMX Setup Guide for Amazon Web Services (AWS) <https://documentation.meraki.com/MX/MX_Installation_Guides/vMX_Setup_Guide_for_Amazon_Web_Services_(AWS)>`_ here is an optional as we will provide a guideline how to advertise spoke VPC CIDRs to branch Cisco Meraki through BGP protocol in the following steps. .. important:: - Assign an EIP to Meraki vMX's interface - Make sure the function "Source/Dest check" on Meraki vMX's interface is disabled - Since One-Armed Concentrator mode is adopted in this document, the vMX is configured with a single Network Interface which means all traffic will be sent and received on this interface. Step 1.2. Check Cisco Meraki vMX status on Meraki Dashboard ----------------------------------------------------------- #. Log in to the Meraki Dashboard. #. Select the "NETWORK" where this Cisco Meraki vMX in Transit VPC locates. #. Go to Security & SD-WAN -> MONITOR -> Appliance status. #. Check whether Cisco Meraki vMX displays "Active" status. |cisco_meraki_aws_vMX_appliance_status| Step 1.3. Enable Hub (Mesh) type ----------------------------------------------------------- #. Go to Security & SD-WAN -> CONFIGURE -> Site-to-site VPN. #. Find the panel "Type" on the top. #. Select the radio button "Hub (Mesh)" to establish VPN tunnels with all hubs and dependent spokes for this Cisco Meraki vMX. |cisco_meraki_aws_vMX_s2s_hub_type| Step 1.4. Enable BGP settings ----------------------------------------------------------- #. Find the panel "BGP settings." #. Select the option "Enabled" for the field "BGP" #. Adjust the values for the fields "BGP VPN AS" and "IBGP VPN Holdtimer" if needed and write down the BGP ASN #. Click "Save." |cisco_meraki_aws_vMX_s2s_bgp_enable| .. important:: Will guide how to set up BGP neighbors for eBGP in the later workflow. 2. Deploy branch Meraki device ================================================================== In this workflow example, we deploy another Meraki vMX in a Spoke VPC as a branch device and configure Hub-and-spoke Auto VPN Connection to verify this solution. Please adjust the topology depending on your requirements. For more Meraki VPN info, please check out the below documents: - `Configuring Hub-and-spoke VPN Connections on the MX Security Appliance <https://documentation.meraki.com/MX/Site-to-site_VPN/Configuring_Hub-and-spoke_VPN_Connections_on_the_MX_Security_Appliance>`_ - `Meraki Auto VPN <https://documentation.meraki.com/MX/Site-to-site_VPN/Meraki_Auto_VPN>`_ Step 2.1. Deploy branch Meraki vMX in Spoke VPC --------------------------------------------------------- - Follow step 1.1. but deploy Meraki vMX in Spoke VPC .. important:: Since Meraki vMX is deployed as a branch device in AWS as an example here, please follow the checklist as below: - Assign an EIP to Meraki vMX's interface - Make sure the function "Source/Dest check" on Meraki vMX's interface is disabled - Since One-Armed Concentrator mode is adopted in this document, the vMX is configured with a single Network Interface which means all traffic will be sent and received on this interface. Make sure both security group and routing table are configured properly. Step 2.2. Check branch Meraki vMX status on Meraki Dashboard --------------------------------------------------------------------- #. Log in to the Meraki Dashboard. #. Select the "NETWORK" where this Cisco Meraki vMX in Spoke VPC locates. #. Go to Security & SD-WAN -> MONITOR -> Appliance status. #. Check whether branch Cisco Meraki device displays "Active" status. |cisco_meraki_aws_branch_vMX_appliance_status| Step 2.3. Enable Spoke type ----------------------------------------------------------- #. Select the "NETWORK" where this Cisco Meraki vMX in Spoke VPC locates. #. Go to Security & SD-WAN -> CONFIGURE -> Site-to-site VPN. #. Find the panel "Type" on the top. #. Select the radio button "Spoke" to establish VPN tunnels with selected hubs. #. Click the link "Add a hub" for the field "Hubs." #. Select the "NETWORK" where the Cisco Meraki vMX in Transit VPC locates for Hubs. |cisco_meraki_aws_branch_vMX_s2s_spoke_type| Step 2.4. Advertise Spoke VPC CIDR ----------------------------------------------------------- 1. Locate "Local networks" in the panel "VPN settings." 2. Click the button "Add a local network." 3. Fill the parameters to advertise Spoke VPC CIDR. +-------------------+---------------------------------------------------------+ | Name | Provide a unique name for the Local networks | +-------------------+---------------------------------------------------------+ | Subnet | Configure Spoke VPC CIDR as an example (192.168.2.0/24) | +-------------------+---------------------------------------------------------+ | VPN participation | VPN on | +-------------------+---------------------------------------------------------+ 4. Click "Save." |cisco_meraki_aws_branch_vMX_s2s_vpn_settings| Step 2.5. Check VPN status ----------------------------------------------------------- #. Select the "NETWORK" where this Cisco Meraki vMX in Spoke VPC locates. #. Go to Security & SD-WAN -> MONITOR -> VPN status. #. Check whether VPN status is Green and VPN Registry is Connected. |cisco_meraki_aws_branch_vMX_s2s_vpn_status| 3. Deploy Aviatrix Multi-Cloud Transit Solution ================================================= Refer to `Global Transit Network Workflow Instructions <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ for the below steps. Please adjust the topology depending on your requirements. Step 3.1. Deploy Aviatrix Multi-Cloud Transit Gateway ------------------------------------------------------------ - Follow this step `Deploy the Transit Aviatrix Gateway <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html#step-2-deploy-the-transit-aviatrix-gateway>`_ to launch Aviatrix Transit gateway in Transit VPC. - In this example, size c5n.4xlarge is selected. .. important:: The Aviatrix Transit Gateway must be deployed in the same available zone where Cisco Meraki vMX locates. Design Pattern #1: Aviatrix Spoke Gateway for encryption traffic ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Step 3.2. Deploy Aviatrix Spoke Gateway for encryption traffic --------------------------------------------------------------- - Follow this step `Deploy Spoke Gateways <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html#step-3-deploy-spoke-gateways>`_ to launch Aviatrix Spoke gateway in Spoke VPC Step 3.3. Attach Spoke Gateways to Transit Network -------------------------------------------------- - Follow this step `Attach Spoke Gateways to Transit Network <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html#step-4-attach-spoke-gateways-to-transit-network>`_ to attach Aviatrix Spoke Gateways to Aviatrix Transit Gateways Design Pattern #2: Spoke VPC through AWS TGW Orchestrator ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Step 3.4. Deploy Spoke VPC through AWS TGW Orchestrator -------------------------------------------------------- - Follow Aviatrix TGW Orchestrator workflow `TGW Plan <https://docs.aviatrix.com/HowTos/tgw_plan.html>`_ to: #. Create AWS TGW. #. Create a New Security Domain and Build Your Domain Connection Policies. #. Prepare Aviatrix Transit GW for TGW Attachment. # Attach Aviatrix Transit GW to TGW. #. Follow Aviatrix TGW Orchestrator workflow `TGW Build <https://docs.aviatrix.com/HowTos/tgw_build.html>`_ to Attach VPC to TGW. 4. Build BGP over LAN ================================================ Step 4.1. Configure BGP over LAN on Aviatrix Transit Gateway ------------------------------------------------------------- 1. Log in to the Aviatrix Controller. 2. Go to MULTI-CLOUD TRANSIT -> Setup -> 3) Connect to VGW / External Device / Aviatrix CloudN / Azure VNG. 3. Select option "External Device" -> "BGP" -> "LAN." 4. Fill the parameters to set up BGP over LAN to Meraki vMX in Transit VPC. +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Transit VPC Name | Select the Transit VPC ID where Transit GW was launched | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Connection Name | Provide a unique name to identify the connection to external device | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Aviatrix Transit Gateway BGP ASN | Configure a BGP AS number that the Transit GW will use to exchange routes with external device | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Primary Aviatrix Transit Gateway | Select the Transit GW | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Enable Remote Gateway HA | Uncheck this option in this example | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Remote BGP AS Number | Configure a BGP AS number that Meraki vMX will use to exchange routes with Aviatrix Transit Primary | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Remote LAN IP | Use the private IP of the Network Interface on Meraki vMX | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Local LAN IP | Leave it blank and the controller will assign an IP in the same subnet where the Remote LAN IP locates. Optionally configure an IP of your choosing within the same subnet where the Remote LAN IP locates. | +----------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ 5. Click "CONNECT" to generate BGP session over LAN. |aviatrix_transit_externel_device_lan| Step 4.2. (Optional) Download the BGP over LAN configuration sample from Aviatrix Controller -------------------------------------------------------------------------------------------- #. Navigate to SITE2CLOUD -> Setup. #. Select the connection that you created with “Connection Name” in the previous step. #. Click the button "EDIT." #. Select Vendor type, Platform, and Software. #. Click "Download Configuration." Step 4.3. Enable and configure BGP over LAN on Cisco Meraki vMX --------------------------------------------------------------- For more Cisco Meraki BGP information, please check this `doc <https://documentation.meraki.com/MX/Networks_and_Routing/BGP>`_ 1. (Optional) Open the downloaded BGP over LAN configuration file. 2. Login Meraki Dashboard. 3. Select the "NETWORK" where this Cisco Meraki vMX in Transit VPC locates. 4. Go to Security & SD-WAN -> CONFIGURE -> Site-to-site VPN. 5. Find the section "BGP neighbors" in the panel "BGP settings." 6. Click the link "Add a BGP neighbor." +----------------+-------------------------------------------------------------------------------------------------------------------+ | Neighbor IP | Use Aviatrix Transit gateway's eth4 private IP. This IP belongs to the same subnet where Meraki vMX eth0 locates. | +----------------+-------------------------------------------------------------------------------------------------------------------+ | Remote AS | Configure Aviatrix Transit Gateway BGP ASN | +----------------+-------------------------------------------------------------------------------------------------------------------+ | Receive limit | Leave it blank or optional in this example | +----------------+-------------------------------------------------------------------------------------------------------------------+ | Allow transit | Uncheck this option in this example | +----------------+-------------------------------------------------------------------------------------------------------------------+ | EBGP Holdtimer | 30 for this example | +----------------+-------------------------------------------------------------------------------------------------------------------+ | EBGP Multihop | 1 for this example | +----------------+-------------------------------------------------------------------------------------------------------------------+ 7. Click "Save." |cisco_meraki_aws_vMX_bgp_over_lan| .. important:: Update Meraki vMX's security group to allow traffic coming from Aviatrix Transit Gateway properly. One of the secure approaches is to specify Aviatrix Transit Gateway's eth4 security group ID as the source for the Inbound rule in Meraki vMX's security group. Please check "Security group rules" in this AWS `doc <https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html>`_ for more info. Step 4.4. Verify LAN status on Aviatrix Controller ---------------------------------------------------------- #. Navigate back to the Aviatrix Controller. #. Go to SITE2CLOUD -> Setup. #. Find the connection that you created with “Connection Name” in the previous step. #. Check the Tunnel Status. |aviatrix_bgp_lan_status_1| #. Go to MULTI-CLOUD TRANSIT -> List. #. Select the Transit Primary Gateway that was created in the previous step. #. Click the button "DETAILS/DIAG." #. Scroll down to the panel "Connections" -> "On-prem Connections." #. Find the connection that you created with “Connection Name” in the previous step. #. Check the Tunnel Status. |aviatrix_bgp_lan_status_2| Step 4.5. Verify BGP session status on Aviatrix Controller ---------------------------------------------------------- #. Go to MULTI-CLOUD TRANSIT -> BGP. #. Find the connection that you created with “Connection Name” in the previous step. #. Check the BGP Status. |aviatrix_bgp_status| Step 4.6. Verify BGP session status on Cisco Meraki vMX ---------------------------------------------------------- #. Login Meraki Dashboard. #. Select the "NETWORK" where this Cisco Meraki vMX in Transit VPC locates. #. Go to Security & SD-WAN -> MONITOR -> Event log. |cisco_meraki_aws_vMX_bgp_event_log| Step 4.7. Verify routing info on Cisco Meraki vMX ---------------------------------------------------------- #. Login Meraki Dashboard. #. Select the "NETWORK" where this Cisco Meraki vMX in Transit VPC locates. #. Go to Security & SD-WAN -> MONITOR -> Route table. #. Check whether Cisco Meraki vMX has the routes to branch Cisco Meraki device via VPN. #. Check whether Cisco Meraki vMX has the routes to Aviatrix Spoke VPC via BGP on LAN. |cisco_meraki_aws_vMX_routing_info| Step 4.8. Verify routing info on branch Cisco Meraki device ----------------------------------------------------------- #. Log in to the Meraki Dashboard. #. Select the "NETWORK" where this branch Cisco Meraki locates. #. Go to Security & SD-WAN -> MONITOR -> Route table. #. Check whether Cisco Meraki vMX has the routes to Aviatrix Spoke VPC via Cisco Meraki vMX in Transit VPC. |cisco_meraki_aws_branch_vMX_routing_info| .. note:: If iBGP protocol betweeen Meraki vMX in Transit VPC and branch Meraki device does not establish properly, please attempt to reboot Meraki vMX in Transit VPC. 5. Ready to go! ================= At this point, run connectivity and performance test to ensure everything is working correctly. 6. Troubleshooting Tips ======================== - Check to make sure "Source/Dest check" on Meraki vMX's interface is disabled. - Check whether the routing table and security group are configured properly. - Check eBGP is established between Aviatrix Transit Gateway and Meraki vMX in Transit VPC. - Check iBGP is established between Meraki vMX and branch Meraki device. .. |cisco_meraki_aws_tgw_orchestrator_diag| image:: transit_gateway_external_device_bgp_over_lan_with_aws_meraki_workflow_media/cisco_meraki_aws_tgw_orchestrator_diag.png :scale: 50% .. |cisco_meraki_aviatrix_transit_solution_diag| image:: transit_gateway_external_device_bgp_over_lan_with_aws_meraki_workflow_media/cisco_meraki_aviatrix_transit_solution_diag.png :scale: 50% .. |cisco_meraki_aws_vMX_appliance_status| image:: transit_gateway_external_device_bgp_over_lan_with_aws_meraki_workflow_media/cisco_meraki_aws_vMX_appliance_status.png :scale: 50% .. |cisco_meraki_aws_vMX_s2s_hub_type| image:: transit_gateway_external_device_bgp_over_lan_with_aws_meraki_workflow_media/cisco_meraki_aws_vMX_s2s_hub_type.png :scale: 50% .. |cisco_meraki_aws_vMX_s2s_bgp_enable| image:: transit_gateway_external_device_bgp_over_lan_with_aws_meraki_workflow_media/cisco_meraki_aws_vMX_s2s_bgp_enable.png :scale: 50% .. |cisco_meraki_aws_branch_vMX_appliance_status| image:: transit_gateway_external_device_bgp_over_lan_with_aws_meraki_workflow_media/cisco_meraki_aws_branch_vMX_appliance_status.png :scale: 50% .. |cisco_meraki_aws_branch_vMX_s2s_spoke_type| image:: transit_gateway_external_device_bgp_over_lan_with_aws_meraki_workflow_media/cisco_meraki_aws_branch_vMX_s2s_spoke_type.png :scale: 50% .. |cisco_meraki_aws_branch_vMX_s2s_vpn_settings| image:: transit_gateway_external_device_bgp_over_lan_with_aws_meraki_workflow_media/cisco_meraki_aws_branch_vMX_s2s_vpn_settings.png :scale: 50% .. |cisco_meraki_aws_branch_vMX_s2s_vpn_status| image:: transit_gateway_external_device_bgp_over_lan_with_aws_meraki_workflow_media/cisco_meraki_aws_branch_vMX_s2s_vpn_status.png :scale: 50% .. |aviatrix_transit_externel_device_lan| image:: transit_gateway_external_device_bgp_over_lan_with_aws_meraki_workflow_media/aviatrix_transit_externel_device_lan.png :scale: 30% .. |cisco_meraki_aws_vMX_bgp_over_lan| image:: transit_gateway_external_device_bgp_over_lan_with_aws_meraki_workflow_media/cisco_meraki_aws_vMX_bgp_over_lan.png :scale: 50% .. |aviatrix_bgp_lan_status_1| image:: transit_gateway_external_device_bgp_over_lan_with_aws_meraki_workflow_media/aviatrix_bgp_lan_status_1.png :scale: 30% .. |aviatrix_bgp_lan_status_2| image:: transit_gateway_external_device_bgp_over_lan_with_aws_meraki_workflow_media/aviatrix_bgp_lan_status_2.png :scale: 30% .. |aviatrix_bgp_status| image:: transit_gateway_external_device_bgp_over_lan_with_aws_meraki_workflow_media/aviatrix_bgp_status.png :scale: 30% .. |cisco_meraki_aws_vMX_bgp_event_log| image:: transit_gateway_external_device_bgp_over_lan_with_aws_meraki_workflow_media/cisco_meraki_aws_vMX_bgp_event_log.png :scale: 50% .. |cisco_meraki_aws_vMX_routing_info| image:: transit_gateway_external_device_bgp_over_lan_with_aws_meraki_workflow_media/cisco_meraki_aws_vMX_routing_info.png :scale: 50% .. |cisco_meraki_aws_branch_vMX_routing_info| image:: transit_gateway_external_device_bgp_over_lan_with_aws_meraki_workflow_media/cisco_meraki_aws_branch_vMX_routing_info.png :scale: 50% .. |cisco_meraki_aviatrix_transit_solution_illustration_diag| image:: transit_gateway_external_device_bgp_over_lan_with_aws_meraki_workflow_media/cisco_meraki_aviatrix_transit_solution_illustration_diag.png :scale: 50% .. |cisco_meraki_aws_tgw_orchestrator_illustration_diag| image:: transit_gateway_external_device_bgp_over_lan_with_aws_meraki_workflow_media/cisco_meraki_aws_tgw_orchestrator_illustration_diag.png :scale: 50% .. disqus:: <file_sep> ################################### Troubleshoot ################################### There are several ways to troubleshoot and debug errors within Aviatrix. Upload tracelog -------------------- On the controller console left side menu, click Troubleshoot, click Logs and select a gateway at Upload Tracelog. The controller and gateway tracelog will be uploaded to Aviatrix. The Aviatrix support team will be alerted. If no gateway is selected, only the controller log is uploaded. Run diagnostics on a gateway ---------------------------- Troubleshoot->Diagnostics->Gateway->Diagnostics, select a gateway to run diagnostics. Click run. When it finishes, click Show to display on the console. The diagnostics test if the gateway is reachable and its services are up and running. Please refer to the `Service Description of Diagnostic Result <http://docs.aviatrix.com/HowTos/Troubleshooting_Diagnostics_Result.html>`__. If you could not determine the root cause based on the diagnostics, click Submit to send the diagnostics result to Aviatrix support team. Debug peering tunnel status ----------------------------- Click Peering on the console. click Diag on each peer pair and run various tests. Debug Site2Cloud tunnel status --------------------------------- Click Site2Cloud on the console. Click Diagnostics. Debug gateway connectivity -------------------------- To test if a gateway can reach a certain IP or host, click Troubleshoot->Diagnostics->Network. At Network Connectivity Utility panel, select a gateway. Specify the remote host name, port number. The TCP protocol test is reliable. Currently UDP test is not reliable. Network Traceroute ------------------- You can run a traceroute function from a selected Aviatrix gateway to test reachability from this gateway to any destination. Go to Troubleshooting -> Network. Scroll down to TRACEROUTE UTILITY. Enter a destination IP or host name and select a gateway and, click Trace Route. The Trace Route results should be displayed when the execution finishes. .. tip:: You can launch an Aviatrix gateway in a specific VPC and public subnet and use it as an EC2 instance to test connectivity to a destination host or IP address. For example, launch an Aviatrix gateway in a Spoke VPC (where the Spoke VPC gateway is launched from the `Transit Network Workflow <http://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_). When you select this test gateway for Trace Route testing, you are effectively testing connectivity going from an EC2 -> Spoke VPC GW -> Transit GW -> VGW -> on-prem network. Packet capture --------------- Click Troubleshoot->Diagnostics->Network. At the Packet Capture panel, select a gateway where you wish to do packet capture. You can further filter on Host and Port number. Click Start to start the capture, click Stop to stop the capture, then click Download to download the pcap file. You can also specify capture time. The pcap file can be viewed by Wireshark. DNS Error ---------- If you see a DNS related error on the controller console, check your VPC/VNet DNS setting. It is possible that the controller or gateway does not have connectivity to the DNS server. If your DNS server is located on-prem, make sure the VPC/VNet where controller is launched has connection to reach the private DNS server. .. disqus:: <file_sep> Advanced Config ================= Configuration Updates with the Aviatrix GUI -------------------------------------------- To update your Aviatrix gateway configuration, see the `Launching a Gateway <https://docs.aviatrix.com/HowTos/gateway.html>`_. To deploy Aviatrix CoPilot, see the `Aviatrix CoPilot Deployment Guide <https://docs.aviatrix.com/HowTos/copilot_getting_started.html>`_. To update your Aviatrix Firewall configuration, see the `Firewall Network (FireNet) Workflow <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html>`_. Configuration Updates with Terraform -------------------------------------------- To update your Aviatrix configuration with Terraform, see the `Aviatrix Terraform Registry <https://registry.terraform.io/providers/AviatrixSystems/aviatrix/latest>`_. Tunnel -------- Specify a IPSec tunnel down detection time. The minimum is 20 Seconds. If Controller is selected, all gateways share the same tunnel down detection time. Aviatrix gateways samples the tunnel status every 10 seconds. Anti-replay Window ------------------ Specify the IPSec tunnel anti-replay window size. - The size range is 0 to 4096. - The default value is 0. - Set the size to 0 to disable anti-replay protection. - If “controller” of “Aviatrix Entity” is selected, all gateways share the same tunnel anti-replay window. Keepalive --------- In normal state, Aviatrix gateways send keep alive messages to the Controller. Keep Alive Speed determines when Controller determines if a gateway is down. See `Gateway State <https://docs.aviatrix.com/HowTos/gateway.html#gateway-state>`_ for more information. Password Requirements ---------------------- Aviatrix uses a password meter to enforce password requirements. The default password requirements are: - Minimum characters - 4. - Maximum characters - 16,777,216 or 16MB. - At least 1 upper and 1 lower case character. - At least 1 numeral character. - At least one special character. Password Management ---------------------- By default, password management is disabled for controller's account users which means there is no restriction for password length and expiration validity check. If company's requires strict regulation for passwords then password restriction can be managed and enabled in Controller's console. Navigate to Settings -> Advanced -> Password Management to enable password management. Password Management allows to put the following restriction for account's user: #. Minimum Password Length #. Maximum Password Age(Days) and #. Enforce Password History which force users to use new strong password. If you are using the Password Management option, the policy default values are: - Minimum characters – 8. - Age limit - 180 days. - Not repeatable times – 5. If you are using the Password Management option, the policy ranges are: - Minimum characters – 8. - Maximum characters – 32. - Age limit is 1 - 365 days. - Not repeatable times is 1 – 12. Credentials --------------- In order to exercise 90 days security compliance requirement for key rotation policy, API key pair and other internal passwords for company IAM account needs to be refreshed frequently. BGP Config ------------ Go to Advanced Config -> BGP BGP Transit GW List #################### If you setup a `Transit Network <http://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_, Transit GWs will be listed under Settings -> Advanced Config -> BGP. Select one Transit GW to view details. - Advertised Networks represents the list of Spoke GW CIDR list. - Learned routes represents the list of on-prem network propagated by VGW. - Local AS Num is the Transit GW AS number you specified at the time of `Step 3 <http://docs.aviatrix.com/HowTos/transitvpc_workflow.html#connect-the-transit-gw-to-aws-vgw>`_ when connecting to VGW. BGP Dampening ############## The BGP dampening feature can be used to suppress flapping routes. It is disabled by default. Currently you cannot configure dampening parameters. BGP Diagnostics ################ Aviatrix BGP is implemented by using `Quagga <https://www.quagga.net/>`__. To troubleshoot BGP problems, go to **Advanced Config** > **BGP** > **Diagnostics** You can either type in `Quagga commands <https://www.nongnu.org/quagga/docs/docs-multi/BGP.html#BGP>`__ or use the |imageGrid| to select one of the pre-defined commands. Overlapping Alert Email ####################### Aviatrix, by default, will alert you if you add a spoke that overlaps with your on-premise network (or, if you start advertising a network from on-premise that overlaps with a spoke). However, there are some cases where you expect overlaps and the alerts are not helpful. For these cases, you can disable the overlap checking. To do this, go to: **MULTI-CLOUD-TRANSIT** > **Advanced Config** > **BGP Configuration** > **BGP Overlapping Alert Email** or in some releases, go to: **MULTI-CLOUD-TRANSIT** > **BGP** > **Configuration** > **BGP Overlapping Alert Email** Toggle the switch to **Disabled** to disable overlap checking. Proxy -------- Proxy configuration is available for Release 6.3 and later. It is a global setting that applies to Controller and all gateways. There are scenarios where a corporation requires all Internet bound web traffic be inspected by a proxy server before being allowed to enter Internet. Such requirement may apply to cloud deployment, and when it happens, both Controller and gateways need to comply to the policy. This is accomplished by enabling and configuring proxy server on the Controller. When a proxy server is configured on the Aviatrix platform (Controller and gateways), all Internet bound HTTP and HTTPS traffic initiated by the Controller and gateways is forwarded to the proxy server first before entering Internet. Such traffic includes all cloud provider API calls made by the Controller and gateways. .. important:: The domain name .aviatrix.com must be excluded by the proxy server from SSL or HTTPS termination. Configuration ################ ========================================= ========================= **Field** **Value** ========================================= ========================= HTTP Proxy proxy server IP address for HTTP traffic HTTPS Proxy proxy server IP address for HTTPS traffic (usually the same as HTTP Proxy field) (Optional) Proxy CA Certificate This field is optional. When a CA Certificate is uploaded, the Controller and gateway expect that the proxy server will terminate a HTTPS request initiated by them and will initiate a new HTTPS request on behalf of them. When this option is not used, the proxy server simply forwards HTTP/HTTPS traffic. ========================================= ========================= Test ~~~~~~ The Test option runs a few HTTPS request to make sure your proxy configuration is correct. Once all fields are configured, click Test to validate if your configuration is correct. If not, results are displayed. Correct the configuration and try again. Apply ~~~~~~~ Apply is clickable only after Test is passed. When Apply is applied, the proxy configuration takes effect. Delete ~~~~~~~ To disable proxy, click Delete. .. |imageGrid| image:: advanced_config_media/grid.png .. disqus:: <file_sep> =========================================================================================== Solving Overlapping Networks with Network Mapped IPsec =========================================================================================== The Scenario ------------------ This tech note illustrates an example solution to a specific use case. In this AWS use case, a customer needs to connect certain on-prem hosts to certain EC2 instances in a VPC over an IPsec tunnel over the Internet, but the on-prem network range overlaps with the VPC CIDR range, and the requirement from the customer is that no NAT function will be performed on the customer side. In addition, traffic can be initiated from either side. The scenario is described in the following diagram: |overlap_rbi| :: VPC CIDR = 10.20.0.0/20, instance-1 in VPC-1 has an IP address 10.24.1.4. On-Prem CIDR = 10.20.0.0/20, host-1 in On-Prem has an IP address 10.24.7.101. The traditional solution is to build IPsec tunnel between the two networks and use SNAT/DNAT rules to translate each addresses, as demonstrated in this `example. <https://docs.aviatrix.com/HowTos/connect_overlap_cidrs.html>`_. Such solution requires a potentially large number of SNAT/DNAT rules which is difficult to configure and maintain. The Solution ------------------ The new solutions uses a new "network mapped" feature in Site2Cloud that removes the need to configure individual SNAT/DNAT rules. This solution uses a Site2Cloud route-based IPsec tunnel using Virtual Tunnel Interface (VTI) between VPC and On-Prem Router. The packet flow is demonstrated as below: 1. instance-1 sends a packet to host-1 with a virtual destination IP address, for example 192.168.3.11. From instance-1's point of view, the destination instance is a virtual address - 192.168.3.11. #. When the packet arrives at the VPC-1 gateway, the gateway does DNAT on the packet to translate the virtual destination IP address to 10.24.7.101 which is the host-1 physical IP address. #. The gateway at VPC then translates the packet source IP address (10.24.1.4) to a virtual source IP address, say it is 172.24.1.4. #. The packet then arrives at On-Prem Cisco IOS Router with destination IP address 10.24.7.101 and source IP address 172.24.1.4. From host-1's point of view, instance-1's address is a virtual IP address - 172.24.1.4. #. When host-1 sends a packet to instance-1, the destination is the virtual IP address 172.24.1.4. #. When the packet arrives at the VPC-1 gateway over the IPSEC tunnel, the VPC gateway translates its destination IP address from virtual address 172.24.1.4 to 10.24.1.4. #. The VPC gateway then translates the source IP address of the packet from 10.24.7.101 to virtual address 192.168.3.11. The Configuration Steps -------------------------------- Following the Site2Cloud Workflow to Launch Gateways ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Log in to the Controller and select Site2Cloud from the left sidebar. Follow the Site2Cloud worflow to launch a gateway in the VPC. (You can follow the `gateway launch instructions in this <http://docs.aviatrix.com/HowTos/gateway.html>`_. Leave optional parameters unchecked.) Creating a Site2Cloud Tunnel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Go to Controller Console > Site2Cloud. Click **+Add New**. Fill the form and click **OK**. Select **Mapped** for the Connection Type field. |s2c_connection| VPC-1 gateway-1 side ######################### For the VPC gateway side, the Local Subnet field should be the subnet of VPC-1 (e.g. 10.24.0.0/20), and the Remote Subnet field should be the subnet of OnPrem Router (e.g. 10.24.0.0/20), as shown below. ================================================== ======================================================================= **Field** **Value** ================================================== ======================================================================= VPC ID/VNet Name Choose VPC ID Connection Type Mapped Connection Name Arbitrary (e.g. S2C-VPC-OnPrem) Remote Gateway Type Generic Tunnel Type Route-based Algorithms Unmark this checkbox Encryption over ExpressRoute/Direct Connect Unmark this checkbox Enable HA Check this box if HA is required Primary Cloud Gateway Select the Aviatrix Gateway created above Remote Gateway IP Address Public IP of IOS Router WAN port (172.16.31.10 in this example) Pre-shared Key Optional (auto-generated if not entered) Remote Subnet (Real) 10.24.0.0/20 (On-Prem Network CIDR) Remote Subnet (Virtual) Any/20 (On-Prem Network Virtual CIDR) Local Subnet (Real) 10.24.0.0/20 (VPC-Cloud Network CIDR) Local Subnet (Virtual) Any/20 (VPC-Cloud Network Virtual CIDR) ================================================== ======================================================================= |vpc_to_onprem_rbipsec| .. important:: Local & Remote Subnet (virtual) IP range could be anything but subnet should be same as Physical/Real subnet. Configure On-Prem Cisco Router ################################### Go to the **Site2Cloud** page. From the Site2Cloud connection table, select the connection created above (e.g. S2C-VPC-OnPrem) and click "Edit". - Select **Cisco** from **Vendor** drop down list, select **ISR, ASR, or CSR** from **Platform** drop down list and select **IOS(XE)** from **Software** drop down list. - Click the **Download Configuration** button to download the **Cisco IOS** Site2Cloud configuration - Save the configuration file as a reference for configuring your Cisco IOS router The following is a sample configuration based on the Site2Cloud configuration above. |ios_config_template| Either ssh into the Cisco router or connect to it directly through its console port. Apply the following IOS configuration to your router: :: ! Aviatrix Site2Cloud configuration template ! ! You need to populate these values throughout the config based on your setup: ! <isakmp_policy_number1>: the isakmp policy number ! <tunnel_number1>: the IPsec tunnel interface number ! <ios_wan_interface1>: the source interface of tunnel packets ! <customer_tunnel_ip1>: any un-used IPv4 address for the tunnel interface ! when static routing is used ! ! -------------------------------------------------------------------------------- ! IPsec Tunnel ! -------------------------------------------------------------------------------- ! #1: Internet Key Exchange (IKE) Configuration ! A policy is established for the supported ISAKMP encryption, ! authentication, Diffie-Hellman, lifetime, and key parameters. ! crypto keyring 52.40.45.197-192.168.3.116 pre-shared-key address 172.16.31.10 key <key> ! crypto isakmp policy 1 encryption aes 256 hash sha256 authentication pre-share group 14 lifetime 28800 crypto isakmp keepalive 10 3 periodic crypto isakmp profile 172.16.31.10-172.16.31.10 keyring 52.40.45.197-172.16.31.10 self-identity address match identity address 172.16.31.10 255.255.255.255 ! !--------------------------------------------------------------------------------- ! #2: IPsec Configuration ! The IPsec transform set defines the encryption, authentication, and IPsec ! mode parameters. ! crypto ipsec transform-set 172.16.31.10-192.168.3.116 esp-aes 256 esp-sha256-hmac mode tunnel crypto ipsec df-bit clear ! crypto ipsec profile 172.16.31.10-192.168.3.116 set security-association lifetime seconds 3600 set transform-set 172.16.31.10-192.168.3.116 set pfs group14 set isakmp-profile 172.16.31.10-172.16.17.3256 ! !--------------------------------------------------------------------------------------- ! #3: Tunnel Interface Configuration ! The virtual tunnel interface is used to communicate with the remote IPsec endpoint ! to establish the IPsec tunnel. ! interface Tunnel1 ip address 10.10.10.10 255.255.255.255 ip mtu 1436 ip tcp adjust-mss 1387 tunnel source GigabitEthernet1 tunnel mode ipsec ipv4 tunnel destination 172.16.31.10 tunnel protection ipsec profile 172.16.31.10-192.168.3.116 ip virtual-reassembly ! !--------------------------------------------------------------------------------------- ! #4: Static Routing Configuration ! The static route directs the traffic to the Aviatrix remote subnets via the tunnel ! interface. ! ip route 172.24.0.0 255.255.240.0 Tunnel1 !--------------------------------------------------------------------------------------- Wait for the tunnel to come up. Testing the Site2Cloud Connection --------------------------------------------------------- Make sure your instance's Security Groups inbound rules are configured properly. From instance-1, you should be able to ping host-1 by "ping 192.168.3.11". From host-1, you should be able to ping instance-1 by "ping 172.24.1.4" .. |s2c_connection| image:: connect_overlap_cidrs_media/s2c_connection.png :scale: 35% .. |overlap_rbi| image:: connect_overlap_cidrs_media/overlap_rbi.png :scale: 40% .. |vpc_to_onprem_rbipsec| image:: connect_overlap_cidrs_media/vpc_to_onprem_rbipsec.png :scale: 35% .. |ios_config_template| image:: connect_overlap_cidrs_media/ios_config_template.png :scale: 30% .. disqus:: <file_sep> =========================================================================== Gateway and Tunnel HA Options =========================================================================== Overview -------------------------------------- The Aviatrix Controller monitors your cloud networking deployment, detects problems, and handles failover resolution automatically. There are 3 options to choose from when deploying Aviatrix in a highly available architecture: +--------------------------------------------------+---------------------------+ | HA Option | Recovery Time ``*`` | +==================================================+===========================+ | `Backup Gateway and Tunnel(s) <#gwha-option3>`__ | ~30 seconds | +--------------------------------------------------+---------------------------+ | `Single AZ Gateway <#gwha-single-az>`__ | 4-5 minutes | +--------------------------------------------------+---------------------------+ | `Backup Gateway(deprecated) <#gwha-backup-gw>`__ | 1-2 minutes | +--------------------------------------------------+---------------------------+ ``*`` Recovery times vary based on many factors including the number of tunnels established. These options give you the flexibility to select the one that meets your requirements for recovery time. For production environments, a quicker recovery time is typically very important. But, for development environments, a longer delay is acceptable. With Aviatrix HA, you can mix and match these options in your deployment to meet your needs. As the recovery time decreases, there may be additional costs to consider. Single AZ has no additional costs. Backup Gateway will incur additional instance charges (for the additional gateway provisioned). Backup Gateway and Tunnel(s) will also incur additional costs. How is a Gateway or Tunnel Determined to be Down? ----------------------------------------------------------------------- See more details `here <../HowTos/gateway.html#gateway-keepalives>`__. .. _gwha_option3: HA Options ------------------ Backup Gateway and Tunnel(s) ############################ .. note:: The recovery time for this option is approximately 30 seconds. |imageGwBackupTunnel| |imageTimer30sec| The backup gateway has its own EIP and active tunnel(s). The backup gateway and tunnels are provisioned when HA is enabled for this gateway. If a problem with the primary gateway or connected tunnel(s) is detected: #. Update the routing table in the VPC/VNet so the target for routes is the backup gateway. #. An email notification is sent to the administrator. .. _gwha_single_az: Single AZ Gateway ################# .. note:: The recovery time for this option is approximately 4-5 minutes. |imageGwSingleAZ| |imageTimer5min| The gateway is actively monitored by the Controller. If there is a problem with the gateway or tunnel(s): #. The gateway is stopped and started again. #. Any configured tunnels are established from the new gateway to their respective terminating gateway. #. An email notification is sent to the administrator. Please look `here <https://docs.aviatrix.com/HowTos/gateway.html#gateway-single-az-ha>`_ for more information. .. _gwha_backup_gw: Backup Gateway ############## .. note:: The recovery time for this option is approximately 1-2 minutes. This feature has been deprecated. Not recommended for new customers. |imageGwBackup| |imageTimer2min| A backup gateway in a different Availability Zone is created when this option is enabled. There are no tunnels terminating with the backup gateway and it does not have its own EIP. If a problem with the primary gateway or connected tunnel(s) is detected: #. The EIP is moved to the backup gateway from the active. #. Tunnels currently connected to the primary gateway are rebuilt on the backup gateway. #. An email notification is sent to the administrator. Deployment Guide ----------------------------- Deploying your desired HA model is simple. Follow these steps to enable HA on your gateway: #. Log in to the Controller. #. Click on the Gateway navigation item. #. Select the gateway in the table and click **Edit** in the upper right. |imageEditGW| #. Follow the steps below for the desired HA option. * **Backup Gateway and Tunnel HA** #. Scroll to Gateway for High Availability Peering. #. Select the subnet where the backup gateway should be deployed. .. tip:: Select an Availability Zone that is different from where your primary gateway is installed. #. Click **+Create** button. |imageEnableBackupGWAndTunnel| * **Single AZ HA** Click **Enable** below Gateway Single AZ HA. |imageEnableSingleAZ| * **Backup Gateway HA (deprecated)** #. Scroll to **Gateway for High Availability**. #. Select the subnet where the backup gateway should be deployed. .. tip:: Select an Availability Zone that is different from where your primary gateway is installed. #. Click the **Enable HA** button. |imageEnableBackupGW| .. |imageEnableBackupGWAndTunnel| image:: gateway_ha_media/controller_edit_backup_gw_tunnel.png :scale: 50% .. |imageEnableBackupGW| image:: gateway_ha_media/controller_edit_backup_gw.png :scale: 50% .. |imageEnableSingleAZ| image:: gateway_ha_media/controller_edit_singleaz.png :scale: 50% .. |imageEditGW| image:: gateway_ha_media/controller_gateway_page.png :scale: 50% .. |imageCostEC2| image:: gateway_ha_media/cost_ec2.png :height: 75px :width: 75px .. |imageCostNoEC2| image:: gateway_ha_media/cost_noec2.png :height: 75px :width: 75px .. |imageCostAviatrix| image:: gateway_ha_media/cost_aviatrix.png :height: 75px :width: 75px .. |imageCostNoAviatrix| image:: gateway_ha_media/cost_noaviatrix.png :height: 75px :width: 75px .. |imageTimer30Sec| image:: gateway_ha_media/timer_30sec.png :height: 75px :width: 75px .. |imageTimer2Min| image:: gateway_ha_media/timer_2min.png :height: 75px :width: 75px .. |imageTimer5Min| image:: gateway_ha_media/timer_5min.png :height: 75px :width: 75px :align: top .. |imageGwSingleAZ| image:: gateway_ha_media/singleaz_gateway.png .. |imageGwBackup| image:: gateway_ha_media/backup_gateway.png .. |imageGwBackupTunnel| image:: gateway_ha_media/backup_gateway_and_tunnel.png <file_sep> ========================================================= Azure Ingress Firewall Setup Solution ========================================================= This document illustrates a simple architecture for Ingress traffic inspection firewall that leverages Azure Load Balancers, `Transit FireNet for Azure <https://docs.aviatrix.com/HowTos/transit_firenet_faq.html>`_, and `Azure Transit with Native Spoke VNets <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#b-attach-azure-arm-spoke-vnet-via-native-peering>`_. The solution also allows you to view the client IP address. The deployment is shown as the diagram below. |transit_firenet_vnet| The key idea is from FireNet point of view, the ingress inspection is simply a VNet-to-VNet traffic inspection. This is accomplished by #. Place an Internet facing Azure Application Gateway in a spoke VNet (in the diagram, this spoke VNet is called Ingress Spoke VNet) to load balance traffic to the VNet where applications reside (Application Spoke VNet). #. Manage Spoke Inspection Policies for the Application Spoke VNet traffic that requires inspection with the Aviatrix Transit VNet. In this unified architecture, firewalls can be used for Ingress, Egress, North-South and VNet-to-VNet filtering. The solution does not need Azure Load Balancers to directly attach to firewall instances which then requires firewall instances to source NAT the incoming traffic from the Internet. Firewall instances can scale out as applications scale for all traffic types. .. Note:: This architecture works for `Azure Application Gateway <https://docs.microsoft.com/en-us/azure/application-gateway/overview>`_. You can create multiple load balancers in the Ingress Spoke VNet. Prerequisite Setup -------------------------------- First, upgrade the Aviatrix Controller to at least version UserConnect-5.3.1428. - https://docs.aviatrix.com/HowTos/inline_upgrade.html In this instruction, we are going to deploy the below topology in Azure. - Azure VNets - Aviatrix Transit VNet (i.e. 192.168.23.0/24) - Ingress Spoke VNet (i.e. 10.20.0.0/16) - Application Spoke VNet (i.e. 10.21.0.0/16) - Azure Transit with Native Spoke VNets topology .. Note:: Aviatrix Transit FireNet for Azure Encrypted Transit topology also supports this Azure Ingress Firewall Solution. Deploy an Aviatrix Transit VNET ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Create an Aviatrix Transit VNet by using the Aviatrix feature `Create a VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ with the Aviatrix FireNet VPC option enabled. 1. Go to the Aviatrix Controller. #. Open Useful Tools on the left sidebar > Create a VPC. #. Click **+ Add new** to create a new VPC with Cloud Type Azure ARM. #. Enable **Aviatrix FireNet VPC** checkbox. Deploying an Ingress Spoke VNET ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Create an Ingress Spoke VNET by using the Aviatrix feature `Create a VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ as the previous step or manually deploying it in Azure portal. Moreover, feel free to use your existing VNet. Deploying an Application Spoke VNET ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Create an Application Spoke VNET by utilizing Aviatrix feature `Create a VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ as the previous step or manually deploying it in Azure portal. Moreover, feel free to use your existing Application VNET. Deploying Azure Transit with Native Spoke VNets Topology ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Follow `Global Transit Network Workflow Instructions (AWS/Azure/GCP/OCI) <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ to deploy Azure Transit with Native Spoke VNets topology. - Create an Aviatrix Transit Gateway in Aviatrix Transit VNET by following the step `Launch a Transit Gateway <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-a-transit-gateway>`_ as the following screenshot. .. important:: For Azure deployment, the Aviatrix Transit Gateway must be launched with the option Enable Transit FireNet Function enabled. The minimum Azure FireNet gateway size is Standard_B2ms. |azure_avx_transit_gw| - Attach both Ingress Spoke VNET and Application Spoke VNET via Azure native peering by following the step `Attach Azure ARM Spoke VNet via native peering <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#b-attach-azure-arm-spoke-vnet-via-native-peering>`_. Managing Transit FireNet ^^^^^^^^^^^^^^^^^^^^^^^^ Follow `Aviatrix Transit FireNet Workflow <https://docs.aviatrix.com/HowTos/transit_firenet_workflow.html#>`_ to deploy manage FireNet policy, and firewall instances. - Manage a spoke inspection policy for the Application spoke VNET by referring to step `Manage Transit FireNet Policy <https://docs.aviatrix.com/HowTos/transit_firenet_workflow.html#manage-transit-firenet-policy>`_ as the following screenshot. |azure_avx_manage_firenet_policy| - Deploy firewall instance in Aviatrix Transit VNet by following the step `Deploy Firewall Network <https://docs.aviatrix.com/HowTos/transit_firenet_workflow.html#deploy-firewall-network>`_ as the following screenshot. Here is the Firewall information in this example for your reference. Please adjust it depending on your requirements. ========================================== ========== **Example setting** **Example value** ========================================== ========== Firewall Image Palo Alto Networks VM-Series Next-Generation Firewall Bundle 1 Firewall Image Version 9.1.0 Firewall Instance Size Standard_D3_v2 Management Interface Subnet Select the subnet whose name contains "gateway-and-firewall-mgmt" Egress Interface Subnet Select the subnet whose name contains "FW-ingress-egress" Username Applicable to Azure deployment only. “admin” as a username is not accepted. Attach Check ========================================== ========== |azure_avx_deploy_firewall| - Set up firewall configuration by referring to `Example Config for Palo Alto Network VM-Series <https://docs.aviatrix.com/HowTos/config_paloaltoVM.html>`_. .. Note:: In Azure, instead of using pem file, please use username/password to ssh into firewall instance to reset password if needed. Additionally, use the same username/password to login into firewall website. Launching an Apache2 Web server in Application Spoke VNET ------------------------------------------------------------------------------ In Application Spoke VNET, create an opensource OS virtual machine and install Apache2 HTTP Server with custom port 8080. ======================== ============== **Example setting** **Example value** ======================== ============== Protocol HTTP Port 8080 ======================== ============== .. Note:: Refer to `Install The Latest Apache2 HTTP Server ( 2.4.34 ) On opensource OS servers <https://websiteforstudents.com/install-the-latest-apache2-2-4-34-on-ubuntu-16-04-17-10-18-04-lts-servers/>`_ to install Apache2 HTTP Server. Refer to `How To Change Apache Default Port To A Custom Port <https://www.ostechnix.com/how-to-change-apache-ftp-and-ssh-default-port-to-a-custom-port-part-1/>`_ to use custom port 8080. Creating Azure Application Gateway ---------------------------------------------- In Ingress Spoke VNET, create an Azure Application Gateway. Make sure you select the following: 1. Create an Azure Application Gateway in Ingress Spoke VNET. |azure_application_gw_creation| 2. Select "Public" for Frontend IP address type in section Frontends. |azure_application_gw_frontend| 3. Select "IP address or hostname" for Target type and configure the private IP of Apache2 Web Server for Target in section Backends. |azure_application_gw_backend| 3. Add a routing rule on Listener depending on your requirement. ======================== ============== **Example setting** **Example value** ======================== ============== Frontend IP Public Protocol HTTP Port 80 ======================== ============== |azure_application_gw_routing_rule_listener| 4. Add a routing rule on Backend targets and create a HTTP setting depending on your requirement. |azure_application_gw_routing_rule_backend_target| 5. Click **Create new** on HTTP settings. |azure_application_gw_routing_rule_http_setting| ======================== ================= **Example setting** **Example value** ======================== ================= Backend protocol HTTP Backend port 8080 ======================== ================= |azure_application_gw_routing_rule_backend_target_02| 6. Review the configuration and click **Create** on the Review + create page. .. note:: Refer to the instruction `Quickstart: Direct web traffic with Azure Application Gateway - Azure portal <https://docs.microsoft.com/en-us/azure/application-gateway/quick-create-portal>`_. Ready to Go ------------------------- Make sure Server (backend pool) status is in Healthy state from the Azure portal page Application Gateway > Backend health. |azure_application_gw_health_check| Run a http request targeting on the Azure Application Gateway Public IP or DNS name. - Find the Frontend public IP address of Azure Application Gateway from the Azure portal page Application Gateway > Overview. |azure_application_gw_frontend_public_IP| - Copy the Frontend public IP address of Azure Application Gateway and paste it on a browser from your laptop/PC. |azure_browser| - Perform tcpdump with port 8080 on Apache2 Web server. |azure_application_server_tcpdump| - The Azure Application Gateway automatically preserves client original IP address in the HTTP header field "X-Forwarded-For (XFF)". .. note:: `Does Application Gateway support x-forwarded-for headers? <https://docs.microsoft.com/en-us/azure/application-gateway/application-gateway-faq#does-application-gateway-support-x-forwarded-for-headers>`_ `What is X-Forwarded-For <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For>`_ `How do I see X forwarded for in Wireshark? <https://osqa-ask.wireshark.org/questions/13384/display-http-header>`_ Viewing Traffic Log on Firewall ------------------------------------------- You can view if traffic is forwarded to the firewall instance by logging in to the Palo Alto VM-Series console. Go to Monitor > Logs > Traffic. Perform http/https traffic from your laptop/PC to the public IP or domain name of Azure Application Gateway. Capturing Client IP in Logs ------------------------------------- To view the client IP address in the access log, follow the instructions in `How to save client IP in access logs <https://aws.amazon.com/premiumsupport/knowledge-center/elb-capture-client-ip-addresses/>`_. 1. Find and open Apache configuration file. :: #vim /etc/apache2/apache2.conf 2. In the LogFormat section, add %{X-Forwarded-For}i as follows: :: ... LogFormat "%{X-Forwarded-For}i %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %b" common ... 3. Save your changes. 4. Reload the Apache service. :: #systemctl reload apache2 5. Review the public/original client IP on apache2 access log. |azure_application_server_apache2_accesslog| .. |transit_firenet_vnet| image:: ingress_firewall_example_media/transit_firenet_vnet.png :scale: 50% .. |azure_avx_transit_gw| image:: ingress_firewall_example_media/azure_avx_transit_gw.png :scale: 30% .. |azure_avx_manage_firenet_policy| image:: ingress_firewall_example_media/azure_avx_manage_firenet_policy.png :scale: 30% .. |azure_avx_deploy_firewall| image:: ingress_firewall_example_media/azure_avx_deploy_firewall.png :scale: 30% .. |azure_application_gw_creation| image:: ingress_firewall_example_media/azure_application_gw_creation.png :scale: 30% .. |azure_application_gw_frontend| image:: ingress_firewall_example_media/azure_application_gw_frontend.png :scale: 30% .. |azure_application_gw_backend| image:: ingress_firewall_example_media/azure_application_gw_backend.png :scale: 30% .. |azure_application_gw_routing_rule_listener| image:: ingress_firewall_example_media/azure_application_gw_routing_rule_listener.png :scale: 30% .. |azure_application_gw_routing_rule_backend_target| image:: ingress_firewall_example_media/azure_application_gw_routing_rule_backend_target.png :scale: 30% .. |azure_application_gw_routing_rule_backend_target_02| image:: ingress_firewall_example_media/azure_application_gw_routing_rule_backend_target_02.png :scale: 30% .. |azure_application_gw_routing_rule_http_setting| image:: ingress_firewall_example_media/azure_application_gw_routing_rule_http_setting.png :scale: 30% .. |azure_application_gw_health_check| image:: ingress_firewall_example_media/azure_application_gw_health_check.png :scale: 30% .. |azure_application_gw_frontend_public_IP| image:: ingress_firewall_example_media/azure_application_gw_frontend_public_IP.png :scale: 30% .. |azure_browser| image:: ingress_firewall_example_media/azure_browser.png :scale: 30% .. |azure_application_server_tcpdump| image:: ingress_firewall_example_media/azure_application_server_tcpdump.png :scale: 30% .. |azure_application_server_wireshark| image:: ingress_firewall_example_media/azure_application_server_wireshark.png :scale: 30% .. |azure_application_server_apache2_accesslog| image:: ingress_firewall_example_media/azure_application_server_apache2_accesslog.png :scale: 50% .. disqus:: <file_sep> ================================================ Troubleshooting IPsec VPN connection with IKEv2 ================================================ This article describes how to troubleshoot IPsec VPN connection with IKEv2 on Aviatrix gateway. Workflow ========= Check Site2Cloud Connection Status ---------------------------------- - Login Aviatrix Controller - Go to SITE2CLOUD -> Setup - Find the Site2Cloud Connection - Check the tunnel status - if the Status displays "Down", please follow the next step Perform the Diagnostics Action "Run analysis" --------------------------------------------- - Go to SITE2CLOUD -> Diagnostics - Select the related information for VPC ID/VNet Name, Connection, and Gateway - Select the option "Run analysis" under Action and click the button "OK" - View the suggestion on the prompt panel to troubleshoot Site2Cloud tunnel down issue - Follow the next step to view logs if needed Troubleshoot the keyword in the Diagnostics Action "Show logs" -------------------------------------------------------------- - Go to SITE2CLOUD -> Diagnostics - Select the related information for VPC ID/VNet Name, Connection, and Gateway - Select the option "Show logs" under Action and click the button "OK" - Review the logs on the prompt panel - Compare your logs with the successful example logs as below |IKEv2_show_log| - Attempt to locate the keyword or failure message during IKEv2/IPsec negotiation. Here are some examples of negotiation failure and hint to fix or troubleshoot it further: - `Keyword: "Error: Failed to deliver message to gateway"`_ - `Keyword: "establishing IKE_SA failed, peer not responding"`_ - `Keyword: "NO_PROPOSAL_CHOSEN"`_ - `Keyword: "AUTHENTICATION_FAILED"`_ - `Keyword: "no shared key found"`_ - `Keyword: "failed to establish CHILD_SA, keeping IKE_SA"`_ Keyword: "Error: Failed to deliver message to gateway" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Probable Causes: - Aviatrix Controller cannot reach to gateway Suggestions: - Refer to `Aviatrix Gateway Troubleshooting Playbook <https://docs.aviatrix.com/TroubleshootingPlaybook/troubleshooting_playbook_aviatrix_gateway.html>`_ Keyword: "establishing IKE_SA failed, peer not responding" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Probable Causes: - Peer IP address is mismatched, or peer IP address is not reachable - UDP Port 500/4500 is not accessible Suggestions: - Troubleshoot connectivity between Aviatrix gateway and peer VPN router Keyword: "NO_PROPOSAL_CHOSEN" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Probable Causes: - Peer IP address is mismatched, or peer IP address is not reachable - IKE version is mismatched (one VPN gateway uses IKEv1 and another one uses IKEv2) - IKEv2 algorithm is mismatched - IPsec algorithm is mismatched Suggestions: - Troubleshoot connectivity between Aviatrix gateway and peer VPN router - Verify that both VPN settings use the same IKEv2 version - Verify that all IKEv2/IPsec algorithm parameters (i.e., Authentication/DH Groups/Encryption) match on both VPN configuration Keyword: "AUTHENTICATION_FAILED" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Probable Causes: - IKE version is mismatched (one VPN gateway uses IKEv1 and another one uses IKEv2) - pre-shared key is mismatched - Identifier configuration is mismatched Suggestions: - Verify that both VPN settings use the same IKEv2 version - Verify that pre-shared key match on both VPN configuration - Verify that Identifier match - By default, Aviatrix utilizes gateway's public IP as Local Identifier. Keyword: "no shared key found" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Probable Causes: - IKE version is mismatched (one VPN gateway uses IKEv1 and another one uses IKEv2) - Identifier configuration is mismatched Suggestions: - Verify that both VPN settings use the same IKEv2 version - Verify that Identifier match - By default, Aviatrix utilizes gateway's public IP as Local Identifier. Keyword: "failed to establish CHILD_SA, keeping IKE_SA" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Probable Causes: - IPsec algorithm is mismatched Suggestions: - Verify that all IPsec algorithm parameters (i.e., Authentication/DH Groups/Encryption) match on both VPN configuration Other troubleshooting documents =============================== - `Support Center Site2Cloud <https://docs.aviatrix.com/Support/support_center_site2cloud.html>`_ - `Aviatrix Site2Cloud connection with IKEv1 End to End traffic Troubleshooting Playbook <https://docs.aviatrix.com/TroubleshootingPlaybook/troubleshooting_playbook_aviatrix_s2c_end_to_end_traffic.html>`_ .. |IKEv2_show_log| image:: site2cloud_media/IKEv2_show_log.png :scale: 50% .. disqus:: <file_sep> ################################### Logs ################################### Upload tracelog --------------- On the controller console left side menu, click Troubleshoot, click Logs and select a gateway at Upload Tracelog. The controller and gateway tracelog will be uploaded to Aviatrix. The Aviatrix support team will be alerted. If no gateway is selected, only the controller log is uploaded. Please refer to `Troubleshoot <http://docs.aviatrix.com/HowTos/troubleshooting.html>`__ for troubleshooting detail. Display Aviatrix Command Log ---------------------------- DISPLAY ~~~~~~~ This feature enables users to view Aviatrix Command Log on GUI. DISPLAY AUDIT ~~~~~~~~~~~~~ This feature enables users to view Aviatrix Audit log on GUI. DOWNLOAD AUDIT ~~~~~~~~~~~~~~ This feature enables users to download Aviatrix Audit log to local. DISPLAY EVENT ~~~~~~~~~~~~~~ This feature enables users to view Aviatrix Event log on GUI. Please refer to `Logging <https://docs.aviatrix.com/HowTos/AviatrixLogging.html>`__ for logging detail. .. disqus:: <file_sep> ============================== CloudN for Site2Cloud ============================== CloudN can be deployed on-prem as a virtual router. This guide helps you to configure Site2Cloud IPsec tunnels on CloudN that connect to an Aviatrix Gateway in an AWS VPC, Azure VNet, or Google Cloud VPC. (CloudN can also connect to any third-party router or firewall for IPsec tunnel). |image8| Configuration Workflow ====================== Before you start, make sure you have the latest software by checking the Dashboard. If an alert message is displayed, click Upgrade to download the latest software. The Site2Cloud on CloudN configuration workflow is very simple. 1. If the remote cloud gateway is an Aviatrix gateway, you should already have a configuration text file for this connection. If you need help getting file, check out `this link. <http://docs.aviatrix.com/HowTos/site2cloud.html>`_ a. Click Site2Cloud on the left navigation panel, and then click **+Add New**. #. Click **Import** (located at the right corner of the page). #. Click **OK**. You are done. #. Refresh the screen, the tunnel should be up. #. Add a static route on the default gateway where CloudN is deployed to point to CloudN as the next hop to reach the remote site. #. If the remote side is NOT an Aviatrix gateway: a. Click Site2Cloud > **+Add New**. #. Enter a Connection Name. For example: store1-to-cloud. #. At Remote Gateway IP Address, fill in the public IP address of the remote gateway. For example, 192.168.127.12 #. Enter the Pre-shared Key. #. Enter Remote Subnet CIDR blocks. For example, 10.2.2.0/24 #. Enter Local Subnet CIDR blocks. For example, 192.168.1.0/24 #. Click **OK**. #. Add a static route on the default gateway where CloudN is deployed to point to CloudN as the next hop to reach the remote site. Troubleshooting =============== To check a tunnel state, go to Site2Cloud. The tunnel status will be displayed in a popup window. To troubleshoot a tunnel state, go to Site2Cloud > Diagnostics. .. |image8| image:: site2cloud_media/image009.png :width: 5.08365in :height: 3.25278in .. disqus:: <file_sep> ================================= Egress FQDN Discovery ================================= Discover what Internet sites your apps visit before you configure `Egress FQDN Filter <https://docs.aviatrix.com/HowTos/FQDN_Whitelists_Ref_Design.html>`_. .. tip:: If you already know the sites you apps visit or the FQDN names you need to apply, skip the Discovery step. Go to Security > Egress Control > Egress FQDN Discovery. Select a gateway from the dropdown menu and click **Start**. The monitoring will start, click **Show** at any time to see the captured destination sites. Click **Stop** to stop the entire Discovery process. Start --------------- When you click **Start**, the Controller will automatically enable SNAT function on the gateway. The Controller looks for all private subnets in the VPC/VNet and replaces any 0.0.0.0/0 > NAT Gateway to instead point to the Aviatrix Gateway. .. Important:: During the Discovery step, the `Exception Rule <https://docs.aviatrix.com/HowTos/FQDN_Whitelists_Ref_Design.html#exception-rule>`_ must be enabled (the checkbox should be marked, which is the default setting). Stop ---------- When you click **Stop**, the VPC/VNet private route table entry for the default route (0.0.0.0/0) will be restored to its previous setting. Show ---------- While the Discovery is in progress, click **Show** at any time to see the captured destination sites. Download ------------------ Click **Download** during or after the Discovery, the destination list will be downloaded. You can later import the list to configure the `FQDN Filter <https://docs.aviatrix.com/HowTos/FQDN_Whitelists_Ref_Design.html>`_. Note that if a gateway is already attached to a FQDN tag, you cannot run the Discovery process, but you can view FQDN results immediately by going to Step 4, Egress FQDN View Log. |discovered_sites| .. |discovered_sites| image:: fqdn_discovery_media/discovered_sites.png :scale: 50% .. |fqdn-new-tag| image:: FQDN_Whitelists_Ref_Design_media/fqdn-new-tag.png :scale: 50% .. |fqdn-add-new-tag| image:: FQDN_Whitelists_Ref_Design_media/fqdn-add-new-tag.png :scale: 50% .. |fqdn-enable-edit| image:: FQDN_Whitelists_Ref_Design_media/fqdn-enable-edit.png :scale: 50% .. |fqdn-add-domain-names| image:: FQDN_Whitelists_Ref_Design_media/fqdn-add-domain-names.png :scale: 50% .. |fqdn-attach-spoke1| image:: FQDN_Whitelists_Ref_Design_media/fqdn-attach-spoke1.png :scale: 50% .. |fqdn-attach-spoke2| image:: FQDN_Whitelists_Ref_Design_media/fqdn-attach-spoke2.png :scale: 50% .. add in the disqus tag .. disqus:: <file_sep> ========================================================= ActiveMesh Design Notes ========================================================= ActiveMesh is the default mode when launching an Aviatrix Transit Gateway. This tech note documents the supported common design patterns while deploying ActiveMesh Gateways. 1. ActiveMesh with AWS TGW for On-Prem Connections --------------------------------------------------------------------- While AWS Transit Gateway (TGW) does not propagate routes to Spoke VPCs, TGW Direct Connect via DXGW and TGW VPN have full functions of failover, multi-path and ECMP in supporting connection to on-prem. This includes: - TGW prefers DXGW to TGW VPN when both advertising the same network. When DXGW goes down, one of the VPN routes take over. - When there are multiple VPN routes, TGW routing policy selects the shortest AS_PATH length. - When there are multiple VPN routes with identical AS_PATH length, TGW VPN distributes traffic with ECMP when it is enabled. In this case, Aviatrix Controller performs the orchestration function in managing route propagation and Aviatrix Transit Gateways are used to connect two AWS TGWs. Design Note: Implementing TGW with VPN backup design could lead to asymmetric routing, that is, with traffic from AWS to on-premises traversing the DX as intended while traffic from on-premises to AWS traversing the IPsec VPN tunnel instead. Traffic from AWS to on-premise prefers the AWS DXGW over the VPN connection because the TGW effectively sets a higher “local preference” (LOCAL_PREF) on the DXGW BGP sessions (refer to Route Evaluation Order as outlined in the AWS Transit Gateway documentation). For traffic from on-premises to AWS, the DX path should be preferred because AWS sets a Multi Exit Discriminator (MED) value of 100 on BGP sessions over VPN links as compared to the default value of 0 over the DX path. This works well in the case DX and VPN are used with a Virtual Private Gateway (VGW) as the same AS is announced over both connections but in case of the TGW, the DX path uses a different ASN compared to the VPN path. The advertised ASN over VPN is the TGW AS while the ASN over DX is the ASN of the DXGW. Note that in case of TGW, the AS path over the DXGW path only consists of the DXGW AS instead of AS path length of two with TGW AS + DXGW AS. This is the result of manually setting the CIDRs to be announced by the AWS DXGW towards on-premises which effectively causes DXGW to originate the routes resulting in a reduced path length of one over DX which is the same AS path length as over the VPN link but different AS path. To ensure that the on-premises routers always consider the MED value, set the “bgp always-compare-med” knob. This forces the router to compare the MED if multiple routes to a destination have the same local preference and AS path length. The deployment is shown in the diagram below. |activemesh_tgw_onprem| 1.1 Advertising Different Routes ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ If on-prem sites advertise non overlapping network CIDRs to TGWs, Transit Gateway peering can proceed without issues. 1.2 Advertising Overlapping Routes ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ If on-prem sites advertise identical network CIDRs or overlapping CIDRs to TGWs (for example, they all advertise 10.0.0.0/8 to their respective TGWs), you must enable `<https://docs.aviatrix.com/HowTos/transit_gateway_peering.html#excluded-network-cidrs>`_ feature on both sides of the Aviatrix Transit Gateways to filter out identical or overlapping CIDRs in order to connect the two regions. .. important:: If you use TGW DXGW/VPN for hybrid connection to on-prem, you cannot use Aviatrix Transit Gateway as the backup router for connecting to the same on-prem network. This is because TGW propagated routes do not present themselves in the TGW route table with any BGP information and as such, it is not possible for the Controller to coordinate the dynamic route updates between TGW and Aviatrix Transit Gateway. 1.3 Overlapping Spoke VPC CIDRs ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ If there are overlapping Spoke VPCs CIDRs attached to the TGWs in two regions and you wish to connect them via Aviatrix Transit Gateway Peering, use `Exclude Network CIDRs <https://docs.aviatrix.com/HowTos/transit_gateway_peering.html#excluded-network-cidrs>`_ on both Aviatrix Transit Gateways to exclude these overlapping Spoke VPC CIDRs. 2. ActiveMesh with Aviatrix Transit GW for On-Prem Connection ----------------------------------------------------------------------------------- |activemesh_avx_onprem| 2.1 Redundant Routers On-Prem ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ If there are two on-prem routers advertising the same network CIDR and connect to Aviatrix Transit Gateway directly, Aviatrix Transit Gateway automatically enables ECMP for traffic from cloud to on-prem. If this is not desired outcome, you should connect on-prem to the Aviatrix Transit Gateway through a VGW or VPN Gateway. 2.2 Multi-Sites ^^^^^^^^^^^^^^^^^^ If Aviatrix Transit Gateways connects to multi sites on-prem directly via BGP, these sites should advertise non overlapping CIDRs to the Aviatrix Transit Gateway. 2.3 Route Propagation ^^^^^^^^^^^^^^^^^^^^^^^ The local Aviatrix Transit Gateway learned routes via BGP are propagated to the peered Aviatrix Transit Gateway. The propagated information includes network CIDRS, AS_PATH and metrics. If the local Aviatrix Transit Gateway learned duplicate network CIDRs (i.e., there are multiple paths to reach the same network CIDRs) via BGP, it uses the following rules to decide which route is propagated to the remote Aviatrix Transit Gateway. - The route with the shortest AS_PATH length wins. - If there are identical AS_PATH lengths, the lowest metric route wins. - If the metrics are all the same, the smallest next hop IP address wins. In another words, there will always be one route advertised to the remote Aviatrix Transit Gateway when identical network CIDRs are learned by the local Aviatrix Transit Gateway. 2.4 Overlapping Spoke VPC/VNet CIDRs ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ If there are overlapping Spoke VPCs CIDRs attached to the TGWs in two regions and you wish to connect them via Aviatrix Transit Gateway Peering, use `Exclude Network CIDRs <https://docs.aviatrix.com/HowTos/transit_gateway_peering.html#excluded-network-cidrs>`_ on both Aviatrix Transit Gateways to exclude these overlapping Spoke VPC/VNet CIDRs. 3. NAT Functions -------------------- SNAT function is supported on the individual connection between the Aviatrix Transit Gateway and the remote sites. Starting Release 5.4, SNAT and DNAT functions are supported on the Spoke Gateway tunnel interface to the Aviatrix Transit Gateway. 4. Egress Routes Propagation Behavior ---------------------------------------- If firewalls are deployed for Internet-bound egress traffic in either FireNet or Transit FireNet deployment, the default routes are propagated to the remote peer by Transit Gateway peering. This allows firewalls to be shared across regions. If you have regional firewalls for egress traffic, make sure you apply filter to filter out the default routes. 4. Configuration Notes ----------------------- 4.1 One On-prem Device ^^^^^^^^^^^^^^^^^^^^^^^^ In this scenario, the on-prem has one device as the diagram below. |activemesh_one_device| If the backup Aviatrix Transit Gateway is launched and the Transit Gateway is launched with ActiveMesh, the configuration should include the following settings: * Enable HA - Mark the checkbox to enable HA if the remote site has two external IP addresses. * Local Tunnel IP - Include two IP addresses in this field: the first one for the primary Aviatrix Transit Gateway, and the second for the backup Aviatrix Transit Gateway (only if it is launched). 4.2 Two On-Prem Devices ^^^^^^^^^^^^^^^^^^^^^^^^^ In this scenario, the on-prem has two devices as the diagram below. |activemesh_two_devices| You should check HA in the configuration and configure the second pair of inside tunnel addresses, as shown below. |activemesh_ha_config| .. |activemesh_tgw_onprem| image:: activemesh_design_notes_media/activemesh_tgw_onprem.png :scale: 30% .. |activemesh_avx_onprem| image:: activemesh_design_notes_media/activemesh_avx_onprem.png :scale: 30% .. |activemesh_config| image:: activemesh_design_notes_media/activemesh_config.png :scale: 30% .. |activemesh_ha_config| image:: activemesh_design_notes_media/activemesh_ha_config.png :scale: 30% .. |activemesh_one_device| image:: activemesh_design_notes_media/activemesh_one_device.png :scale: 30% .. |activemesh_two_devices| image:: activemesh_design_notes_media/activemesh_two_devices.png :scale: 30% .. disqus:: <file_sep> ============================================================== Transit FireNet Workflow with AWS Gateway Load Balancer (GWLB) ============================================================== Starting 6.3, Aviatrix Transit FireNet solution allows you to deploy firewalls functions with AWS Gateway Load Balancer. To learn about Transit FireNet, check out `Transit FireNet FAQ. <https://docs.aviatrix.com/HowTos/transit_firenet_faq.html>`_ If you are looking deploying firewall networks in AWS Transit Gateway (TGW) environment, your starting point is `here. <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html>`_. In this example, Transit VPC with Aviatrix Gateways will be deployed, and two Spoke Gateways (DEV and PROD) will be attached to it as shown below: |topology_trfnet_with_gwlb| Step 1 : Create VPCs *************************** VPCs can be created manually on AWS or directly from Aviatrix Controller. Aviatrix controller has set of useful tools available for users and in this example, VPCs are created following the Useful Tools `Create a VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ guidelines. 1. Login to the Aviatrix Controller with username and password #. Navigate to **Useful Tools -> Create A VPC** #. Add one VPC for Transit FireNet Gateway and select **Aviatrix FireNet VPC** option as shown below. #. Create two more VPCs with **no option/checkbox** selected for Spoke Gateways. |create_vpc| Step 2: Deploy the Transit Aviatrix Gateway *************************************************** Transit Aviatrix Gateway can be deployed using the `Transit Gateway Workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-a-transit-gateway>`_ Prerequisite for AWS ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Transit FireNet builds on the Aviatrix Transit Network where Aviatrix gateways are deployed in both the transit VPC and the spoke VPCs in AWS. Make sure the deployment meets the following specifications: 1. ActiveMesh must be enabled when launching the Aviatrix Transit Gateway. #. The minimum size of the Aviatrix Transit Gateway is c5.xlarge. #. Aviatrix Transit Network must be in Connected mode. Go to Transit Network -> Advanced Config -> Connected Transit. Click Enable. Procedure ~~~~~~~~~~~~~~~~~~~~~ 1. Navigate to **MULTI-CLOUD TRANSIT -> Setup -> #1 Launch an Aviatrix Transit Gateway** #. Choose instance size **C5x.large** #. Enable **ActiveMesh Mode (Mandatory)** #. Enable InsaneMode for higher throughputs (optional) #. Enable Transit VPC GW HA by navigating to **MULTI-CLOUD TRANSIT -> Setup -> #2 (Optional) Enable HA to an Aviatrix Transit Gateway** .. note:: Instance size of c5.xlarge will be required for Insane Mode Encryption for higher throughput. Please see an example below for Transit FireNet GW: |tr_firenet_gw| Step 3: Deploy Spoke Gateways ************************************* Now that we have Aviatrix Transit Gateway, we can deploy Aviatrix Spoke Gateways in the spoke VPCs using `Aviatrix Spoke Gateway Workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-a-spoke-gateway>`_. 1. Navigate to **MULTI-CLOUD TRANSIT -> Setup -> #4 Launch an Aviatrix Spoke Gateway** #. Deploy a Spoke Gateway (GW) in each of the spoke VPCs using defaults while choose correct Account and VPC info #. Choose the Public Subnet #. Enable Spoke Gateway HA by navigating to Transit network -> Setup -> #5 (Optional) Enable/Disable HA at Spoke GW .. note:: Instance size of c5.xlarge will be required for Insane Mode Encryption for higher throughput. |launch_spk_gw| Step 4: Attach Spoke Gateways to Transit Network ******************************************************* Transit and spoke gateways are deployed, next step is to connect them. 1. Navigate to **MULTI-CLOUD TRANSIT -> Setup -> #6a Attach Spoke Gateway to Transit Network** #. Select one spoke at a time and attach to the Transit Gateway. |attach_spk_trgw| .. note:: Transit Gateway is attached to Spoke Gateways, but by default, Transit Gateway will not route traffic between Spoke Gateways. Step 5: Enable Connected Transit ************************************** By default, spoke VPCs are in isolated mode where the Transit will not route traffic between them. To allow the Spoke VPCs to communicate with each other, we need to enable Connected Transit 1. Navigate to **MULTI-CLOUD TRANSIT -> Advanced Config**, select the right Transit Gateway and enable **“Connected Transit”** |connected_transit| Step 6: Configure Transit Firewall Network ************************************************** Transit and Spoke Gateways have now been deployed, next step is to enable the fireNet function and create traffic inspection policy. Let’s start with enabling the firewall function and configure the FireNet policy. 1. Navigate to **MULTI-CLOUD TRANSIT -> Transit FireNet -> #1 Enable Transit FireNet on Aviatrix Transit Gateway** #. Choose the Aviatrix Transit Gateway, check Use AWS GWLB and Click **“Enable”** |en_tr_firenet_gwlb| 3. Navigate to **MULTI-CLOUD TRANSIT -> Transit FireNet -> #2 Manage FireNet Policy** #. Add spokes to the Inspected box for traffic inspection .. note:: By default, FireNet inspects ingress (INET to VPC) and east-west traffic (VPC to VPC) only. |tr_firenet_policy_gwlb| Step 7: Subscribe Firewall Vendor in AWS Marketplace ************************************************************* At this point, FireNet functionality on Transit Gateway is enabled and FireNet policy is created for spokes. It is time to subscribe the firewall vendor and deploy the firewall. 1. Navigate to **Firewall Network -> Setup -> #2 Subscribe to Firewall Vendor Product** in AWS Marketplace #. Follow the link to subscribe to Check Point, Palo Alto or Fortinet in AWS Marketplace. .. note:: Please subscribe the firewall but do not launch the firewall. |subscribe_firewall| Step 8a: Launch and Associate Firewall Instance ***************************************************************** This approach is recommended if this is the first Firewall instance to be attached to the gateway. This step launches a Firewall instance and associates it with one of the FireNet gateways. .. important:: The Firewall instance and the associated Aviatrix FireNet gateway above must be in the same AZ, and, we recommend that the Management interface subnet and Egress (untrust dataplane) interface subnet should not be in the same subnet. Go to Aviatrix Controller's console and navigate to **Firewall Network -> Setup -> Step 7a** and provide all the required input as shown in a table and click **"Launch"** button. .. note:: Vendor's firewall may take some time after launch to be available. ========================================== ========== **Setting** **Value** ========================================== ========== VPC ID The Security VPC created in Step 1. Gateway Name The primary FireNet gateway. Firewall Instance Name The name that will be displayed on AWS Console. Firewall Image The AWS AMI that you have subscribed in Step 2. Firewall Image Version Firewall instance current supported software versions. Firewall Instance Size Firewall instance type. Management Interface Subnet. Select the subnet whose name contains "gateway and firewall management" Egress Interface Subnet Select the subnet whose name contains "FW-ingress-egress". Username Applicable to Azure deployment only. "admin" as a username is not accepted. Password Applicable to Azure deployment only. Key Pair Name (Optional) The .pem file name for SSH access to the firewall instance. Attach (Optional) By selecting this option, the firewall instance is inserted in the data path to receive packet. If this is the second firewall instance for the same gateway and you have an operational FireNet deployment, you should not select this option as the firewall is not configured yet. You can attach the firewall instance later at Firewall Network -> Advanced page. Advanced (Optional) Click this selection to allow Palo Alto firewall bootstrap files to be specified. IAM Role In advanced mode, create an IAM Role on the AWS account that launched the FireNet gateway. Create a policy to attach to the role. The policy is to allow access to "Bootstrap Bucket". Bootstrap Bucket Name In advanced mode, specify a bootstrap bucket name where the initial configuration and policy file is stored. ========================================== ========== 1. CheckPoint Specification ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Check Point Security Gateway do not support AWS GWLB in latest release, and it is in Roadmap for future release. 2. Palo Alto VM-Series Specifications ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Palo instance has 3 interfaces as described below. ======================================================== =============================== ================================ **Palo Alto VM instance interfaces** **Description** **Inbound Security Group Rule** ======================================================== =============================== ================================ eth0 (on subnet -Public-FW-ingress-egress-AZ-a) Egress or Untrusted interface Allow ALL eth1 (on subnet -Public-gateway-and-firewall-mgmt-AZ-a) Management interface Allow SSH, HTTPS, ICMP, TCP 3978 eth2 (on subnet -gwlb-pool) LAN or Trusted interface Allow ALL (Do not change) ======================================================== =============================== ================================ Note that firewall instance eth2 is on the same subnet as AWS GWLB interface. .. important:: For Panorama managed firewalls, you need to prepare Panorama first and then launch a firewall. Check out `Setup Panorama <https://docs.aviatrix.com/HowTos/paloalto_API_setup.html#managing-vm-series-by-panorama>`_. When a VM-Series instance is launched and connected with Panorama, you need to apply a one time "commit and push" from the Panorama console to sync the firewall instance and Panorama. .. Tip:: If VM-Series are individually managed and integrated with the Controller, you can still use Bootstrap to save initial configuration time. Export the first firewall's configuration to bootstrap.xml, create an IAM role and Bootstrap bucket structure as indicated above, then launch additional firewalls with IAM role and the S3 bucket name to save the time of the firewall manual initial configuration. 3. Fortigate Specifications ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FortiGate firewall supports AWS GWLB in their latest 6.4 release, please refer to the FortiOS 6.4 AWS Cookbook, pages 175 through 189. This section covers both North-South and East-West scenarios. Please see the following link: https://fortinetweb.s3.amazonaws.com/docs.fortinet.com/v2/attachments/f4e6f33e-6876-11ea-9384-00505692583a/FortiOS_6.4_AWS_Cookbook.pdf Step 8b: Associate an Existing Firewall Instance ******************************************************* This step is the alternative step to Step 8a. If you already launched the firewall (Check Point, Palo Alto Network or Fortinet) instance from AWS Console, you can still associate it with the FireNet gateway. Go to Aviatrix Controller's console and navigate to **Firewall Network -> Setup -> Step 7b** and associate a firewall with right FireNet Gateway. Step 9: Example Setup for "Allow All" Policy *************************************************** After a firewall instance is launched, wait for 5 to 15 minutes for it to come up. Time varies for each firewall vendor. In addition, please follow example configuration guides as below to build a simple policy on the firewall instance for a test validation that traffic is indeed being routed to firewall instance. Palo Alto Network (PAN) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For basic policy configuration, refer to following steps: 1) `Download VM-Series Access Key <https://docs.aviatrix.com/HowTos/config_paloaltoVM.html#download-vm-series-access-key>`_ 2) `Reset VM-Series Password <https://docs.aviatrix.com/HowTos/config_paloaltoVM.html#reset-vm-series-password>`_ 3) `Login to VM-Series and activate VM-Series license <https://docs.aviatrix.com/HowTos/config_paloaltoVM.html#login-to-vm-series>`_ 4) `Configure VM-Series ethernet1/1 with WAN zone <https://docs.aviatrix.com/HowTos/config_paloaltoVM.html#configure-vm-series-ethernet1-1-with-wan-zone>`_ 5) `Configure VM-Series ethernet1/2 with LAN zone <https://docs.aviatrix.com/HowTos/config_paloaltoVM.html#configure-vm-series-ethernet1-2-with-lan-zone>`_ 6) `Configure Vendor Integration <https://docs.aviatrix.com/HowTos/config_PaloAltoAzure.html?highlight=PAN%20health%20check#vendor-firewall-integration>`_ 7) `Enable HTTPS on VM-Series for Health Check <https://docs.aviatrix.com/HowTos/config_PaloAltoAzure.html?highlight=PAN%20health%20check#enable-vm-series-health-check-policy>`_ 8) `Configure basic Allow-All policy <https://docs.aviatrix.com/HowTos/config_PaloAltoAzure.html?highlight=PAN%20health%20check#configure-basic-traffic-policy-to-allow-traffic-vnet-to-vnet>`_ For Egress Inspection Go to `Firewall Network -> Advanced -> Click on 3 dots -> Enable Egress Through Firewall <https://docs.aviatrix.com/HowTos/firewall_advanced.html#egress-through-firewall>`_ |egress_gwlb| FortiGate (Fortinet) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FortiGate firewall supports AWS GWLB in their latest 6.4 release, please refer to the FortiOS 6.4 AWS Cookbook, pages 175 through 189. This section covers both North-South and East-West scenarios. Please see the following link: https://fortinetweb.s3.amazonaws.com/docs.fortinet.com/v2/attachments/f4e6f33e-6876-11ea-9384-00505692583a/FortiOS_6.4_AWS_Cookbook.pdf Check Point ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Check Point Security Gateway do not support AWS GWLB in latest release. AWS GWLB is in Roadmap for future release. Step 10: Verification *************************** There are multiple ways to verify if Transit FireNet is configured properly: 1. Aviatrix Flightpath - Control-plane Test #. Ping/Traceroute Test between Spoke VPCs (East-West) - Data-plane Test Flight Path Test for FireNet Control-Plane Verification: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Flight Path is a very powerful troubleshooting Aviatrix tool which allows users to validate the control-plane and gives visibility of end to end packet flow. 1. Navigate to **Troubleshoot-> Flight Path** #. Provide the Source and Destination Region and VPC information #. Select ICMP and Private subnet, and Run the test .. note:: EC2 VM instance will be required in AWS, and ICMP should be allowed in security group. Ping/Traceroute Test for FireNet Data-Plane Verification: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Once control-plane is established and no problem found in security and routing polices. Data-plane validation needs to be verified to make sure traffic is flowing and not blocking anywhere. There are multiple ways to check data-plane: 1. One way to SSH to Spoke EC2 instance (e.g. DEV1-VM) and ping other Spoke EC2 to instance (e.g PROD1-VM) to make sure no traffic loss in the path. 2. Ping/traceroute capture can also be performed from Aviatrix Controller. Go to **TROUBLESHOOT -> Diagnostics** and perform the test. Transit FireNet with AWS GWLB Packet Walk ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |gwlb_impementation| **Step 1: Spoke Gateway Connections and Routing Table** |spk_list_1| |spk_list_2| **Step 2: Transit Gateway Connections and Routing Table** |transit_list_1| |transit_list_2| |transit_list_3| **Step 3: Transit to Endpoint Routing (dmz_firewall Route Table)** |aws_cons_1| |aws_cons_2| |aws_cons_3| **Step 4: AWS Gateway Load Balancer Endpoint to Gateway Load Balancer** |aws_cons_4| |aws_cons_5| |aws_cons_6| |aws_cons_7| **Step 5: Load Balancer to Firewall (Palo Alto Networks)** |aws_cons_8| |aws_cons_9| |aws_cons_10| |aws_cons_11| |aws_cons_12| **Step 6: Load Balancer and Firewall (Palo Alto Networks) Routing** |aws_cons_13| |aws_cons_14| **Step 7: Egress Traffic Endpoint Point to NAT GW to Internet** |nat_gw_1| |nat_gw_2| .. |gwlb_impementation| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/gwlb_impementation.png :scale: 35% .. |nat_gw_1| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/nat_gw_1.png :scale: 35% .. |nat_gw_2| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/nat_gw_2.png :scale: 35% .. |aws_cons_1| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/aws_cons_1.png :scale: 35% .. |aws_cons_2| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/aws_cons_2.png :scale: 35% .. |aws_cons_3| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/aws_cons_3.png :scale: 35% .. |aws_cons_4| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/aws_cons_4.png :scale: 35% .. |aws_cons_5| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/aws_cons_5.png :scale: 35% .. |aws_cons_6| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/aws_cons_6.png :scale: 35% .. |aws_cons_7| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/aws_cons_7.png :scale: 35% .. |aws_cons_8| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/aws_cons_8.png :scale: 35% .. |aws_cons_9| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/aws_cons_9.png :scale: 35% .. |aws_cons_10| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/aws_cons_10.png :scale: 35% .. |aws_cons_11| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/aws_cons_11.png :scale: 35% .. |aws_cons_12| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/aws_cons_12.png :scale: 35% .. |aws_cons_13| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/aws_cons_13.png :scale: 35% .. |aws_cons_14| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/aws_cons_14.png :scale: 35% .. |transit_list_1| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/transit_list_1.png :scale: 35% .. |transit_list_2| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/transit_list_2.png :scale: 35% .. |transit_list_3| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/transit_list_3.png :scale: 35% .. |spk_list_1| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/spk_list_1.png :scale: 35% .. |spk_list_2| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/spk_list_2.png :scale: 35% .. |subscribe_firewall| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/subscribe_firewall.png :scale: 35% .. |en_tr_firenet_gwlb| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/en_tr_firenet_gwlb.png :scale: 35% .. |tr_firenet_policy_gwlb| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/tr_firenet_policy_gwlb.png :scale: 35% .. |topology_trfnet_with_gwlb| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/topology_trfnet_with_gwlb.png :scale: 35% .. |create_vpc| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/create_vpc.png :scale: 35% .. |tr_firenet_gw| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/tr_firenet_gw.png :scale: 35% .. |launch_spk_gw| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/launch_spk_gw.png :scale: 35% .. |attach_spk_trgw| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/attach_spk_trgw.png :scale: 35% .. |connected_transit| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/connected_transit.png :scale: 35% .. |egress_gwlb| image:: transit_firenet_workflow_media/transit_firenet_AWS_workflow_media/egress_gwlb.png :scale: 35% .. disqus:: <file_sep> .. toctree:: :numbered: ============================================================================== OpenVPN® with SAML Authentication on Google IDP ============================================================================== Overview ------------------- This guide provides an example on how to configure Aviatrix to authenticate against a Google IDP. When SAML client is used, your Aviatrix Controller acts as the Identity Service Provider (ISP) that redirects browser traffic from client to IDP (e.g., Google) for authentication. Pre-Deployment Checklist ----------------------------------- Before configuring SAML integration between Aviatrix and Google, make sure the following is completed: #. `Aviatrix Controller <#gsaml_aviatrix-controller>`__ is set up and running. #. Have a valid `Google account <#gsaml_google-account>`__ with admin access. #. Download and install the `Aviatrix SAML VPN client <#gsaml_aviatrix-client>`__. .. _gsaml_aviatrix_controller: Aviatrix Controller #################### If you haven’t already deployed the Aviatrix Controller, follow `the Controller Startup Guide <https://docs.aviatrix.com/StartUpGuides/aviatrix-cloud-controller-startup-guide.html>`_. .. _gsaml_google_account: Google Account ############## A Google account with admin access is required to configure the integration. .. _gsaml_aviatrix_client: Aviatrix VPN Client ################### All users must use the Aviatrix VPN client to connect to the system. Download the client for your OS `here <http://docs.aviatrix.com/Downloads/samlclient.html>`__. Configuration Steps ----------------------------- Follow these steps to configure Aviatrix to authenticate against your Google IDP: #. Create a custom `Google SAML App <#gsaml_google-saml-app>`__ for Aviatrix. #. Launch an `Aviatrix Gateway <#gsaml_aviatrix-gateway>`__. #. Create Aviatrix `SAML SP Endpoint <#gsaml_aviatrix-saml-endpoint>`__. #. `Test the Integration <#gsaml_test-integration>`__ is Set Up Correctly. #. Create `Aviatrix VPN User <#gsaml_aviatrix-vpn-user>`__. #. `Validate <#gsaml_validate-entire-process>`__. .. _gsaml_google_saml_app: Create a Google SAML App for Aviatrix ###################################### .. note:: This step is usually done by the Google Admin. #. Log in to the Google Admin portal. #. Follow `Google documentation <https://support.google.com/a/answer/6087519?hl=en>`__ to create a new **custom** application. Click **Setup My Own Custom App**. |imageStep1| Scroll down to Option 2. Click **Download** next to the "IDP metadata" label. |imageStep2| #. Basic Information +-------------------+-----------------+-------------------------------------+ | Field | Value | Description | +===================+=================+=====================================+ | Application Name | Aviatrix | This can be any value. It will be | | | | displayed in Google only. | +-------------------+-----------------+-------------------------------------+ | Description | | This can be any value. | +-------------------+-----------------+-------------------------------------+ | | Aviatrix logo: | Aviatrix logo (optional) | | | | | | Upload logo | | |logoAlias1|_ | | | | | |logoAlias2|_ | | +-------------------+-----------------+-------------------------------------+ |imageStep3| #. Service Provider Details +----------------------+----------------------------------------------------+ | Field | Value | +======================+====================================================+ | ACS URL | ``https://[host]/flask/saml/sso/[SP Name]`` | +----------------------+----------------------------------------------------+ | Entity ID | ``https://[host]/`` | +----------------------+----------------------------------------------------+ | Start URL | ``https://[host]/flask/saml/sso/[SP Name]`` | +----------------------+----------------------------------------------------+ | Signed Response | Mark this checkbox | +----------------------+----------------------------------------------------+ | Name ID | Basic Information / Primary Email (Default) | +----------------------+----------------------------------------------------+ | Name ID Format | Unspecified | "[host]" is the hostname or IP of your Aviatrix Controller. For example, "https://controller.demo.aviatrix.live." "[SP Name]" is an arbitrary identifier. This same value should be used when configuring SAML in the Aviatrix Controller. |imageStep4| #. Attribute Mapping +----------------+-----------------+--------------------------------------+ | Attribute | Category | User field | +================+=================+======================================+ | FirstName | Basic | First Name | +----------------+-----------------+--------------------------------------+ | LastName | Basic | Last Name | +----------------+-----------------+--------------------------------------+ | Email | Basic | Primary Email | +----------------+-----------------+--------------------------------------+ |imageStep5| #. Disable **Signed Response**. #. Open the Service Provider Details for the SAML application just created. Unmark the **Signed Response** checkbox. #. Click **Save**. .. _gsaml_aviatrix_gateway: Launching an Aviatrix VPN Gateway ############################## .. note:: This step is usually completed by the Aviatrix admin. .. note:: This step can be skipped if you already have created a SAML VPN Gateway. 1. Log in to the Aviatrix Controller. 2. Select **Gateway** on the left sidebar. 3. Click the **+ New Gateway**. 4. Enter a Gateway Name. 5. Select the appropriate Account Name, Region, VPC ID, Public Subnet, and Gateway Size. 6. Mark the **VPN Access**. 7. Check **Enable SAML**. |imageGwVPNSAML| 8. For information on the other settings, please refer to `this <./uservpn.html>`__ document. 9. Click **OK** to create the Gateway. .. _gsaml_aviatrix_saml_endpoint: Creating an Aviatrix SAML Endpoint ############################# .. note:: This step is usually completed by the Aviatrix admin. 1. Log in to the Aviatrix Controller. 2. Select OpenVPN® > Advanced on the left sidebar. 3. Select the **SAML** tab. 4. Click **+ Add New**. |imageControllerNavOpenVPNAdvanced| +-------------------------+-------------------------------------------------+ | Field | Value | +=========================+=================================================+ | Endpoint Name | ``SP Name`` (Use the same name you entered | | | in the Google Application previously) | +-------------------------+-------------------------------------------------+ | IDP Metadata Type | Text | +-------------------------+-------------------------------------------------+ | IDP Metadata Text | ``Value Copied from Google`` (Paste the value | | | from Google SAML configuration downloaded | | | in a previous step.) | +-------------------------+-------------------------------------------------+ | Entity ID | Hostname | +-------------------------+-------------------------------------------------+ 5. Click **OK**. .. _gsaml_test_integration: Testing the Integration #################### #. Start the Aviatrix VPN Client. .. note:: If you don't start the client, you will receive a warning from the browser in the last step of this process. 1. Log in to the Aviatrix Controller. 2. Select OpenVPN® > Advanced in the left navigation menu. 3. Select the **SAML** tab. 4. Click **Test** next to the "SP Name" created in the previous step. .. tip:: You will need to assign the new Google application to a test user's Google account before clicking **Test**. 5. You should be redirected to Google. Log in with your test user credentials. .. important:: If everything is configured correctly, once you have authenticated you will be redirected back to the controller and the window will close. .. _gsaml_create_aviatrix_vpn_user: Creating a VPN User ################# 1. Log in to the Aviatrix Controller. 2. Select OpenVPN® > VPN Users in the left navigation menu. 3. Click **+ Add New**. 4. Select the **VPC ID** and **LB/Gateway Name** for your SAML Gateway. 5. Enter the Google username in the User Name field. 6. Enter any valid email address in the User Email field (this is where the cert file will be sent). Alternatively, you can download the cert if you do not enter an email address. 7. Select the **SAML Endpoint**. 8. Click **OK**. .. _gsaml_validate_entire_process: Validating ######## #. Log in to the Aviatrix Controller. #. Select OpenVPN® > VPN Users in the left navigation menu. #. Download the configuration for your test user created in the previous step. #. Open the Aviatrix VPN Client application. #. Click **Load Conf** and select the file downloaded. #. Click **Connect**. .. note:: SAML VPN only supports shared certificates. You can share the certificate among VPN users or create more VPN users. OpenVPN is a registered trademark of OpenVPN Inc. .. |logoAlias1| replace:: Aviatrix logo with red background .. _logoAlias1: https://www.aviatrix.com/news/press-kit/logo-aviatrix.png .. |logoAlias2| replace:: Aviatrix logo with transparent background .. _logoAlias2: https://www.aviatrix.com/images/logo-reverse.png .. |imageStep1| image:: SSL_VPN_Google_SAML_media/gsaml_step1.png :scale: 25% .. |imageStep2| image:: SSL_VPN_Google_SAML_media/gsaml_step2.png :scale: 25% .. |imageStep3| image:: SSL_VPN_Google_SAML_media/gsaml_step3.png :scale: 25% .. |imageStep4| image:: SSL_VPN_Google_SAML_media/gsaml_step4.png :scale: 25% .. |imageStep5| image:: SSL_VPN_Google_SAML_media/gsaml_step5.png :scale: 25% .. |imageGwVPNSAML| image:: SSL_VPN_Google_SAML_media/gw_vpn_saml.png .. |imageControllerNavOpenVPNAdvanced| image:: SSL_VPN_Google_SAML_media/OpenVPN_Advanced_SAML_AddNew.png :scale: 50% .. disqus:: <file_sep> =============================================== Insane Mode POC Instructions =============================================== This document describes the steps for testing functionality and performance with Insane Mode. For more information on Insane Mode, check out `this document. <https://docs.aviatrix.com/HowTos/insane_mode.html>`_ Preparation --------------------------------------------------- a. Upgrade Aviatrix software to the latest version by following the instructions `here <https://docs.aviatrix.com/HowTos/inline_upgrade.html>`_. #. Update IAM policies. It's likely the Aviatrix required IAM policies are out of date. Follow the instructions `here <https://docs.aviatrix.com/HowTos/iam_policies.html#updating-iam-policies>`_ to update IAM policies for Controller account and all gateways accounts. .. tip:: Use Aviatrix Useful Tools to create a new VPC. For Transit VPC, select Aviatrix Transit VPC option. 1. Test Spoke to Spoke Performance ------------------------------------ This phase tests performance between two instances in two different Spoke VPCs. The two Spoke VPCs are connected by two Aviatrix gateways launched in Insane Mode. a. Launch a Spoke gateway. Go to Transit Network -> Setup, scroll down to `Step 4 <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-a-spoke-gateway>`_ to launch a Spoke gateway. Select "Insane Mode Encryption". Select a C5 instance size. (See `this table <https://docs.aviatrix.com/HowTos/insane_mode.html#instance-sizes-and-ipsec-performance>`_ for performance guidance.) The "Public Subnet" field should be auto populated as the Aviatrix Controller looks for an unused /28 CIDR segment in the VPC to create a subnet and launch the Insane Mode gateway. #. Launch another Spoke gateway. Repeat the above step for the second Spoke gateway. #. Build an encrypted tunnel between the two gateways. Go to Peering -> Encrypted Peering -> Add New. Select the two gateways and click OK. #. Test performance. Launch two Linux instances (the instance size should be comparable to the gateway size. For example, they should all be C5.2xlarge) in each Spoke VPC. Open security groups of the instances to allow for inbound traffic from the other Spoke VPC. Note: you can launch the instances in a public subnet in the Spoke VPC, or use `Aviatrix User VPN feature <https://docs.aviatrix.com/HowTos/uservpn.html>`_ to access the instance on the private subnet. When you run an iperf test, you should run them with private IP addresses. For example, the server Linux instance has IP address 10.10.10.109 and the client Linux instance has IP address 10.12.11.100. The client instance should run "iperf3 -c 10.10.10.109 -P 8" where P represents the number of TCP streams and where 10.10.10.109 represents the private IP address of the server Linux instance. .. tip:: You can discover the MTU sizes of your network by going to Troubleshoot -> Network -> GATEWAY UTILITY. Select a gateway, enter a destination IP address, click Trace Path. 2. Test Transit VPC to on-prem Performance -------------------------------------------- This phase tests performance between an instance in the Transit VPC and on-prem VM. It requires you deploy an Aviatrix CloudN hardware appliance in your on-prem. 3. Test Spoke to on-prem Performance ------------------------------------- This phase tests performance between an instance in the Spoke VPC and on-prem. .. |tunnel_diagram| image:: insane_mode_media/tunnel_diagram.png :scale: 30% .. |insane_tunnel_diagram| image:: insane_mode_media/insane_tunnel_diagram.png :scale: 30% .. |insane_transit| image:: insane_mode_media/insane_transit.png :scale: 30% .. |insane_datacenter| image:: insane_mode_media/insane_datacenter.png :scale: 30% .. |datacenter_layout| image:: insane_mode_media/datacenter_layout.png :scale: 30% .. |image1| image:: transitvpc_designs_media/multiRegions.png :width: 5.55625in :height: 3.265480in .. |InsaneBeta| image:: insane_mode_media/InsaneBeta.png :width: 5.55625in :height: 3.265480in .. disqus:: <file_sep> ################################### Create a VPC/VNet ################################### Use this tool to create a `VPC <https://www.aviatrix.com/learning/glossary/vpc.php>`_ in AWS or a `VNet <https://a.aviatrix.com/learning/glossary/vnet.php>`_ in Azure in the region and account of your choice. In addition, starting from 6.1, this tool creates multiple route tables associated with public and private subnets. One use case is to allow traffic load balancing when Aviatrix Spoke gateways are deployed. To create an AWS VPC or Azure VNet: 1. Log into your Aviatrix Controller. 2. Select Useful Tools > Create a VPC from the left sidebar. 3. Click **+Add New**. The VPC/VNet CIDR range is from /16 to /24. Advanced ------------------ Mark the **Advanced** checkbox to customize subnet size and number of pair of subnets (public subnet and private subnet). For example, enter 1 for Number of Availability Zones/Number of Subnets to create 1 public subnet and 1 private subnet in the VPC/VNet. The VPC/VNet CIDR range is from /16 to /24. Aviatrix Transit VPC ---------------------------------------- Mark the **Aviatrix Transit VPC** checkbox to fully populate all necessary subnets and route tables as shown below: The VPC CIDR range for a Transit VPC is from /16 to /23. ========================================== =================== **Subnet name** **Suggested usage** ========================================== =================== Public-gateway-and-firewall-mgmt-az1 Use this subnet to launch Aviatrix primary Transit Gateway. Use this subnet to launch firewall instance in DMZ deployment. Public-gateway-and-firewall-mgmt-az2 Use this subnet to launch Aviatrix backup Transit Gateway. Use this subnet to launch backup firewall instance in a second availability zone in DMZ deployment. Private-FW-north-az1 Use this subnet to create an interface on primary firewall instance that interacts with Aviatrix Main Gateway in DMZ deployment. Private-FW-north-az2 Use this subnet to create an interface on backup firewall instance that interacts with Aviatrix Main Gateway in DMZ deployment. Private-FW-south-az1 Use this subnet to create an interface on primary firewall instance that interacts with Aviatrix Companion Gateway in DMZ deployment. Private-FW-south-az2 Use this subnet to create an interface on backup firewall instance that interacts with Aviatrix Companion Gateway in DMZ deployment. Public-FW-ingress-egress-az1 Use this subnet to create an interface on primary firewall instance handles ingress and egress traffic in DMZ deployment. Public-FW-ingress-egress-az2 Use this subnet to create an interface on backup firewall instance handles ingress and egress traffic in DMZ deployment. ========================================== =================== Aviatrix FireNet VPC/VNet -------------------------------------- Mark the **Aviatrix FireNet VPC** or **Aviatrix FireNet VNet** checkboxes to fully populate all necessary subnets and route tables as shown below: The VPC/VNet CIDR range for a FireNet VPC/VNet is from /16 to /24. ========================================== =================== **Subnet name** **Suggested usage** ========================================== =================== Public-gateway-and-firewall-mgmt-1 Use this subnet to launch Aviatrix primary FireNet Gateway. Use this subnet to launch firewall instance in a DMZ deployment. Public-gateway-and-firewall-mgmt-2 Use this subnet to launch Aviatrix backup FireNet Gateway. Use this subnet to launch backup firewall instance in a DMZ deployment. Public-FW-ingress-egress-1 Use this subnet to create an interface on primary firewall instance handles ingress and egress traffic in DMZ deployment. Public-FW-ingress-egress-2 Use this subnet to create an interface on backup firewall instance handles ingress and egress traffic in DMZ deployment. ========================================== =================== Cloud Type: Azure ----------------------------- Starting from R6.2, the Create a VPC tool programs a default route 0.0.0.0 pointing to the next hop type "None" in User Defined Route Table (UDR) for all private subnets it creates. Any public subnet it creates does not have such UDR default route entry. +----------+--------------------+-------------------+ | **Name** | **Address prefix** | **Next hop type** | +----------+--------------------+-------------------+ | default | 0.0.0.0/0 | None | +----------+--------------------+-------------------+ .. |edit-designated-gateway| image:: gateway_media/edit-designated-gateway.png :scale: 50% .. disqus:: <file_sep> .. toctree:: :numbered: ============================================================================== PingOne for Customers IdP for SAML Integration ============================================================================== Overview ------------ This guide provides an example on how to configure PingOne for Customers as an IdP for an Aviatrix SAML SP (endpoint). When SAML client is used, your Aviatrix controller acts as the Identity Service Provider (ISP) that redirects browser traffic from client to IdP (e.g., PingOne for Customers) for authentication. Before configuring SAML integration between Aviatrix and PingOne for Customers, make sure you have a valid PingOne for Customers account with administrator access. Configuration Steps ------------------- Follow these steps to configure Aviatrix to authenticate against your PingOne for Customers IdP: Step 1. Create a `temporary Aviatrix SP Endpoint <#aviatrix-endpoint>`__ in the Aviatrix Controller Step 2. Create a `PingOne Web SAML App <#pingone-web-saml-app>`__ for Aviatrix in the PingOne for Customers Portal Step 3. Retrieve `PingOne IdP metadata URL <#pingone-idp-metadata>`__ Step 4. Update `Aviatrix SP Endpoint <#pingone-update-saml-endpoint>`__ in the Aviatrix Controller Step 5. `Test the Integration <#pingone-test-integration>`__ is Set Up Correctly .. _aviatrix_endpoint: Step 1. Create an Aviatrix SP Endpoint ######################################## Visit one of the following links based on your use case and follow step1 (Create temporary Aviatrix SP Endpoint for Aviatrix) from the link's Configuration section: If integrating PingOne IdP with `Controller Login SAML Config <https://docs.aviatrix.com/HowTos/Controller_Login_SAML_Config.html#config-31>`_ If integrating PingOne IdP with `OpenVPN with SAML Authentication <https://docs.aviatrix.com/HowTos/VPN_SAML.html#config-31>`_ .. _pingone-web-saml-app: Step 2. Create a PingOne Web SAML App for Aviatrix ############################################### .. note:: This step is usually done by the PingOne for Customers Admin. #. Login to the PingOne Admin portal #. Follow `PingOne documentation <https://docs.pingidentity.com/bundle/p14c/page/lyd1583255784891.html>`__ to add a Web SAML application #. On the top of the page, click Connections. #. On the left, click Applications and then + Application. |pingone_idp_adding_web_saml_app_01| #. Click WEB APP, and then for SAML, click Configure. |pingone_idp_adding_web_saml_app_02| #. Create the application profile by entering the following information: +----------------------+---------------------------------------------------------+ | Field | Value | +======================+=========================================================+ | Application name | A unique identifier for the application. | +----------------------+---------------------------------------------------------+ | Description | (optional)A brief characterization of the application. | +----------------------+---------------------------------------------------------+ | Icon | (optional)A pictorial representation of the application.| | | Use a file up to 1MB in JPG, JPEG, GIF, or PNG format. | +----------------------+---------------------------------------------------------+ #. For Configure SAML Connection, enter the following: +------------------------------+---------------------------------------------------+ | Field | Value | +------------------------------+---------------------------------------------------+ | ACS URLs | ``https://[host]/flask/saml/sso/[Endpoint Name]`` | +------------------------------+---------------------------------------------------+ | Signing certificate | PingOne SSO Certificate for Default environment | +------------------------------+---------------------------------------------------+ | Signing | Sign Assertion | +------------------------------+---------------------------------------------------+ | Signing Algorithm | RSA_SHA256 | +------------------------------+---------------------------------------------------+ | Encryption | DISABLED | +------------------------------+---------------------------------------------------+ | Entity ID | ``https://[host]/`` | +------------------------------+---------------------------------------------------+ | SLO endpoint | Not Specified | +------------------------------+---------------------------------------------------+ | SLO response endpoint | Not Specified | +------------------------------+---------------------------------------------------+ | SLO binding | HTTP POST | +------------------------------+---------------------------------------------------+ | Assertion validity duration | 300 | +------------------------------+---------------------------------------------------+ | Target Application URL | Not Specified | +------------------------------+---------------------------------------------------+ | Enforce signed Authn request | Disabled | +------------------------------+---------------------------------------------------+ | Verification certificate | No Verification Certificates Selected | +------------------------------+---------------------------------------------------+ .. note:: ``[host]`` is the hostname or IP of your Aviatrix controller. For example, ``https://controller.demo.aviatrix.live`` ``[Endpoint Name]`` is an arbitrary identifier. This same value should be used when configuring SAML in the Aviatrix controller. ``[Entity ID]`` is using ``https://[host]/`` as default if you select `Hostname` option when configuring SAML in the Aviatrix controller. |pingone_idp_configuring_saml_connection| #. Click Save and Continue. #. For attribute mapping, click the button "+ADD ATTRIBUTE" and then select "PingOne Attribute" to map PingOne user attribute to an attribute in this application as below. +------------------------+-----------------------+ | PINGONE USER ATTRIBUTE | APPLICATION ATTRIBUTE | +------------------------+-----------------------+ | User ID | saml_subject | +------------------------+-----------------------+ | Given Name | FirstName | +------------------------+-----------------------+ | Family Name | LastName | +------------------------+-----------------------+ | Email Address | Email | +------------------------+-----------------------+ .. note:: Notes: User ID is a default required in PingOne |pingone_idp_configuring_attribute_mapping| #. Click Save and Close. #. Enable the WEB SAML APP |pingone_idp_enable| .. _pingone_idp_metadata: Step 3. Retrieve PingOne IdP metadata ##################################### .. note:: This step is usually completed by the PingOne for Customers admin. #. After the application is created in PingOne, click Connections on the top of the page and then click Applications on the left. #. Locate the Web SAML application that we just created. #. Click the details icon to expand the Web SAML application and then click the button "Configuration". #. Copy the URL from the IDP Metadata URL from the CONNECTION DETAILS. This value will be used to configure the Aviatrix SP Endpoint. |pingone_idp_retrieve_idp_metadata_url| .. _pingone_update_saml_endpoint: Step 4. Update Aviatrix SP Endpoint ################################### .. note:: This step is usually completed by the Aviatrix admin. PineOne IdP provides IdP Metadata through URL obtained in Retrieve `PingOne IdP metadata URL <#pingone-idp-metadata>`__ step. PingOne for Customers IdP requires a custom SAML request template. Continue with updating Aviatrix SAML Endpoint by visiting one of the following links based on your use case: #. If integrating PineOne IdP with `Controller Login SAML Config <https://docs.aviatrix.com/HowTos/Controller_Login_SAML_Config.html#config-34>`_ #. If integrating PineOne IdP with `OpenVPN with SAML Authentication <https://docs.aviatrix.com/HowTos/VPN_SAML.html#config-34>`_ +-------------------------+-------------------------------------------------+ | Field | Value | +=========================+=================================================+ | Endpoint Name | ``[Endpoint Name]`` (Use the same name you | | | entered in the PingONe Application previously) | +-------------------------+-------------------------------------------------+ | IdP Metadata Type | URL | +-------------------------+-------------------------------------------------+ | IdP Metadata URL | ``URL copied from PingOne`` (IdP metadata URL) | +-------------------------+-------------------------------------------------+ | Entity ID | Select `Hostname` | +-------------------------+-------------------------------------------------+ | Custom SAML Request | Check the box and either copy the below format | | Template | into the prompt text box or modify it | +-------------------------+-------------------------------------------------+ |pingone_idp_reformat_custom_saml_request_template| .. code-block:: xml <?xml version="1.0" encoding="UTF-8"?> <samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ID="$ID" Version="2.0" IssueInstant="$Time" Destination="$Dest" ForceAuthn="false" IsPassive="false" ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" AssertionConsumerServiceURL="$ACS"> <saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">$Issuer</saml:Issuer> <samlp:NameIDPolicy xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" Format="urn:oasis:names:tc:SAML:2.0:nameid-format:transient" SPNameQualifier="$SPNameQualifier" AllowCreate="true"></samlp:NameIDPolicy> <samlp:RequestedAuthnContext xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" Comparison="exact"><saml:AuthnContextClassRef xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</saml:AuthnContextClassRef> </samlp:RequestedAuthnContext> </samlp:AuthnRequest> .. _pingone_test_integration: Step 5. Test the Integration ############################# Continue with testing the integration by visiting one of the following links based on your use case: 1. If integrating PingOne IdP with `Controller Login SAML Config <https://docs.aviatrix.com/HowTos/Controller_Login_SAML_Config.html#config-35>`_ #. Click `Settings` in the left navigation menu #. Select `Controller` #. Click on the `SAML Login` tab 2. If integrating PingOne IdP with `OpenVPN with SAML Authentication <https://docs.aviatrix.com/HowTos/VPN_SAML.html#config-35>`_ #. Expand `OpenVPN®` in the navigation menu and click `Advanced` #. Stay on the `SAML` tab You can quickly validate that the configuration is complete by clicking on the **Test** button next to the SAML endpoint. OpenVPN is a registered trademark of OpenVPN Inc. .. |logoAlias1| replace:: Aviatrix logo with red background .. _logoAlias1: https://www.aviatrix.com/news/press-kit/logo-aviatrix.png .. |logoAlias2| replace:: Aviatrix logo with transparent background .. _logoAlias2: https://www.aviatrix.com/images/logo-reverse.png .. |pingone_idp_adding_web_saml_app_01| image:: SAML_Integration_PingOne_IdP_media/pingone_idp_adding_web_saml_app_01.png .. |pingone_idp_adding_web_saml_app_02| image:: SAML_Integration_PingOne_IdP_media/pingone_idp_adding_web_saml_app_02.png .. |pingone_idp_configuring_saml_connection| image:: SAML_Integration_PingOne_IdP_media/pingone_idp_configuring_saml_connection.png .. |pingone_idp_configuring_attribute_mapping| image:: SAML_Integration_PingOne_IdP_media/pingone_idp_configuring_attribute_mapping.png .. |pingone_idp_enable| image:: SAML_Integration_PingOne_IdP_media/pingone_idp_enable.png .. |pingone_idp_retrieve_idp_metadata_url| image:: SAML_Integration_PingOne_IdP_media/pingone_idp_retrieve_idp_metadata_url.png .. |pingone_idp_reformat_custom_saml_request_template| image:: SAML_Integration_PingOne_IdP_media/pingone_idp_reformat_custom_saml_request_template.png .. |imageControllerNavOpenVPNAdvanced| image:: SAML_Integration_PingOne_IdP_media/OpenVPN_Advanced_SAML_AddNew.png :scale: 50% .. disqus:: <file_sep> ============================================================ Aviatrix CloudWAN Workflow ============================================================ .. important:: This feature has been **deprecated** from release 6.8.1148. Instead, use Aviatrix Secure Edge to attach on-prem hardware to the cloud. See `Aviatrix Secure Edge FAQ <http://docs.aviatrix.com/HowTos/edge-faq.html>`_. Registering a Branch Router --------------------------------------- Register a branch router to the Controller so the Controller can access its configuration, make changes to it, and monitor its health and statistics. Connecting to the Controller -------------------------------------------------- After a branch router is registered, the Controller connects to its publicly accessible interface of the branch router to retrieve its configuration. Preparing to Attach ---------------------------- This step retrieves the IOS router configuration and let user select the network interfaces. In the dropdown menu, select the branch device. Click **Upload Config**. After the configuration is uploaded, the dropdown menu should the list of interfaces. Select one and click **Save**. Attaching Branch to Cloud ----------------------------------------- This step has 3 options. It creates an IPsec tunnel between the IOS router and the Aviatrix Transit Gateway, between the IOS router and TGW VPN or IOS router and Azure vWAN. Option 1: Attaching to an Aviatrix Transit Gateway ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ If you connect the branch router to an Aviatrix Transit Gateway, refer to the following fields to attach the branch router. ========================================= ========================== Input Field Value ========================================= ========================== Branch A registered branch router. Aviatrix Transit Gateway An Aviatrix Transit Gateway in AWS. (Other cloud types not supported) Connection Name A unique name for the connection. BGP Select BGP if BGP is the protocol between branch and Aviatrix Transit Gateway. Aviatrix Transit Gateway BGP ASN If BGP is selected, enter the BGP ASN number for the Aviatrix Transit Gateway. Branch Router's BGP ASN If BGP is selected, enter BGP ASN number on the branch router. Remote Subnet(s) If Static is selected, enter the on-prem subnet CIDRs that have connectivity with cloud VPCs. Algorithm Default is unchecked. Leave it unchecked. Enable Global Accelerator Check the box to enable AWS Global Accelerator for the branch router to hop onto the nearest AWS edge and traverse the AWS backbone to get to the Aviatrix Transit Gateway. Enable Branch Router HA Check the box if there is a second interface with public IP address to build a redundant IPSEC tunnel. Pre-shared Key Optional parameter. Leave it unchecked. Local Tunnel IP Optional parameter. Leave it unchecked. Remote Tunnel IP Optional parameter. Leave it unchecked. ========================================= ========================== Option 2: Attaching to TGW VPN ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To connect a branch router to TGW VPN, refer to the following fields to attach the branch router. ========================================= ========================== Input Field Value ========================================= ========================== Branch A registered branch router. AWS Transit Gateway An AWS Transit Gateway. Connection Name A unique name for the connection. Branch Router's BGP ASN Only BGP is supported. Enter BGP ASN number on the branch router. Algorithm Default is unchecked. Leave it unchecked. Security Domain Name An Aviatrix TGW Orchestrator Security Domain Enable Global Accelerator Check the box to enable AWS Global Accelerator for the branch router to hop onto the nearest AWS edge and traverse the AWS backbone to get to the AWS TGW. ========================================= ========================== Option 3: Attaching to Azure vWAN ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To connect a branch router to Azure vWAN, select Azure Virtual WAN. For a detailed example, refer to `CloudWAN on Azure vWAN Configuration Example <https://docs.aviatrix.com/HowTos/cloud_wan_workflow_azure_vwan.html>`_. ========================================= ========================== Input Field Value ========================================= ========================== Branch A registered branch router. Azure Virtual WAN Azure vWAN option Access Account Name The Access Account for Azure subscription Resource Group The resource group on Azure Hub Name Azure vWAN Hub created on Azure portal Connection Name A unique name for the connection. Branch Router's BGP ASN Only BGP is supported. Enter BGP ASN number on the branch router. ========================================= ========================== List/Edit ------------ This page allows you to do manual edit of an registered or connected IOS router. Highlight a branch device and click **Edit**. Two panels should come up. On the left side is the latest IOS router configuration. Click **Show Previous Commit Diff** to highlight the diffs in configuration. On the right side of the panel, you can enter IOS commands to make changes. For example, to change the router name, enter the following commands and click **Commit**. :: hostname myrouter Saving & Restoring Config ------------------------------------ For each branch router under management, multiple copies of IOS configuration can be saved on the Aviatrix Controller. Go to CloudWAN > List/Edit page, select one branch router under management, click the 3 dots skewer, select **Save Config**. Enter the Configuration Name and optional description. Saved Configurations can be applied to a branch router via "Restore A Configuration". Go to CloudWAN > List/Edit page, select one branch router, click the 3 dots skewer, and click **Save Config**. On the Restore a Configuration page, select a saved configuration and click **Restore**. The action will trigger a commit of saved IOS configuration to the router. Click **Show Config** to view the saved configuration. AWS Network Manager Integration ------------------------------------------------------- Aviatrix CloudWAN can be integrated with AWS Network Manager for visualization. Follow the steps below to: - Create a Global Network - Register AWS Transit Gateway - Register Branch Device Configuration Tags ---------------------------- Aviatrix CloudWAN automatically programs CLIs required to connect to Aviatrix Transit Gateway or TGW VPN. There are times when you need to add additional CLIs to the routers. Configuration Tags provide a way to manage these additional CLIs in a scalable way. A tag contains a block of CLI commands. A tag can be attached to one or more branch routers. When Commit a tag, CLIs commands in the tag is committed to the routers attached to the tag. Creating a Tag -------------------------- Provide a unique name to a new tag. For example, name the tag tier1-branches. Editing a Tag ---------------------- For a given tag, enter CLI commands exactly the way it should be programmed. Attaching to Branch Routers ---------------------------------------- Select branch routers to be part of Include or Exclude list to a given tag. Committing a Tag to Branch Router -------------------------------------------- Select a tag, click **Commit**. The CLIs in the tag are committed to the branch routers attached to the tag. .. |cloud_wan_1| image:: cloud_wan_faq_media/cloud_wan_1.png :scale: 30% .. |cloud_wan_2| image:: cloud_wan_faq_media/cloud_wan_2.png :scale: 30% .. disqus:: <file_sep>========================================================= Transit Connection to Cisco ASA over the internet. ========================================================= 1. From the Controller go to Transit Network -> Setup -> Launch a Transit VPC GW. |image1| 2. Connect the transit VPC GW to the CicsoASA. Go to Transit Network -> Setup -> Connect to VGW/External Device. select External Device and input the following parameters. a. BGP Local AS number: ASN of the transit VPC GW b. BGP Remote AS number: ASN of the CiscoASA c. Remote Gateway IP Address: CiscoASA WAN Public ip. |image2| 3. Download the configuration by going to Site2Cloud -> Click on the Connection. select generic and Download Configuration and configure on CiscoASA accordingly. |image3| The following is a sample configuration based on the site2cloud configuration above. |image4| 4. Apply the following configuration to your CiscoASA: |image5| Note: The tunnel IP addresses are configured accordingly with the configuration file downloaded from above. 5. After configuring the router the tunnel should change the status from down to up. |image6| 6. Go to Transit Network -> Advanced Config on the Controller and Click on Diagnostics and select the GW name from the dropdown list and select Show Ip bgp Command from the predefined Show list to verify the BGP Routes. |image7| |image8| .. |image1| image:: ./Transit_ExternalDevice_CiscoASA_media/ciscoASA1.png :width: 7.00000 in :height: 5.00000 in .. |image2| image:: ./Transit_ExternalDevice_CiscoASA_media/ciscoASA2.png :width: 7.00000 in :height: 5.00000 in .. |image3| image:: ./Transit_ExternalDevice_CiscoASA_media/ciscoASA3.png :width: 7.00000 in :height: 5.00000 in .. |image4| image:: ./Transit_ExternalDevice_CiscoASA_media/ciscoASA4.png :width: 7.00000 in :height: 5.00000 in .. |image5| image:: ./Transit_ExternalDevice_CiscoASA_media/ciscoASA5.png :width: 100% .. |image6| image:: ./Transit_ExternalDevice_CiscoASA_media/ciscoASA6.png :width: 7.00000 in :height: 5.00000 in .. |image7| image:: ./Transit_ExternalDevice_CiscoASA_media/ciscoASA7.png :width: 7.00000 in :height: 5.00000 in .. |image8| image:: ./Transit_ExternalDevice_CiscoASA_media/ciscoASA8.png :width: 7.00000 in :height: 5.00000 in .. disqus:: <file_sep>## Whitepaper documents will be stored here These documents are more high-level descriptions of cloud-based issues and application <file_sep> **A few important notes before we launch the instance:** 1. This document complements the existing deployment guide that was designed to help you to associate a Palo Alto VM-Series. We are going to assume that you have completed all steps up to `launching and associating a firewall instance <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#launching-and-associating-firewall-instance>`_ before launching this firewall instance. Launching and associating a firewall instance is not necessary as it is Palo Alto VM-Series specific. 2. Currently we do not have a full integration between the Aviatrix dashboard and the Netgate pfSense, which means that you will not be able to dynamically update the firewall routing table, as it is currently possible with the Palo Alto VM-Series. ========================================================= Setting up Firewall Network (FireNet) for Netgate PFSense ========================================================= Complete the first six steps (up to `Launching and Associating a Firewall Instance <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#launching-and-associating-firewall-instance>`_) of the Firewall Network Workflow in Aviatrix Controller to prepare your Firewall VPC (FireNet VPC). This will also set up the subnets that you will need for launching your PFsense instance. ============================================== Deploying a PFsense Instance from the AWS Marketplace ============================================== 1. Go to aws.amazon.com/marketplace and search for the pfSense AMI in AWS Marketplace. Continue to **Subscribe**. |image1| 2. On the next screen, accept the terms, and you should be able to continue. 3. On the next page, choose **Amazon Machine Image** as fulfillment option, choose the proper region and click **Launch**. 4. On the next page, Choose Action should be set to Launch through EC2 and then click **Launch**. You might want to use the pfSense docs `page <https://docs.netgate.com/pfsense/en/latest/solutions/aws-vpn-appliance/launching-an-instance.html>`_ as reference as well. 5. Now, choose your instance size. For this deployment we are going to need 2 network interfaces: management/egress and LAN. A 3-interface deployment is possible (separating management from egress) but not required, as it will also require a larger instance (due to the extra ENI). 6. You can start with a t3.large for example, although for better network performance you might want to select a different instance type (m5, c5 or c5n) and a larger instance size. For more information on this subject, see this AWS `document <https://aws.amazon.com/ec2/instance-types/ >`_ and the pfSense docs `page <https://docs.netgate.com/pfsense/en/latest/solutions/aws-vpn-appliance/launching-an-instance.html>`_ as well. 7. On the instance details page, the most relevant setting for any deployment is the subnet selection for the ENIs eth0 and eth1. If you have followed all the steps on the Firewall page, then your subnet selection should follow this logic: • Eth0 for both management and egress and it should be placed in the subnet FireNet-vpc-Public-FW-ingress-egress. • Eth1 as the LAN interface should be placed in the subnet aviatrix-FW-GW-dmz-firewall (same AZ as eth0). |image2| 8. At the bottom of this page, click **Add device** to create eth1 and select the proper subnet. |image3| 9. Then click **Next: Add storage** – the default setting should be fine. 10. Then click **Next: Add Tags** – if you use tags in your environment, this is the time. 11. Then click **Next: Configure Security Group** – by default you are going to see pfSense default rules for HTTP, HTTPS, SSH and OpenVPN. You can then click **Review and Launch** or you should isolate the instance public interfaces with the following three rules. • All inbound traffic allowed for your own public IP (you will have to SSH to the instance) • All inbound traffic allowed for the Controller IP (even though only TCP port 443 and ICMP will be used) • All inbound traffic allowed for RFC 1918 addresses (this should cover your spoke CIDRs and allow you to perform IDS/IPS) 12. Please note that as soon as you attach an EIP to any instance, it will start receiving random hits from the Internet and you should guarantee that unwanted traffic is simply being dropped, so you don’t pay for “rejects/resets” being sent from of your firewall/VPC. 13. The next page will be a summary containing all of your previous choices, as well as any relevant AWS warning on how you can improve your deployment (e.g: open security groups, AMI usage tier consideration, etc). 14. Once you click **Launch** you will be prompted to choose the .pem key – please download the key now if you have not done it already and archive it in a secure location, as you are going to use it to SSH into the instance to enable GUI/web interface access. 15. If you would like to, you can monitor the instance until it is up via the AWS console (see the screenshot below). Once the instance passes all the health checks, please open a terminal and SSH into the instance using the proper keys and the user “admin,” so can grep the auto-generated password. |image4| 16. The pfSense console allows you to assign the interfaces and its IPs using options 1 and 2, but you can also do that via the web interface. |image5| |image6| 17. Please open a browser and go to https://the_instance_EIP. You will have to accept the self-assigned certificate and then will be prompted with a screen like the one below. Just enter the username as admin and the password you have just saved on the previous step. |image7| 18. The Setup Wizard will take you through some basic steps, which will allow you to configure: • On step 2: Hostname and domain for the instance, primary and secondary DNS servers and whether DHCP should be able to override it – if you want to use AWS VPC DNS, leave the checkbox marked. • On step 3: The timezone and NTP server – please remember that the AWS NTP server can be reached at 169.254.169.123. • On step 6: You can change your password. • And step 7 reloads the configuration. 19. Once you are done with the Setup Wizard, you should double-check your interfaces assignments (xn0/WAN and xn1/LAN) and set xn1 to DHCP. Also, don’t forget to disable **Source/dest Check** for the eth1 interface in the AWS Console as explained `here <https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html#change_source_dest_check>`_. |image8| |image9| 20. The next step is to update the route table. For the purpose of this guide, we suggest adding three routes, each for a RFC1918 address pointing to the private IP of the eth2/ENI of the Aviatrix Gateway in question (whether you are attaching the instance to the main or to the backup gateway). 21. Please make sure that the gateway of the xn0/WAN interface has been selected as default, so your egress traffic can be routed to the VPC IGW. |image10| 22. The next step is to configure the Aviatrix Gateway that the instance will be attached to (either the main or the backup) as an object. Please go to System > Routing > Gateway and click **+ Add**. The IP address of the eth2 interface of the Aviatrix Gateway selected can be found in the AWS: EC2 > Network Interfaces. |image11| 23. One you have configured the Aviatrix Gateway, you can use it as next hop. Just go to System > Routing > Static Routes and click **+ Add**. Repeat this step for all three RF1918 subnets: |image12| 24. Great. Let’s configure the NAT policy. By default, pfSense will perform automatic outbound NAT for both interfaces, which we cannot have for the xn1/LAN interface. So please go to Firewall > NAT > Outbound and create an exception mapping like the one below – to not NAT anything exiting via xn1: |image13| 25. Now the next step is to change the default selection of NAT to be the second option: “Hybrid Outbound NAT rule generation (Automatic Outbound NAT + rules below)” – then click **Save** and then **Apply Changes**. 26. Now we need to double-check the firewall rules are according to your project. If you have already enforced the WAN inbound control at the Security Group level while launching the instance, all you need to confirm is that you are not being more restrictive at the firewall level, so please make sure you are allowing everything at the LAN level. |image14| 27. The final step is to monitor your traffic to confirm that the inspection is being performed as configured. Please go to Status > System Logs > Firewall > Dynamic View. Use the funnel icon to filter your logs accordingly. In this example we have ICMP traffic being inspected in an East-West flow (192.168.240.22 > 10.10.10.10), as well as egress pings to disney.com from the same host. |image15| Great. You are now good to repeat this process to add more instances to talk to the main gateway and also to the backup gateway. The difference regarding the backup gateway attachment is that the subnets will be in a different AZ. For more information on the Firewall network solution, please refer to this `link <https://docs.aviatrix.com/HowTos/firewall_network_faq.html>`_. .. |image1| image:: ./config_PFsense_media/image1.png :width: 100% .. |image2| image:: ./config_PFsense_media/image2.png :width: 100% .. |image3| image:: ./config_PFsense_media/image3.png :width: 100% .. |image4| image:: ./config_PFsense_media/image4.png :width: 100% .. |image5| image:: ./config_PFsense_media/image5.png :width: 100% .. |image6| image:: ./config_PFsense_media/image6.png :width: 100% .. |image7| image:: ./config_PFsense_media/image7.png :width: 100% .. |image8| image:: ./config_PFsense_media/image8.png :width: 100% .. |image9| image:: ./config_PFsense_media/image9.png :width: 100% .. |image10| image:: ./config_PFsense_media/image10.png :width: 100% .. |image11| image:: ./config_PFsense_media/image11.png :width: 100% .. |image12| image:: ./config_PFsense_media/image12.png :width: 100% .. |image13| image:: ./config_PFsense_media/image13.png :width: 100% .. |image14| image:: ./config_PFsense_media/image14.png :width: 100% .. |image15| image:: ./config_PFsense_media/image15.png :width: 100% <file_sep> =============================== Deploying Aviatrix Secure Edge =============================== This document provides instructions for deploying Aviatrix Secure Edge on VMware ESXi or on open-source Kernel-based Virtual Machine (KVM). For additional information about Aviatrix Secure Edge, see `Aviatrix Secure Edge FAQ <http://docs.aviatrix.com/HowTos/edge-faq.html>`_. For examples of Aviatrix Secure Edge design patterns, see `Aviatrix Secure Edge Design Patterns <http://docs.aviatrix.com/HowTos/edge-design-patterns.html>`_. Aviatrix Secure Edge Network Connectivity ========================================= The following diagram shows an example of network connectivity for Aviatrix Edge Gateway to Transit Gateway in AWS. |edge-network-connectivity| Prerequisites ============= Aviatrix Secure Edge requires the following: - Aviatrix Controller 6.8 - VMware ESXi - OVA image for VMware ESXi (see `Downloading the Aviatrix Edge Gateway Image File <http://docs.aviatrix.com/HowTos/edge-2.0-workflow.html#downloading-the-aviatrix-edge-gateway-image-file>`_). - VMware ESXi 6.7 or 7.0.1 - Sufficient VMware ESXi resources to run Edge Gateway (see `Aviatrix Secure Edge Installation Requirements`_). - (Optional) VMware vCenter Server For information about installing VMware products, refer to the VMware product documentation. - KVM - QCOW2 image for KVM (see `Downloading the Aviatrix Edge Gateway Image File <http://docs.aviatrix.com/HowTos/edge-2.0-workflow.html#downloading-the-aviatrix-edge-gateway-image-file>`_). - KVM server running in Linux Bare Metal Server - CentOS 7.6-1810 - QEMU Version 1.5.3, Release 160.el7_6.3 - Sufficient KVM resources to run Edge Gateway (see `Aviatrix Secure Edge Installation Requirements`_). For information about installing KVM products, refer to KVM product documentation. - Aviatrix Transit Gateway BGP ASN configured. High-Performance Encryption (HPE) is optional for Edge 2.0 attachments. - Access to Aviatrix Controller using the Internet or private network with DNS resolution from the Edge Gateway Management interface - BGP-enabled router to peer with Edge Gateway LAN interface via BGP over LAN Downloading the Aviatrix Secure Edge Image File ------------------------------------------------ Before you begin the deployment of the Edge Gateway, download the Aviatrix Secure Edge image file from Aviatrix Support Portal. You will use the image file to deploy the Aviatrix Secure Edge virtual machine. 1. Log in to the Aviatrix Support Portal: `<https://support.aviatrix.com>`_. 2. From the top navigation menu, click on **Downloads**. 3. Answer the questions that are presented, then click **Download** next to the image that you want. The Aviatrix Secure Edge image file downloads to your Downloads folder. Aviatrix Secure Edge Installation Requirements ============================================== The following sections describe the virtual machine instance configuration, network interfaces, ports and protocols, and access requirements for the Edge Gateway to communicate with the Aviatrix Controller and the Aviatrix Transit Gateway. Virtual Machine CPU and Memory Configurations --------------------------------------------- The following table provides CPU and memory configurations of the virtual machine instance supported for the Aviatrix Edge Gateway deployment. +---------------------+----------------------+--------------------------+------------------------+ | **Deployment Type** | **Hardware Profile** | **Storage Requirements** | **Note** | +=====================+======================+==========================+========================+ | Small | 2 vCPU - 4GB | 64 GB | PoC / Test only | +---------------------+----------------------+--------------------------+------------------------+ | Medium | 4 vCPU - 8GB | 64 GB | <5Gbps throughput | +---------------------+----------------------+--------------------------+------------------------+ | Large | 8 vCPU - 16GB | 64 GB | ~10Gbps throughput | +---------------------+----------------------+--------------------------+------------------------+ | X-Large | 16 vCPU - 32GB | 64 GB | ~10Gbps throughput | +---------------------+----------------------+--------------------------+------------------------+ .. Important:: Aviatrix recommends that you not change the Aviatrix Secure Edge VM resource allocation after deploying it. Aviatrix support may not be able to assist with any issue that occurs on a system with customized resource allocation. Over subscription of host resources can lead to a reduction of performance and your instance could become unstable. We recommend that you follow the guidelines and the best practices for your host hypervisor. Aviatrix Secure Edge Networking and Ports and Protocols ------------------------------------------------------- |edge-network-port-protocol| The following sections describe the Aviatrix Secure Edge network interfaces, port, and protocols. Aviatrix Secure Edge Network Interfaces ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Aviatrix Edge Gateway has three interfaces: one WAN interface on eth0, one LAN interface on eth1, and one Management interface on eth2. +-----------------------+------------------------------------------------------------------------+ |**Interface** | **Description** | +=======================+========================================================================+ |WAN eth0 | Interface to connect to the Aviatrix Transit Gateway. | | | Requires a default gateway and Layer 3 reachability to Transit Gateway | | | Private or Public IP. | +-----------------------+------------------------------------------------------------------------+ |LAN eth1 | Interface to connect to the LAN network. Requires a BGP session with | | | LAN Router. | +-----------------------+------------------------------------------------------------------------+ |Management eth2 | Interface to connect to the Aviatrix Controller. Requires a default | | | gateway, DNS access and Internet access to Aviatrix Controller, | | | Aviatrix software download, and tracelog upload. | +-----------------------+------------------------------------------------------------------------+ Aviatrix Secure Edge Ports and Protocols ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. Important:: The Aviatrix Controller requires access to the following ports for Edge Gateway deployment. You must allow access on these ports on your firewall. - MGMT: TCP 443 access to the Aviatrix Controller’s public IP address - MGMT: TCP 443 access to the Aviatrix Controller’s private IP address (only permit this access if you selected **Management over Private Network** for management IP connectivity) - WAN: UDP 500/4500 +------------+-------------------------------------------+--------------+----------+-----------------------+ |**Source** | **Destination** | **Protocol** | **Port** | **Purpose** | +============+===========================================+==============+==========+=======================+ | WAN eth0 | Aviatrix Transit Gateway eth0 private or | UDP | 500 | IPsec | | | public IP address. | | | | +------------+-------------------------------------------+--------------+----------+-----------------------+ | WAN eth0 | Aviatrix Transit Gateway eth0 private or | UDP | 4500 | IPsec | | | public IP address. | | | | +------------+-------------------------------------------+--------------+----------+-----------------------+ | Mgmt eth2 | DNS server. | UDP | 53 | DNS lookup | +------------+-------------------------------------------+--------------+----------+-----------------------+ | Mgmt eth2 | Aviatrix Controller FQDN or | TCP | 443 | Edge to Controller | | | public or private IP address. | | | | +------------+-------------------------------------------+--------------+----------+-----------------------+ | Mgmt eth2 | Aviatrix CoPilot FQDN or | UDP | 5000 | Syslog | | | public or private IP address. | | | | +------------+-------------------------------------------+--------------+----------+-----------------------+ | Mgmt eth2 | Aviatrix CoPilot FQDN or | UDP | 31283 | Netflow | | | public or private IP address. | | | | +------------+-------------------------------------------+--------------+----------+-----------------------+ For additional Edge Gateway access requirements, see `Aviatrix Products: Required Access for External Sites <https://aviatrix.zendesk.com/hc/en-us/articles/4417312119437-Aviatrix-Products-Required-Access-for-External-Sites>`_. Aviatrix Secure Edge Deployment Workflow ======================================== The diagram below provides a high-level view of the four-step process for deploying Aviatrix Secure Edge in Aviatrix Controller. You have the option to use either VMware ESXi or an open-source Kernel-based Virtual Machine (KVM) to deploy the Aviatrix Secure Edge VM and attach the ZTP **.iso** file. |edge-deploy-workflow| 1. Create the Edge Gateway ZTP ISO Image File --------------------------------------------- .. note:: You must have port 443 open to the IP address of the Aviatrix Controller. For the required access for Edge Gateway deployment, refer to `Aviatrix Secure Edge Ports and Protocols <http://docs.aviatrix.com/HowTos/edge-2.0-workflow.html#aviatrix-secure-edge-ports-and-protocols>`_. To create the Edge Gateway ISO image file, follow these steps. 1. Log in to Aviatrix Controller 6.8. 2. Go to **MULTI-CLOUD TRANSIT** > **Setup** 3. In the **Launch an Aviatrix Spoke Gateway** page, enter the following values: a. **Cloud Type**: Is always set to **Aviatrix**. b. **ZTP File Type**: Select **iso**. .. note:: The ISO file is the equivalent of the Zero-Touch Provisioning (ZTP) token. ZTP allows network engineers to remotely deploy and provision network devices at remote locations. For KVM deployments, **cloud-init** is also supported. c. **Gateway Name**: Enter a name for the new Edge Gateway. d. **Site ID**: Select an existing Site ID or create a new Site ID by entering a name (such as, edge-01) and click **Add item**. For guidance on whether to select an existing Site ID or create a new one, see `Edge Site ID Guidelines`_. e. **Management Connection Type**: Select DHCP or Static, depending on your environment. .. note:: Steps (f-n) are applicable only for static IP configuration on the management interface. For IP and DNS settings, enter using the applicable format. For example, if the Edge Gateway's WAN IP is 10.1.1.151, enter 10.1.1.151/24 or what your netmask is. f. **Management Interface IP/Mask**: Enter the management interface IP/mask for the Edge VM. g. **Default Gateway IP**: Enter the IP address of the Default Gateway for the Management Subnet. h. **Primary DNS Server**: Enter the DNS server IP address. i. **Secondary DNS server**: Enter the DNS server IP address, this field is optional. j. **WAN Interface IP/Mask**: Enter the interface IP/mask for the Edge VM. k. **WAN Default Gateway**: Enter the IP address of the Edge WAN interface. l. **Management Over Private Network**: Check the box if the Edge management connection to the Aviatrix Controller is over a private network. Leave it unchecked if the connection is over the public internet. m. **Management Egress IP CIDR**: Enter the IP address of the Edge VM visible to the Aviatrix Controller (IP address to be allowed in the Controller Security Group. This IP is optional and can be added later). This field adds a security bypass filter rule for the incoming traffic on TCP/443 to your Controller. n. **LAN Interface IP/Mask**: Enter the interface IP/mask for the Edge VM. o. **Active-Standby**: Check the box for active-standby mode (see `Active-Standby Edge`_.) Leave unchecked for Active-Active mode. .. Important:: The Active-Active and Active-Standby modes are configured when you create the first Edge ZTP for a particular Site ID. If you need to change a configuration from Active-Active to Active-Standby, delete all the Edge Gateway for that Site ID and recreate the Edge Gateway with the new setting. |edge-launch-spoke-gateway| 4. To create the ISO image file, click **Create**. Aviatrix Controller prompts you to download the ISO file. Controller downloads the ZTP **.iso** file to your downloads folder. 5. Log in to your ESXi or KVM host and upload the **.iso** file to a datastore or storage device. .. Note:: Controller displays a message that confirms when you have successfully downloaded the **.iso** file you created for the Edge gateway. The .iso file will expire 24 hours after you create it, so you must mount the .iso file to an Edge VM to complete the Edge gateway registration within that timeframe, as you cannot download it again and will have to repeat the above steps. Next, deploy the Edge virtual machine and attach the ZTP **.iso** file in the VMware or KVM environment. See `Deploy Edge Virtual Machine and Attach ZTP ISO File`_. Edge Site ID Guidelines ^^^^^^^^^^^^^^^^^^^^^^^ Aviatrix Secure Edge uses Site ID to identify an Edge location and Edge Gateway pair. This allows to group multiple Edge Gateways at the same Edge location using the same Site ID. Multiple Edge Gateways can be grouped and deployed in Active-Active or Active-Standby mode. Follow these guidelines to decide whether to use an existing Site ID or create a new one. - Use an existing Site ID if: - You want to have Active-Standby on 2 Edge Gateways (assign the same Site ID). - You want to have ECMP on multiple Edge Gateways (assign the same Site ID). - Edge Gateways with the same Site ID: - Can only join the same domain. - Can have the same or different local ASN. - Need to have FireNet traffic inspection configured per site. - If you want to configure FireNet management on the Edge Gateway, you need to configure it per site. - When multiple Edge Gateways are attached to a common transit, the transit will propagate routes from Edge Gateways with the same Site ID to other Edge Gateways with a different Site ID but will not propagate routes from the Edge Gateways to other Edge Gateways with the same Site ID. 2. Deploy Aviatrix Secure Edge Virtual Machine and Attach ZTP ISO File ---------------------------------------------------------------------- To deploy the Edge virtual machine on KVM, skip to step `2c. Deploying the Aviatrix Secure Edge Virtual Machine in KVM`_. 2a. Deploying the Aviatrix Secure Edge Virtual Machine in VMware ESXi ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To deploy the Aviatrix Secure Edge virtual machine in VMware ESXi, follow these steps. 1. Download the ESXi OVA file by using the link provided to you by Aviatrix Support. See `Downloading the Aviatrix Secure Edge Image File <http://docs.aviatrix.com/HowTos/edge-2.0-workflow.html#downloading-the-aviatrix-edge-gateway-image-file>`_. 2. Log in to VMware vSphere Web client to access the ESXi host. You can use vSphere Web client to manage ESXi host, launch a VM, mount ISO files, and start and stop the Aviatrix Edge Gateway. 3. To load the OVA file into the ESXi using vSphere, go to: **ESXi** > **Virtual Machines** > **Create/Register VM**. 4. Select **Deploy a virtual machine from an OVF or OVA file**. Click **Next**. 5. Enter a name for the Edge VM and drag the OVA file into the blue pane. Click **Next**. |edge_ova_load_file| 6. In the Select storage page, select the storage device for the instance you created (the OVA is installed in this instance). Click **Next**. 7. In the Deployment options window, enter the network interface mappings and select the Deployment type. (Refer to the pull-down menu or see `Virtual Machine CPU and Memory Configurations <http://docs.aviatrix.com/HowTos/edge-2.0-workflow.html#virtual-machine-cpu-and-memory-configurations>`_.) .. Note:: If necessary, you can change the network interface mappings after deployment. |edge_ova_deploy_options| 8. Click **Next**. 9. In the Ready to complete page, click **Finish**. Next, attach the ZTP **.iso** and the Edge will auto-mount the media which contains the configuration file to be provisioned to the Edge. 2b. Attaching the ISO Image to the Aviatrix Secure Edge Virtual Machine in VMware ESXi ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. note:: * The ZTP ISO file can only be used for a single Edge VM instance, and only one time for that instance. * The ZTP token expires after 24 hours. If you wait too long to boot up the VM with the attached ISO image, it will not work. In that case, delete the Edge Gateway in the Controller UI and create a new Edge Gateway to receive a new ISO file. 1. Upload the ISO file you downloaded from Aviatrix Controller to your VMware datastore. 2. In vSphere, select the Edge VM you created and click **Edit settings**. 3. Select the **Virtual Hardware** tab. 4. Next to CD/DVD Drive 1, click the down arrow and select **Datastore ISO file** from the pull-down menu. 5. To load the ISO to the virtual CD drive, next to **Status**, check **Connect at power on**. 6. Next to the CD/DVD Media field, click **Browse**. Select the ISO file you downloaded. |edge_edit_settings| .. note:: **Connect at power on** (step 4) is required when you attach the ISO image to the VM for the first time. If the VM is powered on at the time you attach the ISO image, select the **Datastore ISO file** and save the configuration to make the ISO available to ZTP. 7. Click **Save**. Next, verify Edge in Controller. See `Verifying the Edge Gateway in Controller`_. 2c. Deploying the Aviatrix Secure Edge Virtual Machine in KVM ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Before you begin, on the KVM Linux host ensure the LAN, WAN, and MGMT network bridges are associated with the physical ethernet interfaces on the KVM sever. Refer to the KVM product documentation. 1. Download the KVM QCOW2 file by using the link provided to you by Aviatrix Support. See `Downloading the Aviatrix Secure Edge Image File <http://docs.aviatrix.com/HowTos/edge-2.0-workflow.html#downloading-the-aviatrix-edge-gateway-image-file>`_. 2. Launch Virtual Machine Manager UI to access the KVM host. 3. Create a new virtual machine from an existing disk image. a. From File menu, select **New virtual machine**. b. Select the option **Import existing disk image**. c. Click **Forward**. |edge-kvm-new-vm| 4. Provide the path to the KVM QCOW2 file and specify the operating system type and version. a. Enter the path or use the Browse button to locate the KVM QCOW2 file you previously downloaded. b. For **OS type**, select **Linux**. c. For **Version**, select **Ubuntu 18.04 LTS**. d. Click Forward. |edge-kvm-new-vm-2| 5. Enter the memory and CPU settings for the Edge Gateway VM and click **Forward**. |edge-kvm-new-vm-3| 6. Enter a name for the Edge Gateway VM and check the **Customize configuration before install** checkbox, then click **Finish**. |edge-kvm-new-vm-4| 7. Add the LAN and MGMT virtual bridge interfaces. a. Click **Add Hardware**. |edge-kvm-new-vm-5| b. In **Add New Virtual Hardware**, select **Network** from the left pane and add two additional network interfaces for the LAN and MGMT virtual bridges. The virtual bridge for the WAN interface is automatically added as part of the VM image creation. a. For **Network source**, select the name of the virtual bridge for the LAN interface. b. For **Device model**, select **virtio**. c. Repeat steps a and b and add the virtual bridge for the MGMT interface. |edge-kvm-new-vm-6| 8. Choose the storage device and attach the **iso** file to the VM. a. In **Add New Virtual Hardware**, select **Storage** from the left pane. b. Select the option **Select or create custom storage**. c. Click **Manage**. d. Locate and select the KVM **iso** file which you previously uploaded. e. Click **Choose Volume**. f. Click **Finish**. |edge-kvm-new-vm-7| 9. Click **Begin Installation** to create the Edge Gateway VM instance on the KVM host. After you attach the ZTP **.iso**, the KVM hypervisor will auto-mount the media which contains the configuration file to provision the Edge Gateway. For more information about deploying virtual machines and attaching .iso file in KVM, refer to KVM product documentation. Next, verify Edge in Controller. See `Verifying the Edge Gateway in Controller`_. 2d. Enabling Multiqueue virtio-net on KVM ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Multiqueue virtio-net allows network performance to scale with the number of vCPUs, by allowing packet processing (packet sending and receiving) through multiple TX and RX queues. To enable Multiqueue virtio-net support on KVM, when launching the Edge Gateway VM using virt-install, add the **driver_queues** parameter to the network interface details. --network bridge=<*bridge-name*>, model=virtio,driver_queues=*N* where, *N* is the number of vCPUs. .. Note:: KVM Hypervisor does not support configuration of RX/TX queue size during runtime. RX/TX queue size should be configured during Edge VM bootup. 2e. Verifying the Edge Gateway in Controller ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To verify the Edge Gateway is up, wait for 5 minutes after you have attached the ZTP **.iso** file then do the following: 1. In Aviatrix Controller, go to **Multi-Cloud Transit** > **List** > **Spoke**. 2. In the **State** column, verify that the Edge Gateway you created is in the **up** state. Click the refresh button to update the registration status. |edge-verify| If the Edge Gateway status is not **up**, you can troubleshoot Edge connectivity using CLI commands on the Edge Gateway console. See `Troubleshooting Edge Gateway Connectivity`_. Next, attach the Edge Gateway to the Transit Gateway. See `Attach the Edge Gateway to the Transit Gateway`_. 3. Attach the Edge Gateway to the Transit Gateway ------------------------------------------------- For Edge Gateway attachment over a public network, you must update the WAN Public IP on the Edge Gateway and configure BGP ASN on the Edge Gateway before you attach Edge Gateway to the Transit Gateway. 3a. Update WAN Public IP ^^^^^^^^^^^^^^^^^^^^^^^^ To update the WAN Public IP, follow these steps. 1. In Aviatrix Controller, go to **Gateway** > **Select a Spoke Gateway**. 2. Select the Edge Gateway you want to attach and click **Edit**. 3. In IP Configurations, click **Discover Public IP**. 4. Verify the WAN Public IP and click **Update**. .. Important:: If you have multiple Edge Gateways, make sure each Edge Gateway has a unique WAN Public IP. |edge-ip-config| 3b. Configure BGP ASN on the Edge Gateway ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To configure BGP AS Number (ASN) on the Edge Gateway, follow these steps. 1. In Aviatrix Controller, go to **MULTI-CLOUD TRANSIT** > **Advanced Config** > **Edit Spoke**. 2. In the **BGP Spoke Gateway** pull-down menu, select the Edge Gateway you created and enter the Local AS Number for the Edge Gateway. 3. Click **CHANGE**. 3c. Attach Edge Gateway to Transit Gateway ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ After you have updated the WAN Public IP on the Edge Gateway and configured the BGP ASNs on both the Transit and Edge Gateway, follow these steps to attach the Edge Gateway to the Transit Gateway. .. Important:: To create an Insane Mode attachment, make sure the Transit Gateway is created with Insane Mode enabled. .. Note:: If you want Jumbo Frame enabled on the Edge Gateway, make sure to enable Jumbo Frame on the Edge Gateway before you attach it to the Transit Gateway. See `Jumbo Frame <http://docs.aviatrix.com/HowTos/gateway.html#jumbo-frame>`_. 1. In Aviatrix Controller, go to **MULTI-CLOUD TRANSIT** > **List** > **Spoke**. Confirm that the Edge Gateway you created is up. 2. Navigate to **MULTI-CLOUD TRANSIT** > **Setup** > **Attach / Detach** > **1a Attach Spoke Gateway to Transit Network**. |edge-attach-spoke-to-transit| 3. In the **Spoke Gateway/Source Gateway** pull-down menu, select the Edge Gateway you created. 4. In the **Transit Gateway/NextHop Gateway** pull-down menu, select your Transit Gateway. 5. To connect over a private network, check **Over Private Network** box. Leave unchecked to connect using a public network. 6. To configure Jumbo Frame on Edge Gateway, check **Jumbo Frame** box. 7. To build High-Performance Encryption (HPE), check **Insane Mode** box. Leave unchecked if you do not require HPE. .. Note:: For **Insane Mode Tunnel Number**, enter the number of HPE tunnels to create for Insane Mode over the Internet or private network. 8. Click **ATTACH**. 9. Verify the Edge Gateway attachment in the following ways: * From Controller: Navigate to **Multi-Cloud Transit** > **List** > **Spoke** * From CoPilot: Navigate to **Topology** > **Network Graph** > **Network**. 4. Connect the Edge Gateway to an External Device (BGP over LAN) ---------------------------------------------------------------- To connect the Edge Gateway to LAN Routing using BGP over LAN, follow these steps. 1. Go to **MULTI-CLOUD TRANSIT** > **Setup** > **External Connection**. 2. In **Connect to VGW/External Device/Azure VNG**, enter the following values: a. Select these options: **External Device**, **BGP**, and **LAN**. b. **VPC Name/Site ID**: Select an existing Edge Site ID from the drop-down list. c. **Connection Name**: Enter a unique name to identify the connection to the LAN router. d. **Aviatrix Gateway BGP ASN**: Enter the BGP AS number the Edge Gateway will use to exchange routes with the LAN router. e. **Primary Aviatrix Gateway**: Select the Edge Gateway you created. f. **Remote BGP AS Number**: Enter the BGP AS number configured on the LAN router. g. **Remote LAN IP**: Enter the LAN router IP address for BGP peering. h. **Local LAN IP**: Enter the Edge LAN interface IP address for BGP peering. |edge-connect-external-device| 2. Click **CONNECT**. Active-Active Edge and Active-Standby Edge Modes ================================================ When deploying multiple Edge Gateways, you have the option to use Active-Active mode or Active-Standby mode for connectivity between Edge Gateways and Transit Gateways. Active-Active Edge ------------------ In Active-Active mode, all Edge-to-Transit connections perform load sharing and transit the traffic. .. Note:: Active-Active mode can support more than 2 Edge Gateways. While there is no maximum number of Edge Gateways, Aviatrix recommends a maximum of 4. Active-Standby Edge ------------------- Active-Standby mode provides the flexibility on Aviatrix Transit Gateways and Aviatrix BGP Spoke Gateways to connect to on-prem with only one active peering and one backup/standby peering. |edge-active-standby| .. Important:: * The Active-Standby Preemptive setting is per site or location and is decided when you create the first Edge Gateway for that site. You cannot choose a different setting when you add more Edge Gateways to that site. For more information about preemptive and non-preemptive Active-Standby modes, see `Active-Standby <https://docs.aviatrix.com/HowTos/transit_advanced.html#active-standby>`_. Transitive Routing ================== The Transitive Routing feature allows an Edge Gateway to forward routes between multiple Transit Gateways that are connected to it. In Aviatrix Secure Edge, you have the option to enable or disable Transitive Routing for an Edge Gateway; it is disabled by default. |edge-transitive-routing| Configuring Transitive Routing ------------------------------ To configure Transitive Routing, follow these steps. 1. Log in to Aviatrix Controller. 2. Attach the Edge Gateway to the first Transit Gateway. Follow the steps in `3b. Attach the Edge Gateway to the Transit Gateway`_. 3. Repeat and attach the Edge Gateway to the second Transit Gateway. 4. Navigate to **MULTI-CLOUD TRANSIT** > **Advanced Config** > **Transitive Routing**. 5. Click the toggle to enable Transitive Routing. 6. Verify routes on each Aviatrix Transit Gateway. Transit Peering over Public Network for Backup Path =================================================== If you have a multi-cloud environment across Cloud Service Providers, for example, AWS and Azure, you can create Transit Gateway Peering over public network and use the Transit Gateway Peering as a secondary or backup path while the Edge Gateway with Transitive Routing enabled is used as the primary path for forwarding traffic. |edge-transit-peering| Configuring Transit Peering over Public Network ----------------------------------------------- To create Transit Peering over public network to use as backup path, follow these steps. 1. In the Aviatrix Controller, go to **MULTI-CLOUD TRANSIT** > **Transit Peering**. 2. Create a Transit Gateway Peering by following the `Multi-Cloud Transit Gateway Peering over Public Network Workflow <https://docs.aviatrix.com/HowTos/transit_gateway_peering_over_public_network_workflow.html>`_. 3. Go to **MULTI-CLOUD TRANSIT** > **Advanced Config**. Select the first Transit Gateway and take note the Local AS Number. 4. Scroll down to the **Connection AS Path Prepend** section. Select the Transit Peering connection name. 5. In the **Prepend AS Path** field, input the same Local AS Number three times separated by space. |edge-transit-peering-config| 6. Repeat steps 3, 4, and 5 for the second Transit Gateway. Interactions with NAT ===================== In Aviatrix Secure Edge, the following NAT scenarios are supported: - Customized SNAT on Edge Gateway - For traffic initiated from Edge location towards Transit Gateway or CSP. - DNAT on Edge Gateway - For traffic initiated from CSP towards Edge location. .. Note:: ActiveMesh connections are available in the NAT connection for non-HPE connections. Default RBAC Access Account for Edge ==================================== In Aviatrix Secure Edge, you have the option to create a default RBAC group and assign users to this group with permissions to create, delete, and manage Edge Gateways. Creating the Default RBAC Access Account for Edge ------------------------------------------------- To create an RBAC group with permissions to create, delete, and manage Edge gateways, follow these steps. 1. Log in to Aviatrix Controller 6.8. 2. Go to **ACCOUNTS** > **Permission Groups** > **ADD NEW**. 3. In the **Group Name** field, enter a name for the group, and then click **OK**. 4. In **Permission Groups**, select new group name, and then click **MANAGE PERMISSION**. 5. In **Permissions for group "Group Name"**, click **ADD NEW**. 6. In **Add permissions to group "Group Name"**, select Gateway – All read/write for Gateway. 7. Click **OK**, and then click **Close**. |edge-rbac| 8. In **Permission Groups**, select the new group name, and then click **MANAGE ACCESS ACCOUNTS**. 9. In **Access accounts for group "Group Name"**, click **ADD NEW**. 10. In **Add access accounts to group "Group Name"**, select **edge_admin**. |edge-rbac-edgeadmin| 11. Click **OK**, and then click **Close**. You can now create or assign a user account with the newly created RBAC group. Selective Gateway Upgrade for Aviatrix Secure Edge -------------------------------------------------- The Aviatrix Secure Edge base OS is not upgradeable. To update the base OS to a newer version, you need to deploy the latest version of the Aviatrix Edge image to a new VM. As Aviatrix Secure Edge base OS is not field upgradeable, Aviatrix Secure Edge does not support selective gateway image update and software rollback. Troubleshooting Edge Gateway Connectivity ----------------------------------------- You can use the Clish commands below to troubleshoot the Edge Gateway. .. Note:: Once the Edge Gateway registers with the Aviatrix Controller, the password changes to the WAN IP of the Edge Gateway. +-----------------------------------+--------------------------------------------------------+ | Command | Description | +===================================+========================================================+ | change_console_password | Changes the password for the CLI login. | +-----------------------------------+--------------------------------------------------------+ | check_conduit | Check conduit state. | +-----------------------------------+--------------------------------------------------------+ | check_network [dns][reachability] | Troubleshoot network connectivity. | +-----------------------------------+--------------------------------------------------------+ | diagnostics | Show gateway diagnostics from | | | /home/ubuntu/cloudx-aws/avx_edge_status.json, which is | | | written by register process or reset_config process. | +-----------------------------------+--------------------------------------------------------+ | logout | Log out of the console. | +-----------------------------------+--------------------------------------------------------+ | ping [-c count] [dest] | Ping destination, optional parameter ping packet count.| | | The default is 5. | +-----------------------------------+--------------------------------------------------------+ | reboot | Reboot the system. | +-----------------------------------+--------------------------------------------------------+ | set_controller_ip [controller_ip] | Set the Controller IP address, usually performed after | | | Controller migration when the Controller IP address | | | is changed. | +-----------------------------------+--------------------------------------------------------+ | show_interfaces | Show output from the command “ifconfig -a | more”. | +-----------------------------------+--------------------------------------------------------+ | show_routes | Show output from the command “ip route show table all”.| +-----------------------------------+--------------------------------------------------------+ About BGP and Routing over Public and Private Networks ------------------------------------------------------ If the connectivity to the Cloud Service Provider (CSP) is over a private network: - The edge (WAN) router runs a BGP session to VGW (AWS) where the edge router advertises an Edge Gateway WAN subnet network, and the VGW advertises the Transit VPC CIDR. - The Edge Gateway LAN interface runs a BGP session to the edge router where the edge router advertises the on-prem network address range to Edge Gateway LAN interface. - The Edge Gateway WAN interface runs a BGP session to the Transit Gateway in the Transit VPC where Transit Gateway advertises all Spoke VPC CIDRs to the Edge Gateway, and the Edge Gateway advertises on-prem network to the Transit Gateway. If the connectivity to the CSP is over a public network: - The Edge Gateway LAN and WAN interfaces do not use public IP addresses. The interfaces rely on the edge router or Firewall NAT function and Internet connectivity. - The Edge Gateway LAN interface runs a BGP session to the edge router where the edge router advertises the on-prem network address range to the Edge Gateway LAN interface. .. |edge_ova_deploy_options| image:: CloudN_workflow_media/edge_ova_deploy_options.png :scale: 50% .. |edge_edit_settings| image:: CloudN_workflow_media/edge_edit_settings.png :scale: 50% .. |edge_ova_load_file| image:: CloudN_workflow_media/edge_ova_load_file.png :scale: 50% .. |edge-active-standby| image:: CloudN_workflow_media/edge-active-standby.png :scale: 50% .. |edge-attach-spoke-to-transit| image:: CloudN_workflow_media/edge-attach-spoke-to-transit.png :scale: 50% .. |edge-connect-external-device| image:: CloudN_workflow_media/edge-connect-external-device.png :scale: 50% .. |edge-deploy-ova-template| image:: CloudN_workflow_media/edge-deploy-ova-template.png :scale: 50% .. |edge-deploy-workflow| image:: CloudN_workflow_media/edge-deploy-workflow.png :scale: 60% .. |edge-ip-config| image:: CloudN_workflow_media/edge-ip-config.png :scale: 50% .. |edge-launch-spoke-gateway| image:: CloudN_workflow_media/edge-launch-spoke-gateway.png :scale: 50% .. |edge-multiple-transit-redundant| image:: CloudN_workflow_media/edge-multiple-transit-redundant.png :scale: 50% .. |edge-multiple-transit-single-edge| image:: CloudN_workflow_media/edge-multiple-transit-single-edge.png :scale: 50% .. |edge-network-connectivity| image:: CloudN_workflow_media/edge-network-connectivity.png :scale: 50% .. |edge-network-port-protocol| image:: CloudN_workflow_media/edge-network-port-protocol.png :scale: 50% .. |edge-rbac| image:: CloudN_workflow_media/edge-rbac.png :scale: 50% .. |edge-rbac-edgeadmin| image:: CloudN_workflow_media/edge-rbac-edgeadmin.png :scale: 50% .. |edge-transitive-routing| image:: CloudN_workflow_media/edge-transitive-routing.png :scale: 50% .. |edge-transit-peering| image:: CloudN_workflow_media/edge-transit-peering.png :scale: 50% .. |edge-transit-peering-config| image:: CloudN_workflow_media/edge-transit-peering-config.png :scale: 50% .. |edge-verify| image:: CloudN_workflow_media/edge-verify.png :scale: 50% .. |edge-kvm-new-vm| image:: CloudN_workflow_media/edge-kvm-new-vm.png :scale: 40% .. |edge-kvm-new-vm-1| image:: CloudN_workflow_media/edge-kvm-new-vm-1.png :scale: 40% .. |edge-kvm-new-vm-2| image:: CloudN_workflow_media/edge-kvm-new-vm-2.png :scale: 40% .. |edge-kvm-new-vm-3| image:: CloudN_workflow_media/edge-kvm-new-vm-3.png :scale: 40% .. |edge-kvm-new-vm-4| image:: CloudN_workflow_media/edge-kvm-new-vm-4.png :scale: 40% .. |edge-kvm-new-vm-5| image:: CloudN_workflow_media/edge-kvm-new-vm-5.png :scale: 40% .. |edge-kvm-new-vm-6| image:: CloudN_workflow_media/edge-kvm-new-vm-6.png :scale: 40% .. |edge-kvm-new-vm-7| image:: CloudN_workflow_media/edge-kvm-new-vm-7.png :scale: 40% <file_sep> ========================================================= TGW Design Patterns ========================================================= Many design patterns exist to deploy your network with the AWS Transit Gateway Orchestrator. Here are some examples. .. important:: While the design pattern diagrams use a single symbol to represent the Aviatrix Gateways, all designs can be implemented with multi-AZ high availability. Dev & Prod Isolated Design ----------------------------------- If you like to build network segmentation between Dev/QA VPCs and Production VPCs, but require shared service VPC and on-prem to reach each VPC, consider the diagram below. diagram below. |dev_prod_design| In this network design, you need to create two custom Security Domains, Dev_Domain and Prod_Domain. At the Plan page Step 2, select **Create Custom Security Domain** and fill in the information. Make sure you multi-select Shared_Service_Domain and Aviatrix_Edge_Domain for Connect to Security Domains. Apply this step for both Dev_Domain and Prod_Domain. Dev & Prod Isolated Design with TGW Direct Connect or VPN ------------------------------------------------------------------------------ Aviatrix integrates native TGW Direct Connect and VPN to connect to on-prem while allowing you to connect to multiple cloud as Spoke VPCs. |tgw_hybrid| All-in-Cloud with Multi Security Domains ------------------------------------------------------------ If you are only concerned about VPC-to-VPC segmentation, you can deploy Aviatrix Controller for an all-in-cloud segmented network, as shown below. |all-in-cloud| Connecting Transit Gateways in Multi-Regions Multi-Cloud ------------------------------------------------------------------------- You can use Aviatrix Transit GWs to connect AWS Transit Gateways in multi-regions and multi-cloud deployment, as shown below. |multi-region| TGW Orchestrator for Cross-Region and Multi-Cloud Spoke ---------------------------------------------------------------------- You can extend the TGW to a different region with transit peering and then spokes in a different cloud. |multi_cloud_transit_peering| Full-Mesh Network Design --------------------------------- If you like to build a full-mesh network that allows all VPCs and on-prem to communicate with each other, you do not need to create any custom Security Domains. Simply use the built-in Default_Domain and Aviatrix_Edge_Domain for the deployment, as shown below. |default_domain_design| At Plan page Step 2, select **Full mesh network**. Fully Isolated Network Design - 1 ----------------------------------------- If you would like to build a fully isolated network where no VPCs can communicate with each other except to the shared service VPC and on-prem, you need to create a Security Domain for each VPC and connect each domain to the Shared_Service_Domain. |fully_isolated_network_design| In this network design, you need to create a custom Security Domain for each VPC. If this design does not scale for you, consider the `Aviatrix Transit Network workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ where all VPCs are by default isolated to each other. Fully Isolated Network Design - 2 ------------------------------------------- An alternative design for a fully isolated deployment is to have a group of VPCs share one Security Domain but `disabling VPC route propagation <https://docs.aviatrix.com/HowTos/tgw_build.html#attach-vpc-to-tgw>`_ when attaching a VPC, as shown in the diagram below. |fully_isolated_2| The advantage of this design is to keep the Security Domains to minimum. You can specify connection policies for a domain to communicate with another domain, such as Aviatrix Edge Domain or Aviatrix FireNet Domain, without the VPC in the domain being able to talk to each other. Fully Isolated Network with Multi-Sites VPN -------------------------------------------------------- You can use TGW native VPN capability to connect to multi-sites VPN. Since VPN connection is in Default Security Domain, you need to build connection policy for each VPC domain. |tgw_multi_sites| Integrating with Distributed Egress Control Design ---------------------------------------------------------- For any of the TGW design patterns, you may deploy Aviatrix distributed Egress FQDN in each VPC. In this example, a full-mesh deployment is expanded to include Egress FQDN support, as shown below. |default_egress| Follow the instructions for `FQDN <https://docs.aviatrix.com/HowTos/FQDN_Whitelists_Ref_Design.html>`_ to deploy egress control function. High Performance Transit - Insane Mode ----------------------------------------------------- Deploy an Aviatrix hardware appliance on-prem to achieve 10Gbps Transit Network throughput. Added benefit is that traffic over Direct Connect is encrypted. |insane-mode| Firewall Network ------------------------- Simplify and scale your firewall deployment with Aviatrix Firewall Network solution. For more information, check out `Firewall Network FAQ <https://docs.aviatrix.com/HowTos/firewall_network_faq.html>`_. |firewall_network| TGW Native Hybrid Network ---------------------------- Aviatrix supports TGW VPN and TGW Direct Connect for connecting to remote site or on-prem network, as shown in the diagram below. |firenet| Connecting to China Regions ---------------------------------------- If the majority of deployment is outside China regions, the best way to connect China region VPC or VNets are to use the cloud native AWS VGW or Azure VPN gateway and connect them to Aviatrix Transit Gateway by IPsec tunnels, as shown in the diagram below. This architecture applies to all other cloud providers that have presence in China regions. On the Aviatrix side, use the option `External Devices <https://docs.aviatrix.com/HowTos/transitgw_external.html>`_ when making the connection. |tgw_china| Connecting to Other Cloud Providers ------------------------------------------------- To connect any network of a cloud provider that is not AWS, Azure, GCP, and Oracle Cloud, use the native VPN gateway of these cloud providers to build VPN tunnels to the Aviatrix Transit Gateway to connect to the rest of the deployment, as shown in the diagram below. On the Aviatrix side, use the option `External Devices <https://docs.aviatrix.com/HowTos/transitgw_external.html>`_ when making the connection. |tgw_other_cloud| Extending Security Domains to On-Prem Sites --------------------------------------------------------- If the Aviatrix Transit Gateway connects to multiple sites over IPsec or GRE tunnels, the Security Domains can be extended to each site as shown below, where Blue Domain in the cloud can only communicate with Site 2, Green Domain can only communicate with Site 1. Routes are only advertised within the domain and data traffic is segmented by the Security Domains. |edge_seg| .. |default_domain_design| image:: tgw_design_patterns_media/default_domain_design.png :scale: 30% .. |default_egress| image:: tgw_design_patterns_media/default_egress.png :scale: 30% .. |fully_isolated_network_design| image:: tgw_design_patterns_media/fully_isolated_network_design.png :scale: 30% .. |fully_isolated_2| image:: tgw_design_patterns_media/fully_isolated_2.png :scale: 30% .. |dev_prod_design| image:: tgw_design_patterns_media/dev_prod_design.png :scale: 30% .. |all-in-cloud| image:: tgw_design_patterns_media/all-in-cloud.png :scale: 30% .. |multi-region| image:: tgw_design_patterns_media/multi-region.png :scale: 30% .. |insane-mode| image:: tgw_design_patterns_media/insane-mode.png :scale: 30% .. |transit-DMZ| image:: tgw_design_patterns_media/transit-DMZ.png :scale: 30% .. |tgw_china| image:: tgw_design_patterns_media/tgw_china.png :scale: 30% .. |tgw_other_cloud| image:: tgw_design_patterns_media/tgw_other_cloud.png :scale: 30% .. |firewall_network| image:: firewall_network_faq_media/firewall_network.png :scale: 30% .. |firenet| image:: firewall_network_media/firenet.png :scale: 30% .. |tgw_multi_sites| image:: tgw_design_patterns_media/tgw_multi_sites.png :scale: 30% .. |tgw_hybrid| image:: tgw_design_patterns_media/tgw_hybrid.png :scale: 30% .. |multi_cloud_transit_peering| image:: tgw_design_patterns_media/multi_cloud_transit_peering.png :scale: 30% .. |edge_seg| image:: tgw_design_patterns_media/edge_seg.png :scale: 30% .. disqus:: <file_sep> ========================================================================================= Use IPv6 to Connect Overlapping VPC CIDRs ========================================================================================= The IPv6 technique --------------------- If you have two overlapping VPC CIDRs and need to connect them together, the normal technique is to use SNAT and DNAT to translate the IP addresses. This tech note describes an alternative approach. In this approach, it assumes the EC2 instances are capable of addressing each other with IPv6 addresses. The idea is that even though two VPC CIDRs are overlapping with IPv4 addresses, the IPv6 network address ranges are always unique. If the EC2 instances are capable of communicating with each other with IPv6, then we just need to build a IPv4 tunnel that tunnels IPv6 address. The diagram is shown as below. |ipv6_peering| In the above diagram, both VPC CIDRs are 10.9.0.0/20. The requirement is to have EC2 instances in each VPC to communicate with each other via IPv6 addresses. Step 1. Launch Aviatrix gateways in each VPC ---------------------------------------------- Login to the Controller. Go to Gateways -> Add New to launch a gateway in each VPC. Step 2. Enable IPv6 on the gateway ----------------------------------- Login to the Controller. At the Gateway page, highlight one gateway, click Edit. Scroll down to IPv6, click Enable. Do the same for the second gateway. When IPv6 is enabled on the gateway, the Controller enables IPv6 on the VPC CIDR (auto assign one), the gateway instance and the subnet where the gateway is launched. You can validate this by login to the AWS Console EC2 and check for both gateway IPv6 address and the associated subnet. Step 3. Enable encrypted peering ---------------------------------- Login to the Controller. Go to Peering -> Encrypted Peering -> Add New. Select the gateways launched and click OK. This step builds an IPSec encrypted tunnel between the two gateways, where the tunnel endpoints are IPv4 addresses of the gateways but the tunnel policy is IPv6 for the two VPC CIDRs. Step 4. Enable IPv6 on EC2 and subnet -------------------------------------- 4.1 Enable IPv6 on EC2 ^^^^^^^^^^^^^^^^^^^^^^^^^ Login to AWS console. Select the instance you want to ping. Click Action -> Networking -> Manage IP Addresses. Assign a new IPv6 address, as shown below. |ipv6_addr| Repeat the same step for the destination address. Make sure you configure the instance Security Group to inbound allow IPv6 address. 4.2 Enable IPv6 on subnet ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Login to AWS console VPC, select the subnet, click Actions -> Edit IPv6 CIDRs. Make sure you enter some numbers that are unique. |ipv6_subnet| 4.3 Edit EC2 Security Group ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Login to AWS console EC2. Select the instance and Edit Security Group to enable inbound IPv6, as shown below. |ipv6_security_group| Step 5. Ping -------------- Use command "ping6" to ping IPv6 address. For example :: ping6 fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b All done. .. |ipv6_peering| image:: ipv6_peering_media/ipv6_peering.png :scale: 30% .. |ipv6_addr| image:: ipv6_peering_media/ipv6_addr.png :scale: 30% .. |ipv6_subnet| image:: ipv6_peering_media/ipv6_subnet.png :scale: 30% .. |ipv6_security_group| image:: ipv6_peering_media/ipv6_security_group.png :scale: 30% .. disqus:: <file_sep> ########################################################## Extending Your vmware Workloads to Public Cloud ########################################################## 1 Overview ================= Aviatrix Systems provides a next-generation cloud networking solution built from the ground up for the public cloud. Aviatrix simplifies the way you enable `site to cloud <https://www.aviatrix.com/learning/cloud-security-operations/site-to-cloud-vpn/>`_, user to cloud and cloud to cloud secure connectivity and access. The solution requires no new hardware and deploys in minutes. Aviatrix CloudN is a virtual appliance deployed in datacenter. Aviatrix Cloud Interconnect (ACX), also known as Datacenter Extension is a unique technology on CloudN. It manages your public cloud address space and allows rapid scaling of AWS Virtual Private Cloud (VPC) by removing the pain point of building secure connections to the VPCs. |image1| 2 ACX Key Benefits ============================================= **Manage Cloud Address Space** No more spreadsheet to manage your cloud address space. **Easy to Deploy** Deployed without touching existing network infrastructure. **Fast to Provision** Provision a VPC with secure tunnel to datacenter in minutes. **Simple to Use** 1-click operation to create and delete a VPC with secure tunnels. **Rapid Scaling** Creates multiple VPCs in any region with secure connectivity. **Full Mesh Connectivity** inter region VPCs can be securely peered in minutes. **IT Supported Self Service** Workflow allows multiple users to create VPCs. **Billing Visibility** Supports multiple AWS accounts for different departments, DevOps and projects **Remote Access Capability**. Built in VPN server allows remote workers to access VPC directly. Ideal for partners and remote workers. 3 How it Works =============== 3.1 Mix Layer 2 and Layer 3 Technologies ----------------------------------------- CloudN uses mixed Layer 2 and Layer 3 technologies whereas the CloudN virtual appliance behaves as a Layer 2 bridge and the Gateway (launched by CloudN at VPC creation time) behaves as a Layer 3 router. The design of CloudN as a Layer 2 bridge makes it possible to build an overlay IPSec tunnel to AWS VPC without involving edge routers in the network. The design of Gateways as a Layer 3 router makes it possible for the VPC to fully utilize all AWS VPC underlying infrastructures and services without requiring any software agent to reside in any of the instances. Instances within the VPC communicate with each other directly and transparently without involvement of a Gateway. From the user’s perspective, what CloudN creates is a standard VPC. CloudN views each VPC as the smallest autonomous environment. It allows you to create security policies to deny any subnet or hosts on premise to access any VPC. For example, you may want to block developers from accessing the production VPC. By default, inter-VPC communication is blocked. By using VPC/VNet peering capability, you can establish direct secure tunnels among VPCs in the same region or across different regions. Enterprise users can access instances seamlessly in all private and public subnets over the secure tunnel using instance private addresses. All instances on private subnets can reach back to enterprise. Optionally packets from instances on private subnets can reach Internet directly without being first sent back to the enterprise. 3.2 Dividing Subnets --------------------- CloudN works by dividing the subnet where cloudN is deployed into sub segments (or smaller subnets). The VPC CIDRs created by cloudN are one of the sub segments. The mechanism is illustrated below. VPC in the below diagram could be replaced with a VNet. |image2| Where a local subnet 10.16.0.0/16 has the default gateway 10.16.0.1, the subnet is divided into 4 sub segments. The default gateway and CloudN IP address fall into one segment. The rest of each segment is mapped to a VPC CIDR, in this case, the VPC CIDRs are 10.16.32.0/19, 10.16.64.0/19 and 10.16.96.0/19. If this subnet 10.16.0.0/16 is reachable from other networks in the enterprise, then the instances inside each VPC take private IP address as if they are on the local subnet 10.16.0.0/16. For users in the enterprise, it is as if they are communicating with hosts on the local network. 4 Pre Configuration Checklist ============================= 4.1 AWS EC2 Account -------------------- You need to have an AWS account to use most of the commands on CloudN. Note that CloudN supports multiple cloud accounts with each one associated with a different AWS IAM account, but there needs to be at least one to start with. 4.2 Plan Cloud Address Space ---------------------------- CloudN manages your cloud address space. Carve out an unused consecutive network address space in your datacenter. The CIDR block of this address can be determined by how many VPCs you will need and how big the address space you can allocate. For example, a CIDR block with /16 address range can create as many as 254 VPCs. Once you have created all the VPCs from the allocated address space, you can always allocate a new address space and launch a new CloudN virtual appliance. 4.3 Deploy the Aviatrix CloudN Virtual Appliance ------------------------------------------------- Reference `the startup guide <http://docs.aviatrix.com/en/latest/StartUpGuides/CloudN-Startup-Guide.html>`__ to deploy the virtual appliance. Check and make sure you can access the Aviatrix Controller dashboard and login with an admin account. The default URL for the Aviatrix Controller is: https://<Private IP address of Aviatrix Controller> 5 Configuration Steps ===================== 5.1 Onboarding and create a cloud account -------------------------------------------- Upon logging in to the controller for the first time, follow the onboarding process to create a cloud account that corresponds to an AWS IAM account. Aviatrix CloudN uses the account's IAM credential to execute AWS APIs to create a VPC and necessary resources. 5.2 Create a VPC and build an encrypted tunnel ------------------------------------------------- After going through onboarding steps, click ACX. Provide a name for the VPC you are about to create, select an AWS region, and click Launch. In a few minutes of time, a VPC, public subnet and private subnet in each AZ of the selected region, IGW and routing tables will be created; an Aviatrix Gateway will be launched and an encrypted tunnel will be created. You then can launch instances in the VPC and access the instances by their private IP addresses. Repeat the above steps for more VPC with encrypted tunnel creations. .. |image0| image:: media/image1.png :width: 3.5in :height: 0.5in .. |image1| image:: media/ACX.png :width: 6.50000in :height: 4in .. |image2| image:: media/image3.png :width: 6.5in :height: 2.5in .. |image3| image:: media/image4.png :width: 7in :height: 4in :scale: 150% .. add in the disqus tag .. disqus:: <file_sep> ============================================ Connecting OpenVPN Users to Onprem ============================================ In this tutorial we will cover the basic routing needed to allow users connected to Aviatrix's OpenVPN service to access On-prem. This documentation assumes that there is an existing OpenVPN Gateway and a configured Site2Cloud tunnel. For more information on creating either, please refer to these links: - `Creating an OpenVPN Gateway <https://docs.aviatrix.com/HowTos/uservpn.html>`_ - `Creating Site2Cloud Connection <https://docs.aviatrix.com/HowTos/site2cloud.html>`_ Topology -------------- =============================== ================================================================= **Network** **CIDR** =============================== ================================================================= Client Network 192.168.43.0/24 OpenVPN Gateway Network 10.99.245.0/24 On-prem Network 10.200.0.0/16 =============================== ================================================================= Configuration -------------- 1. Add the On-prem Networks to the OpenVPN Configuration ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Controller > OpenVPN > Edit Config > MODIFY SPLIT TUNNEL - Add the Onprem CIDR block (ig, 10.200.0.0/16) to Additional CIDR - If Split Tunnel is set to "No" then no changes need to be made 2. Establish Connectivity Between the OpenVPN Gateway and the Site2Cloud or Transit Gateway ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Depending on your network's use case, please refer to the links below: - `TGW Orchestration <https://docs.aviatrix.com/HowTos/tgw_plan.html>`_ - `Aviatrix Transit Network <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ 3. Add the OpenVPN Gateway CIDR to the Site2Cloud Configuration ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A. The Site2Cloud Connection is built on a Spoke Gateway Controller > Site2Cloud > select tunnel > Local Subnet(s) - Add the OpenVPN Gateway Network to Local Subnets(s) (ig, 10.99.245.0/24) - The remote Firewal/Router will need to add the OpenVPN Gateway's network (10.99.245.0/24) to it's IPSec policy - The User VPN client network (ig, 192.168.43.0/24) will be SNAT'ed off of the OpenVPN Gateway's local IP (ig, 10.99.245.x) B. The Site2Cloud Connection is Built on a Transit Gateway with BGP - Transit Gateways configured with BGP should advertise the OpenVPN network automatically Conclusion -------------- Users connected to the SSL VPN should now be able to route through the OpenVPN Gateway back to On-prem. Troubleshooting -------------- - Confirm the VPN User policy allows for connectivity to the On-prem network - Log out of the Aviatrix VPN client and reconnect - this will refresh your device's local routes - If this a TGW solution, confirm that the OpenVPN Gateway's Security Domain is connected to the S2C Security Domain - If this is a BGP solution confirm that Transit Gateway is advertising the OpenVPN Gateway network (ig, 10.99.245.0/24) - On the remote firewall or router check for any ACLs that would block the OpenVPN Gateway Network - In AWS confirm there are no NACLs or Security Groups blocking the traffic <file_sep> ==================== Private Mode ==================== Private Mode is a global setting that offers secure orchestrated intra- and multi-cloud networking by removing the need for public IPs for Aviatrix gateways. Web proxies are used for the gateways to access the internet. All communication is done via native cloud constructs such as Load Balancers, Private Link Services, and peering connections, which act as the underlay for the Aviatrix encrypted Transit network. After Private Mode is configured you can create gateways using `Multi-Cloud Transit <https://https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_. Starting with Controller release 6.9, DNAT and SNAT are supported on gateways while using Private Mode. |topology-private-mode| Cloud environments (providers) that support this feature are AWS, AWS GovCloud, Azure, and Azure Government. +-----------------------+--------------------------------------+ |Controller Location | Gateways | +=======================+======================================+ |AWS GovCloud | AWS, Azure, Azure Government | +-----------------------+--------------------------------------+ |AWS | AWS GovCloud, Azure, Azure Government| +-----------------------+--------------------------------------+ Prerequisites -------------- - `Configure the permissions for Private Mode and GWLB-Based FireNet <https://docs.aviatrix.com/HowTos/aviatrix_iam_policy_requirements.html>`_. This is very important; you cannot deploy your Private Mode resources without these permissions. Please see sections 6 and 15 in the referenced document. - Upgrade to 6.8. - An Aviatrix Controller in AWS or AWS GovCloud. It is best to set up Private Mode from a new Controller that does not have any previously deployed gateways. Private Mode will not work if you already have public gateways deployed in your Controller. - A version of CoPilot that supports Private Mode, if you want to send syslog or Netflow data to CoPilot from the gateways. You must already have deployed CoPilot from the Private Mode Controller. When you deploy CoPilot from the Controller you must select a subnet that has outbound internet access. **NOTE:** (AWS) For CoPilot ARM-based images, Private Mode is currently not supported. - If you want to associate a CoPilot instance, it must be in the same VPC as the Controller. - If setting up Private Mode in a multi-cloud deployment, a private underlay between the CSPs must exist (Direct Connect for AWS or Express Route for Azure). Preparing Your Single Cloud Private Mode Environment ---------------------------------------------------- When you prepare your single cloud Private Mode environment, you are building a Link Service; creating subnets for the Link Service; and attaching Controller/CoPilot/proxy to the Link Service target. #. To enable Private Mode, in the Controller, navigate to Settings > Private Mode > Controller. After enabling Private Mode: - All gateways you create will use private IPs. You will not be able to create or deploy non-private gateways. A mixture of public and private IPs is not possible. - The existing eth0 private IP is used for the Controller. 2. (optional) If you want to view syslog and Netflow data gathered by the gateways in CoPilot, you must associate a CoPilot instance with the Controller. This ensures that data is sent to CoPilot (you must have already deployed CoPilot from the Private Mode Controller as per the above Prerequisites). a. On the Controller tab, select a CoPilot instance and click Associate. b. In CoPilot, navigate to Settings > CoPilot > CoPilot Association and enter the private IP address of the CoPilot instance. |private-mode-enable| 3. On the Intra-Cloud tab, enter the access account name, region, and VPC ID of the Controller to create a Link Service and click Create. |private-mode-intracloud| This creates a Link Service in the selected region that endpoints in that cloud can connect with. It also attaches the CoPilot instance (if configured) and proxy (configured in the following section; you can configure the AWS proxy first if you like). You are only allowed to create one Link Service per region (AWS and Azure). If you associated a CoPilot instance in step 2 above, you must ensure that your CoPilot Security Group is open to the IP addresses you configure when creating the Link Service. .. note:: The expected Link Service configuration for AWS/AWS GovCloud is having one Link Service in each region where you want to launch gateways. However, if you have two AWS/AWS GovCloud accounts, you can have one Link Service used by both accounts in the same region, or you can have a Link Service in each account in the same region. 4. If you have multiple regions in your AWS/AWS GovCloud CSP you must set up a Link Service for each one by repeating the previous step. Creating AWS Proxy for Single Cloud Private Mode ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #. You must create a proxy that will sit behind the Link Service and securely direct traffic to the internet. This proxy must be in the same VPC as the Controller where Private Mode is enabled. You must launch this proxy virtual machine in AWS/AWS GovCloud. To create the AWS/AWS GovCloud proxy do the following: a. Launch your preferred HTTPS proxy; it must be listening on port 3128. b. Make sure your proxy security group is open to the the IPs of the Link Service (created in step 3 above). This ensures that the Link Service IPs have access to the proxy. You can find the IP addresses under Settings > Private Mode > List > Link Service List. c. Make sure the proxy has access to the internet. #. After creating this proxy: a. Navigate to Private Mode > Controller and add the AWS proxy instance you created. b. Click Update. The proxy instance/VM is now associated with Private Mode and will be attached to the Link Service (assuming you have already created it as per step 3 above). |private-mode-aws-proxy| If you are configuring Private Mode in a single cloud, the process is now complete (AWS/AWS GovCloud only). Preparing Your Multi-Cloud Environment -------------------------------------- You must have completed the steps under “Preparing Your Single Cloud Private Mode Environment”. See the table at the beginning of this document for where you can create your multi-cloud endpoints. In a multi-cloud Private Mode environment, you are creating endpoints in a multi-cloud access VPC attached to the intra-cloud Link Service; building a multi-cloud Link Service; and attaching a multi-cloud proxy (Azure only) to the Link Service target. #. On the Multi-Cloud Access tab, enter the Access Account Name, Region, VPC ID of the multi-cloud access VPC, and the Intra-Cloud Link VPC ID you want to connect to. Click Create. This launches an endpoint in the new multi-cloud access VPC for Direct Connect/Express Route to connect to. It also creates the necessary subnets, route tables, and endpoint security groups. |private-mode-multicloud-access| 2. On the Multi-Cloud Link tab, you create the multi-cloud Link Service and prepare it for the proxy that will be attached in the next step. In Azure, you only need to create multiple Link Services if desired for scalability. Enter the Cloud Type, Access Account Name, Region, VPC ID, and Multi-Cloud Access VPC ID. |private-mode-multicloud-link| .. note:: You must have already set up the private underlay (cross-cloud link, such as Direct Connect or Express Route) that will connect the two CSPs. Also, you only need to create a proxy using the two steps below if you are connecting Azure/Azure Government to your existing AWS/AWS GovCloud CSP. If you are connecting AWS/AWS GovCloud to an existing CSP you can skip these steps. 3. Create the Azure-related proxy (Azure HTTPS and TCP proxy must be in the same VNet as the Link Service it is associated with): a. Launch your preferred HTTPS and TCP proxies. These must be in the same VM as each other. b. Set up the HTTPS proxy as per the AWS proxy you created for single cloud (listening on port 3128). c. For the TCP proxy, you need to map incoming requests on port 443. Also map ports 31283 (Netflow data) and 5000 (remote syslog) if you want this information to be visible in CoPilot. d. For the TCP proxy, the ports should forward requests for ports 443, 31283 and 5000 to the DNS entry for the multi-cloud access endpoint that the proxy is communicating to on the Controller cloud. The DNS entry is located under Settings > Private Mode > List > Multi-Cloud Access Endpoint List. .. note:: If your proxy has a public IP, make sure the SKU is Standard and not Basic. 4. On the Multi-Cloud Link tab under Attach/Update Proxy, enter the Cloud Type, Access Account Name, and Link Service. Only instances that are in the same VNet as the Link Service are listed. 5. Attach the proxy you just created by clicking Attach and then Update. This proxy server is the Link Service target for traffic from Azure gateways. Only do this if you had to create a proxy for Azure/Azure Government. |private-mode-multicloud-proxy| Creating Gateways ----------------- After completing your single cloud or multi-cloud configuration, you can launch transit or spoke gateways from Multi-Cloud Transit. .. note:: In Private Mode, transit peering always occurs over a private network. If your transit gateway and its backup use HPE/Insane Mode, transmission will always occur over a private network regardless of whether you enable Peering Over Private Networks. In the Controller, navigate to Multi-Cloud Transit > Setup. On the Transit/Spoke tabs, enter the information required to launch your gateways. For more information see: - `Launch an Aviatrix Transit Gateway <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-an-aviatrix-transit-gateway>`_ - `Launch an Aviatrix Spoke Gateway <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-an-aviatrix-spoke-gateway>`_ Deleting Multi-Cloud Access VPC and Link Service ------------------------------------------------ On the Delete Functions tab you can remove the multi-cloud access endpoint and/or the intra/multi-cloud link service. If you have dependent resources you must resolve the dependencies first. Disabling Private Mode ---------------------- If you want to disable Private Mode, you must delete all gateways and Private Mode resources. If you do not delete gateways or resources first, you will receive errors when you attempt to disable Private Mode. Backup/Restore -------------- When in Private Mode, you can restore the Controller and related Private Mode configuration if the restoration is done in the same VPC as the previous Controller. You cannot restore a Controller that has been created in a different VPC. The restoration will change the targets of the Link Services to the new Controller. Click `here <https://docs.aviatrix.com/HowTos/controller_backup.html>`_ for more information on backup/restore. Limitations ----------- In Private Mode the following Aviatrix functionality is not available: - Site2Cloud - AWS TGW - Controller Security tab - You cannot launch gateways in the same VPC/VNet as the Link Service VPC/VNet - BGP over LAN - BGP over Spoke - Insane mode to Internet - FQDN Gateway - Egress through Firewall - Enable Egress Transit FireNet - Software rollback to 6.7 is not supported (since Private Mode did not exist prior to 6.8) .. |topology-private-mode| image:: privatemode_media/topology-private-mode.png :scale: 30% .. |private-mode-enable| image:: privatemode_media/private-mode-enable.png :scale: 30% .. |private-mode-intracloud| image:: privatemode_media/private-mode-intracloud.png :scale: 30% .. |private-mode-multicloud-link| image:: privatemode_media/private-mode-multicloud-link.png :scale: 30% .. |private-mode-multicloud-access| image:: privatemode_media/private-mode-multicloud-access.png :scale: 30% .. |private-mode-multicloud-proxy| image:: privatemode_media/private-mode-multicloud-proxy.png :scale: 30% .. |private-mode-aws-proxy| image:: privatemode_media/private-mode-aws-proxy.png :scale: 30% .. disqus: <file_sep>============================================== Aviatrix Controller and Gateway Release Notes ============================================== .. important:: Aviatrix strongly recommends you perform the tasks in the operations checklist including a dry run upgrade before upgrading your deployment of the Aviatrix network platform. Taking the time to perform dry runs and backing up your Aviatrix Platform configuration reduces the potential for issues during the upgrade and allows you to easily restore your configuration if there are issues after the upgrade. Correct any issues you find during your preparation before proceeding with an Aviatrix upgrade. If you cannot resolve all issues after following the preparation and dry run procedures, please open a ticket with `Aviatrix Support <https://support.aviatrix.com/>`_. If you are upgrading from release 6.5.x or later, follow the guidelines and procedures in `Upgrading the Aviatrix Cloud Network Platform <https://docs.aviatrix.com/HowTos/selective_upgrade.html>`_. If you are upgrading from release 6.4.x or earlier, follow the guidelines and procedures in `Inline Software Upgrade for 6.4 and Earlier Releases <https://docs.aviatrix.com/HowTos/inline_upgrade.html>`_. If you deploy your Aviatrix platform with Terraform, see the `Aviatrix Terraform Release Notes <https://registry.terraform.io/providers/AviatrixSystems/aviatrix/latest/docs/guides/release-notes>`_. Public Preview Features ======================== Aviatrix releases features in public preview mode to offer you the opportunity to experiment with concepts and features that may develop into official product offerings. Your valuable feedback helps shape and improve the experience for everyone. - Features in public preview mode are fully tested and safe for deployment in production environments. - Public preview mode feature options, performance, and scalability may be limited compared to the final feature. - Aviatrix does not charge for using features in public preview mode. You could be charged if the public preview feature is promoted to an officially supported feature. - If a feature in public preview mode is promoted to an officially supported product it will be announced in the product release notes. - Public preview mode features are clearly marked in the UI. Private Preview Features ========================= Aviatrix releases features in private preview mode to offer you the opportunity to experiment with concepts and features that may develop into official product offerings. Your valuable feedback helps shape and improve the experience for everyone. - Features in private preview mode should not be deployed in production environments. - Features in private preview mode may have undergone limited testing. - Support for features in private preview mode may be limited and handled with low priority. - Aviatrix does not charge for using features in private preview mode. You could be charged if the private preview feature is promoted to an officially supported feature. - If a feature in private preview mode is promoted to an officially supported product it will be announced in the product release notes. - Private preview mode features are clearly marked in the UI but are disabled by default. If you wish to enable a private preview mode feature, please contact your sales representative. .. important:: For the release notes of Controller and Gateway software versions 7.0 and later, click `here <https://docs.aviatrix.com/documentation/latest/release-notes/software-release-notes/software-release-notes.html>`_. The content below is a list of release notes for software versions 6.9 and earlier. 6.9.733 Release Notes (08/29/23) ========================================== **Issues Corrected in Aviatrix Release 6.9.733** * **AVX-43546** - After the Aviatrix Controller lost Management connection to a Transit/Edge Gateway, the Gateway lost all learned routes from the on-prem environment. * **AVX-43547** - On a newly registered CloudN, users could not create attachments to multiple transits from a single CloudN Gateway. * **AVX-43552** - A previous method for adding new metrics to interface RRD files caused unnecessary delay and decreased performance. Resolved this issue so that the new metrics are available without the extra expense of time and performance. You must upgrade to software version 7.0.1307 or 7.1.XXXX or later to access the new metrics. * **AVX-44525** - (GCP) Upgrading a GCP Transit Gateway with BGPoLAN and Firenet features enabled might have resulted in the loss of direct connectivity to firewall appliance management. * **AVX-45566** - VPN NAT for gateway traffic didn’t work as expected because one of the NAT-related chains is missing in the iptables. Action required: Upgrade your gateway image. * **AVX-45569** - Linux auditd logs filled the disk space of some instances. * **AVX-45571** - (Azure) After an Azure FireNet-enabled gateway image upgrade, the gateway went into the “config_fail” state. Action required: To resolve this issue, try restarting the gateway. If the gateway state does not change, please contact Aviatrix Support. * **AVX-44818** - Bootstrap configuration for a firewall took longer than expected, causing traffic loss from the Transit Gateway. Use the following two attributes in Terraform to provide sufficient time for the firewalls to be configured via Bootstrap so that the configuration is applied to the firewalls. Note that the specific values for these attributes * number_of_retries - (Optional) Number of retries for save or synchronize. (Set to at least 1, default is 0) * retry_interval - (Optional) Retry interval in seconds for save or synchronize. Example: 900. Default value: 300. Recommended: 900. **Known Issues in Aviatrix Release 6.9.733** * **AVX-45156** - On an AEP Dell device, when you configure a Transit Gateway attachment with HPE (High Performance Encryption) mode, you could not set the tunnel count to more than 2. If you have a higher bandwidth/performance requirement which requires more tunnels, please contact Aviatrix Support for help. * **AVX-45567** - (GCP) Simultaneous, multiple GCP gateway image upgrades in the same GCP project might fail. To resolve this issue, try upgrading the gateway images again. * **AVX-45682** - A rare issue with a gateway software upgrade may cause the BGP neighbor status to go down. To resolve this issue, restart the gateway. * **AVX-45684** - This issue occurs when you try to do a dry run for a Controller software version upgrade with more than one version in the pending list for upgrading. When you choose “latest” as the default version for the upgrade, the Controller incorrectly runs the dry run for the last version to upgrade to instead of the next upgrade version. For example, if you are running a dry run for 6.8 > 6.9 > 7.0 > 7.1, the Controller ran the dry run for 7.1 instead of 6.9. To resolve this issue, when you do a dry run, make sure to manually enter the next upgrade version instead of leaving the default, “latest.” For example, when you upgrade from 6.8 > 6.9 > 7.0 > 7.1, enter “6.9” as the version for the dry run. 6.8.1826 Release Notes (08/29/23) =========================================== **Issues Corrected in Aviatrix Release 6.8.1826** * **AVX-43546** - After the Aviatrix Controller lost Management connection to a Transit/Edge Gateway, the Gateway lost all learned routes from the on-prem environment. * **AVX-43547** - On a newly registered CloudN, users could not create attachments to multiple transits from a single CloudN Gateway. * **AVX-44525** - (GCP) Upgrading a GCP Transit Gateway with BGPoLAN and Firenet features enabled might have resulted in the loss of direct connectivity to firewall appliance management. * **AVX-45566** - VPN NAT for gateway traffic didn’t work as expected because one of the NAT-related chains is missing in the iptables. Action required: Upgrade your gateway image. * **AVX-45569** - Linux auditd logs filled the disk space of some instances. * **AVX-45571** - (Azure) After an Azure FireNet-enabled gateway image upgrade, the gateway went into the “config_fail” state. * **AVX-44818** - Bootstrap configuration for a firewall took longer than expected, causing traffic loss from the Transit Gateway. Use the following two attributes in Terraform to provide sufficient time for the firewalls to be configured via Bootstrap so that the configuration is applied to the firewalls. Note that the specific values for these attributes * number_of_retries - (Optional) Number of retries for save or synchronize. (Set to at least 1, default is 0) * retry_interval - (Optional) Retry interval in seconds for save or synchronize. Example: 900. Default value: 300. Recommended: 900. **Known Issues in Aviatrix Release 6.8.1826** * **AVX-45156** - On an AEP Dell device, when you configure a Transit Gateway attachment with HPE (High Performance Encryption) mode, you could not set the tunnel count to more than 2. If you have a higher bandwidth/performance requirement which requires more tunnels, please contact Aviatrix Support for help. * **AVX-45567** - (GCP) Simultaneous, multiple GCP gateway image upgrades in the same GCP project might fail. To resolve this issue, try upgrading the gateway images again. * **AVX-45682** - A rare issue with a gateway software upgrade may cause the BGP neighbor status to go down. To resolve this issue, restart the gateway. * **AVX-45683** - (GCP) Upgrading a GCP Transit Gateway with BGPoLAN and FireNet features enabled from any in 6.7 or 6.8 releases might result in 7-10 seconds of traffic loss of direct connectivity to firewall appliance management. * **AVX-45684** - This issue occurs when you try to do a dry run for a Controller software version upgrade with more than one version in the pending list for upgrading. When you choose “latest” as the default version for the upgrade, the Controller incorrectly runs the dry run for the last version to upgrade to instead of the next upgrade version. For example, if you are running a dry run for 6.8 > 6.9 > 7.0 > 7.1, the Controller ran the dry run for 7.1 instead of 6.9. To resolve this issue, when you do a dry run, make sure to manually enter the next upgrade version instead of leaving the default, “latest.” For example, when you upgrade from 6.8 > 6.9 > 7.0 > 7.1, enter “6.9” as the version for the dry run. 6.7.1601 Release Notes (06/14/23) ========================================= **Enhanced Features in Aviatrix Release 6.7.1601** * **AVX-41036** - (AWS) Added support for the UAE (United Arab Emirates) region, or me-central-1, for AWS Gateways and VPCs. 6.9.545 Release Notes (05/04/2023) =============================================== **Enhanced Features in Aviatrix Release 6.9.545** * **AVX-36880** - You can now upgrade images for multiple non-Activemesh standalone Aviatrix Gateways in batches, instead of individually. This improvement makes the image upgrade process faster and more efficient for this type of gateway. You can upgrade non-Activemesh gateway images in batch if they have no peerings, or if only one of the gateways has a peering. If more than one non-Activemesh gateway has a peering, the batch image upgrade will fail. .. note:: Only one image-upgrade session is allowed for non-Activemesh gateways. This means that all desired gateways must be included in a single upgrade session. However, multiple non-Activemesh gateways can be upgraded simultaneously as part of a single upgrade session. Please see `Upgrading Gateway Images <https://docs.aviatrix.com/documentation/latest/platform-administration/gateway-image-migration.html?expand=true>`_ for more information. * **AVX-38963** - Previously, the Aviatrix OpenVPN® feature could not be used in conjunction with Site2Cloud certificate-based authentication. Now, you can use both features at the same time. 6.8.1646 Release Notes (05/04/2023) ================================================ **Enhanced Features in Aviatrix Release 6.8.1646** * **AVX-36880** - You can now upgrade images for multiple non-Activemesh standalone Aviatrix Gateways in batches, instead of individually. This improvement makes the image upgrade process faster and more efficient for this type of gateway. You can upgrade non-Activemesh gateway images in batch if they have no peerings, or if only one of the gateways has a peering. If more than one non-Activemesh gateway has a peering, the batch image upgrade will fail. .. note:: Only one image-upgrade session is allowed for non-Activemesh gateways. This means that all desired gateways must be included in a single upgrade session. However, multiple non-Activemesh gateways can be upgraded simultaneously as part of a single upgrade session. Please see `Upgrading Gateway Images <https://docs.aviatrix.com/documentation/latest/platform-administration/gateway-image-migration.html?expand=true>`_ for more information. * **AVX-38963** - Previously, the Aviatrix OpenVPN® feature could not be used in conjunction with Site2Cloud certificate-based authentication. Now, you can use both features at the same time. 6.7.1583 (04/24/23) ============================= **Important Notices in Aviatrix Release 6.7.1583** **AVX-34656** - * ActiveMesh 1.0 is no longer supported in release 6.8.1148. A Controller upgrade from 6.7.1583 to 6.8.1148 will be blocked if the Controller is running ActiveMesh 1.0. To migrate to ActiveMesh 2.0, go to Settings > Maintenance > Migration > ActiveMesh 2.0 before you upgrade to 6.8.1148. * (Azure) Azure FireNet gateway without a Load Balancer is no longer supported in 6.8.1148. A Controller upgrade from 6.7.1583 to 6.8.1148 will be blocked if you have such a deployment. Before you upgrade, rebuild any Azure FireNet gateway to enable a Load Balancer. **Enhanced Features in Aviatrix Release 6.7.1583** **AVX-36747** - Aviatrix Controller and gateway images are switching from Racoon based IKE to Strongswan based IKE. Your Controller and gateways will use the image’s Linux kernel version to determine which IKE-type to enable. If the Linux kernel version is 5.4 (or newer), upgrade is supported. 6.9.529 (04/24/2023) ========================= **Enhanced Features in Aviatrix Release 6.9.529** * **AVX-36880** - You can now upgrade images for multiple non-Activemesh Aviatrix Gateways in batches, instead of individually. This improvement makes the image upgrade process faster and more efficient for this type of gateway. You can upgrade non-Activemesh gateway images in batch if they have no peerings, or if only one of the gateways has a peering. If more than one non-Activemesh gateway has a peering, the batch image upgrade will fail. .. note:: Only one image-upgrade session is allowed for non-Activemesh gateways. This means that all desired gateways must be included in a single upgrade session. However, multiple non-Activemesh gateways can be upgraded simultaneously as part of a single upgrade session. Please see `Upgrading Gateway Images <https://docs.aviatrix.com/documentation/latest/platform-administration/gateway-image-migration.html>_` for more information. * **AVX-39732** - (Azure) Aviatrix has added support for the following Standard_Dxs_v5 instance types for VMs (Virtual Machines): * Standard_D2ds_v5 * Standard_D4ds_v5 * Standard_D8ds_v5 * Standard_D16ds_v5 * Standard_D32ds_v5 * Standard_D48ds_v5 * Standard_D64ds_v5 This enhancement was added to enable you to resize from Standard_Dx_v3 instance types to the Standard_Dxs_v5 instance types listed above. This resizing was not possible with previously-supported Standard_Dxs_v5 instance types. See `here <https://learn.microsoft.com/en-us/azure/virtual-machines/azure-vms-no-temp-disk>_` for more information about resizing VMs in Azure. **Issues Corrected in Aviatrix Release 6.9.529** * **AVX-38158** - (Alibaba) With CoPilot Security Group Management enabled, when you brought up gateways in Ali cloud, they would be missing Security Group rules on CoPilot. This issue meant there would be no visibility of netflow and syslog data from the gateways. * **AVX-38161** - If a Spoke Gateway has multiple Custom Mapped or Mapped Site2Cloud connections, Forward Traffic to Transit configuration enabled, and the same virtual destination CIDRs are configured in other Site2Cloud connections, a failover in one connection will cause TCP sessions belonging to the other connections to drop. * **AVX-39023** - Gateway Diagnostics would encounter an error and not display the results. 6.9.522 (04/17/2023) ===================== * **AVX-10154** - (Azure) If you have deployed Aviatrix gateways in Azure that use a companion-gateway-version less than or equal to “aviatrix-companion-gateway-v8,” upgrade to software release 6.7.1185 or newer before performing an image upgrade of these gateways. No immediate action is required. Do not perform any `Out-of-band <https://read.docs.aviatrix.com/HowTos/general_glossary.html#oob-out-of-band>`_ or Manual activity related to Azure unmanaged disks, as they will be `retired <https://azure.microsoft.com/en-gb/updates/azure-unmanaged-disks-will-be-retired-on-30-september-2025/>`_ in 2025. * **AVX-27396** - (Azure) You can now use HPE (High Performance Encryption) on the following Azure instances: * B2ms * D2_v4 * D4_v4 * D2_v5 (12.5 Gbps compared to D2_v4 5 Gbps) * D4_v5 (12.5 Gbps compared to 10 Gbps with D4_v4) * D8_v5 * D16_v5 * **AVX-32231** - A new safety check has been added to help avoid configuration errors. With this safety check, you cannot set up your Spoke Gateway with Custom Mapped/Mapped configuration with Overlapping CIDRs in any of the following: Local Initiated Traffic Destination Virtual CIDRs Remote Initiated Traffic Source Virtual CIDRs Remote Subnet (Virtual) * **AVX-32894** - (Azure) You can now use Accelerated Networking on Azure gateways with instance sizes that support this feature. See the list of supported instance sizes `here <https://learn.microsoft.com/en-us/azure/virtual-network/accelerated-networking-overview>`_. * **AVX-34431** - (AWS) AWS gateways will now support a new instance type, C6in, in select regions. * **AVX-35789** - Previously, if the gateway daemon code experienced errors, it could be difficult to receive alerts for those errors. Now, if the gateway daemon code experiences errors, you receive a notification through the Controller’s bell icon. * **AVX-38080** - The wait limit for communication between gateways and the Controller has been extended from 2.5 minutes to 10 minutes. This extension provides the necessary time for gateways to successfully upgrade. * **AVX-36562** - The FlightPath feature has two improvements: * This feature can now track egress traffic to the Internet. * FlightPath now selects the route with the lowest metric when traversing the Linux route table. * **AVX-36246** - Added new API endpoints for Datadog: "ddog-gov.com", "us3.datadoghq.com", "us5.datadoghq.com". * **AVX-36425** - You can now configure DNAT in non-active gateways. * **AVX-36747** - Aviatrix Controller and gateway images are switching from IKE-type Racoon to IKE-type Strongswan. Your Controller and gateways will use the image’s Linux kernel version to determine which IKE-type to enable. If the Linux kernel version is 5.4(or newer), Strongswan is enabled. **Issues Corrected in Aviatrix Release 6.9.522** * **AVX-28468** - Equinix can workaround this issue by allowing the Controller’s IP address access SSH port 22 in the VNF's ACL. By doing this, sshgw can directly SSH to the VM via its public IP. * **AVX-20197** - After the Single AZ HA setting on a gateway was enabled and the GSO/GRO setting was disabled, the gateway may have auto-restarted multiple times. * **AVX-34680** - When you deleted a GCP gateway with a Site2Cloud connection, certain gateway resources were deleted before the Controller rejected the deletion. * **AVX-35096** - (Azure) An API error may have caused the Controller to become unresponsive. * **AVX-35646** - Previously, the gateway name reported in logs generated by the HTTP/HTTPS FQDN enforcer was “NA.” Now, the gateway name is correctly reported for newly created gateways. * **AVX-35844** - (AWS) When you had a Transit Gateway attached to an AWS TGW and many Site2Cloud connections, the TGW list and plan page loaded slowly. * **AVX35958** - The primary and HA gateway shared the same remote IP configuration. * **AVX-36387** - (AWS) You received a gateway error message, “Missing account or VPC,” when you tried to bring up a gateway. * **AVX-36794** - If a Spoke Gateway has multiple Custom Mapped or Mapped Site2Cloud connections, Forward Traffic to Transit configuration enabled, and the same virtual destination CIDRs are configured in other Site2Cloud connections, a failover in one connection will cause TCP sessions belonging to the other connections to drop. * **AVX-36893** - A Controller restore may have failed if the Controller had some dangled files. * **AVX-36913** - (GCP) GCP gateways may experience CPU spikes every 10 minutes. * **AVX-36971** - A gateway instance could shut down as you used the Monitor Gateway Subnet feature. * **AVX-37020** - (Azure) Upgrading certain older Azure gateways was unsuccessful because they did not have the “gw_subnet_cidr” attribute. * **AVX-37066** - Under certain conditions, when you tried to download Egress FQDN logs or stats, the download failed and you received an error message: ... 'utf-8' codec can't decode byte ... * **AVX-37801** - (Azure) Deleting an Azure Spoke Gateway incorrectly deleted user-created RFC1918 routes in the VNet route table. * **AVX-38409** - A gateway credential could be doubly encrypted. * **AVX-38471** - If the quagga bgp Debian packages were not installed properly, the Aviatrix Controller would try to reinstall the package instead of failing the gateway configuration. * **AVX-38682** - (GCP) When you selected the CheckPoint BYOL image as the third-party firewall option, the CheckPoint PAYG image came up instead. * **AVX-39037** - If you added policy rules to Distributed Firewalling, additional and unnecessary code could always run, even if the rules were deleted. * **AVX-39040** - Gateways reconnecting to the Controller could cause a resource leak on the gateway. **Known Issues in Release 6.9.522** * **AVX-36138** - Gateway initialization, including Cloud Gateway creation, Cloud Gateway Image Upgrade, or Cloud Gateway Software Rollback fails if you completed both of the operations below (regardless of order): * Changing the controller time zone to those ahead of UTC/GMT. For example, for Australia/Sydney (AEST), the offset UTC is UTC+11:00. * PKI re-bootstrap (including Certificate Domain Update and Gateway CA Certificate Upload) * If you’ve already completed the actions above, try your gateway initialization again after X hours where X is the time zone difference between your Controller and the UTC/GMT. For example, if you change the Controller time zone to Australia/Sydney (AEST) and then upload the Gateway CA Certificate at 09:00, you need to wait until 20:00 (09:00 plus the 11:00-hour offset) to successfully create/replace/rollback any cloud gateway. * **AVX-37895** - (Azure) Gateway deployment in Azure can fail if the Network Security Group (NSG) is not applied on the Controller’s Network Interface Card (NIC). If this happens, use one of two methods to resolve the issue: * Disable and reenable the Controller Security Group management. This requires a disruption in traffic. * In Azure, locate the NSG, which uses the format AVX-SG-<Pubic -IP>, and attach this NSG manually to the Controller’s NIC. This method does not require disruption in traffic. * **AVX-36492** - When single-IP HA (High Availability) is enabled on Aviatrix Gateways and the HA gateway goes up, a bug may cause the security group to not be added to the gateway. To resolve this issue, manually add the security group to the HA gateway. 6.8.1621 (04/13/2023) ============================================ **Enhanced Features in Release 6.8.1621** * **AVX-10154** - (Azure) If you have deployed Aviatrix gateways in Azure that use a companion-gateway-version less than or equal to “aviatrix-companion-gateway-v8,” upgrade to software release 6.7.1185 or newer before performing an image upgrade of these gateways. No immediate action is required. Do not perform any `Out-of-band <https://read.docs.aviatrix.com/HowTos/general_glossary.html#oob-out-of-band>`_ or Manual activity related to Azure unmanaged disks, as they will be `retired <https://azure.microsoft.com/en-gb/updates/azure-unmanaged-disks-will-be-retired-on-30-september-2025/>`_ in 2025. * **AVX-27396** - (Azure) You can now use HPE (High Performance Encryption) on the following Azure instances: * B2ms * D2_v4 * D4_v4 * D2_v5 (12.5 Gbps compared to D2_v4 5 Gbps) * D4_v5 (12.5 Gbps compared to 10 Gbps with D4_v4) * D8_v5 * D16_v5 * **AVX-32231** - A new safety check has been added to help avoid configuration errors. With this safety check, you cannot set up your Spoke Gateway with Custom Mapped/Mapped configuration with Overlapping CIDRs in any of the following: Local Initiated Traffic Destination Virtual CIDRs Remote Initiated Traffic Source Virtual CIDRs Remote Subnet (Virtual) * **AVX-32894** - (Azure) You can now use Accelerated Networking on Azure gateways with instance sizes that support this feature. See the list of supported instance sizes `here <https://learn.microsoft.com/en-us/azure/virtual-network/accelerated-networking-overview>`_. * **AVX-34431** - (AWS) AWS gateways will now support a new instance type, C6in, in select regions. * **AVX-35789** - Previously, if the gateway daemon code experienced errors, it could be difficult to receive alerts for those errors. Now, if the gateway daemon code experiences errors, you receive a notification through the Controller’s bell icon. * **AVX-38080** - The wait limit for communication between gateways and the Controller has been extended from 2.5 minutes to 10 minutes. This extension provides the necessary time for gateways to successfully upgrade. * **AVX-36425** - You can now configure DNAT in non-active gateways. * **AVX-36562** - The FlightPath feature has two improvements: * This feature can now track egress traffic to the Internet. * FlightPath now selects the route with the lowest metric when traversing the Linux route table. * **AVX-36747** - Aviatrix Controller and gateway images are switching from IKE-type Racoon to IKE-type Strongswan. Your Controller and gateways will use the image’s Linux kernel version to determine which IKE-type to enable. If the Linux kernel version is 5.4(or newer), Strongswan is enabled. **Issues Corrected in Release 6.8.1621** * **AVX-20197** - After the Single AZ HA setting on a gateway was enabled and the GSO/GRO setting was disabled, the gateway may have auto-restarted multiple times. * **AVX-34680** - When you deleted a GCP gateway with a Site2Cloud connection, certain gateway resources were deleted before the Controller rejected the deletion. * **AVX-35096** - (Azure) An API error may have caused the Controller to become unresponsive. * **AVX-35646** - Previously, the gateway name reported in logs generated by the HTTP/HTTPS FQDN enforcer was “NA.” Now, the gateway name is correctly reported for newly created gateways. * **AVX-35844** - (AWS) When you had a Transit Gateway attached to an AWS TGW and many Site2Cloud connections, the TGW list and plan page loaded slowly. * **AVX-35958** - The primary and HA gateway shared the same remote IP configuration. * **AVX-36387** - (AWS) You received a gateway error message, “Missing account or VPC,” when you tried to bring up a gateway. * **AVX-36546** - FlightPath may have incorrectly shown Spoke and Transit Gateway routes as inactive if the Controller and Gateways were using the following software versions: 7.0.1373, 7.0.1383, 6.9.308, or 6.8.1483. * **AVX-36794** - If a Spoke Gateway has multiple Custom Mapped or Mapped Site2Cloud connections, Forward Traffic to Transit configuration enabled, and the same virtual destination CIDRs are configured in other Site2Cloud connections, a failover in one connection will cause TCP sessions belonging to the other connections to drop. * **AVX-36893** - A Controller restore may have failed if the Controller had some dangled files. * **AVX-36971** - A gateway instance could shut down as you used the Monitor Gateway Subnet feature. * **AVX-37020** - (Azure) Upgrading certain older Azure gateways was unsuccessful because they did not have the “gw_subnet_cidr” attribute. * **AVX-37066** - Under certain conditions, when you tried to download Egress FQDN logs or stats, the download failed and you received an error message: ... 'utf-8' codec can't decode byte ... * **AVX-37801** - (Azure) Deleting an Azure Spoke Gateway incorrectly deleted user-created RFC1918 routes in the VNet route table. * **AVX-38409** - A gateway credential could be doubly encrypted. * **AVX-38471** - If the quagga bgp Debian packages were not installed properly, the Aviatrix Controller would try to reinstall the package instead of failing the gateway configuration. * **AVX-38682** - (GCP) When you selected the CheckPoint BYOL image as the third-party firewall option, the CheckPoint PAYG image came up instead. * **AVX-39037** - If you added policy rules to Distributed Firewalling, additional and unnecessary code could always run, even if the rules were deleted. **Known Issues in Aviatrix Release 6.8.1621** * **AVX-36138** - Gateway initialization, including Cloud Gateway creation, Cloud Gateway Image Upgrade, or Cloud Gateway Software Rollback fails if you completed both of the operations below (regardless of order): * Changing the controller time zone to those ahead of UTC/GMT. For example, for Australia/Sydney (AEST), the offset UTC is UTC+11:00. * PKI re-bootstrap (including Certificate Domain Update and Gateway CA Certificate Upload) * If you’ve already completed the actions above, try your gateway initialization again after X hours where X is the time zone difference between your Controller and the UTC/GMT. For example, if you change the Controller time zone to Australia/Sydney (AEST) and then upload the Gateway CA Certificate at 09:00, you need to wait until 20:00 (09:00 plus the 11:00-hour offset) to successfully create/replace/rollback any cloud gateway. * **AVX-36492** - When single-IP HA (High Availability) is enabled on Aviatrix Gateways and the HA gateway goes up, a bug may cause the security group to not be added to the gateway. To resolve this issue, manually add the security group to the HA gateway. * **AVX-37895** - (Azure) Gateway deployment in Azure can fail if the Network Security Group (NSG) is not applied on the Controller’s Network Interface Card (NIC). If this happens, use one of two methods to resolve the issue: Disable and reenable the Controller Security Group management. This requires a disruption in traffic. In Azure, locate the NSG, which uses the format AVX-SG-<Pubic -IP>, and attach this NSG manually to the Controller’s NIC. This method does not require disruption in traffic. 6.9.355 (03/24/2023) ==================================== **Enhanced Features in Release 6.9.355** * **AVX-32231** - A new safety check has been added to help avoid configuration errors. With this safety check, you cannot set up your Spoke Gateway with Custom Mapped/Mapped configuration with Overlapping CIDRs in any of the following: * Local Initiated Traffic Destination Virtual CIDRs * Remote Initiated Traffic Source Virtual CIDRs * Remote Subnet (Virtual) **Issues Corrected in Release 6.9.355** * **AVX-34680** - When you deleted a GCP gateway with a Site2Cloud connection, certain gateway resources were deleted before the Controller rejected the deletion. * **AVX-35646** - Previously, the gateway name reported in logs generated by the HTTP/HTTPS FQDN enforcer was “NA.” Now, the gateway name is correctly reported for newly created gateways. * **AVX-36971** - The Monitor Gateway Subnet feature could shut down gateways during their initialization phase but not in subsequent phases. * **AVX-36794** - If a Spoke Gateway has multiple Custom Mapped or Mapped Site2Cloud connections, Forward Traffic to Transit configuration enabled, and the same virtual destination CIDRs are configured in other Site2Cloud connections, a failover in one connection will cause TCP sessions belonging to the other connections to drop. * **AVX-37020** - (Azure) Upgrading certain older Azure gateways was unsuccessful because they did not have the “gw_subnet_cidr” attribute. 6.8.1512 (03/24/2023) ==================================== **Enhanced Features in Release 6.8.1512** * **AVX-32231** - A new safety check has been added to help avoid configuration errors. With this safety check, you cannot set up your Spoke Gateway with Custom Mapped/Mapped configuration with Overlapping CIDRs in any of the following: * Local Initiated Traffic Destination Virtual CIDRs * Remote Initiated Traffic Source Virtual CIDRs * Remote Subnet (Virtual) **Issues Corrected in Release 6.8.1512** * **AVX-34680** - When you deleted a GCP gateway with a Site2Cloud connection, certain gateway resources were deleted before the Controller rejected the deletion. * **AVX-35646** - Previously, the gateway name reported in logs generated by the HTTP/HTTPS FQDN enforcer was “NA.” Now, the gateway name is correctly reported for newly created gateways. * **AVX-36971** - The Monitor Gateway Subnet feature could shut down gateways during their initialization phase but not in subsequent phases. * **AVX-36794** - If a Spoke Gateway has multiple Custom Mapped or Mapped Site2Cloud connections, Forward Traffic to Transit configuration enabled, and the same virtual destination CIDRs are configured in other Site2Cloud connections, a failover in one connection will cause TCP sessions belonging to the other connections to drop. * **AVX-37020** - (Azure) Upgrading certain older Azure gateways was unsuccessful because they did not have the “gw_subnet_cidr” attribute. 6.9.349 (03/20/2023) ==================================== **Enhanced Features in Release 6.9.349** * **AVX-36246** - Added new API endpoints for Datadog: "ddog-gov.com", "us3.datadoghq.com", "us5.datadoghq.com". 6.9.331 (02/16/2023) ================================== **Enhanced Features in Release 6.9.331** * **AVX-35773** - During vendor integration with Panorama, increased the wait time for a Panorama commit to 1 minute. Because it can take some time for Panorama to commit template changes, doing a device push before that commit is ready could cause incomplete routes being pushed to devices. The increased wait time ensures that the Panorama commit is complete before the device push. * **AVX-36147** - Removed the peering status check during the configuration workflow for NAT gateways. Now, you can configure NAT without waiting for the connection status to be UP. **Issues Corrected in Release 6.9.331** * **AVX-32921** - Some VPN user traffic to certain destinations was dropped on the VPN Gateway. This issue could occur when the VPN Gateway was rebooted and old VPN profile rules were not cleaned up from the system iptables. * **AVX-34845** - Removed a file from managed CloudN or the CaaG device during an upgrade to improve security. * **AVX-35077** - (Azure) If the Azure Spoke Gateways were down and a Transit Gateway propagated to an Azure Spoke Gateway with the default route, the Spoke VNet could not program route table default routes. * **AVX-35613** - When the Controller’s timezone was set to any other time zone than UTC (Coordinated Universal Time), a software upgrade became stuck at 99% progress. * **AVX-35728** - If an incorrect passphrase was entered when attempting to enable SSH access to your Controller, a bug was causing all the keys for on-prem managed CloudN or CaaG devices to be removed. 6.8.1509 (02/16/2023) ================================== **Enhanced Features in Release 6.8.1509** * **AVX-35773** - During vendor integration with Panorama, increased the wait time for a Panorama commit to 1 minute. Because it can take some time for Panorama to commit template changes, doing a device push before that commit is ready could cause incomplete routes being pushed to devices. The increased wait time ensures that the Panorama commit is complete before the device push. * **AVX-36147** - Removed the peering status check during the configuration workflow for NAT gateways. Now, you can configure NAT without waiting for the connection status to be UP. **Issues Corrected in Release 6.8.1509** * **AVX-32921** - Some VPN user traffic to certain destinations was dropped on the VPN Gateway. This issue could occur when the VPN Gateway was rebooted and old VPN profile rules were not cleaned up from the system iptables. * **AVX-34845** - Removed a file from managed CloudN or the CaaG device during an upgrade to improve security. * **AVX-35077** - (Azure) If the Azure Spoke Gateways were down and a Transit Gateway propagated to an Azure Spoke Gateway with the default route, the Spoke VNet could not program route table default routes. * **AVX-35613** - When the Controller’s timezone was set to any other time zone than UTC (Coordinated Universal Time), a software upgrade became stuck at 99% progress. * **AVX-35728** - If an incorrect passphrase was entered when attempting to enable SSH access to your Controller, a bug was causing all the keys for on-prem managed CloudN or CaaG devices to be removed. **Known Issues in Release 6.8.1509** * **AVX-29183** - Performing a dry run in 6.8.1148 and later versions will fail if the CSP Gateway’s image and/or CloudNs are based on IKE-type Racoon**, even though the upgrade from version 6.8.1148 to 6.9.128 will succeed. Aviatrix recommends performing an image upgrade of gateways running IKE-type Racoon before performing the software upgrade. An image upgrade will upgrade the gateway image version and thereby change the IKE-type on the gateways from Racoon to Strongswan. Please follow the steps below to perform a `Gateway Image Upgrade <https://docs.aviatrix.com/documentation/latest/platform-administration/gateway-image-migration.html>`_: Controller > Settings > Maintenance > Selective Gateway Upgrade > Select the gateway which lists IKE-type Racoon > click **Image Upgrade**. Gateways running older images will not be able to upgrade from 6.7.1185 to 6.8.1148 without performing an image upgrade of gateways to switch to IKE-type Strongswan. All gateways must run Strongswan prior to upgrading to version 6.8.1148. ** If your account uses Racoon-based CloudN, contact Aviatrix Support to replace your CloudN hardware to Strongswan before upgrading to version 6.8.1148. 6.7.1574 (02/16/2023) ================================== **Upgrade Prerequisites in Release 6.7.1574** * **AVX-29183** - (Cloud gateways) An image upgrade to 6.7.1574 and later versions will fail if the Cloud Gateway is based on IKE-type Racoon**. You must perform an image upgrade of Cloud gateways running IKE-type Racoon before performing the software upgrade. An image upgrade will upgrade the gateway image version and thereby change the IKE-type on the gateways from Racoon to Strongswan. Please follow the steps below to upgrade these Cloud gateways: Controller > Settings > Maintenance > Selective Gateway Upgrade > Select the gateway which lists IKE-type Racoon > click Image Upgrade. Cloud gateways running older images will not be able to upgrade from 6.6.5224 to 6.7.1574 without performing an image upgrade of gateways to switch to IKE-type Strongswan. All Cloud gateways must run Strongswan prior to upgrading to version 6.1574. ** If your account uses Racoon-based Cloud, contact Aviatrix Support to replace your Cloud hardware to Strongswan before upgrading to version 6.7.1574. ** Note that CloudN Gateways, as opposed to Cloud gateways, can run Racoon-based gateways up to release 6.8.1148. **Enhanced Features in Release 6.7.1574** * **AVX-35773** - During vendor integration with Panorama, increased the wait time for a Panorama commit to 1 minute. Because it can take some time for Panorama to commit template changes, doing a device push before that commit is ready could cause incomplete routes being pushed to devices. The increased wait time ensures that the Panorama commit is complete before the device push. **Issues Corrected in Release 6.7.1574** * **AVX-34845** - Removed a file from managed CloudN or the CaaG device during an upgrade to improve security. * **AVX-35077** - (Azure) If the Azure Spoke Gateways were down and a Transit Gateway propagated to an Azure Spoke Gateway with the default route, the Spoke VNet could not program route table default routes. * **AVX-35613** - When the Controller’s timezone was set to any other time zone than UTC (Coordinated Universal Time), a software upgrade became stuck at 99% progress. * **AVX-35728** - If an incorrect passphrase was entered when attempting to enable SSH access to your Controller, a bug was causing all the keys for on-prem managed CloudN or CaaG devices to be removed. **Known Issues in Release 6.7.1574** * **AVX-29183** - (Cloud gateways) An image upgrade to 6.7.1574 and later versions will fail if the Cloud Gateway is based on IKE-type Racoon**. See the Upgrade Prerequisites section. 6.7.1550 (02/01/2023) ================================== **Issues Corrected in Release 6.7.1550** * **AVX-26020** - When you did a Controller backup and restore, the Controller temporarily lost its BGP routes. This loss caused network flapping and a loss of traffic until the routes were restored. * **AVX-34823** - (AWS and Azure) In AWS accounts in the Controller that were onboarded using a key and secret instead of IAM Roles, an error occurred when you tried to bring up an Azure gateway. **Known Issues in Release 6.7.1550** .. warning:: **AVX-30776** - (Azure) To avoid Azure gateway image upgrade issues with unmanaged disks, `upgrade <https://read.docs.aviatrix.com/HowTos/Migration_From_Marketplace.html>`_ to Controller version 6.7.1550 before upgrading your gateway image. 6.8.1483 (02/01/2023) ================================== **Feature Enhancements in Aviatrix Release 6.8.1483** * **AVX-34591** - (AWS) Added support for the UAE (United Arab Emirates) region, or me-central-1, for AWS Gateways and VPCs. **Issues Corrected in Aviatrix Release 6.8.1483** * **AVX-34823** - (AWS and Azure) In AWS accounts in the Controller that were onboarded using a key and secret instead of IAM Roles, an error occurred when you tried to bring up an Azure gateway. **Known Issues in Aviatrix Release 6.8.1483** * **AVX-27704** - When a gateway had too many routes, the CoPilot Cloud Routes page did not display anything. .. warning:: **AVX-30776** - (Azure) To avoid Azure gateway image upgrade issues with unmanaged disks, `upgrade <https://read.docs.aviatrix.com/HowTos/Migration_From_Marketplace.html>`_ to Controller version 6.7.1550 before upgrading your gateway image. 6.9.308 (02/01/2023) ================================== **Feature Enhancements in Aviatrix Release 6.9.308** * **AVX-34591** - (AWS) Added support for the UAE (United Arab Emirates) region, or me-central-1, for AWS Gateways and VPCs. **Issues Corrected in Aviatrix Release 6.9.308** * **AVX-34823** - (AWS and Azure) In AWS accounts in the Controller that were onboarded using a key and secret instead of IAM Roles, an error occurred when you tried to bring up an Azure gateway. **Known Issues in Aviatrix Release 6.9.308** * **AVX-27704** - When a gateway had too many routes, the CoPilot Cloud Routes page did not display anything. .. warning:: **AVX-30776** - (Azure) To avoid Azure gateway image upgrade issues with unmanaged disks, `upgrade <https://read.docs.aviatrix.com/HowTos/Migration_From_Marketplace.html>`_ to Controller version 6.7.1550 before upgrading your gateway image. 6.9.295 (01/24/2023) ================================== **Issues Corrected in Release 6.9.295** * **AVX-34401** - After the Controller was updated to the 6.7.1376 software version with the AVX-25632 bug fix, you could not attach a CloudN as a Gateway (CaaG) to an Azure Transit Gateway. * **AVX-34887** - BGP learned routes have been optimized to handle 10K routes with long AS Path lengths from multiple neighbors. This update helps you scale your network successfully. 6.8.1469 (01/24/2023) ================================== **Issues Corrected in Release 6.8.1469** * **AVX-34401** - After the Controller was updated to the 6.7.1376 software version with the AVX-25632 bug fix, you could not attach a CloudN as a Gateway (CaaG) to an Azure Transit Gateway. * **AVX-34887** - BGP learned routes have been optimized to handle 10K routes with long AS Path lengths from multiple neighbors. This update helps you scale your network successfully. 6.7.1535 (01/24/2023) ================================== **Issues Corrected in Release 6.7.1535** * **AVX-34401** - After the Controller was updated to the 6.7.1376 software version with the AVX-25632 bug fix, you could not attach a CloudN as a Gateway (CaaG) to an Azure Transit Gateway. * **AVX-34887** - BGP learned routes have been optimized to handle 10K routes with long AS Path lengths from multiple neighbors. This update helps you scale your network successfully. 6.7.1526 (01/09/2023) ================================= **Enhanced Features in Release 6.7.1526** * **AVX-33814** - When an account had too many S2C connections, transit segmentation pages failed to load. **Issues Corrected in Aviatrix Release 6.7.1526** * **AVX-28175** - If you created an Azure Transit Gateway of size Dv4 and Dsv4 with BGP over LAN interfaces and HPE, you experienced an error: *[AVXERR-TRANSIT-0173] FireNet and BGP over LAN features require at least 4 interfaces.* * **AVX-31614** - When the Cloud VPC/VNet route table was full, new routes were not programmed when old routes were withdrawn. 6.9.282 (01/06/2023) ================================== **Enhanced Features in Release 6.9.282** * **AVX-26394** - For users authenticated using SAML to log in to Controller, you can now block them from logging in if they do not have a Profile. Previously, such users would be logged in as read-only. You can enable this option using the Block Empty Profiles toggle switch per SAML endpoint in your Controller. Navigate to Settings > Controller > SAML login. * **AVX-28938 (AWS)** - You can now overcome the 1000-rule limitation in AWS for security group rules per instance by using the Controller Security Access Control feature. Instead of using AWS Security groups to control access to the Controller, the Controller itself manages incoming TCP 443 access. You can configure this feature using API 2.5. Please contact Aviatrix Support for more information. * **AVX-32976** - Aviatrix now supports service in the Azure China North 3 region. * **AVX-33021** - When authenticating a Site2Cloud connection using PSK-based authentication, you can now ignore or skip the Remote ID check by entering ““ in the Remote Identifier field. This enhancement lets you authenticate connections for Remote ID types that Aviatrix Gateways do not support, including IPv6, FQDN, or email. This change also allows you to check if a tunnel is down because of a mismatched Remote ID. You can enter ““ in the Remote Identifier field, and if the tunnel comes up, the Remote ID could be mismatched. * **AVX-33814** - When an account had too many S2C connections, transit segmentation pages failed to load. * **AVX-34089** - You can now use the KEY_ID as the remote identifier in the Pre-Shared Key authentication for editing Site2Cloud connection configuration. **Issues Corrected in Aviatrix Release 6.9.282** * **AVX-25209** - The Aviatrix rsyslog may have unexpectedly stopped forwarding logging packets to remote server(s). * **AVX-28175** - If you created an Azure Transit Gateway of size Dv4 and Dsv4 with BGP over LAN interfaces and HPE, you experienced an error: *[AVXERR-TRANSIT-0173] FireNet and BGP over LAN features require at least 4 interfaces.* * **AVX-30621 (AWS)** - Controllers with a large number of access accounts experienced excessive memory usage. * **AVX-31614** - When a Cloud VPC/VNet route table was full, new routes were not programmed when old routes were withdrawn. * **AVX-32351** - During Packet Capture, if you clicked **Download** multiple times, you received an error message: “Failed to open file.” Now, you can download successfully even if you click **Download** multiple times. * **AVX-32283** - Certain web operations related to the Egress FQDN feature stalled due to fragmented TLS handshake packets. As a solution, the Aviatrix team coupled handling of these fragmented packets with the handling of packets with no SNI. To allow connections with fragmented client hellos to go through, enable your Controller’s FQDN configuration to allow packets with no SNI to go through. * **AVX-32730** - You could not modify a UserVPN LDAP configuration and upload a CA certificate when more than one VPN Gateway was deployed behind a load balancer. * **AVX-32904** - If the Edge node could not access the Aviatrix release server because of a firewall setting or because the Management was over a private network, enabling the FIPS caused the Edge gateway to fail. The gateway could not be recovered. * **AVX-33791** - When the Netflow feature was either enabled or disabled, the NAT iptables rules could have been lost. **Features Deprecated in Aviatrix Release 6.9.282** **AVX-31334** * The Transitive Peering feature is deprecated. This feature's functionality will be replaced by Aviatrix Multi-Cloud Transit. * Aviatrix recommends deleting Transitive Peerings from your account, and then upgrading your Controller. 6.8.1455 (01/06/2023) ============================== **Enhanced Features in Release 6.8.1455** * **AVX-26394** - For users authenticated using SAML to log in to Controller, you can now block them from logging in if they do not have a Profile. Previously, such users would be logged in as read-only. You can enable this option using the Block Empty Profiles toggle switch per SAML endpoint in your Controller. Navigate to Settings > Controller > SAML login. * **AVX-28938 (AWS)** - You can now overcome the 1000-rule limitation in AWS for security group rules per instance by using the Controller Security Access Control feature. Instead of using AWS Security groups to control access to the Controller, the Controller itself manages incoming TCP 443 access. You can configure this feature using API 2.5. Please contact Aviatrix Support for more information. * **AVX-30716** - Previously, Aviatrix Edge gateways were listening on port 111 on all interfaces. Now, Aviatrix has removed the open port 111 to improve security. * **AVX-33021** - When authenticating a Site2Cloud connection using PSK-based authentication, you can now ignore or skip the Remote ID check by entering ““ in the Remote Identifier field. This enhancement lets you authenticate connections for Remote ID types that Aviatrix Gateways do not support, including IPv6, FQDN, or email. This change also allows you to check if a tunnel is down because of a mismatched Remote ID. You can enter ““ in the Remote Identifier field, and if the tunnel comes up, the Remote ID could be mismatched. * **AVX-33814** - When an account had too many S2C connections, transit segmentation pages failed to load. * **AVX-34089** - You can now use the KEY_ID as the remote identifier in the Pre-Shared Key authentication for editing Site2Cloud connection configuration. **Issues Corrected in Aviatrix Release 6.8.1455** * **AVX-25209** - The Aviatrix rsyslog may have unexpectedly stopped forwarding logging packets to remote server(s). * **AVX-28175** - If you created an Azure Transit Gateway of size Dv4 and Dsv4 with BGP over LAN interfaces and HPE, you experienced an error: *[AVXERR-TRANSIT-0173] FireNet and BGP over LAN features require at least 4 interfaces*. * **AVX-31614** - When the Cloud VPC/VNet route table was full, new routes were not programmed when old routes were withdrawn. * **AVX-32351** - During Packet Capture, if you clicked **Download** multiple times, you received an error message: “Failed to open file.” Now, you can download successfully even if you click **Download** multiple times. * **AVX-32283** - Certain web operations related to the Egress FQDN feature stalled due to fragmented TLS handshake packets. As a solution, the Aviatrix team coupled handling of these fragmented packets with the handling of packets with no SNI. To allow connections with fragmented client hellos to go through, enable your Controller’s FQDN configuration to allow packets with no SNI to go through. * **AVX-32807** - Resolved an asymmetric traffic flow issue with the rxhash network setting. Note that this fix is essential for customers who are upgrading Azure Gateway images from v8 to v13. * **AVX-33791** - When the Netflow feature was either enabled or disabled, the NAT iptables rules could have been lost. **Features Deprecated in Aviatrix Release 6.8.1455** **AVX-31334** * The Transitive Peering feature is deprecated. This feature's functionality will be replaced by Aviatrix Multi-Cloud Transit. * Aviatrix recommends deleting Transitive Peerings from your account, and then upgrading your Controller. 6.8.1400 (11/18/2022) =============================== **Issues Corrected in Aviatrix Release 6.8.1400** **AVX-32273** - Known Aviatrix CSP (Cloud Service Provider) gateway base images launched in release 6.3, 6.4, and 6.5 with default python 2.7.17 are not compatible with python 3.6.9 in the versions (6.8.1148 and newer) of Aviatrix software. To avoid this issue, upgrade your Controller to the latest version and `upgrade <https://read.docs.aviatrix.com/HowTos/gateway-image-migration.html>`_ all gateways images launched in 6.5 or older to the latest version. 6.9.223 (11/18/2022) =============================== **Issues Corrected in Aviatrix Release 6.9.223** **AVX-32273** - Known Aviatrix CSP (Cloud Service Provider) gateway base images launched in release 6.3, 6.4, and 6.5 with default python 2.7.17 are not compatible with python 3.6.9 in the versions (6.8.1148 and newer) of Aviatrix software. To avoid this issue, upgrade your Controller to the latest version and `upgrade <https://read.docs.aviatrix.com/HowTos/gateway-image-migration.html>`_ all gateways images launched in 6.5 or older to the latest version. 6.7.1506 (11/14/2022) ================================= **Issues Corrected in Aviatrix Release 6.7.1506** **AVX-13508** – (AWS users) When you launch a gateway, the gateway uses the Default encryption key set in your AWS account > EC2 > Settings > EBS encryption. Previously, to use a key other than the Default key, you had to go to your AWS account > EC2 > Settings > EBS encryption and click Manage. Now, if you want to use a different encryption key than the Default encryption key, you can use Terraform or API to specify which encryption key to use for this gateway. * **AVX-25209** – The Aviatrix rsyslog may have unexpectedly stopped forwarding logging packets to remote server(s). * **AVX-26005** - When you did a Controller backup and restore, the Controller temporarily lost its BGP routes. This loss caused network flapping and a loss of traffic until the routes were restored. * **AVX-26020** – Previously, when a Controller backup and restore was performed, the Controller temporarily lost its BGP routes. This loss caused network flapping and a loss of traffic until the routes were restored. * **AVX-28821** – When a Controller’s time zone was changed to any time zone other than UTC, CoPilot did not display host information under Performance > Network Metrics for the Last Hour. Note: To resolve this issue in versions older than release 6.9.b, restart cloudxd in your Controller by going to Diagnostics > Services > CloudXD > Actions > Restart. * **AVX-29016** – When a CAAG or Edge Gateway was registered while your LAN/WAN interface was down, the CloudN list would fail to display. You could not perform basic actions like Diag, Deregister, or Reset Configuration. * **AVX-30443** – BGP learned routes were temporarily removed and then added back ActiveMesh 1.0 was migrated to ActiveMesh 2.0. This issue could cause traffic interruption. **Features Deprecated in Aviatrix Release 6.7.1506** **AVX-31334** * The Transitive Peering features is deprecated. This features’ functionality will be replaced by Aviatrix Multi-Cloud Transit. * Aviatrix recommends deleting Transitive Peerings from your account, and then upgrading your Controller. 6.9.221 (11/04/2022) ========================================== **New Features in Release 6.9.221** **Controller Security Access Control** Attention AWS users. The Controller Security Access Control feature overcomes the 1000-rule limitation of AWS security group rules per instance. Instead of using AWS Security Groups to control access to the Controller, the Controller itself manages incoming TCP 443 access. You can configure this feature using API 2.5. Please contact Aviatrix Support for more information. **Issues Corrected in Aviatrix Release 6.9.221** **AVX-25209** – The Aviatrix rsyslog may have unexpectedly stopped forwarding logging packets to remote server(s). **Deprecated Features in Aviatrix Release 6.9.221** * The Transitive Peering features is deprecated. This features’ functionality will be replaced by Aviatrix Multi-Cloud Transit. * Aviatrix recommends deleting Transitive Peerings from your account, and then upgrading your Controller. 6.8.1398 (11/04/2022) ====================================== **New Features in Release 6.8.1398** **Controller Security Access Control** Attention AWS users. The Controller Security Access Control feature overcomes the 1000-rule limitation of AWS security group rules per instance. Instead of using AWS Security Groups to control access to the Controller, the Controller itself manages incoming TCP 443 access. You can configure this feature using API 2.5. Please contact Aviatrix Support for more information. **Issues Corrected in Aviatrix Release 6.8.1398** **AVX-25209** – The Aviatrix rsyslog may have unexpectedly stopped forwarding logging packets to remote server(s). **Deprecated Features in Aviatrix Release 6.8.1398** * The Transitive Peering feature is deprecated. This feature's functionality will be replaced by Aviatrix Multi-Cloud Transit. * Aviatrix recommends deleting Transitive Peerings from your account, and then upgrading your Controller. 6.9.188 (10/21/2022) ========================================== **Issues Corrected in Aviatrix Release 6.9.188** * **AVX-28821** - When you changed a Controller’s time zone to any time zone other than UTC, CoPilot did not display host information under Performance > Network Metrics for the Last Hour. .. note:: To resolve this issue in versions older than release 6.9.188, restart cloudxd in your Controller by going to Diagnostics > Services > CloudXD > Actions > Restart. * **AVX-28898** - A large number of Site2Cloud connections degraded your Controller’s responsiveness. * **AVX-29364** – When a GRE tunnel goes down, your gateway withdraws routes. Previously, gateways withdrew routes one at a time, which could take a long time. This enhancement ensures that gateways withdraw routes in bulk to speed up the process. * **AVX-29691** - Under scale setups with thousands of tunnels, when micro-segmentation was disabled, the process could still run and consume an entire CPU core. * **AVX-30443** – BGP learned routes were temporarily removed and then added back when you migrated ActiveMesh 1.0 to ActiveMesh 2.0. This issue could cause traffic interruption. * **AVX-30545** - A gateway using a Linux kernel version older than 4.20 will see a configure route failure with an error message: Failed to get real route: protocol not available. To avoid this issue, upgrade your gateways to the latest image. 6.8.1369 (10/21/2022) ============================== **Issues Corrected in Aviatrix Release 6.8.1369** .. important:: Before upgrading to 6.8.1369, upgrade your gateway images to the latest image. * **AVX-28821** - When you changed a Controller’s time zone to any time zone other than UTC, CoPilot did not display host information under Performance > Network Metrics for the Last Hour. .. note:: To resolve this issue in versions older than release 6.8.1369, restart cloudxd in your Controller by going to Diagnostics > Services > CloudXD > Actions > Restart. * **AVX-28898** - A large number of Site2Cloud connections degraded your Controller’s responsiveness. * **AVX-29364** - When a GRE tunnel goes down, your gateway withdraws routes. Previously, gateways withdrew routes one at a time, which could take a long time. This enhancement ensures that gateways withdraw routes in bulk to speed up the process. * **AVX-29691** - Under scale setups with thousands of tunnels, when micro-segmentation was disabled, the process could still run and consume an entire CPU core. * **AVX-30443** - BGP learned routes were temporarily removed and then added back when you migrated ActiveMesh 1.0 to ActiveMesh 2.0. This issue could cause traffic interruption. * **AVX-30545** - A gateway using a Linux kernel version older than 4.20 will see a configure route failure with an error message: Failed to get real route: protocol not available. To avoid this issue, upgrade your gateways to the latest image. 6.9.161 (09/30/2022) =========================== **Issues Corrected in Aviatrix Release 6.9.161** * **AVX-26004** - Resolved an issue involving AWS accounts and permissions. If you onboarded an AWS account to your Controller, but your Controller didn’t have permission for some regions in that account, your account would print traceback logs, sometimes in large amounts. These logs did not affect performance but were unhelpful for managing your accounts. This fix suppressed those logs. * **AVX- 27653** - Resolved two issues that could cause gateways to crash: the conduit binary could become overwhelmed by Linux kernel netlink messages, and IP fragmented packets could trigger a kernel crash if the packet fragment was smaller than the UDP header. This fix included releasing a new kernel driver. .. important:: If you experienced this issue, **restart your gateway** to use the new kernel driver. * **AVX-27657** - A full memory would cause the gateway’s tunnels to flap. * **AVX-28242** - Fixed an issue that prevented OpenVPN users from connecting to their VPN after adding a second search domain separated by a comma (Controller > Edit Config > Modify Split Tunnel). Now, OpenVPN users can enter multiple search domain names separated by commas in a split tunnel configuration. * **AVX-29002** - If you mapped a Site2Cloud configuration to a Spoke Gateway and then upgraded your gateway image with version 6.8.1148 software, traffic to your remote Site2Cloud connection would break. * **AVX-29016** - When you registered a CAAG or Edge Gateway while your LAN/WAN interface was down, the CloudN list would fail to display. You could not perform basic actions like Diag, Deregister, or Reset Configuration. **Known Issues in Aviatrix Release 6.9.161** * **AVX-29643** - There is an MSS clamp at 1370 whenever packets need to cross an AWS inter-region peering or any other underlay that does not support jumbo frames. 6.8.1342 (09/30/2022) =============================== **Issues Corrected in Aviatrix Release 6.8.1342** * **AVX-26004** - Resolved an issue involving AWS accounts and permissions. If you onboarded an AWS account to your Controller, but your Controller didn’t have permission for some regions in that account, your account would print traceback logs, sometimes in large amounts. These logs did not affect performance but were unhelpful for managing your accounts. This fix suppressed those logs. * **AVX-27653** - Resolved two issues that could cause gateways to crash: the conduit binary could become overwhelmed by Linux kernel netlink messages, and IP fragmented packets could trigger a kernel crash if the packet fragment was smaller than the UDP header. This fix included releasing a new kernel driver. .. important:: If you experienced this issue, **restart your gateway** to use the new kernel driver. * **AVX-27657** - A full memory would cause the gateway's tunnels to flap. * **AVX-28242** - Fixed an issue that prevented OpenVPN users from connecting to their VPN after adding a second search domain separated by a comma (Controller > Edit Config > Modify Split Tunnel). Now, OpenVPN users can enter multiple search domain names separated by commas in a split tunnel configuration. * **AVX-29002** - If you mapped a Site2Cloud configuration to a Spoke Gateway and then upgraded your gateway image with version 6.8.1148 software, traffic to your remote Site2Cloud connection would break. * **AVX-29016** - When you registered a CAAG or Edge Gateway while your LAN/WAN interface was down, the CloudN list would fail to display. You could not perform basic actions like Diag, Deregister, or Reset Configuration. 6.7.1480 (09/20/2022) ========================= **Feature Enhancements in 6.7.1480** * **AVX-23493** - You can now use the secondary IP as the Destination CIDR in SNAT/DNAT rules as long as the gateway is not in Insane Mode. * **AVX-25957** - Improved the performance of enabling an Egress FQDN tag so that the process is 5x faster. With this enhancement, adding a rule to an Egress FQDN tag is up to 50x faster. **Issues Corrected in 6.7.1480** * **AVX-17842** - Exception error displayed in version 6.7.1186 with spoke gateways in Azure, with SNAT and Insane Mode Encryption enabled. * **AVX-25499** - An Aviatrix regular gateway (as opposed to a Transit or Spoke Gateway), did not have routes to local VPC CIDRs. * **AVX-26933** - When you created a route-based Site2Cloud connection from the Controller's Site2Cloud setup page and selected the HA gateway as the primary source gateway, the route table was not populated correctly. * **AVX-27658** - Updated API call to retrieve specific transit Firenet spoke policies. * **AVX-27716** - An error may show "configuration not up-to-date" while upgrading an old image (kernel versions prior to version 5.4) to 6.8.1149. The old image will upgrade despite this error. 6.8.1311 (09/12/2022) ========================= **New Features in Release 6.8.1311** * (`Public Preview <https://docs.aviatrix.com/HowTos/Controller_and_Software_Release_Notes.html#public-preview-features>`_ feature) **Network Security Scanner** - The Security Scanner enables you to detect vulnerabilities of instances that an attacker could potentially exploit within your Aviatrix-managed VPCs/VNets. * To run the scanner, open Aviatrix CoPilot and navigate to Topology. * Select an instance (not a gateway) in the map and click the **Security Scanner** button in the resource's properties pane. * Enter one port, multiple ports, or a range of ports to scan and click **Run**. A Scan Report opens on the right. Note that this feature only inspects TLS/SSL protocols. **Enhanced Features in Release 6.8.1311** * **Secondary IP as Destination CIDR** - If you tried to set a gateway's secondary IP as the Destination CIDR of NAT rules, you received an error message. You can now use this secondary IP as the Destination CIDR as long as the gateway is not in Insane Mode. * **Micro-segmentation** - Micro-segmentation is now supported on AWS GovCloud and Azure Government as well as AWS, Azure, and GCP. * **Performance Improvements for Egress FQDN Tags** - Improved the performance of enabling an Egress FQDN tag so that the process is 5x faster. With this enhancement, adding a rule to an Egress FQDN tag is up to 50x faster. **Issues Corrected in Aviatrix Release 6.8.1311** * **AVX-25499** - An Aviatrix regular gateway (as opposed to a Transit or Spoke Gateway), did not have routes to local VPC CIDRs. * **AVX-26020** - When you did a Controller backup and restore, the Controller temporarily lost its BGP routes. This loss caused network flapping and a loss of traffic until the routes were restored. * **AVX-26933** - When you created a route-based Site2Cloud connection from the Controller's Site2Cloud setup page and selected the HA gateway as the primary source gateway, the route table was not populated correctly. * **AVX-27215** - When you have a large network with FireNet gateways, applying Terraform took a long time and may have overused the Controller CPU. * **AVX-27323** - When you exported a Terraform configuration from your Controller, the downloaded config file may have shown incorrect information. For example, if you exported a gateway configuration by navigating to Useful Tools > Export To Terraform > Gateway > gateway_snat OR gateway_dnat, the downloaded config file may have incorrectly shown that the snat_policy: - Has an interface argument with the tunnel interface ID. - Has a connection argument with the transit connection ID. * In this situation, the correct config info would be that the snat_policy: - Has an interface argument with an empty value. - Has a connection argument with the transit connection ID. * **AVX-27330** - Fixed upgrade issue if the customer deployed GW before 5.3. * **AVX-27716** - An error may show “configuration not up-to-date†while upgrading an old image (kernel versions prior to version 5.4) to 6.8.1149. The old image will upgrade despite this error. * **AVX-27732** - FIPS 140-2 is neither supported nor required for Edge devices. Previously, if you tried to enable FIPS on the Controller, the edge gateway configuration would fail. Now, if you try to enable user-vpn in FIPS mode silently, the Edge gateways will bypass the request. * **AVX-27820** - Resolved an issue that sometimes caused a Controller to read the VPC CIDR of a gateway incorrectly. This issue caused an error message when OpenVPN was enabled: "Failed to initialize GlobalConfigDB:" Error while trying to migrate from MongoDB to Etcd: Invalid IP address 1." 6.9.128 (09/09/2022) ===================== **Important Notices for Release 6.9.128** **Upgrading CloudN** *CloudN users*: * Make sure that your CloudN hardware is *version 2.1 or a later version*. If your hardware is 2.0 or earlier, you will need a hardware refresh.  * *Replace* CloudN hardware version prior to 2.1 with *CloudN hardware version 2.1 or later*. You could also migrate to Aviatrix Edge.  .. note:: To check which CloudN hardware version you are currently using, check your server. A server with a single SSD is running HW version 2.0 or a prior version and needs an update. A server with dual SSD Hard Disk drives is HW 2.1 or a later version and does not need an update.  - **AVX-37948** - (CoPilot users) The system metric Memory Free (memory_free) used in CoPilot for configuring alerts had been using a definition that was inconsistent with the operating system (OS) definition. Starting in 6.9.128 the metrics memory_available and memory_free are consistent with the OS definition. Due to this change, after upgrading your Controller, you may receive many Memory Free alerts indicating the memory free dropped. To mitigate this issue, you can change your alert configurations from using mem_free to using memory_available instead. **Enhanced Features in Release 6.9.128** * **Micro-segmentation** - `Micro-segmentation <https://docs.aviatrix.com/HowTos/secure_networking_microsegmentation.html>`_ is now supported on AWS GovCloud and Azure Government as well as AWS, Azure, and GCP. * **NAT Support for Private Mode** - NAT (Network Address Translation) is now supported on gateways while using `Private Mode <https://docs.aviatrix.com/HowTos/privatemode.html>`_. This enhancement includes: * DNAT and customized SNAT. * Terraform support for NAT. * **New Metered Offer in AWS and Azure** - Aviatrix offers a new metered license, **Aviatrix Secure Networking Platform Metered 2208-Universal 24x7 Support**, in the AWS and Azure marketplaces. This license offers access to upcoming Aviatrix features and flexible billing options. * New customers can subscribe to this license using the `AWS Getting Started Guide <https://docs.aviatrix.com/StartUpGuides/aws_getting_started_guide.html>`_ or `Azure Startup Guide <https://docs.aviatrix.com/StartUpGuides/azure-aviatrix-cloud-controller-startup-guide.html>`_. * Existing customers, migrate to this license as soon as possible to access upcoming new features and flexible billing options. See the AWS or Azure sections of `this document <https://docs.aviatrix.com/HowTos/Migration_From_Marketplace.html>`_. * **Secondary IP as Destination CIDR** - If you tried to set a gateway's secondary IP as the Destination CIDR of NAT rules, you received an error message. You can now use this secondary IP as the Destination CIDR as long as the gateway is not in Insane Mode. **Public Preview Features in Aviatrix Release 6.9.128** (`Public Preview <https://docs.aviatrix.com/HowTos/Controller_and_Software_Release_Notes.html#public-preview-features>`_ feature) **Network Security Scanner** - The Security Scanner enables you to detect vulnerabilities of instances that an attacker could potentially exploit within your Aviatrix-managed VPCs/VNets. * To run the scanner, open Aviatrix CoPilot and navigate to Topology. * Select an instance (not a gateway) in the map and click the **Security Scanner** button in the resource's properties pane. * Enter one port, multiple ports, or a range of ports to scan and click **Run**. A Scan Report opens on the right. Note that this feature only inspects TLS/SSL protocols. **Issues Corrected in Aviatrix Release 6.9.128** * **AVX-27215** - When you have a large network with FireNet gateways, applying Terraform took a long time and may have overused the Controller CPU. * **AVX-27716** - An error may show “configuration not up-to-date†while upgrading an old image (kernel versions prior to version 5.4) to 6.8.1149. The old image will upgrade despite this error. * **AVX-27732** - FIPS 140-2 is neither supported nor required for Edge devices. Previously, if you tried to enable FIPS on the Controller, the edge gateway configuration would fail. Now, if you try to enable user-vpn in FIPS mode silently, the Edge gateways will bypass the request. * **AVX-27820** - Resolved an issue that sometimes caused a Controller to read the VPC CIDR of a gateway incorrectly. This issue caused an error message when OpenVPN was enabled: "Failed to initialize GlobalConfigDB: Error while trying to migrate from MongoDB to Etcd: Invalid IP address 1." **Known Issues in Aviatrix Release 6.9.128** * **AVX-35490** - After a Controller software upgrade or a CloudXD restart, the Controller migrates BGP routes, automatically triggering an “Approve New Routes” email for existing pending CIDRs on gateways with learned CIDRs approval enabled. This issue has no functional impact. Approved CIDRs remain intact and no routes are changed. 6.8.1149 (08/17/2022) ===================== **Issues Corrected in Aviatrix Release 6.8.1149** - **AVX-27330** - Fixed upgrade issues for gateways deployed before version 5.3. **Known Issues in Aviatrix Release 6.8.1149** - **AVX-27716** - An error may show "configuration not up-to-date" while upgrading an old image (kernel versions prior to version 5.4) to 6.8.1149. The old image will upgrade despite this error. 6.7.1436 (08/16/2022) ===================== **Issues Corrected in Aviatrix Release 6.7.1436** - **AVX-18788** - When a GCP spoke/transit using insane mode and attached to other gateway is resized to a larger size the network throughput does not increase as expected. This fix ensures that spoke/transit gateway throughput increases the network throughput when resized to a larger size. - **AVX-24610** - When the AWS TGW API returns an error to search routes from a route table, the VPN /Direct Connect learned routes are withdrawn. It should be treated as no change. - **AVX-24730** - The user should be able to go to the Settings > Controller > Login Customization page, the page allows the user to change the admin login restriction setting and set controller banner. - **AVX-24860** - Enabled support for legacy Azure Germany North Region. Azure does not allow users to create a new resource group in the legacy Germany North Region however users can still access or update the resource created in the legacy region previously. - **AVX-25128** - An exception is seen when migrating transit gateway tunnel status in MongoDB to etc. when transit gateway has CloudN attached. When migrating transit gateway tunnel status in MongoDB to etcd, for transit gateways that have CloudN attached, use CloudN private_ip for peer_ip to fix the exception. If tunnel status in MongoDB does not have peer_ip, update it with peer_ip based on peer info from tunnel status msg controller received from a gateway. When a GCP spoke/transit using insane mode and attached to another gateway is resized to a larger size the network throughput does not increase as expected. This fix ensures that spoken/transit gateway throughput increases the network throughput when resized to a larger size. - **AVX-25641** - When the customer configures the route-based mapped site2cloud connections (including enabling Forward Traffic to Transit) with tunnel or gateway failover or subnet editing, some customer traffic could be dropped. This is because the code incorrectly updates the routing parts of the connection. To fix the issue, the customer should update the versions with the fix, and image upgrades the gateways to get rid of the incorrect routing information on the gateway so that the new code can rebuild the correct routing. - **AVX-25721** - For a spoke gateway, if the CIDR propagated from transit gateway has longer prefix than the CIDR propagated from S2C connection, existing software ignores the route/CIDR from transit gateway. The patch fixes this error and keeps longer prefix route from transit gateway. - **AVX-25976** - With this change, we will not program unnecessary entries in the VPC route table for DNAT configured with s2c connection. Thus, there is nothing to be cleaned up when the DNAT configuration is removed. - **AVX-25993** - The logging service for Rsyslog supports up to 9 profiles. It is a bug in which the configuration during restore allows each profile enablement to start the Rsyslog service (6 times or more) in less than 2 seconds. The system service defaults 5 times in 10 seconds; otherwise, the Rsyslog service will fail in "starting". The fix is to ensure that the Rsyslog service is only restarted once for all profiles. - **AVX-26086** - Corrected the logic to program the learned 0.0.0.0/0 route on the Azure cloud route table. - **AVX-26208** - Corrected issue with Security Group Management in certain cases when restoring from a backup. - **AVX-26374** - The controller database can go into a state where it has empty peer IPs for tunnels between transit gateways and CloudN devices. This prevents the gateway snapshot creation and prevents configuration/route updates being propagated to the gateway. This Software patch script will correct the controller database entries. - **AVX-26852** - If users have/use 65535 in their BGP route AS path at the beginning of the path before any other ASN's, it is replaced with IMPLICIT. This prevents an exception from occurring and prevents BGP route flapping. **Known Issues in Aviatrix Release 6.7.1436** - **AVX-24701** - When the AWS TGW API returns an error to search routes from a route table, the VPN /Direct Connect learned routes are withdrawn. It should be treated as no change. - **AVX-25459** - If you have one of the VPC CIDRs as same as the spoke gateway's subnet CIDR, some routes cannot be updated correctly in the spoke gateway route table. - **AVX-25709** - Exception seen when disabling TGW Firenet la launched before the 6.3 release. - **AVX-26684** - GRE external connection may miss routes on the HA Transit. **Deprecated Features in Aviatrix Release 6.7.1436** Transitive Peering Feature Deprecated - The Transitive Peering feature is deprecated. This feature's functionality will be replaced by `Aviatrix Multi-Cloud Transit <https://docs.aviatrix.com/HowTos/transit_gateway_peering.html>`_. (AWS) UserVPN Gateways Do Not Support Classic Load Balancers **AVX-24015** - (AWS) AWS classic Load Balancers are not supported with UserVPN gateways. Instead, `migrate <https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/migrate-classic-load-balancer.html>`_ to Network Load Balancers in your AWS account. 6.6.5721 (08/16/2022) ===================== **Issues Corrected in Aviatrix Release 6.6.5721** - **AVX-18788** - When a GCP spoke/transit using insane mode and attached to other gateway is resized to a larger size the network throughput does not increase as expected. This fix ensures that spoke/transit gateway throughput increases the network throughput when resized to a larger size. - **AVX-24610** - When the AWS TGW API returns an error to search routes from a route table, the VPN /Direct Connect learned routes are withdrawn. It should be treated as no change. - **AVX-24730** - The user should be able to go to the Settings > Controller > Login Customization page, the page allows the user to change the admin login restriction setting and set controller banner. - **AVX-24860** - Enabled support for legacy Azure Germany North Region. Azure does not allow users to create a new resource group in the legacy Germany North Region however users can still access or update the resource created in the legacy region previously. - **AVX-25459** - If you have one of the VPC CIDRs as same as the spoke gateway's subnet CIDR, some routes cannot be updated correctly in the spoke gateway route table. - **AVX-25490** - New controller versions could be hit with error messages upon upgrade, such as "TypeError: '1370' has type str, but expected one of: int, long". This is because the previous version has some gateway level tunnel configurations which could have some values of the string type, and the newer version expects the integer type. The latest controller image versions with the fix will automatically convert the string values into integer values so that the upgrade could finish. - **AXV-25514** - If users have/use 65535 in their BGP route AS path at the beginning of the path before any other ASN's, it is replaced with IMPLICIT. This prevents an exception from occurring and prevents BGP route flapping. - **AVX-25641** - When the customer configures the route-based mapped site2cloud connections (including enabling Forward Traffic to Transit) with tunnel or gateway failover or subnet editing, some customer traffic could be dropped. This is because the code incorrectly updates the routing parts of the connection. To fix the issue, the customer should update the versions with the fix, and image upgrades the gateways to get rid of the incorrect routing information on the gateway so that the new code can rebuild the correct routing. - **AVX-25673** - After using SITE2CLOUD Diagnostics 'Enable verbose logging', 'Disable verbose logging' fails to disable verbose logging. - **AVX-25721** - For a spoke gateway, if the CIDR propagated from transit gateway has longer prefix than the CIDR propagated from S2C connection, existing software ignores the route/CIDR from transit gateway. The patch fixes this error and keeps longer prefix route from transit gateway. - **AVX-25976** - With this change, we will not program unnecessary entries in the VPC route table for DNAT configured with s2c connection. Thus, there is nothing to be cleaned up when the DNAT configuration is removed. - **AVX-25993** - The logging service for Rsyslog supports up to 9 profiles. It is a bug in which the configuration during restore allows each profile enablement to start the Rsyslog service (6 times or more) in less than 2 seconds. The system service defaults 5 times in 10 seconds; otherwise, the Rsyslog service will fail in "starting". The fix is to ensure that the Rsyslog service is only restarted once for all profiles. - **AVX-26086** - Corrected the logic to program the learned 0.0.0.0/0 route on the Azure cloud route table. - **AVX-26208** - Corrected issue with Security Group Management in certain cases when restoring from a backup. - **AVX-27359** - CloudN SW upgrade from image prior to 6.6.5721 need to use "upgrade to a custom release" to upgrade to latest 6.6 (6.6.5721). **Known Issues in Aviatrix Release 6.6.5721** - **AVX-24701** - When the AWS TGW API returns an error to search routes from a route table, the VPN /Direct Connect learned routes are withdrawn. It should be treated as no change. - **AVX-25709** - Exception seen when disabling TGW Firenet la launched before the 6.3 release. - **AVX-26684** - GRE external connection may miss routes on the HA Transit. 6.8.1148 (08/09/2022) ===================== **Important Notices in Aviatrix Release 6.8.1148** - **AVX-26666** - For gateway rollback to work in 6.8, your Controller and gateways must be on the latest version of 6.7 (6.7.1376) before upgrading to 6.8. - **AVXSRE-395** - Aviatrix is continuously improving its products and services, requiring to migrate to new IP addresses. Therefore, if you are filtering out part of all the traffic from your controllers to the Internet, please update your rules to allow Aviatrix Central Services according to our Support Portal: Aviatrix Products: `Required Access for External Sites <https://aviatrix.zendesk.com/hc/en-us/articles/4417312119437-Aviatrix-Products-Required-Access-for-External-Sites>`_ - **AVX-31465** - **CloudN users**: Before upgrading your Controller to version 6.8.1148, make sure your CloudN base software is upgraded to version 6.6.5721 or a later version. .. note:: To check which CloudN base software version you are currently using, log into your CloudN IP address. The following Private Preview Features are available in this release: - **Managed CloudN for AWS and Azure China** - Managed CloudN for AWS and Azure China provides High-Performance Encryption (Insane Mode) to on-premises locations in China with CloudN. Refer to `Managed CloudN Workflows <https://docs.aviatrix.com/HowTos/CloudN_workflow.html>`_. - **AVX-37948** - (CoPilot users) The system metric Memory Free (memory_free) used in CoPilot for configuring alerts had been using a definition that was inconsistent with the operating system (OS) definition. Starting in 6.8.1148 the metrics memory_available and memory_free are consistent with the OS definition. Due to this change, after upgrading your Controller, you may receive many Memory Free alerts indicating the memory free dropped. To mitigate this issue, you can change your alert configurations from using mem_free to using memory_available instead. **New Features in Aviatrix Release 6.8.1148** - **Aviatrix Edge 2.0** - The Aviatrix Edge solution enables enterprises to extend the Cloud operational model to the edge network for consistent and repeatable architecture, management, visibility, security, and control. This cloud-out architecture enables enterprises to leverage the Aviatrix platform ubiquitous support for edge connectivity. The result is secure, seamless connectivity to edge locations such as data centers, co-locations, remote sites, provider locations, branch offices, and retail stores. Aviatrix Edge 2.0 solution is offered in VMware ESXi and KVM form factors that lets you deploy an Edge Gateway with Spoke Gateway capabilities at the edge network. For more information about Aviatrix Edge, refer to the `Aviatrix Edge FAQ <https://docs.aviatrix.com/HowTos/edge-faq.html>`_. - **Azure BGP over LAN multi-peer and Azure Route Server Integration** - Aviatrix now supports multi-peer BGP Over LAN connections in Azure. This feature offers new functionality, such as the ability to interoperate with multiple third-party virtual appliances such as SD-WAN cloud instances without having to use any tunnelling protocols such as IPsec. Please see `this document <https://docs.aviatrix.com/HowTos/azure_bgpolan_multi_peer.html>`_ for more information. - **Certificate-Based Authentication for Site2Cloud VPN** - You can now use certificate-based authentication when configuring a Site2Cloud connection between your Aviatrix gateways and external devices. Currently only the Palo Alto VM-Series firewall is supported as an external device. See `here <https://docs.aviatrix.com/HowTos/site2cloud-cacert.html>`_ for more information. - **HPE for AWS/Azure China** - AWS China and Azure China CSPs now support High Performance Encryption (HPE). - **Aviatrix Controller Deployment from Azure China** - Aviatrix now supports deploying a Controller from Azure China. See `this document <https://docs.aviatrix.com/HowTos/aviatrix_china_overview.html>`_ for more information about which Aviatrix features and services are available for China marketplaces. Please note that Aviatrix CoPilot is still only available in AWS China. - **Preserve AS Path** - In 6.7.1319, we introduced a new toggle, "Preserve AS Path". When enabled, this toggle ensured gateways retained the AS path in manually advertised routes, and that routes would be advertised as local if the route did not exist in best route DB. This change improves failover behavior; gateways will stop advertising any manually advertised CIDR if it is no longer in the best DB (the route is no longer advertised as local). - **Private Mode Phase 1** - Private Mode is a global setting that offers secure orchestrated intra- and multi-cloud networking by removing the need for public IPs for Aviatrix gateways. `Click here for more information about Private Mode <https://docs.aviatrix.com/HowTos/privatemode.html>`_. **Enhanced Features in Aviatrix Release 6.8.1148** - **CoPilot Clustered Deployment from Aviatrix Controller UI (AWS CSP only)** - If you deployed Aviatrix Controller in AWS, you now have the option to deploy Aviatrix CoPilot as a clustered (fault tolerant) system directly from your Aviatrix Controller UI. For detailed information, see the Aviatrix CoPilot Deployment Guide. - **Near-hitless GW Resize/Replace** -- Aviatrix cloud and routing orchestration enhancements now allow for near hitless traffic loss when performing an image upgrade or when resizing a gateway from the Controller (applies to HA pairs). - **Site2Cloud Individual IPSec Tunnel Reset** - Aviatrix now allows gateways with multiple Site2Cloud tunnels to reset individual non-HPE or strongSwan IPSec tunnels instead of restarting the entire VPN service. This functionality does not disrupt other attached tunnels. This is not supported for IPSec racoon tunnels. - **CoPilot Notification Thresholds** - Notification thresholds can be set on gateway tunnel counts configured in CoPilot to send alert notifications via the UI and email. - **Site2Cloud Mapped NAT** - Site2Cloud mapped NAT now supports 32 remote/on-prem CIDRs and ten Site2Cloud connections. The AWS Spoke gateway size must be at least t3.small (or equivalent size in other CSPs). You should keep the number of routes in the landing Spoke VPC route tables to a minimum for better performance of landing Spoke gateway failovers or upgrades. Using RFC 1918 CIDRs to map the remote/on-prem CIDRs is strongly recommended. **Deprecated Features in Aviatrix Release 6.8.1148** - ActiveMesh 1.0 is deprecated in this release. You can upgrade to ActiveMesh 2.0 using the Controller's Migrate option. - The Transitive Peering feature is deprecated. This feature's functionality will be replaced by `Aviatrix Multi-Cloud Transit <https://docs.aviatrix.com/HowTos/transit_gateway_peering.html>`_. **UI Enhancements in Aviatrix Release 6.8.1148** - Support for deploying a CoPilot clustered deployment - Support for deploying Aviatrix Edge Gateway - Added CA Certificate section in Site2Cloud (Controller) - Added Private Mode section in Settings (Controller) **Issues Corrected in Aviatrix Release 6.8.1148** - **AVX-10899** - When a new subnet was added to a Google Cloud VPC after a spoke was created, the firewall rules were not getting updated to reflect the new subnet. After this fix, when a new subnet is added, the firewall rule is updated when attaching Spoke to Transit. If a Spoke is already attached to Transit and a new subnet is added, the Spoke needs to be detached and reattached to update the firewall rule. - **AVX-17284** - Fixed Stateful firewall log throttling. The logs no longer undergo quick rotation. - **AVX-17650** - Previously the Controller was stuck at 99% when performing a custom upgrade dry run on CloudN. This no longer occurs. - **AVX-18788** - When the instance size of a GCP Spoke/Transit Gateway using Insane Mode that is attached to another gateway is increased network throughput increases accordingly. - **AVX-19569** - Fixed the issue of "TCP" protocol FQDN rules for port 8443 not being enforced when an "HTTP" protocol FQDN rule for port 8443 exists. - **AVX-20038** - Fixed the issue where the "aviatrix-Aviatrix-Ingress-routing" edge route table was not programmed correctly when PSF gateway was deployed to a public subnet matching its VPC's CIDR. - **AVX-21889** - You can now successfully insert a stateful Firewall Rule using a reference rule from previously existing rules. - **AVX-22495** - Occasionally an AWS Transit FireNet Gateway Image upgrade would result in config_fail with the error message "failed to bring up interface eth3". This error no longer occurs. - **AVX-22928** - If you delete a GCP gateway that is connected to an external gateway, you now see an error in the Controller indicating that deletion is not possible because of the external connection. Previously, the gateway was removed from the database and an error was not displayed in the Controller. To delete the GCP gateway, you must first delete the connection to the external gateway. - **AVX-23292** - On Edge gateways, if the "clish" command "˜diagnostics" is typed before Controller registration is run, it will show an exception saying the diagnostics file does not exist. After the fix, an error message displays indicating that gateway registration is not triggered. - **AVX-23383** - Improved the function of Aviatrix gateways in High-Performance Encryption (HPE) mode by increasing the number of interfaces an NTP service can handle from 1024 to 4096. - **AVX-23407** - The best route may not have been selected correctly based on the AS path lengths and metric values among routes of the same BGP connection. When this route was used to represent the BGP source and compared with route from other sources, the result could be incorrect. - **AVX-23725** - Improved the storage methods for FQDN tags. The domain names in FQDN tags for Egress FQDN Filter will now be stored in a case-insensitive manner. For example, tag1: www.Google.com, TCP, 443 and tag2: www.google.com, TCP, 443 will be stored as one tag (www.google.com, TCP, 443). - **AVX-23809** - When the maximum number of buckets supported for Private S3 is reached, the correct error is displayed. - **AVX-24658** - The Python scheduler has been improved to accommodate more tasks. This ensures that all tasks are scheduled and triggered on time without being missed or having to wait. - **AVX-24701/24610** - Previously when the Controller ran an API call to AWS to pull the routes from the AWS GW (when attached to an Aviatrix Transit Gateway) and the API returned an error, the Controller withdrew the routes. Now when the API returns an error the Controller no longer changes the routes and waits to run the API again. - **AVX-24730** - The Settings > Controller > Login Customization†page in the Aviatrix Controller now displays as expected. - **AVX-24860** - Enabled support for legacy Azure Germany North Region. Azure does not allow you to create new resource groups in this region. However, you can access and/or update resources previously created in this legacy region. - **AVX-25082** - An uncaught exception caused the Aviatrix metering system to report metering inaccurately. This has been fixed. - **AVX-25128** - An exception occurs when migrating Transit Gateway tunnel status in MongoDB to etcd when the Transit Gateway has a CloudN attached. To fix this issue, when migrating Transit Gateway tunnel status in MongoDB to etcd that have CloudN attached, use the CloudN private_ip for the peer_ip. If the tunnel status in MongoDB does not a peer_ip, update it with the peer_ip based on the peer information from the gateway tunnel status message received by the Controller. - **AVX-25228** - Under certain conditions a gateway can be deleted but its peering information is still in the peering_info database, which can cause an exception. Now, the gateway information is removed from the peering_info database when the gateway is deleted. - **AVX-25256** - A control plane service running on a gateway no longer consumes multiple gigabytes of memory when there are many IPsec tunnels. - **AVX-25257** - An inefficient lookup routine in our internal routing service on Transit gateways running in Azure resulted in a persistently high CPU usage for a large number (1000+) of tunnels. This has been corrected. - **AVX-25289** - A bug in the Preserve AS Path feature resulted in manual summary CIDRs not present in the best route database being listed in BGP Advertise CIDRs on the BGP page for the HA gateway. The routes are programmed correctly; this is a display-only issue. Customers who have enabled this feature must disable and re-enable the feature on the Transit gateway to correct the display issue. - **AVX-25425** - The dry run for 6.8.1148 will fail if the CSP gateways are using an older AMI, but the upgrade will succeed. To prevent any issues with your gateways, performing an "Image Upgrade" from the Controller (Settings > Maintenance > Upgrade) is recommended. CSP gateways with older AMIs (released in early 2021) may not be able to upgrade after 7.0. - **AVX-25524** - Fix filter removed after auto-refresh gateway list. - **AVX-25632** - Fixed the issue where the Aviatrix Controller was creating more tunnels which exceeds the maximum throughput of the CSP, for the same gateway instance sizes in terms of core counts. - **AVX-25687** - When single SNAT is enabled, traffic toward the Spoke VPC CIDRs is no longer SNAT'ed. Before this change, all traffic egress from Spoke GW eth0 interface would be SNAT'ed, leading to asymmetric traffic on Transit gateways. - **AVX-25993** - The logging service for Rsyslog supports up to nine profiles. The configuration during restore allowed each profile enablement to start the Rsyslog service (6 times or more) in less than 2 seconds. The system service defaults five times in 10 seconds; otherwise, the Rsyslog service will fail in "starting". The fix ensures that the Rsyslog service is only restarted once for all profiles. - **AVX-26007** - The only user actions possible during a restore are enabling remote support or uploading tracelog. All other actions are blocked. - **AVX-26086** - Corrected the logic to program the learned 0.0.0.0/0 route on the Azure CSP route table. - **AVX-26095** - An improperly configured security group prevented gateways from sending keepalive checks to the Aviatrix Controller. This should have marked the gateways as down. However, because of a bug in our internal service, the Controller continued to mark those gateways as up. - **AVX-26188** - IPsec tunnel re-establishment time on the Transit gateway has been improved when there is a large number of tunnels. This will shorten the time it takes to recover from a failure event. **Known Issues in Aviatrix Release 6.8.1148** - **AVX-13908** - In a Site2Cloud connection, the public or private IP address of the remote endpoint is used as the Remote Identification. If one side uses a public IP and the other side uses a private IP, the Site2Cloud connection will not be established since the remote identification does not match. - **AVX-24650** - Single SNAT is not supported in Private Mode. - **AVX-25641** - When the customer configures the route-based mapped Site2Cloud connections (including enabling Forward Traffic to Transit) with tunnel or gateway failover or subnet editing, some customer traffic could be dropped. This is because the code incorrectly updates the routing parts of the connection. To fix the issue, you should upgrade your Controller to version 6.8.1148; 6.6e or later; or 6.7b or later. You must also perform an image upgrade on the gateways that is equivalent to the Controller version. This removes the incorrect routing information on the gateway so that the new code can rebuild the correct routing. - **AVX-26115, AVX-27062** - Micro-segmentation: Before upgrading from 6.7 to 6.8: - remove invalid characters or spaces, if any, in app domain or policy names - if there is a policy that contains port 0, change it to a valid value - port ranges should follow < lower port number - higher port number > format - **AVX-25673** - After Site2Cloud verbose logging is enabled, it cannot be disabled in the UI. - **AVX-26419** - If you are connecting to another Aviatrix device, using IKEv2 is preferred. IKEv2 support started in version 5.0.2667. If you configure IKEv1 in a Site2Cloud connection that uses certificate-based authentication and is connecting to another Aviatrix device, you must add the intermediate CA's in addition to the root CA. When an intermediate CA is renewed and re-authentication is attempted, the Site2Cloud connection will go down until you add the new certificate. - **AVX-27653** - If you are using software version 6.8.1148 on an outdated gateway image, your Controller could have a memory limitation issue. `Upgrade <https://docs.aviatrix.com/HowTos/gateway-image-migration.html>`_ your gateway images to avoid this issue. - **AVX-35490** - After a Controller software upgrade or a CloudXD restart, the Controller migrates BGP routes, automatically triggering an “Approve New Routes” email for existing pending CIDRs on gateways with learned CIDRs approval enabled. This issue has no functional impact. Approved CIDRs remain intact and no routes are changed. **Features Deprecated in Aviatrix Release 6.8.1148** (AWS) UserVPN Gateways Do Not Support Classic Load Balancers **AVX-24015** - (AWS) AWS classic Load Balancers are not supported with UserVPN gateways. Instead, `migrate <https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/migrate-classic-load-balancer.html>`_ to Network Load Balancers in your AWS account. 6.7.1376 (08/02/2022) ========================= **Important Notices in Aviatrix Release 6.7.1376** - **AVX-26277** - Controllers running earlier versions of Aviatrix Controller software on AWS AMI version 051022 (released June 9, 2022) will halt due to resource exhaustion after a period of time depending on the level of activity the Controller sees. If using AWS AMI version 051022, you must upgrade to version 6.7.1376 (or 6.6.5712) to prevent this behavior. **Enhancements in Aviatrix Release 6.7.1376** - **AVX-25470: Create single HPE tunnel for Transit and Spoke Attachments** - By default, when HPE is used for Transit peering and Spoke attachments over private IPs, Aviatrix creates the maximum number of HPE tunnels possible given the instance sizes. This enhancement adds the ability to create a single HPE tunnel for Transit peering and spoke attachments over private IPs. Both Transit and Spoke Gateways must have HPE enabled. In Terraform you can enable this by setting the "enable_max_performance" field to "false" when creating Transit peering and Spoke attachments. If using HPE for private Transit peering and Spoke attachments, please re-create those connections once “enable_max_performance†option is enabled. - **AVX25657: CoPilot Notification Thresholds** - Notification thresholds can be set on gateway tunnel counts configured in CoPilot to send alert notifications via the UI and email. **Issues Corrected in Aviatrix Release 6.7.1376** - **AVI-2021-0006** - Fixed a remote code execution vulnerability for users of Aviatrix VPN. - **AVX-23386** - Upgraded Spire to fix CVE-2021-27099, CVE-2021-27098, CVE-2021-44716, and CVE-2022-24675. - **AVX-25514** - An exception no longer occurs when migrating Transit gateway BGP routes from MongoDB to etcd if the BGP routes have 65535 in the AS path. Possible BGP route flapping is also prevented. - **AVX-24658** - The Python scheduler has been improved to accommodate more tasks. This ensures that all tasks are scheduled and triggered on time without being missed or having to wait. - **AVX-25082** - An uncaught exception caused the Aviatrix metering system to report metering inaccurately. This has been fixed. - **AVX-25128** - An exception occurs when migrating Transit Gateway tunnel status in MongoDB to etcd when the Transit Gateway has a CloudN attached. To fix this issue, when migrating Transit Gateway tunnel status in MongoDB to etcd that have CloudN attached, use the CloudN private_ip for peer_ip. If the tunnel status in MongoDB does not a peer_ip, update it with the peer_ip based on the peer information from the gateway tunnel status message received by the Controller. - **AVX-25257** - An inefficient lookup routine in our internal routing service on Transit gateways running in Azure resulted in a persistently high CPU usage for a large number (1000+) of tunnels. This has been corrected. - **AVX-25289** - A bug in the Preserve AS Path feature resulted in manual summary CIDRs not present in the best route database being listed in BGP Advertise CIDRs on the BGP page for the HA gateway. The routes are programmed correctly; this is a display-only issue. Customers who have enabled this feature must disable and reenable the feature on the Transit gateway to correct the display issue. - **AVX-25632** - Fixed the issue where the Aviatrix Controller was creating more tunnels which exceeds the maximum throughput of the CSP, for the same gateway instance sizes in terms of core counts. - **AVX-25687** - When single SNAT is enabled, traffic toward the Spoke VPC CIDRs is no longer SNAT'ed. Before this change, all traffic egress from Spoke GW eth0 interface would be SNAT'ed, leading to asymmetric traffic on Transit gateways. - **AVX-25993** - The logging service for Rsyslog supports up to nine profiles. The configuration during restore allowed each profile enablement to start the Rsyslog service (6 times or more) in less than 2 seconds. The system service defaults five times in 10 seconds; otherwise, the Rsyslog service will fail in "starting". The fix ensures that the Rsyslog service is only restarted once for all profiles. - **AVX-26007** - The only user actions possible during a restore are enabling remote support or uploading tracelog. All other actions are blocked. - **AVX-26086** - Corrected the logic to program the learned 0.0.0.0/0 route on the Azure CSP route table. - **AVX-26095** - An improperly configured security group prevented gateways from sending keepalive checks to the Aviatrix Controller. This should have marked the gateways as down. However, because of a bug in our internal service, the Controller continued to mark those gateways as up. - **AVX-26188** - For cases where Transit gateways had a large number of tunnels and encountered a failover event, strongSwan would take a long time to reestablish and restore tunnels, since strongSwan was configured to monitor all interfaces on the gateway. strongSwan config was altered to only monitor the eth0 interface, which results in a shorter restoration time. - **AVX-26205** - The number of available threads in strongSwan was increased to improve scalability and support more than 2000 tunnels. - **AVX-26374** - The Controller database had empty peer IPs for tunnels between Transit Gateways and CloudN. This prevented the gateway snapshot creation, and also prevented configuration/route updates from being propagated to the gateway. This software patch script will correct the Controller database entries. 6.6.5712 (08/02/2022) ========================= **Important Notices in Aviatrix Release 6.6.5712** - **AVX-26277** - Controllers running earlier versions of Aviatrix Controller software on AWS AMI version 051022 (released June 9, 2022) will halt due to resource exhaustion after a period of time depending on the level of activity the Controller sees. If using AWS AMI version 051022, you must upgrade to version 6.6.5712 (or 6.7.1376) to prevent this behavior. **New Features in Aviatrix Release 6.6.5712** - **AVX-25289** - In 6.7.1319, Aviatrix introduced a new toggle, "Preserve AS Path". When enabled, this toggle ensured gateways retained the AS path in manually advertised routes, and that routes would be advertised as local if the route did not exist in the best route DB. This change improves failover behavior; gateways will stop advertising any manually advertised CIDR if it is no longer in the best DB (the route is no longer advertised as local). **Issues Corrected in Aviatrix Release 6.6.5712** - **AVI-2021-0006** - Fixed a remote code execution vulnerability for users of Aviatrix VPN. - **AVX-23386** - Upgraded Spire to fix CVE-2021-27099, CVE-2021-27098, CVE-2021-44716, and CVE-2022-24675. - **AVX-25514** - An exception no longer occurs when migrating Transit gateway BGP routes from MongoDB to etcd if the BGP routes have 65535 in the AS path. Possible BGP route flapping is also prevented. - **AVX-24658** - The Python scheduler has been improved to accommodate more tasks. This ensures that all tasks are scheduled and triggered on time without being missed or having to wait. - **AVX-25082/25598** - Stale transit peering entries in the database resulted in an issue listing transit peers. This resulted in incorrect metered billing. - **AVX-25128** - An exception occurs when migrating Transit Gateway tunnel status in MongoDB to etcd when the Transit Gateway has a CloudN attached. To fix this issue, when migrating Transit Gateway tunnel status in MongoDB to etcd that have CloudN attached, use the CloudN private_ip for peer_ip. If the tunnel status in MongoDB does not a peer_ip, update it with the peer_ip based on the peer information from the gateway tunnel status message received by the Controller. - **AVX-25257** - An inefficient lookup routine in our internal routing service on Transit gateways running in Azure resulted in a persistently high CPU usage for a large number (1000+) of tunnels. This has been corrected. - **AVX-25993** - The logging service for Rsyslog supports up to nine profiles. The configuration during restore allowed each profile enablement to start the Rsyslog service (6 times or more) in less than 2 seconds. The system service defaults five times in 10 seconds; otherwise, the Rsyslog service will fail in "starting". The fix ensures that the Rsyslog service is only restarted once for all profiles. - **AVX-26007** - The only user actions possible during a restore are enabling remote support or uploading tracelog. All other actions are blocked. - **AVX-26086** - Corrected the logic to program the learned 0.0.0.0/0 route on the Azure CSP route table. - **AVX-26095** - An improperly configured security group prevented gateways from sending keepalive checks to the Aviatrix Controller. This should have marked the gateways as down. However, because of a bug in our internal service, the Controller continued to mark those gateways as up. - **AVX-26188** - For cases where Transit gateways had a large number of tunnels and encountered a failover event, strongSwan would take a long time to reestablish and restore tunnels, since strongSwan was configured to monitor all interfaces on the gateway. strongSwan config was altered to only monitor the eth0 interface, which results in a shorter restoration time. - **AVX-26205** - The number of available threads in strongSwan was increased to improve scalability and support more than 2000 tunnels. - **AVX-26374** - The Controller database had empty peer IPs for tunnels between Transit Gateways and CloudN. This prevented the gateway snapshot creation, and also prevented configuration/route updates from being propagated to the gateway. This software patch script will correct the Controller database entries. 6.7.1325 (07/25/2022) ========================= **Issues Corrected in Aviatrix Release 6.7.1325** - **AVX-25128** - An exception is seen when migrating Transit Gateway tunnel status in MongoDB to etcd when Transit Gateway has CloudN attached. Fix: #. When migrating Transit Gateway tunnel status in MongoDB to etcd, for Transit Gateways that have CloudN attached, use CloudN private_ip for peer_ip to fix the exception. #. If tunnel status in MongoDB does not have peer_ip, update it with peer_ip based on peer info from the tunnel status msg controller received from a gateway. 6.6.5667 (07/25/2022) ========================= **Issues Corrected in Aviatrix Release 6.6.5667** - **AVX-25128** C An exception is seen when migrating Transit Gateway tunnel status in MongoDB to etcd when Transit Gateway has CloudN attached. Fix: #. When migrating Transit Gateway tunnel status in MongoDB to etcd, for Transit Gateways that have CloudN attached, use CloudN private_ip for peer_ip to fix the exception. #. If tunnel status in MongoDB does not have peer_ip, update it with peer_ip based on peer info from the tunnel status msg controller received from a gateway. 6.7.1324 (07/06/2022) ========================= **Feature Enhancements in 6.7.1324** - **AVX-25293** - Jumbo frames can be enabled and disabled for GRE tunnels. 6.6.5662 (06/15/2022) ========================= **Feature Enhancements in 6.6.5662** - **AVX-21263** - Improved email notifications. When a GRE tunnel in your account goes down or up, the Aviatrix Controller sends the GRE tunnel status change to the registered email address(es). This email notification contains the timestamp for the tunnel status change. - **AVX-23383** - Improved the function of Aviatrix gateways in High-Performance Encryption (HPE) mode by increasing the number of interfaces an NTP service can handle from 1024 to 4096. **Issues Corrected in Aviatrix Release 6.6.5662** - **AVX-21823** - Image upgrade causing incorrect firewall_rtb config on AWS Transit FireNet with network exclude list. - **AVX-21889** - You can now successfully insert a stateful Firewall Rule using a reference rule from previously existing rules. - **AVX-22791** - Starting with release 6.6, the Controller consolidates emails so that emails with the same email address and subject line are combined (helping limit the number of emails while still delivering important status notifications). These email notifications were being consolidated incorrectly. - **AVX-23407** - The best route may not have been selected correctly based on the AS path lengths and metric values among routes of the same BGP connection. When this route was used to represent the BGP source and compared with route from other sources, the result could be incorrect. 6.7.1319 (06/10/2022) ========================= **Feature Enhancements in 6.7.1319** * **AVX-21263** - Improved email notifications. When a GRE tunnel in your account goes down or up, the Aviatrix Controller sends the GRE tunnel status change to the registered-email-address(es). This email notification contains the timestamp for the tunnel status change. * **AVX-23069** - Added a new toggle switch, “Preserve AS Path,†to Multi-Cloud Transit > Advanced Config. This option allows you to preserve an AS Path during manual BGP route advertisements, which reduces the chances of routing loops and wrong route selection on the peer side. * You can enable this option in both the Gateway Manual BGP Advertised Network List and the Connection Manual BGP Advertised Network List, and on Transit and Spoke Gateways. * When the “Preserve AS Path†option is disabled, the AS path is stripped during BGP route advertisements from Transit or Spoke Gateways to neighbors. * **AVX-23105** - Enhanced Controller validation for micro-segmentation. The Controller now checks that gateway kernel version is greater or equal to 5.4.0 before allowing you to configure micro-segmentation. Micro-segmentation requires this minimum kernel for data plane enforcement. * **AVX-23163** - The account/gateway auditing interval has been changed from every hour to every 24 hours. This change improves the memory performance of the Controller. * **AVX-23383** - Improved the function of Aviatrix gateways in High Performance Encryption (HPE) mode by increasing the number of interfaces an NTP service can handle from 1024 to 4096. * **AVX-23725** - Improved the storage methods for FQDN tags. The domain names in FQDN tags for Egress FQDN Filter will now be stored in a case insensitive manner. For example, tag1: www.Google.com, tcp, 443 and tag2: www.google.com, tcp, 443 will be stored as one tag (www.google.com, tcp, 443). **Public Preview Features in 6.7.1319** The following Public Preview Features are available in this release: * **Micro-segmentation** – Micro-segmentation provides granular network security policy enforcement for distributed applications in the cloud. It enables a unified network access policy model for your applications with distributed points of policy enforcement throughout your network. For information about micro-segmentation, see `Secure Networking with Micro-Segmentation <https://docs.aviatrix.com/HowTos/secure_networking_microsegmentation.html>`_ in the Aviatrix product documentation. The **Micro-segmentation** public preview feature has the following enhancements: * AVX-23249 - **Micro-segmentation rule priority** – You can now specify a priority number to the micro-segmentation rules you create. The priority number determines the order in which your rules are applied. A lower priority number indicates higher precedence, with the highest priority being 0. * AVX-23536 - **Micro-segmentation system messages** – You can now view a list of system messages about your micro-segmentation configurations by clicking the bell icon in the CoPilot action bar. **Issues Corrected in Aviatrix Release 6.7.1319** * **AVX-21889** – You can now successfully insert a stateful Firewall Rule using a reference rule from previously existing rules. * **AVX-21946** - Micro-segmentation policy logging could display the incorrect policy UUID. * **AVX-22110** - Micro-segmentation policy statistics could be overcounted. * **AVX-22181** - The Controller crashed when using an Azure API to get VNet routing tables. The crash occurred because the system did not consider the possibility of a failure case in which “NoneType†is returned. * **AVX-22184** - When an Edge Gateway expires, its state is listed as “waiting†on the Upgrade page. This “waiting†Gateway prevents the Controller from successfully upgrading. The actual state of the edge is “Expired,†which is shown in the CloudN > List. If an Edge Gateway is expired in your Controller, navigate to CloudN > List on the left sidebar. On the Registered Devices page, select the Edge Gateway with the state “waiting,†click the Diag dropdown menu, and select Reset Configuration. Then, your Controller can successfully upgrade. * **AVX-22208** - Launching a new GCP Gateway with Insane Mode and peering it with another GCP Insane Mode Gateway failed to program the Linux route table correctly. This issue is caused by GCE HPE Gateways with HA pairs to have incorrect entries for secondary IP addresses. The gateway could not recover from this error; you had to terminate the existing gateway and launch a new one. * **AVX-22504** - An error displayed when the Alibaba Cloud subnet list was empty: “TypeError: 'NoneType' object is not subscriptable.†Now, the Controller resolves the error automatically without displaying an error message. * **AVX-22791** - Starting with release 6.6, the Controller consolidates emails so that emails with the same email address and subject line are combined (helping limit the number of emails while still delivering important status notifications). These email notifications were being consolidated incorrectly. * **AVX-22903** - After a new Controller was launched for the first time, there were no routes from the Transit Gateway to the Spoke Gateway. * **AVX-22929** - Potential micro-segmentation app domain filter issue: If an account ID was associated with more than one account name, an app domain may have shown an empty list of resolved CIDRs when one of those account names was used as match criteria for a VM or VPC/VNet filter. * **AVX-22934** - ICMP packets could have nonfunctioning associated ports. * **AVX-23077** - A gateway would continue trying to enforce micro-segmentation policies on deleted network interfaces. * **AVX-23187** - On the Selective Gateway Upgrade page (available in your Controller through Settings > Maintenance), the table has been improved to display more information about your gateways. The table has two new columns: State and Update Status. 1. **State** - This column displays the state of a gateway: up, down, waiting (for a newly launched gateway waiting to go up), and config_fail (if the gateway configuration failed). 2. **Update Status** - This column displays the status of a gateway that you just updated: * **upgrading** - The update is processing and sending a message to the gateway. * **downloading** - The gateway received the upgrade request and is downloading the gwsw.tgz. * **downloaded** - The gateway has downloaded the information and preparing to install. * **installing** - The gateway is installing the update. * **initializing** - The gateway is running the gateway upgrade service which includes initializing modules and restarting services. * **complete** - The latest update is complete. * **upgrade_fail** - The upgrade failed due to a gateway being stopped, a hardware failure, network reachability, or another issue. Try restarting the gateway from your Controller or directly from the related CSP, and then redo the software upgrade. If the "upgrade_fail" status persists, please do an image upgrade. * **AVX-23407** - The best route may not have been selected correctly based on the AS path lengths and metric values among routes of the same BGP connection. When this route was used to represent the BGP source and compared with route from other sources, the result could be incorrect. * **AVX-23437** - A packet that matched both a source and a destination app domain could be misclassified. * **AVX-23925** - Having many micro-segmentation policies (the maximum is 64 policies) might result in performance degradation. **Known Issues in 6.7.1319** * **AVX-21307** - In the 6.7 release, when you create a large number of gateways using Terraform, some gateways may end in a config_fail state. This rare issue may be related to a transient network or release server connectivity (too many gateways' connections for download of packages). To resolve this issue, replace the gateways that show the “config_fail†state. 6.4.3057 (05/26/2022) ======================= Issues Corrected in Aviatrix Release 6.4.3057 - **AVI-2022-0002** - A vulnerability was discovered which could allow an unauthenticated attacker to run arbitrary commands against Aviatrix gateways. This is not known to be exploited. - **AVX-23200** - When connectivity is lost between a Controller and a Gateway, and the Controller is unable to perform a health check on the Gateway by establishing an HTTPS connection, then an SSH-based connection will be used to perform the health check. The results of the health check are supposed to assist the Controller in determining whether a data-plane change is necessary (e.g., routing table updates). 6.5.3233 (05/26/2022) ======================= Issues Corrected in Aviatrix Release 6.5.3233 - **AVI-2022-0002** - A vulnerability was discovered which could allow an unauthenticated attacker to run arbitrary commands against Aviatrix gateways. This is not known to be exploited. - **AVX-10577** - Licensing metrics were not visible. - **AVX-19811** - You can now insert a stateful firewall policy by specifying the position where you want to insert the policy. This feature is presently available through **Insert Stateful Firewall Rules** API using **position** param. The **position** param is 1 indexed. - **AVX-20271** - Restricted concurrent uploads to make it harder for a remote attacker to fill the disk to defend against a denial-of-service attack. The check was too restrictive and causing concurrent uploads to overwrite each other. We enhanced the feature to allow for concurrency without sacrificing the original defense. - **AVX-21238** - High Performance Encryption (HPE) Gateways with many HPE peerings that have transit segmentation enabled would encounter an Out of Memory (OOM) issue. The gateway failed to recover even after a reboot.  - **AVX-21332** - You can now use “insert_stateful_firewall_rules†API to insert stateful firewall rules, even when the table is empty. - **AVX-22040** - Exception seen when disconnecting a firewall domain from Aviatrix edge domain on an AWS Transit Gateway. - **AVX-23200** - When connectivity is lost between a Controller and a Gateway, and the Controller is unable to perform a health check on the Gateway by establishing an HTTPS connection, then an SSH-based connection will be used to perform the health check. The results of the health check are supposed to assist the Controller in determining whether a data-plane change is necessary (e.g., routing table updates). Known Issues in Release 6.5.3233 - **AVX-22976** - When you roll back a non-AWS primary and HA gateway together in any of the following patterns, one of the rollbacks fails: * 6.6.5612 to 6.6 * 6.6.5612 to 6.5 * 6.5.3233 to 6.5 To avoid this issue, roll back one gateway at a time between primary and HA gateways. If you experience a configuration failure, roll back the gateway for which the configuration failed again. 6.6.5612 (05/12/2022) ======================= **Important Notices in Aviatrix Release 6.6.5612** - **AVX-20579** - In order for release 6.7 to roll back to 6.6 correctly, the Controller and gateways must be running official **6.6.5612** or a release after **6.6.5612** before moving to 6.7. - **AVX-22443** - For a rollback from 6.7 to **6.6.5612** to run successfully, upgrade from **6.6.5404** or **6.6.5545** to **6.6.5612** before upgrading to 6.7. **Issues Corrected in Aviatrix Release 6.6.5612** - **AVI-2022-0002** - A vulnerability was discovered which could allow an unauthenticated attacker to run arbitrary commands against Aviatrix gateways. This is not known to be exploited. - **AVX-10577** - Licensing metrics were not visible. - **AVX-20408** - Added an extra check to prevent an exception that can occur while adding a VPC object. The exception caused the VPC to unexpectedly become unavailable from a Spoke Gateway. - **AVX-20485** - When you added a Site2Cloud Connection with HA that had Local/Remote Tunnel IP (Primary) settings, but the connection was missing Local/Remote Tunnel IP (Backup), the configuration failed with an error. - **AVX-20978** - Only one active profile rsyslog config showed up in gateways, even when the gateway had multiple profiles. - **AVX-21238** - High Performance Encryption (HPE) Gateways with many HPE peerings that have transit segmentation enabled encountered an Out of Memory (OOM) issue. The gateway failed to recover even after a reboot. - **AVX-21332** - You can now use “insert_stateful_firewall_rules†API command to insert stateful firewall rules, even when the table is empty. - **AVX-22040** - Exception seen when disconnecting a firewall domain from an Aviatrix Edge domain on an AWS Transit Gateway. - **AVX-22396** - Due to a VPC ID exception, upgrading an OCI Transit FireNet Gateway failed if the gateway had an associated firewall and an HAGW (High Availability Gateway). **Known Issues in Release 6.6.5612** - **AVX-22630** - If you are running an older Controller image, you may experience an error (*pymongo.errors.OperationFailure: exception: invalid operator '$filter'*) while trying to view the transit tunnel status. A workaround for this issue is to migrate to the latest Controller image. - **AVX-22976** - When you roll back a non-AWS primary and HA gateway together in any of the following patterns, one of the rollbacks fails: * 6.6.5612 to 6.6. * 6.6.5612 to 6.5. To avoid this issue, roll back one gateway at a time between primary and HA gateways. If you experience a configuration failure, roll back the config_fail gateway again. - **AVX-23006** - When you create a regular gateway immediately after creating a Public Subnet Filtering (PSF) gateway with GuardDuty enabled, a RACE occurs. The RACE can accidentally block the newly created gateway, which is front ended by this PSF gateway. Please wait for the PSF Gateway to finish creation before creating the regular gateway. **Feature Upgrade Notice** - **AVX-22884** - The Standalone CloudN workflow is not supported for releases later than 6.5. A Standalone CloudN upgrade from Release 6.5 to 6.6 or from Release 6.6 to 6.7 is not supported. You should plan to migrate your Standalone CloudN deployment to Managed CloudN. To migrate to Managed CloudN, see `this document <https://docs.aviatrix.com/HowTos/CloudN_workflow.html#migrating-a-standalone-cloudn-to-a-managed-cloudn>`_. **Note**: From Release 6.6.5404 onwards, registering CloudN with the Controller does not require the CloudN and the Controller to be the same version. You can register CloudN version 6.6 with Controller version 6.7. 6.7.1186 (05/11/2022) ======================= **Issues Corrected in Aviatrix Release 6.7.1186** - **AVX-22903** - After a new controller is launched for the first time, there are no routes from the Transit Gateway to the Spoke Gateway. 6.7.1185 (05/09/2022) ======================= **Important Notice in Release 6.7.1185** * **AVX-37948** - (CoPilot users) The system metric Memory Free (memory_free) used in CoPilot for configuring alerts had been using a definition that was inconsistent with the operating system (OS) definition. Starting in 6.7.1185 the metrics memory_available and memory_free are consistent with the OS definition. Due to this change, after upgrading your Controller, you may receive many Memory Free alerts indicating the memory free dropped. To mitigate this issue, you can change your alert configurations from using mem_free to using memory_available instead. **New Features in Aviatrix Release 6.7.1185** * **Deploy CoPilot from your controller UI (AWS cloud only)** — If you deployed Aviatrix Controller in AWS, you now have the option to deploy Aviatrix CoPilot directly from your controller UI. This eliminates the need to go to the AWS marketplace and simplifies a few steps for provisioning the CoPilot instance. When deploying this way, the controller deploys CoPilot in the same region/availability zone where it is homed. For instructions, see "CoPilot instance launch using Controller UI (AWS Only)" in the Aviatrix CoPilot documentation. .. note:: If you want to deploy CoPilot in a different AWS region/availability zone than where your controller is homed or in a different cloud, follow the instructions in "CoPilot instance launch from cloud provider marketplace" to deploy CoPilot. * **Aviatrix Secure Edge** - Aviatrix Secure Edge has a virtual from factor that lets you deploy an Edge Gateway as a standard virtual machine (VM). It is designed to enable enterprises migrating to the cloud to integrate their on-premises footprint as spokes into the enterprise cloud backbone. For more information about Secure Edge, refer to `Secure Edge FAQ <http://docs.aviatrix.com/HowTos/secure_edge_faq.html>`_. * **Deploy CoPilot from your controller UI (AWS cloud only)** - If you deployed Aviatrix Controller in AWS, you now have the option to deploy Aviatrix CoPilot directly from your controller UI. This eliminates the need to go to the AWS marketplace and simplifies a few steps for provisioning the CoPilot instance. When deploying this way, the controller deploys CoPilot in the same region/availability zone where it is homed. For instructions, see the discussion about launching a CoPilot instance from the Controller UI in Aviatrix CoPilot Deployment Guide. Note: If you want to deploy CoPilot in a different AWS region/availability zone than where your controller is homed or in a different cloud, please deploy CoPilot manually from the CSP marketplace. **Enhanced Features in Aviatrix Release 6.7.1185** * **Transit Peering over Public Network** - Aviatrix Transit Gateway peering over public network now supports Transit Gateway peering over the internet using Insane Mode High-Performance Encryption (HPE) between GCP and Azure, AWS, OCI. `<http://docs.aviatrix.com/HowTos/transit_gateway_peering.html#peering-over-public-network>`_. * **Subnet-Level Inspection in Azure** - Subnet-Level inspection in Azure is enhanced to optimize intra-VNet traffic behavior. With this optimization, traffic between VMs in the same subnet and intra-VNet traffic between VMs in different subnets and the same subnet group is routed through the Azure native Virtual Network instead of the Aviatrix Spoke Gateway. If traffic inspection is desired between subnets in a VNet, the subnets must be in different subnet groups. For more information, refer to Using Subnet Inspection in Azure to Redirect Subnet-Level Traffic to `Aviatrix Transit FireNet and NGFW <http://docs.aviatrix.com/HowTos/transit_subnet_inspection_azure.html>`_. **UI enhancements in Aviatrix Release 6.7.1185** - Added support for CoPilot deployment. **Terminology Changes in Aviatrix Release 6.7.1185** - Renamed "Security Domains" to "Network Domain" In releases prior to Controller 6.7, the term security domain was used to refer to the segments you define for Aviatrix network segmentation. Security domain is renamed network domain in the controller UI and documentation. - Renamed "Peering Menu" to "Native Peering" **Known Issues in Aviatrix Release 6.7.1185** - **AVI-2022-0002** - A vulnerability was discovered which could allow an unauthenticated attacker to run arbitrary commands against Aviatrix gateways. This is not known to be exploited. - **AVX-22184** - When an Edge Gateway expires, its state is listed as “waiting†on the Upgrade page. This “waiting†Gateway prevents the Controller from successfully upgrading. The actual state of the edge is “Expired,†which is shown in the CloudN > List. If an Edge Gateway is expired in your Controller, navigate to CloudN > List on the left sidebar. On the Registered Devices page, select the Edge Gateway with the state “waiting,†click the Diag dropdown menu, and select Reset Configuration. Then, your Controller can successfully upgrade. - **AVX-22810** - After a successful platform upgrade, the gateway status indicates the operation is complete before the operation actually completes. - **AVX-22851** - During a rare telemetry related timing issue, gateway deletion and creation operations may experience exceptions that send the admin an exception email. This was caused by the software attempting to access a gateway object that does not exist. **Workaround**: If the newly created gateway does not come up because of this issue, the workaround is to upgrade the gateway image. - **AVX-35490** - After a Controller software upgrade or a CloudXD restart, the Controller migrates BGP routes, automatically triggering an “Approve New Routes” email for existing pending CIDRs on gateways with learned CIDRs approval enabled. This issue has no functional impact. Approved CIDRs remain intact and no routes are changed. **Issues Corrected in Aviatrix Release 6.7.1185** - **AVI-2022-0002** - A vulnerability was discovered which could allow an unauthenticated attacker to run arbitrary commands against Aviatrix gateways. This is not known to be exploited. - **AVX-10577** - Licensing metrics were not visible. - **AVX-16122** - The Packet Logging toggle switch on the Stateful Firewall > Policy tab page was not working. - **AVX-17174** - Controller traceroute utility not showing first-hop when HPE is enabled between Spoke and Transit. - **AVX-18291** - Failed daily and manual controller backups due to a rare corner case condition. - **AVX-18700** - When the Stateful firewall rules reach above 500 rows of rules during add/insert/delete the firewall rule, it will throw error as “Command to execute is too long.†- **AVX-18796** - The Controller to Gateway control channel uses certificate-based authentication. The Intermediate Certificate Authority (ICA) certificate TTL is set to renew automatically every 6 months. A week before the TTL expiration, the ICA will prepare the next certificate as part of the rotation. During this period, if any Gateway gets re-certified, the Controller will use the newly prepared/activated ICA certificate to sign it. If the Gateway flaps and reconnects during this period, the controller will reject these connections resulting in the Gateway being marked down. Since this issue can result in the controller marking gateways down, Aviatrix strongly recommends upgrading your software to a version that includes the issue correction. Note that after this fix, the certificate's validity changes from 60 days to 30 days. The rotation frequency also changes from 30 days to 15 days. - **AVX-18876** - For BGP connections associated with the domain, "seen" routes learned from this connection got re-advertised back to the same connection when these BGP routes are in the best DB. - **AVX-19811** - You can now insert a stateful firewall policy by specifying the position where you want to insert the policy. This feature is presently available through “Insert Stateful Firewall Rules†API using “position†param. The “position†param is 1 indexed. - **AVX-20022** - You can now configure the gateway interfaces to enable or disable generic receive offload (GRO) and generic segmentation offload (GSO). - **AVX-20173** - Incorrect gateways configured when disabling Transit FireNet on the gateway. - **AVX-20271** - Restricted concurrent uploads to make it harder for a remote attacker to fill the disk to defend against a denial-of-service attack. The check was too restrictive and causing concurrent uploads to overwrite each other. We reworked the feature to allow for concurrency without sacrificing the original defense. - **AVX-20616** - Supported filtering and pagination of security domain policies. This change makes the Add/Modify Connection Policy feature easier to use, especially in accounts that have a large number of policies. - **AVX-20706** - While configuring the Panorama integration for FireNet on the vendor integration page, selecting “FW to show†caused an exception. - **AVX-20970** - Ignore the default RFC1918 routes check in the unselected route tables when you attach a Spoke Gateway with the selective route tables. - **AVX-21215** - Changed the terms “RBAC Group†and “Permission Group“ to “Permission Group“ on the “Account User†page to avoid confusion. - **AVX-21332** - You can now use "insert_stateful_firewall_rules" API command to insert stateful firewall rules, even when the table is empty. - **AVX-21740** - Terraform error prevented an interface from being specified for SNAT and DNAT policies when using policy-based connections. - **AVX-22040** - Exception seen when disconnecting a firewall domain from Aviatrix edge domain on an AWS Transit Gateway. - **AVX-22443** - In order for 6.7 to rollback back to 6.6 correctly, upgrade controllers to any 6.6 release after 6.6.5545 before upgrading to 6.7. - **AVX-22808** - Insert_stateful_firewall_rules now inserts the rule in a correct order both in the control plane and the IP tables when it is done using the reference rule. - **AVX-22847** - The gateway is stuck in an upgrade "initializing" state and needs ways to recover effectively during scaling. **Private Preview Features in Release 6.7.1185** The following `Private Preview Features`_ are available in this release: - **Micro-segmentation** - Micro-segmentation provides granular network security policy enforcement for distributed applications in the cloud. It enables a unified network access policy model for your applications with distributed points of policy enforcement throughout your network. For information about micro-segmentation, see `Secure Networking with Micro-Segmentation <https://docs.aviatrix.com/HowTos/secure_networking_microsegmentation.html>`_ in the Aviatrix product documentation. - **Web Application Firewall** - The Aviatrix Web Application Firewall (WAF) feature detects and blocks malicious traffic before it reaches your controller. Enabling the Aviatrix WAF helps protect your applications from malicious activity by filtering the HTTP and HTTPS traffic. The WAF is enabled by with a button on the WAF tab in the Aviatrix Controller settings. **Important Notices in Release 6.7.1185** (CoPilot users) The system metric *Memory Free* (memory_free) used in CoPilot for configuring alerts had been using a definition that was inconsistent with the operating system (OS) definition. Starting 6.7 the metrics memory_available and memory_free are consistent with the OS definition. 6.4.3049 (04/08/2022) ======================= **Issues Corrected in Aviatrix Release 6.4.3049** - **AVX-16838** - A newly created Controller failed to get its public IP, causing some gateways to fail to start. - **AVX-18878** - Sessions may be prevented from getting immediately logged out after certain API calls. - **AVX-19811** - You can now insert a stateful firewall policy by specifying the position where you want to insert the policy. This feature is presently available through "Insert Stateful Firewall Rules†API using "position†param. The "position†param is 1 indexed. - **AVX-20064** - Enabled users to insert a Force Drop rule on the top of the list of Stateful Firewall rules without changing the order of the rules in the table. - **AVX-20159** - When a user does an image upgrade/rollback on multiple gateways simultaneously, it could hit an exception in race condition, causing some gateway upgrade/rollback failures. These failures could cause the FireNet Gateway to not function properly after the upgrade/rollback. - **AVX-20271** - Restricted concurrent uploads to make it harder for a remote attacker to fill the disk to defend against a denial-of-service attack. The check was too restrictive and causing concurrent uploads to overwrite each other. We reworked the feature to allow for concurrency without sacrificing the original defense. - **AVI-2022-0004** - Fixed an internally-reported vulnerability that would allow an authenticated user to gain command line privileges on the controller. This is not known to be exploited. 6.5.3166 (04/06/2022) ======================= **Enhanced Features in Release 6.5.3166** - **AVX-15117** - Large (4G+) tracelog uploads consumed excessive CPU, which caused gateway flapping. Optimized performance for launching gateways, viewing tunnel status, and uploading trace logs in large deployments. - **AVX-16906** - Extended support for AES-256-GCM encryption for Site2Cloud IPsec tunnels. - **AVX-20064** - Enabled users to insert a Force Drop rule on the top of the list of Stateful Firewall rules without changing the order of the rules in the table. **UI Enhancements in Release 6.5.3166** - **AVX-19672** - Added an error message when adding a new Site2Cloud connection to warn users that AES-256-GCM encryption algorithms are not supported on older gateway images. **Issues Corrected in Aviatrix Release 6.5.3166** - **AVX-16122** - The Packet Logging toggle switch on the Stateful Firewall > Policy tab page was not working. - **AVX-16838** - A newly created Controller failed to get its public IP, causing some gateways to fail to start. - **AVX-17650** - CloudN custom upgrade dry run GUI hanging at 99%, but commands.log showing succeeded. - **AVX-18796** - The Controller to Gateway control channel uses certificate-based authentication. The Intermediate Certificate Authority (ICA) certificate TTL is set to renew automatically every 6 months. A week before the TTL expiration, the ICA will prepare the next certificate as part of the rotation. During this period, if any Gateway gets re-certified, the Controller will use the newly prepared/activated ICA certificate to sign it. If the Gateway flaps and reconnects during this period, the controller will reject these connections resulting in the Gateway being marked down. Since this issue can result in the controller marking gateways down, Aviatrix strongly recommends upgrading your software to a version that includes the issue correction. Note that after this fix, the certificate's validity changes from 60 days to 30 days. The rotation frequency also changes from 30 days to 15 days. - **AVX-18878** - Sessions may be prevented from getting immediately logged out after certain API calls. - **AVX-20159** - When a user does an image upgrade/rollback on multiple gateways simultaneously, it could hit an exception in race condition, causing some gateway upgrade/rollback failures. These failures could cause the FireNet Gateway to not function properly after the upgrade/rollback. - **AVI-2022-0004** - Fixed an internally-reported vulnerability which would allow an authenticated user to gain command line privileges on the controller. This is not known to be exploited. - **AVX-20970** - Ignore the default RFC1918 routes check in the unselected route tables when you attach a Spoke Gateway with the selective route tables. 6.6.5545 (03/31/2022) ======================= **New Features in Release 6.6.5545** - **AVX-14021** - The Aviatrix Controller now supports OCI Gov Cloud accounts. To onboard these accounts, find the Aviatrix image in the OCI Gov Marketplace and subscribe. Then, open the Onboarding page in your Aviatrix Controller and use the `Oracle Onboarding Guide <https://docs.aviatrix.com/HowTos/oracle-aviatrix-cloud-controller-onboard.html>`_ to begin onboarding. **Enhanced Features in Release 6.6.5545** - **AVX-14100** - Added support for c2-standard-60 instance type for Aviatrix Insane Mode on GCP. For Insane Mode on GCP performance throughput, refer to `GCP Performance Test Results <https://docs.aviatrix.com/HowTos/insane_mode_perf.html?highlight=gcp%20performance%20test%20results#gcp-performance-test-results>`_. - **AVX-15117** - Large (4G+) tracelog uploads consumed excessive CPU, which caused gateway flapping. - **AVX-20423** - Optimized performance for launching gateways, viewing tunnel status, and uploading trace logs in large deployments. - **AVX-17030** - In a Site2Cloud connection, the same IP address in the remote gateway peer and the remote subnet is now supported. This is useful when configuring a Site2Cloud connection to a third-party environment where only one public IP address is exposed. For more information, refer to the `Site2Cloud FAQs <https://docs.aviatrix.com/HowTos/site2cloud_faq.html>`_. - **AVX-19161** - Added New Site2Cloud RX Balancing option to the Multi-Cloud Transit > Advanced Config > Edit Transit page. Enabling this option can increase forwarding throughput on Aviatrix Transit Gateways for BGP-over-GRE External Device traffic (a.k.a. Site2Cloud or S2C GRE tunnels), in these situations: * On certain topologies that require high throughput, with External Devices that limit the number of GRE tunnels. * Where maintaining a high number of GRE tunnels increases operational burden. Note: This option is only available for Aviatrix Transit Gateways deployed in AWS on C5 and C5n instance types (except for c5.large and c5n.large). - **AVX-20200** - Clarified a confusing error message in an automated exception email that had little context: "AttributeError: 'NoneType' object has no attribute 'resource_guid'â€. - **AVX-20022** - You can now configure the gateway interfaces to enable or disable generic receive offload (GRO) and generic segmentation offload (GSO). - **AVX-20383** - Added support for updating the secondary CIDRs in firewall-related VPC route tables for Azure FireNet gateways. The secondary CIDRs are usually added by user OOB (Out of Band) in a CSP. Then, an API needs to be called to manually update the changed CIDR set normally to the gateway route tables. However, for an Azure cloud case, the firewall-related VPC route tables also need to be updated. This product enhancement ensures that update. The API involved is "update_encrypted_spoke_vpc_cidrsâ€. **UI Enhancements in Release 6.6.5545** - **AVX-15459** - Replaced ‘vpc_id with "OCID" for OCI Gateways to make sure these values are unique. Now, every OCI vpc_id value has been migrated from vpc_name to OCID. For example, "vpc-oracle-test†is migrated to "ocid1.vcn.oc1.iad.aaaaaaaaba3pv6wkcr4jqae5f44n2b2m2yt2j6rx32uzr4h25vqstifsfdsq.†The Controller UI will display <vpc_id>~~<vpc_name> in the VPC ID field for better readability: for example, "ocid1.vcn.oc1.iad.aaaaaaaaba3pv6wkcr4jqae5f44n2b2m2yt2j6rx32uzr4h25vqstifsfdsq~~vpc-oracle-test.†- **AVX-18941** - Removed the Site2Cloud Standalone CloudN feature to improve routing functionality for Controllers upgraded to release 6.6 or above. Customers running Standalone CloudN in earlier releases (6.4 or below) can upgrade existing CloudN hardware or plan for an upgrade to Aviatrix Edge. - **AVX-20616** - Supported filtering and pagination of security domain policies. This change makes the Add/Modify Connection Policy feature easier to use, especially in accounts that have large number of policies. **Known Issues in Release 6.6.5545** - **AVX-20656** - If you have AWS CloudWatch enabled in your deployment, disable it before upgrading from 6.5 to any 6.6 release. If you upgrade while AWS CloudWatch is still enabled, the system will enter a config fail state and the network will go down. You can return the system to sane condition by using Disable/Enable CloudWatch. - **AVX-20978** - Only one active profile rsyslog config shows up in gateways, even when the gateway has multiple profiles. A workaround for this issue is to remove the entire Syslog profile index and then add them back using Terraform. Then, the rsyslog configs appears in all gateways. **Issues Corrected in Aviatrix Release 6.6.5545** - **AVX-14253** - An Azure Transit Gateway took excessive time to advertise a newly attached Spoke Gateway's CIDRs over BGP. - **AVX-16122** - After successfully enabling packet logging for either allow all or deny all base policy for stateful firewalls, packet logging was automatically removed. - **AVX-16838** - A newly created Controller failed to get its public IP, causing some gateways to fail to start. - **AVX-17058** - The S2C EIPs of Single IP HA gateways were leaked on gateway deletion after stopping/starting the gateway. - **AVX-19498** - When using S2C Single IP HA, the gateway EIP was not released after the gateway deletion. - **AVX-19811** - You can now insert a stateful firewall policy by specifying the position where they want to insert the policy. This feature is presently available through "Insert Stateful Firewall Rules†API using "position†param. The "position†param is 1 indexed. - **AVX-20064** - Enabled users to insert a Force Drop rule on the top of the list of Stateful Firewall rules without changing the order of the rules in the table. - **AVX-20109** - Some gateway software upgrades failed with an "Archive is too short†message, but a software upgrade succeeded after retrying. - **AVX-20159** - When a user does an image upgrade/rollback on multiple gateways simultaneously, it could hit an exception in race condition, causing some gateway upgrade/rollback failures. These failures could cause the FireNet Gateway to not function properly after the upgrade/rollback. - **AVX-20173** - Incorrect gateways configured when disabling Transit FireNet on the gateway. - **AVI-2022-0004** - Fixed an internally-reported vulnerability which would allow an authenticated user to gain command line privileges on the Controller. This is not known to be exploited. - **AVX-20271** - Improved the cleanup of concurrent uploads that temporary files created by concurrent route updates. This fix prevents the overwrite of the temporary update files. - **AVX-20471** - When both Transit Gateways of a transit peering didn't have an AS number configured, CIDRs from static connection at one Transit Gateway would not be propagated to the peering Transit Gateway. - **AVX-20647** - Performance fix for route processing in multi-domain environment. - **AVX-20765** - If you had a TGW Firewall domain that enabled egress inspection, but this firewall's domain was not connected to the Aviatrix Edge Domain, this setup enabled management access from the Aviatrix Edge domain. This issue caused the default route 0.0.0.0/0 to be incorrectly propagated to the Transit Gateway in the Aviatrix Edge domain. - **AVX-20970** - Ignore the default RFC1918 routes check in the unselected route tables when you attach a Spoke Gateway with the selective route tables. 6.6.5413 (03/18/2022) ====================== **Issues Corrected in Release 6.6.5413** - **AVX-20271** - Restricted concurrent uploads to make it harder for a remote attacker to fill the disk and better defend against denial of service attacks. Overly restrictive checks allowed concurrent uploads to overwrite each other. This update allows for concurrency without sacrificing the original defensive goals. - **AVX-20502** - Controller upgrade from 6.5 to 6.6 causes BGP to go down on Aviatrix Transit Firenet. The issue occurs when the following conditions are met: #. The AWS Transit FireNet is enabled. #. The Transit FireNet gateway is attached to the AWS Transit Gateway as an edge gateway. #. The AWS Transit Gateway is added to the Transit FireNet inspection list. 6.5.3012 (03/17/2022) =================================== **Issues Corrected in Aviatrix Release 6.5.3012** - **AVX-18796** - The Controller to Gateway control channel uses certificate-based authentication. The Intermediate Certificate Authority (ICA) certificate TTL is set to renew automatically every 6 months. A week before the TTL expiration, the ICA will prepare the next certificate as part of the rotation. During this period, if any Gateway gets re-certified, the Controller will use the newly prepared/activated ICA certificate to sign it. If the Gateway flaps and reconnects during this period, the controller will reject these connections resulting in the Gateway being marked down. Since this issue can result in the controller marking gateways down, Aviatrix strongly recommends upgrading your software to a version that includes the issue correction. Note that after this fix, the certificate's validity changes from 60 days to 30 days. The rotation frequency also changes from 30 days to 15 days. - **AVX-20109** - Upgrade procedure update. If you are upgrading your controller and gateways from 6.5 to 6.6, you cannot use the selective gateways feature. #. From the Aviatrix Controller, go to Settings > Maintenance > Selective upgrade and perform a Platform Upgrade to 6.6 with all gateways selected. For more information, see `Upgrading the Aviatrix Cloud Network Platform <https://docs.aviatrix.com/HowTos/selective_upgrade.html>`_. #. If you see an "Archive is too short†message of any given gateway during the platform upgrade, you need to perform step 3. Otherwise, you can skip step 3. #. After the Upgrade is done, go to Settings > Maintenance > Selective upgrade and select the gateways listed in the "Archive is too short" message. Perform the gateway software upgrade again. **Known Issues in Aviatrix Release 6.5.3012** - **AVX-20201** - Controller sends false alert email about CloudN after upgrading or rebooting Managed CloudN configurations. You can ignore this false alert email. 6.4.3015 (03/17/2022) ===================================== **Issues Corrected in Aviatrix Release 6.4.3015** - **AVX-18796** - The Controller to Gateway control channel uses certificate based authentication. The Intermediate Certificate Authority (ICA) certificate TTL is set to renew automatically every 6 months. A week before the TTL expiration, the ICA will prepare the next certificate as part of the rotation. During this period if any Gateway gets re-certified, the Controller will use the newly prepared/activated ICA certificate to sign it. If the Gateway flaps and reconnects during this period, the controller will reject these connections resulting in the Gateway being marked down. Since this issue can result in the controller marking gateways down, Aviatrix strongly recommends upgrading your software to a version that includes the issue correction. - **AVX-20109** - Upgrade procedure update. If you are upgrading your controller and gateways from 6.5 to 6.6, you cannot use the selective gateways feature. #. From the Aviatrix Controller, go to Settings > Maintenance > Selective upgrade and perform a Platform Upgrade to 6.6 with all gateways selected. For more information, see `Upgrading the Aviatrix Cloud Network Platform <https://docs.aviatrix.com/HowTos/selective_upgrade.html>`_. #. If you see an "Archive is too short" message of any given gateway during the platform upgrade, you need to perform step 3. Otherwise, you can skip step 3. #. After the Upgrade is done, go to Settings > Maintenance > Selective upgrade and select the gateways listed in the "Archive is too short" message. Perform the gateway software upgrade again. **Known Issues in Aviatrix Release 6.4.3015** - **AVX-20201** - Controller sends false alert email about CloudN after upgrading or rebooting Managed CloudN configurations. You can ignore this false alert email. 6.6.5409 (03/13/2022) ====================== **Issues Corrected in Release 6.6.5409** - **AVX-18796** - The Controller to Gateway control channel uses certificate based authentication. The Intermediate Certificate Authority (ICA) certificate TTL is set to renew automatically every 6 months. A week before the TTL expiration, the ICA will prepare the next certificate as part of the rotation. During this period if any Gateway gets re-certified, the Controller will use the newly prepared/activated ICA certificate to sign it. If the Gateway flaps and reconnects during this period, the controller will reject these connections resulting in the Gateway being marked down. Since this issue can result in the controller marking gateways down, Aviatrix strongly recommends upgrading your software to a version that includes the issue correction. - **AVX-20109** - Upgrade procedure update. If you are upgrading your controller and gateways from 6.5 to 6.6, you cannot use the selective gateways feature. #. From the Aviatrix Controller, go to Settings > Maintenance > Selective upgrade and perform a Platform Upgrade to 6.6 with all gateways selected. For more information, see `Upgrading the Aviatrix Cloud Network Platform <https://docs.aviatrix.com/HowTos/selective_upgrade.html>`_. #. If you see an "Archive is too short" message of any given gateway during the platform upgrade, you need to perform step 3. Otherwise, you can skip step 3. #. After the Upgrade is done, go to Settings > Maintenance > Selective upgrade and select the gateways listed in the "Archive is too short" message. Perform the gateway software upgrade again. . **Known Issues in Aviatrix Release 6.6.5409** - **AVX-20201** - Controller sends false alert email about CloudN after upgrading or rebooting Managed CloudN configurations. You can ignore this false alert email. - **AVX-20502** - Controller upgrade from 6.5 to 6.6 causes BGP to go down on Aviatrix Transit FireNet. The issue occurs when the following conditions are met: #. The AWS transit FireNet is enabled. #. The Transit FireNet gateway is attached to the AWS Transit Gateway as an edge gateway. #. The AWS Transit Gateway is added to the Transit FireNet inspection list. 6.6.5404 (02/28/2022) ====================== **Enhanced Features in Release 6.6.5404** - Added support for gateway rollback from 6.6.a to versions 6.6 and 6.5. - Added new option for users to select between preemptive or non-preemptive failover behavior for Active/Standby deployments for S2C connections. - Added support for BGP on Spoke route propagation control to Transit. - Added support for BGP MD5 authentication. **Public Preview Features in Release 6.6.5404** The following `Public Preview Features`_ are available in this release: - Azure Subnet-Level Inspection enables inspection by Aviatrix Transit FireNet solution for traffic flowing between subnets within a VNet or in different VNets. For more information, refer to `Using Subnet Inspection in Azure to Redirect Subnet-Level Traffic to Aviatrix Transit FireNet and NGFW <https://docs.aviatrix.com/HowTos/transit_subnet_inspection_azure.html>`_. **UI Enhancements in Release 6.6.5404** - Improved the sub-menu BGP located under Transit FireNet on the left sidebar in the Aviatrix Controller. **Known Issues in Release 6.6.5404** - **AVX-10002** - Firewall's URL inspection rules are dropping packets with controller(or spire).aviatrixnetwork.com and showing failed registration. - **AVX-16838** - Release server API showing an error during IP update. - **AVX-17650** - CloudN custom upgrade dry run GUI hanging at 99%, but commands.log showing succeeded. - **AVX-20502** - Controller upgrade from 6.5 to 6.6 causes BGP to go down on Aviatrix Transit FireNet. The issue occurs when the following conditions are met: #. The AWS Transit FireNet is enabled. #. The Transit FireNet Gateway is attached to the AWS Transit Gateway as an edge gateway. #. The AWS Transit Gateway is added to the Transit FireNet inspection list. - **AVX-20978** - Only one active profile rsyslog config shows up in gateways, even when the gateway has multiple profiles. A workaround for this issue is to remove the entire Syslog profile index and then add them back using Terraform. Then, the rsyslog configs appears in all gateways. **Issues Corrected in Release 6.6.5404** - **AVX-18803** - Unable to detach external device connection from Transit due to Exception Error. - **AVX-18845** - Exception is seen while "adding/deleting" routes on Stand-Alone CloudN. - **AVX-18876** - For BGP connections associated with domain, seen routes learned got re-advertised back to same connection when these BGP routes are in BestDB. - **AVX-18878** - Sessions may be prevented from getting immediately logged out after certain API calls in the RNE. 6.6.5230 (02/09/2022) ====================== **Issues Corrected in Release 6.6.5230** - **AVX-14504** - Terraform relies on the API get_instance_by_id / CLI "firewall_instance get instance --instance_id <ID>" to refresh the state of the aviatrix_firewall_instance resource. However, in some Azure FireNet deployments the API returns the incorrect value for the attached Transit Gateway. - **AVX-18700** - When the stateful firewall rules configured on a gateway reaches a limit of 500 and above, while performing "Add/Delete/Insert" operations the following error may be encountered - "Command to execute too long". **Known Issues in Release 6.6.5230** - **AVX-20502** - Controller upgrade from 6.5 to 6.6 causes BGP to go down on Aviatrix Transit FireNet. The issue occurs when the following conditions are met: #. The AWS Transit FireNet is enabled. #. The Transit FireNet Gateway is attached to the AWS Transit Gateway as an edge gateway. #. The AWS Transit Gateway is added to the Transit FireNet inspection list. 6.5.3006 (02/09/2022) ====================== **Issues Corrected in Release 6.5.3006** - **AVX-14504** - Terraform relies on the API get_instance_by_id / CLI "firewall_instance get instance --instance_id <ID>" to refresh the state of the aviatrix_firewall_instance resource. However, in some Azure FireNet deployments the API returns the incorrect value for the attached Transit Gateway. - **AVX-17620** - Improved stateful firewall duplicate rule checks if duplicate rules are already present in the system. - **AVX-17332** - While onboarding a Google account either through UI or Terraform, subsequent onboarding attempts with incorrect Google Project ID will display an error. - **AVX-18148** - Excessive load on cloudxd induced due to rsyslog monitoring certain user visible changes.Excessive email alerts generated about rsyslog while trying to reduce rsyslog monitoring load on core processes. - **AVX-18291** - Daily controller backup failing with traceback on command 'tar' returning non-zero exit status. - **AVX-18700** - When the stateful firewall rules configured on a gateway reaches a limit of 500 and above, while performing "Add/Delete/Insert" operations the following error may be encountered - "Command to execute too long". 6.4.3008 (02/09/2022) ===================== **Issues Corrected in Release 6.4.3008** - **AVX-17620** - Improved stateful firewall duplicate rule checks if duplicate rules are already present in the system. 6.6.5224 (01/23/2022) ===================== **Enhanced Features in Release 6.6.5224** - Added support for Aviatrix Spoke Gateway to External Device (BGP-Enabled Spoke). Introduced in Aviatrix release 6.6, you can now create Spoke Gateways that are BGP-enabled and NAT-enabled. Aviatrix Cloud Network Platform has always supported NAT in a way that most enterprises need in order to meet their business and technical requirements. Using BGP-enabled and NAT-enabled Spoke Gateways gives you yet more capabilities to implement policy based SNAT/DNAT functions in strategic places in your network architecture. For more information, see the discussion about `Aviatrix Spoke Gateway to External Device <https://docs.aviatrix.com/HowTos/spokegw_external.html>`_. - Added support for Google Cloud Platform (GCP) BGP over LAN to support multi peer instance. This allows Aviatrix Transit Gateways to communicate with a pair of instances in the same VPC in GCP without running any tunnelling protocol such as IPSec or GRE. For more information, see the discussion about `GCP Multi-cloud Transit BGP over LAN Workflow <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_gcp_workflow.html>`_. - Added support for AWS TGW Connect over Direct Connect. Amazon Web Services (AWS) enables AWS customers to integrate their Software Defined Wide Area Network (SD-WAN) devices with AWS Transit Gateway and AWS Direct Connect so they can use their existing SD-WAN devices to connect their on-premises networks to an AWS Transit Gateway. In support of this, Aviatrix enables you to create one or multiple Transit Gateway Connect attachments over Direct Connect. You can also create Transit Gateway Connect peer attachments. For instructions, see the topic `Enable AWS TGW connect over Direct Connect <https://docs.aviatrix.com/HowTos/tgwconnect.html>`_. - Added support for Aviatrix Controller Security Assertion Markup Language (SAML) based authentication user VPN access in Azure. For instructions, see the topic `Azure SAML Authorization VPN Access <https://docs.aviatrix.com/HowTos/azure_saml_auth_vpn_access.html>`_. - Added support for FireNet with PAN in AWS China. - Added support for Checkpoint integration with private SSH keys. **UI Enhancements in Release 6.6.5224** - Improved FireNet and Multi-Cloud Transit workflows reducing clicks and navigation steps. - Decommissioning and Renaming of CLOUDWAN to CLOUDN. - Notification bar includes message history. - Guided "What's New" information for first Aviatrix Controller user login. - Launch CoPilot from the Aviatrix Controller App Drawer. - Enable daily backup added to notification menu. - Use consistent naming in action menu and config box for the list view of Transit Gateway. **Changed Behaviors in Release 6.6.5224** - The 6.6 release introduces a behavior change in the Multi-Cloud Transit Active-Standby Site2Cloud behavior, if the setting is enabled. After a failover, when the primary gateway is back up, the traffic is switched over automatically back to the primary Site2Cloud connection. This brings more predictability and fits into the model of most on-prem firewalls. In 6.6, this behavior cannot be adjusted. If Active-Standby is disabled (which is the default setting), there is no behavior change. If you have questions about this behavior, please contact your Aviatrix account team. - Before 6.6, when BGP ECMP is enabled, routes from different domain can be combined to form ECMP at gateway. This is incorrect behavior and is fixed in 6.6, such that only BGP routes from the same domain can be combined for ECMP. - Aviatrix no longer supports non-ActiveMesh transit network configurations beginning in release 6.6. Aviatrix recommends that if you are running version 6.5 or earlier, you upgrade to version 6.5.1922 or a higher 6.5 version before upgrading to 6.6. **Upgrade Behaviors and Restrictions in Release 6.5224** - To upgrade to 6.6, you must manually enter "6.6" in the Aviatrix Controller upgrade window. - You cannot rollback to Aviatrix version 6.5 after upgrading to 6.6. **Known Issues in Release 6.6.5224** - Cannot add more than 2 remote and 2 local subnet pair tunnels to a Site2Cloud policy based connection with the Aviatrix Controller. - Workaround: Use Site2Cloud to delete or add new subnet pair tunnels to a Site2Cloud policy based connection. - OCI is not yet compatible with the 6.6 release. Until a new image is available, initializing your controller to the latest will fail. - Workaround: initialize your controller to 6.5 first and upgrade to 6.6. Controllers already installed with 6.3 or newer should be able to upgrade to 6.6 without issue. - The controller's database version and schema are changed in 6.6. You might notice that there will be a brief period of error messages in the controller's log while this change is happening. The errors should stop without user intervention after the upgrade is complete. **AVX-35490** - After a Controller software upgrade or a CloudXD restart, the Controller migrates BGP routes, automatically triggering an “Approve New Routes” email for existing pending CIDRs on gateways with learned CIDRs approval enabled. This issue has no functional impact. Approved CIDRs remain intact and no routes are changed. **Issues Corrected in Release 6.6.5224** - **AVX-14515** - Exception seen when configuring vendor integration with a Palo Alto Firewall VM which has no route tables. - **AVX-14568** - If there are any GWs that are not reachable by the controller before the Controller HA Migration starts, the control planes of these GWs will be out of sync because there will be an implicit control-plane certificate re-bootstrap as a part of Control HA Migration process. The issue exists before 6.5.2835 (exclusive) and all 6.4 releases. - **AVX-14754** - When Controller Security Group Management is enabled and launching a gateway causes controller SG to reach limit, it will show correct error "The maximum number of rules per security group has been reached. - **AVX-14822** - Controller Security Group Management will add gateway IP rule to customer attached controller SGs as well as controller created SGs. - **AVX-15180** - Allows you to configure default route as destination CIDR in customized SNAT. - **AVX-15454** - Deleted dependency of storage account for Azure China gateways. - **AVX-15639** - When replacing a gateway using image upgrade the new gateway was missing the Aviatrix-Created-Resource tag. - **AVX-15651** - Incorrect existing references to default Aviatrix AWS IAM role names. - **AVX-15704** - While creating an IKEv2 enabled site2cloud connection, you will see "Failed to establish a new connection" error.snat - **AVX-15978** - The conntrack "allow all" rule should always be placed above the "drop all" rule in the order of operations. - **AVX-16100** - You can configure DNAT on transit GW, either ActiveMesh or non-ActiveMesh connection. - **AVX-16375** - For policy based site2cloud connection, if one of the s2c tunnel is down on a Transit Gateway, traffic from attached spoke, or peering transit, or AWS TGW to the Transit Gateway will be dropped. - **AVX-16450** - Addressed issues with CloudN registration in some scenarios. - **AVX-16486** - Improved IPSec performance on high latency links. - **AVX-16494** - Performance optimization in monitoring IPSec states. - **AVX-16496** - When upgrading a standalone CloudN implementation: - For CloudN versions < 6.5.2613: Full outbound access on TCP ports 80 and 443 on CloudN Management is required. - For CloudN versions >= 6.5.2613: Please follow the `Internet Access <https://docs.aviatrix.com/HowTos/CloudN_insane_mode.html#internet-access>`_ instructions. For a list of required FDQNs, please see `Required Access for External Sites <https://aviatrix.zendesk.com/hc/en-us/signin?return_to=https%3A%2F%2Faviatrix.zendesk.com%2Fhc%2Fen-us%2Farticles%2F4417312119437-Aviatrix-Products-Access-to-external-FQDN-required>`_. - **AVX-17027** - The UI upgrade progress bar getting stuck at 99% during standalone CloudN upgrade. - **AVX-17302** - Secondary CIDRs in OCI VCN not advertised to Transit Gateway. - **AVX-17420** - If the account is deleted or deactivated from AWS, VPC attachment from AWS TGW is getting deleted. You must manually clean up all blackhole routes (RFC1918 or customized routes) on AWS. - **AVX-17432** - For route based, unmapped S2C, when the connection is down, the routes for the remote CIDRs are still associated with the connection, i.e. the routes are not removed. - **AVX-17512** - Addressed an issue in NAT programming on Spoke-HA when sync-to-ha is enabled. - **AVX-17582** - Closed potential security issue the controller UI console. - **AVX-17628** - Closed potential SSH security issue for users upgrading from previous releases. - **AVX-17740** - Launching a gateway on a Native GWLB FireNet VPC is incorrectly allowed. Disabling Native GWLB FireNet before detaching the VPC from its TGW (if it was attached to one) was incorrectly allowed. - **AVX-17849** - Existing issues in Flightpath for Azure NSG's. - **AVX-18047** - Jumbo Frame support on the GRE connection not enabled. - **AVX-18148** - Excessive load on cloudxd induced due to rsyslog monitoring certain user visible changes.Excessive email alerts generated about rsyslog while trying to reduce rsyslog monitoring load on core processes. - **AVX-18149** - Controller becoming slow or non-responsive when executing large number of certain API requests. - **AVX-18164** - The performance of the API to list the security policies of a gateway is not satisfactory. 6.5.2898 (01/11/2022) ===================== **Issues Corrected in Aviatrix Release 6.5.2898** - **AVX-9033** - Some logs are too big on CloudN. - **AVX-14426** - Tunnels take a long time to become established and on occasion can flap even during establishment in IPSEC IKE interoperability. - **AVX-14659** - Tunnel flaps when attaching Spoke Gateways running IPSec strongSwan to Transit Gateways running IPSec racoon, or Transit Gateways running IPSec strongSwan to Transit Gateways running IPSec racoon. - **AVX-16967** - When a SNAT rule is added/removed for a gateway, it needs to check if the NAT rule is duplicated in the route tables. The checking is dependent on the NAT routes if load balanced or generic (not load balanced). You must miss the checking for duplicated routes to include the HA gateways in the interface list. It may give a wrong conclusion that some NAT rules were duplicated. - **AVX-17214** - If any conntrack module related errors are observed in 6.5. (g's build number) and after, AVXERR format can be used for first level debugging. 'AVXERR-CONNTRACK-0001': 'Gateway Error: {}', 'AVXERR-CONNTRACK-0002': 'Required/Invalid option: {}' 'AVXERR-CONNTRACK-0003': 'Not found/File error: {}' 'AVXERR-CONNTRACK-0004': 'Not Supported: {}' - **AVX-17349** - Closed vulnerability AVI-2021-0008, allowing an unauthenticated attacker partial access to configuration information on controllers and an unauthenticated network-adjacent attacker API access on gateways. - **AVX-17420** - If the account is deleted or deactivated from AWS, VPC attachment from AWS TGW is getting deleted. You must manually clean up all blackhole routes (RFC1918 or customized routes) on AWS. - **AVX-17628** - Hardened SSH security for legacy users. - **AVX-17740** - Launching a gateway on a Native GWLB FireNet VPC was incorrectly allowed. Disabling Native GWLB FireNet before detaching the VPC from its TGW (if it was attached to one) was incorrectly allowed. - **AVX-18149** - Controller becoming slow or non-responsive when executing large number of certain API requests. **Known Behaviors in Aviatrix Release 6.5.2898** - If your Controller is running 6.4 and you have ControllerHA enabled, there is a very small chance that your HA recovery might fail if your Controller goes down by any chance. If that happens, you can manually restore the backup on your new Controller. To avoid this, please upgrade to the 6.5 release. - **AVX-16496** - When upgrading a standalone CloudN implementation: - For CloudN versions < 6.5.2613: Full outbound access on TCP ports 80 and 443 on CloudN Management is required. - For CloudN versions >= 6.5.2613: Please follow the instructions at Standalone `CloudN Deployment Checklist <https://docs.aviatrix.com/HowTos/CloudN_insane_mode.html?highlight=StandAlone%20CloudN%20>`_. For a list of required FDQNs, please see `Required Access for External Sites <https://aviatrix.zendesk.com/hc/en-us/signin?return_to=https%3A%2F%2Faviatrix.zendesk.com%2Fhc%2Fen-us%2Farticles%2F4417312119437-Aviatrix-Products-Access-to-external-FQDN-required>`_. - **AVX-15458** - After Controller and standalone CloudN's are upgraded from 6.3 to 6.4, to access CloudN device in web UI: - Use CloudN management IP address inside on-premises network. - Use CloudN LAN IP address from Spoke workplace in the CSP network. - **AVX-17221** - If you have Managed CloudN, Aviatrix requires you to follow the Managed instructions and allow access to the sites mentioned for the CloudN Managed Port. If your Managed CloudN ends up in a "config_fail" state after your Controller is upgraded, you have the following options: Option 1: #. Deregister your CloudN. Follow the instructions to allow management port outbound access. #. Follow NTP sync instructions at `Managed CloudN Workflows <https://docs.aviatrix.com/HowTos/CloudN_workflow.html#step-2-2-configure-ntp-sync-and-smtp-services>`_. #. Register your CloudN. Option 2: Open a ticket with `Aviatrix Support <https://support.aviatrix.com/>`_. 6.4.2995 (01/11/2022) ===================== **Issues Corrected in Aviatrix Release 6.4.2995** - **AVX-14537** - Error establishing Raccoon native CaaG attachment with larger transit instance size (Ex: c5.4xlarge, Standard_D8_v3) and number of IPSec Tunnels > 32. - **AVX-17349** - Closed vulnerability AVI-2021-0008, allowing an unauthenticated attacker partial access to configuration information on controllers and an unauthenticated network-adjacent attacker API access on gateways. 6.5.2835 (12/10/2021) ===================== **Issues Corrected in Aviatrix Release 6.5.2835** - **AVX-9033** - The routing logs are not rotated on CloudN and are not included in the trace logs. - **AVX-14298** - The following CVEs were addressed in this release: `CVE-2007-2243 <https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2007-2243>`_ and `CVE-2004-1653 <https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2004-1653>`_. - **AVX-14659** - IPSec tunnel flapping between gateways running different flavors of IPSec infra. - **AVX-16121** - After a successful image upgrade, the gateway state changes from success to config_fail after about 5 minutes. - **AVX-16563** - Security Group Management feature fails on an Aviatrix Controller deployed in GCP after a Controller Migration operation. - **AVX-16912** - Cannot create Transit GW with HA in OCI using Terraform scripts. - **AVX-16967** - Deleting one or more Customized SNATs generates a "route already exists in route table" error. - **AVX-17489** - When deleting one CIDR from the spoke customized advertise CIDR list, the CIDR should only be removed from the Transit Gateway and the rest of the network. However, during deletion the CIDR was removed from the spoke itself, which deletes the routes added for static S2c. **Known Issues in Aviatrix Release 6.5.2835** - If your Controller is running 6.4 and you have ControllerHA enabled, there is a very small chance that your HA recovery might fail if your Controller goes down by any chance. If that happens, you can manually restore the backup on your new Controller. To avoid this, please upgrade to the 6.5 release. - **AVX-16121** - In Aviatrix version 5.x, Logstash Forwarder was replaced by `Filebeat Forwarder <https://docs.aviatrix.com/HowTos/AviatrixLogging.html#filebeat-forwarder>`_ in the supported logging services. If you enabled logstash before this switch, please disable/enable logstash on the Filebeat Forwarder in "Controller/Logging" before upgrading your Aviatrix Controller, otherwise your Gateways might come up in the "config_fail" state after the upgrade. You might need to update your configuration on your collection side to accommodate this change. If you already upgraded and have Gateways in the "config_fail" state, you can do an "Image Upgrade" on the impacted Gateway to resolve the issue. - **AVX-17221** - If you have Managed CloudN, Aviatrix requires you to follow the Managed instructions and allow access to the sites mentioned for the CloudN Managed Port. If your Managed CloudN ends up in a "config_fail" state after your Controller is upgraded, you have the following options: Option 1: #. Deregister your CloudN. Follow the instructions to allow management port outbound access. #. Follow NTP sync instructions at `Managed CloudN Workflows <https://docs.aviatrix.com/HowTos/CloudN_workflow.html#step-2-2-configure-ntp-sync-and-smtp-services>`_. #. Register your CloudN. Option 2: Open a ticket with `Aviatrix Support <https://support.aviatrix.com/>`_. 6.4.2973 (11/19/2021) ===================== - If your Controller is running 6.4 and you have ControllerHA enabled, there is a very small chance that your HA recovery might fail if your Controller goes down by any chance. If that happens, you can manually restore the backup on your new Controller. To avoid this, please upgrade to the 6.5 release. - **AVX-16121** - In Aviatrix version 5.x, Logstash Forwarder was replaced by `Filebeat Forwarder <https://docs.aviatrix.com/HowTos/AviatrixLogging.html#filebeat-forwarder>`_ in the supported logging services. If you enabled logstash before this switch, please disable/enable logstash on the Filebeat Forwarder in "Controller/Logging" before upgrading your Aviatrix Controller, otherwise your Gateways might come up in the "config_fail" state after the upgrade. You might need to update your configuration on your collection side to accommodate this change. If you already upgraded and have Gateways in the "config_fail" state, you can do an "Image Upgrade" on the impacted Gateway to resolve the issue. - **AVX-17221** - If you have Managed CloudN, Aviatrix requires you to follow the Managed instructions and allow access to the sites mentioned for the CloudN Managed Port. If your Managed CloudN ends up in a "config_fail" state after your Controller is upgraded, you have the following options: Option 1: #. Deregister your CloudN. Follow the instructions to allow management port outbound access. #. Follow NTP sync instructions at `Managed CloudN Workflows <https://docs.aviatrix.com/HowTos/CloudN_workflow.html#step-2-2-configure-ntp-sync-and-smtp-services>`_. #. Register your CloudN. Option 2: Open a ticket with `Aviatrix Support <https://support.aviatrix.com/>`_. **Issues Corrected in Aviatrix Release 6.4** - **AVX-15653** - Controller image migration fails to progress past the initialization state. - **AVX-16494** - CPU overconsumption by IP processes on gateways. - **AVX-16601** - In some corner cases, if the API enable_gateway_auto_recovery option is used on the Controller to overcome the Azure maintenance windows it causes the ethernet interfaces on the gateways to go missing. In some cases, the API failed to stop and start the affected gateways. If you have this feature enabled, please disable it and then enable it again after the upgrade or open a Support ticket at https://support.Aviatrix.com to get assistance. 6.5.2721 (11/18/2021) ===================== **Issues Corrected in Aviatrix Release 6.5.2721** - **AVX-15735** - CoPilot unable to display gateway active sessions from the Aviatrix Controller. - **AVX-16494** - CPU overconsumption by IP processes on gateways. - **AVX-16572** - Listing interfaces on a gateway takes a long time with large number of Site2Cloud connections. - **AVX-16601** - In some corner cases, if the API enable_gateway_auto_recovery option is used on the Controller to overcome the Azure maintenance windows it causes the ethernet interfaces on the gateways to go missing. In some cases, the API failed to stop and start the affected gateways. If you have this feature enabled, please disable it and then enable it again after the upgrade or open a Support ticket at https://support.Aviatrix.com to get assistance. **Feature Enhancements in Aviatrix Release 6.5.2721** - **AVX-9927** - Added message for unstable network connectivity prompting user to refresh page to reconnect. - **AVX-10080** - Added support for Transit Firenet in AWS China for Checkpoint. 6.3.2551 (11/12/2021) ===================== **Issues Corrected in Aviatrix Release 6.3.2551** - **AVX-16569** - Controller image migration fails to progress past the initialization state. 6.3.2548 (11/04/2021) ===================== **Issues Corrected in Aviatrix Release 6.3.2548** - **AVX-15897** - Fixed an issue for Gateway Replace/Create/ForceUpgrade operations if Splunk logging was enabled on it, which was seen on all releases after 10/13/2021 (when Splunk behavior changed). - **AVX-15985** - Fixed the issue where the Controller get_gateway_stats API was returning stats for deleted interfaces. - **AVX-16017** - Users were unable to create Microsoft Azure Resource Manager (ARM) China Gateway for the 6.3 version. This issue was fixed by updating an Azure China image link for 6.3. - This release includes a fix for the security vulnerability AVI-2021-0006 that would allow an unauthenticated attacker to execute arbitrary code on the Controller (this vulnerability was also fixed by our security patch released on 10/25/2021 as described here https://docs.aviatrix.com/HowTos/UCC_Release_Notes.html#security-patch-note-10-25-2021). 6.4.2945 (10/31/2021) ===================== **Issues Corrected in Aviatrix Release 6.4** - **AVX-11175** - FQDN feature will handle any case changes to the UserAgent field made by a proxy. - **AVX-15438** - For gateways with HPE connections to other gateways or CloudN gateways, a resize-up operation will make use of excess capacity, but a later replace operation might cause gateway to go to config_fail state. This fix addresses the issue. - **AVX-15528** - The real-time status of the gateway is not returned in GCP when there are a large number of instances in the VPC. - **AVX-15599** - Cannot launch a gateway on private OOB Controller. - **AVX-15897** - Fixed an issue for Gateway Replace/Create/ForceUpgrade operations if Splunk logging was enabled on it, which was seen on all releases after 10/13/2021 (when Splunk behavior changed). - **AVX-15978** - The conntrack allow all rule should always be above DROP all rule. The order should be honored. Fixed in this release. - **AVX-15985** - Fixed the issue where Controller get_gateway_stats API was returning stats for deleted interface. - **AVX-16066** - Stateful-Firewall ESTABLISHED rule deleted from FORWARD chain. - **AVX-16100** - Fix that allows configuration of DNAT on transit GW on non-active mesh connection. 6.5.2613 (10/28/2021) ===================== **Issue Corrected in Aviatrix Release 6.5** - **AVX-15444** - This fixes CaaG registration version check error. 6.5.2608 (10/27/2021) ===================== **Feature Enhancements in Aviatrix Release 6.5** - Added support for AWS BGP over LAN to support multiple peer instances. Scale up to 10 BGP over LAN peers per Transit Gateway, and 20 total per Transit Gateway pair. This provides a higher throughput, better redundancy, and a consolidation of BGP over LAN peers for on-prem connectivity on a pair of Transit Gateways. For more information, see the discussion about `BGP over LAN Multi-Peer <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_workflow.html#bgp-over-lan-multi-peer>`_. - Added fields "ec2 role" and "app role" in the Controller UI to support custom roles for AWS IAM based accounts. It is highly recommended to use a customized name for "ec2 role" and "app role" instead of the Aviatrix default roles for better security. - **AVX-15101** - Added support for Azure Government Cloud Availability Zones. **Issues Corrected in Aviatrix Release 6.5** - **AVX-9927** - The Controller does a page refresh automatically when detecting a network issue. - **AVX-11175** - FQDN feature will handle any case changes to the UserAgent field made by a proxy. - **AVX-13851** - Site2cloud edit to update Local Identifier as private IP for External Device connection will update all tunnels correctly. - **AVX-14224** - Improvements to Spire Gateway Service for handling a large number of gateways. - **AVX-14240** - Improved messaging for CloudN without public IP. - **AVX-14397** - CaaG's state changed to config_fail due to a wrong certificate name. - **AVX-14600** - Support Palo Alto Firewall vendor integration with multiple IPs configured on the eth interfaces - **AVX-14610** - Corrected non-ASCII characters while displaying the logs from Troubleshoot->Logs. - **AVX-14619** - Fixed an issue causing packet drops when migrating from ActiveMesh 1.0 to 2.0. - **AVX-14678** - Support multiple firewalls to be created and attached to Transit Gateway in Azure when Panorama vendor integration is configured. - **AVX-14700** - Addressed an issue where some Gateways could be reported in a down state if Certificate Domain is updated. - **AVX-14729** - Fixed an issue with cloudN upgrade failing dry run caused due to SSLError (Cert Expired). - **AVX-14820** - Addressed an issue with Gateways being in up state during an upgrade from 6.4 to 6.5. - **AVX-15012** - Exception error during disabling OCI transit FireNet function. - **AVX-15071** - Fixed firewall tuple setting from changing during Controller upgrade. - **AVX-15083** - Fixed issues with Site2Cloud with "Single IP HA" feature having issues with customized SNAT features when "sync to HA gateway" configuration is enabled. - **AVX-15138** - Fixed route table priority to deal with CIDR overlap between advertised routes from Transit and CaaG/CloudN eth2 MGMT interface. - **AVX-15198** - Process optimization to avoid db updates when Transit Gateway details are listed by the Aviatrix Controller or CoPilot. - **AVX-15238** - Fixed a CaaG registration failure issue after the cert domain is changed from default. - **AVX-15332** - Fixed an issue that was causing the Controller migration process to fail. - **AVX-15454** - Deleted dependency of storage account for Azure China gateways. - **AVX-15528** - The real-time status of the gateway is not returned in GCP when there are a large number of instances in the Project. - **AVX-15639** - When replacing a gateway using image upgrade the new gateway was missing the Aviatrix-Created-Resource tag. This has been fixed by ensuring the tag is added while launching the new gateway. - **AVX-15653** - Fixed an issue where Controller migration fails when custom IAM roles and limited permissions are used. - **AVX-15704** - Fixed the issue when creating an IKEv2 enabled site2cloud connection, where "Failed to establish a new connection" error displays. - **AVX-15897** - Fixed an issue for Gateway Replace/Create/ForceUpgrade operations if Splunk logging was enabled on it, which was seen on all releases after 10/13/2021 (when Splunk behavior changed). - **AVX-15978** - The conntrack allow all rule should always be above DROP all rule. The order should be honored. Fixed in this release. - **AVX-15985** - Fixed the issue where Controller get_gateway_stats API was returning stats for deleted interface. - **AVX-16100** - Fix that allows configuration of DNAT on transit GW on non-ActiveMesh connection. - **AVX-16130** - Fixed an issue where S2C GRE tunnel was showing it was down even though the S2C connection passing traffic with BGPoGRE was up. - This release includes a fix for the security vulnerability AVI-2021-0006 that would allow an unauthenticated attacker to execute arbitrary code on the Controller (this vulnerability was also fixed by our security patch released on 10/25/2021 as described here https://docs.aviatrix.com/HowTos/UCC_Release_Notes.html#security-patch-note-10-25-2021). - The following CVEs were addressed in this release: `CVE-2007-2243 <https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2007-2243>`_ and `CVE-2004-1653 <https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2004-1653>`_. **Known Behaviors in Aviatrix Release 6.5** - **AVX-16151** - The [NAT] incorrect tunnel is used during DNAT rule programming for Transit Gateway with HA. When DNAT is configured on non-active-mesh Transit Gateway with "Sync to HA" enabled, the DNAT rule may not be programmed correctly on HA Gateway and the Transit Gateway failover may see traffic impact. **Workaround** The workaround for this issue is that the DNAT config needs to be separately programmed on the primary and HA Gateway rather than programming on the primary Gateway side with "Sync to HA" enabled. 6.4.2859 (9/22/2021) ===================== **Feature Enhancements in Aviatrix Release 6.4** - **AVX-15101** - Added support for Azure Government Cloud Availability Zones. - Enhanced stateful firewall functionality. - Enhanced certificate functionality. **Issues Corrected in Aviatrix Release 6.4** - **AVX-14678** - Unable to create multiple firewalls attached to the same Transit Gateway in Azure environments. - **AVX-15138** - When a Spoke or Transit Gateway advertises a CIDR that overlaps with a CaaG or StandAlone CloudN MGMT eth2 subnet, and the client application accesses the device through the eth2 MGMT interface, the reply traffic is not returned through the eth2 MGMT interface. - **AVX-15198** - When Transit Gateway details are listed by the Aviatrix Controller or CoPilot, an exception may occur because the request is in replica mode and incorrectly tries to update the Mongo DB. 6.5.1905 (8/24/2021) ===================== **New Features in Aviatrix Release 6.5** **Selective Upgrades** To facilitate less disruptive upgrades and reduce maintenance windows Aviatrix provides a rolling selective upgrade process. You can choose to upgrade all Aviatrix gateways simultaneously or select specific gateways and regions to upgrade in logical groups conforming to your network update policies and maintenance windows. For more information, see `Upgrading the Aviatrix Cloud Network Platform <https://docs.aviatrix.com/HowTos/selective_upgrade.html>`_. **Feature Enhancements in Aviatrix Release 6.5** - **AVX-9881** - Added support for using the same Azure Virtual Network name and resource group names under different subscriptions. - **AVX-10188** - Added warning message when disabling the import certificate which includes the impact and effects of disabling the certificate. - **AVX-10493** - Added support for Alibaba cloud including China regions in Aviatrix FlightPath. - **AVX-10799** - Added support for Alibaba cloud including Global and China regions to Aviatrix VPC Tracker. - **AVX-13615** - Added AWS GuardDuty support for AWS GovCloud monitoring. **Modified Behaviors in Aviatrix Release 6.5** - **AVX-9894** - Removed deprecated optional custom logging fields for Splunk, Sumo, and Filebeat from the user interface. - **AVX-10113** - When you import security certificates on the gateways and controller, the certificate must include the proper FQDN. For example: openssl req -new -subj "/C=GB/CN=foo" \ -addext "subjectAltName = DNS:foo.co.uk" \ -addext "certificatePolicies = 172.16.31.10" \ -newkey rsa:2048 -keyout key.pem -out req.pem Alternatively, you can add the SubjectAlternateName (SAN) tag in the openssl.cnf file before generating the certificate. The SAN tag makes sure your certificate includes the SubjectAlternateName which is validated by the Apache server on the controller. Versions of UserConnect-6.4 and later require the proper SubjectAlternateName including altNames be set in the certificates when they are imported. If the SAN is not specified, importing the certificates fails. - **AVX-14009** - Added option to allow all traffic from the local VPC CIDR block to the network security group created during the OCI gateway creation process. Previously, only TCP port 443 traffic from the controller was added to the security group. By default, OCI allows all traffic from RFC1918 blocks. This change only applies to non-RFC1918 VPC CIDR block configurations. **Known Behaviors in Aviatrix Release 6.5** *Upgrading to Aviatrix Release 6.5* - This behavior does not affect ActiveMesh gateways. In non-ActiveMesh environments, only one transit or Spoke Gateway can have the image upgraded or the software rolled back at a time. If you select multiple gateways, you receive an error message. For multiple API calls to replace gateways using Terraform, only one gateway is allowed and the others fail. For Terraform calls, Aviatrix recommends you set parallelism=1. *Gateway Issue Discovered After Upgrade* In rare cases where the controller and a group of gateways are selected for upgrade and a fatal bug is discovered in the new software, a situation where the controller and gateways remain running different versions could develop. If this condition occurs assistance from Aviatrix Support is required. For example: A controller and gateways are running version 6.5.200. - You upgrade the controller and a subset of gateways to 6.5.300. - You rollback the gateways to 6.5.200 because of a bug in the 6.5.300 software. - Now the controller is running 6.5.300 and all gateways are running 6.5.200, and the gateways cannot successfully be upgraded to 6.5.300 because of the bug. - The bug is resolved in controller version 6.5.400, so you want to upgrade to 6.5.400 to resolve the issue. However, this is not supported because the controller and gateways must be running the same software version before the controller can be upgraded. - In this corner case, you must contact Aviatrix Support to upgrade the controller to the newer version. Support will diagnose the issue and provide the API operation required to perform the con-troller upgrade. *Gateway Rollbacks* Gateway rollback operations are not supported after Controller restore operations. **Issues Corrected in Aviatrix Release 6.5** - **AVX-10552** - Changed TGW VPN tunnel details response in API so list_attachment_route_table_detail returns are in dictionary format rather than a long string. 6.4.2830 (08/28/2021) ===================== **Issues Corrected** - **AVX-13787** Incorrect gateway status is reported for default routes when an OCI gateway in insane mode is attached to a Transit FireNet gateway. - **AVX-14295** When on-premise routes are injected or withdrawn, they are incorrectly removed in connected domain route tables. - **AVX-14426** Newly deployed cloud gateways use a new IKE implementation and may cause negotiation issues when spoke or on-premise tunnels are configured with an older IKE implementation on one side and the new Aviatrix IKE implementation on the transit side. You may observe tunnels taking a long time to become established, and on occasion may observe route flapping even after the tunnel is established. - **AVX-14689** Creating an Aviatrix gateway in the Alibaba Cloud may fail because the public IP address may not get converted to an elastic IP address. 6.4.2791 (08/20/2021) ===================== - **Bug fix** The FQDN egress filtering gateway blocks traffic after adding whitelisting tags to the egress filtering gateway. 6.4.2783 (07/15/2021) ===================== - **Bug fix** This issue is related to our smallest supported instance size in AWS which is t2.micro. In 6.4 the t2.micro instances were under additional memory pressure because of new services enabled in 6.4. As a result, some customers may experience gateway down events after upgrading to 6.4. This issue resolves those issues by optimizing several scheduled jobs which burden the t2.micro appliances. - **Enhancement** In order to alleviate memory pressure on our smallest supported AWS instance size; t2.micro, we now enable swap memory on instances with less than 1G of memory. This allows short periods of over-provision to be tolerated by the operating system ensuring continuous operations. R6.4.2776 (07/13/2021) ======================== .. note:: - If upgrading from 6.3 to 6.4, please make sure to upgrade the image to 6.3 latest first before upgrading it to release 6.4. - Starting 6.4, Standalone CloudN no longer support HPE over Internet - **Bug fix** NAT rule is missing after replacing a gateway with and S2C mapped tunnel. - **Bug fix** When an S2C mapped tunnel route is modified the old iptable entry is not removed. - **Bug fix** HA Controller restorations partially fail when DataDog API is integrated. - **Bug fix** In Azure clouds the Controller does not deploy more than one firewall instance in the same availability set as the Controller. - **Bug fix** False license expiration alerts can be sent to subscribers. - **Bug fix** When adding a FireNet instance to the routing path, the default value of the "Attach" flag should be "false". - **Bug fix** In some implementations, the firewall does not block traffic to subdomains of domains that are on the whitelist. - **Bug fix** The RBAC permissions for Site2cloud configuration download are not correct. - **Bug fix** Failed to attach HPE Spoke to Transit due to route already exists error. - **Bug fix** Controller unable to push RFC-1918 route to Panorama. - **Bug fix** Azure Peering UI filter not working. - **Bug fix** Unable to enter User VPN filter content fields on the Controller dashboard. - **Enhancement** Reduced memory consumption for BGP event monitoring process and other processes. - **Enhancement** Improved reliability by requiring the OVPN file to use the Global Accelerator DNS name to resolve to the 2 static IP addresses of the accelerator. - **Enhancement** Allow changes to the MTU setting in the Aviatrix OVPN client during runtime. - **Enhancement** Shortened execution time and memory usage for removing list_vpc and list_saml_info users. - **Enhancement** Allow the same PSK to be used for primary and backup Aviatrix gateways based on S2C tunnel policy. - **Enhancement** Allow use of colon in tags. R6.4.2674 (06/26/2021) ======================== - **Bug fix** In AWS and Azure clouds, gateway and FireNet tag keys and values do not support the colon (:) and other special characters. - **Bug fix** Added support for Azure Controller Security Group Management allowing the Network Security Group and the Azure Controller to use different Resource Groups. - **Bug fix** Added support for Multiple Dynamic SAML Profile attributes for controller login in list format. - **Bug fix** Added size suggestions for deploying ActiveMesh Insane Mode gateway instances in Azure India regions. - **Bug fix** Transit list page displays exceptions during gateway deployment. R6.4.2672 (06/11/2021) ======================== - **Bug fix** Gateway FQDN logs fail to download resulting in an error message. - **Bug fix** Availability Domain and Fault Domain not available in OCI gateway and firewall instances. - **Bug fix** Terraform bug fix, cannot delete all gateway tags. - **Bug fix** SNAT cannot be disabled on Azure Spoke Gateway. - **Bug fix** OCI Gateways deployed with Active Mesh are not being deployed in separate Availability Domains. - **Bug fix** CAAG OCI, OCI tunnels missing after replacing the OCI Transit Gateway - **Bug fix** Aviatrix Controller in Azure unable to push RFC-1918 route to Panorama in OCI. - **Bug fix** Intermittent connectivity issues from CoPilot to Controller. - **Bug fix** Enabling FQDN Discovery fails, some configuration changes are not removed, and the network connection breaks. - **Bug fix** Upgrade fails when upgrades from 6.3 to 6.4 using the upgrade to latest release feature. - **Bug fix** Cannot add certificates to LDAP configuration, error C:\fakepath\user.crt does not exist. - **Enhancement** Aviatrix Controller blocks multiple simultaneous logins from one account. R6.4.2618 (05/30/2021) ======================== .. note:: Customers using Azure Controller Release 6.3 and managed CloudN, should hold off upgrading Controller with CloudN to 6.4 until next 6.4-patch - **Bug fix** Enabling segmentation caused some routes missing in the spoke routing table - **Bug fix** Fixed exception for SAML VPN connection. - **Bug fix** In Ali Cloud, Transit Gateway showed all connections down. - **Bug fix** In some corner cases Controller HA, backup/restore broke the control connection between the controller and CloudN. - **Bug fix** Fixed exception when downloading the OCI OVPN file. - **Bug fix** Fixed Managed CloudN exception during registration. - **Enhancement** In IAM policy, enable parallel role swapping after role name change. R6.4.2561 (05/18/2021) ======================== .. note:: Customers should hold off upgrading Controller with CloudN to 6.4 until next 6.4-patch - **Bug fix** When FQDN gateways deployed in HA topologies have private route tables with the IAM deny policy applied, the default route restoration fails when the FQDN feature is disabled. Default route restoration only works only in non-HA topologies. - **Bug fix** In the Alibaba cloud, after running for a while BGP sessions on the IPSEC tunnel can go down at random. - **Bug fix** When using insane mode over the internet, missing Elastic IP addresses can cause some tunnels not to come up. - **Bug fix** When a new Transit Gateway for FireNet is launched on Azure, a false notification indicating that interface eth1 is down and needs to be restarted manually is sent. - **Bug fix** Disconnecting last BGP connection does not clear the IP prefix configuration. - **Bug fix** When a new best path is selected, old routes are deleted causing traffic interruptions. - **Bug fix** In GCP, when FireNet and FQDN Filtering are enabled the gateway is no longer associated with the existing instance group after the gateway is replaced. - **Bug fix** Deleting then recreating transit peering connections blocks some tunnels from delivering traffic. - **Bug fix** In GCP, after a NIC connection goes down the gateway fails to restart. - **Bug fix** Route updates can take excessive time after upgrading to 6.4. - **Bug fix** Unable to attach OCI Spoke Gateway to OCI Transit Gateway after upgrading to 6.4. - **Bug fix** When a spoke is attached to an egress IP, the skip public route table update operation is not working. - **Bug fix** Some gateways may not be upgraded during the 6.4 upgrade process. - **Bug fix** When FQDN gateways deployed in HA topologies have private route tables with the IAM deny policy applied, the default route restoration fails when the FQDN feature is disabled. Default route restoration only works only in non-HA topologies. - **Bug fix** Block creating a global network from AWS China controllers. - **Bug fix** In Alibaba clouds, after deleting a Transit Gateway you may find invalid paths to certificates. - **Bug fix** Enable the custom Gateway IAM role feature for AWS China and Government clouds through the API. R6.4.2499 (05/10/2021) ======================== 1. Multi-Cloud Transit Network -------------------------------- - **Alibaba Cloud Support** expands the Aviatrix Multi-Cloud Transit solution to support the Alibaba Cloud. This includes support for Ali Global and Ali China region. For more information, check out `Alibaba Cloud Account Credential Setup <https://docs.aviatrix.com/HowTos/aviatrix_account_alibaba.html>`_ - **China Multi-Cloud Network Architecture Support** expands the Aviatrix Multi-Cloud Transit solution to AWS, Azure, and Alibaba public clouds in China regions. For more information, check out `Aviatrix China Overview <https://docs.aviatrix.com/HowTos/aviatrix_china_overview.html>`_. Support includes: * Aviatrix Controller image and CoPilot image in AWS China Marketplace. * Multi-Cloud Transit solution in AWS China, Azure China and Alibaba China regions. - **Multi-Tier Transit** supports the hierarchical Multi-Cloud Transit Gateway deployment model, and adds the ability to traverse more than two Aviatrix Multi-Cloud Transit Gateways. This feature improves operational simplicity by aggregating multiple Aviatrix Transits. One use case is centralized firewall design for multiple Aviatrix-Transits in a single region, which allows in-region traffic without any inspection. To configure Multi-Tier Transit, go to Multi-cloud Transit -> Advance Config. Select the Transit Gateway and enable the Multi-Tier Transit feature. For more information, refer to `Multi-Tier Transit doc <https://docs.aviatrix.com/HowTos/transit_advanced.html#multi-tier-transit>`_ - **Transit Peering Insane Mode Support over Public Network** provides high performance Transit Gateway peering to multi-cloud networks with public network connectivity between AWS and Azure only. To configure Insane Mode over public networks, go to Multi-cloud Transit -> Transit Peering -> +Add New. Select the option Insane mode over Internet for a new peering connection. For more information, refer to `Peering over Public Network or Internet doc <https://docs.aviatrix.com/HowTos/transit_gateway_peering.html#peering-over-public-network-or-internet>`_ - **OCI Transit Insane Mode Support** expands our Insane Mode Encryption Service to OCI networks. The support includes Insane Mode for VCN to VCN encrypted peering and Transit Peering connections. Launch an OCI gateway with Insane Mode enabled to get started. For more information, refer to `OCI Performance Test Results <https://docs.aviatrix.com/HowTos/insane_mode_perf.html#oci-performance-test-results>`_ - **IAM Role and Policy for Gateways** separate IAM policy for Aviatrix gateway. API support only. - **BGP Connection Holdtime** can now be modified through the Aviatrix Controller. One use case of modifying BGP Hold Timer is to have a quicker BGP failover time. For more information, refer to `BGP Hold Time doc <https://docs.aviatrix.com/HowTos/transit_advanced.html#bgp-hold-time>`_ 2. FireNet ------------- - **Aviatrix Transit FireNet for OCI** allows you to deploy firewall instances in OCI. The OCI FireNet can be used for East-West, North-South and Ingress-Egress inspection with Palo Alto Networks VM-Series only. For more information, check out `Transit FireNet Workflow for OCI <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_oci.html>`_ and `Example Config for Palo Alto Network VM-Series in OCI <https://docs.aviatrix.com/HowTos/config_paloaltoOCI.html>`_. - **FireNet Fortinet Integration Enhancement** now supports Fortinet firewall integration with the Aviatrix Transit FireNet solution. This integration allows automatic route updates in Fortigate routing tables by the Aviatrix Controller. You no longer need to statically configure RFC 1918 or any other routes in Fortigate. This integration is supported for AWS, Azure, and GCP Public clouds only. For more information, check out `Transit FireNet Workflow for AWS, Azure, GCP, and OCI <https://docs.aviatrix.com/HowTos/transit_firenet_workflow.html>`_ - **Check Point CloudGuard in GCP** is now available when deploying Aviatrix Transit FireNet. Refer to this example `CheckPoint workflow in GCP <https://docs.aviatrix.com/HowTos/transit_firenet_workflow.html#transit-firenet-workflow-for-aws-azure-and-gcp>`_ for more details. - **Fortinet Fortigate for GCP** is now available in GCP when deploying Aviatrix Transit FireNet. - **Custom AMI Support for Firewall Instances** allows customer to launch the special images provided by firewall vendors. API support only. 3. Site2Cloud --------------- - **Dynamic routes update for Site2Cloud Connections** adds the capability to auto advertise or remove the remote subnet automatically based on the Up/Down status of the Site2Cloud tunnel. To configure dynamic routes for Site2Cloud, go to Multi-Cloud Transit -> List -> Spoke -> Select Spoke Gateway and click "Auto Advertise Spoke S2C CIDRs" to enable dynamic routes. For more information, refer to `Auto Advertise Spoke Site2Cloud CIDRs doc <https://docs.aviatrix.com/HowTos/transit_list.html#auto-advertise-spoke-site2cloud-cidrs>`_ - **Site2Cloud Single Public IP Failover Support** enhances the HA mechanism to use a single public IP address and single tunnel from the remote site (on-prem) point of view. To configure Site2Cloud Single Public IP Failover, go to Site2Cloud -> Add New -> Enable HA. Check the box to Enable Single IP HA to activate Single Public IP Failover. This applies to AWS and Azure only. For more information, refer to `Site2Cloud IPSec VPN Instructions <https://docs.aviatrix.com/HowTos/site2cloud.html>`_ - **Jumbo Frame Support** adds the ability to turn on/off Insane Mode jumbo frame support for the Site2Cloud tunnel between the Aviatrix Transit Gateway and CloudN. To enable jumbo frame support, go to Site2Cloud -> Select Site2Cloud connection to CloudN. Click Edit and enable jumbo frame support. For more information, refer to `Jumbo Frame doc <https://docs.aviatrix.com/HowTos/site2cloud.html#jumbo-frame>`_ 4. Security --------------- - **Egress FQDN Enhancement** is now supported for multiple Egress FQDN gateways in GCP. This feature includes support for GCP Shared VPC as well as Distributed and Centralized Egress for FQDNs. 5. Operations ----------------- - **Create a VPC Enhancement** adds an option in "Create a VPC" to select an existing Resource Group for Azure under Advanced options. - **Co-Pilot integration with Controller** delivers the operational simplicity you need by presenting Aviatrix Controller as a single-pane of glass for managing the Day 0, Day 1 and Day 2 operations of the cloud fabric. The integration with Co-Pilot brings additional capabilities including the SAML and DUO integration, and RBAC control. To configure the CoPilot Controller integration, log into the Aviatrix Controller console and go to Settings -> CoPilot -> Enable CoPilot Association to integrate CoPilot with Aviatrix Controller. For more information, refer to `CoPilot doc <https://docs.aviatrix.com/HowTos/Settings_CoPilot.html>`_ - **Performance and Scalability Improvements** Significant performance improvements for the Aviatrix Multi-Cloud Network Architecture (MCNA) especially for a very large enterprise networks. - **Route Table Optimization** allows customer to skip public route table programming. This is supported in AWS only. For more information, refer to `Transit List doc <https://docs.aviatrix.com/HowTos/transit_list.html>`_ - **Notification Enable/Disable Option** gives an ability to customers to disable exception emails send to Aviatrix. For more information, refer to `How to not send exception notification to Aviatrix doc <https://docs.aviatrix.com/HowTos/alert_and_email.html#how-to-not-send-exception-notification-to-aviatrix>`_ 6. Behavior Change Notice -------------------------- - Aviatrix is setting the public IP address of a peer device as the default remote identifier for an S2C connection. If the peer device uses its private IP address as the local identifier, the user needs to manually update the private IP of the peer device to use the remote identifier. In the Aviatrix Controller, go to the Aviatrix S2C page -> Edit connection -> Remote Identifier and update the private IP of the peer device to use the remote identifier. - The API "get_transit_or_spoke_gateway_details" result format changed. - Two CaaG can't have the same public IP, e.g. mgmt interface behind the same NAT gateway. 7. Before you Upgrade -------------------------- - Gateway FQDN names (gateway_name + aviatrixnetwork.com) longer than 64 characters will prevent gateways from booting up correctly. - Standalone CloudN cannot be upgrade to 6.4. - Please review the latest field notices (FN#22 - 28), and take a recommended action for any `field notices <https://docs.aviatrix.com/HowTos/field_notices.html>`_ applicable to your environment. - Aviatrix released new gateway and Controller images/AMIs for AWS and Azure. R6.3.2475 (05/22/2021) ======================= - **End of life** Gateway images based on old opensource OS versions deprecated. You MUST replace these with new opensource OS version images before upgrading to 6.4. Refer to FN28 for more details. - **Bug fix** Fixed exception for OCI gateway launch. - **Bug fix** Fixed bug in GCP FireNet with Palo Alto VM-Series image version listing. - **Bug fix** In some corner cases Controller HA, backup/restore breaks the control connection between the controller and CloudN. - **Bug fix** Fixed an issue with BGP route advertisement after spoke attachment - **Bug fix** When a gateway NIC goes down, an alert will be triggered and the gateway will be taken down and brought back up again after self-remediation. - **Bug Fix** If a VNet route table is deleted unexpectedly, VNets could connect to the wrong Transit Gateway spoke for the subscription. When VNets under different subscriptions use the same Resource group name, and both Spoke VNets connect to different Transit Gateways, the controller cannot distinguish which VNet should attach to which gateway. R6.3.2415 (04/19/2021) ======================= - **Co-Pilot integration with Controller** delivers operational simplicity by presenting Aviatrix Controller and CoPilot in a single pane of glass for managing the Day 0, Day 1 and Day 2 operations of the cloud fabric. The Aviatrix Controller integration with Co-Pilot adds capabilities to the Controller including SAML and DUO integration, and RBAC control. To configure the CoPilot Controller integration, log into the Aviatrix Controller console and go to Settings -> CoPilot -> Enable CoPilot Association to integrate CoPilot with Aviatrix Controller. - **Enhancement** Improved CloudN to controller reachability mechanism for public and private subnets. - **Enhancement** Improved error handling for Aviatrix Controller HA process. - **Bug fix** Fixed the backup restoration API response for Aviatrix Controller HA mechanism. - **Bug fix** Blocked the exclude CIDR feature for Native GWLB FireNet. - **Bug fix** Fixed exception for Site2Cloud remote subnet modifications. - **Bug fix** Corrected invalid netflow data sent to CoPilot. - **Bug fix** Fixed GCP security rule for Site2Cloud over private IP. - **Bug fix** Corrected route table programming for native GWLB. - **Bug fix** Fixed gateway creation issue when customized IAM policy is used in AWS. - **Bug fix** Fixed default route restoration for FQDN when discovery is disabled. - **Bug fix** Improved error messages for native GWLB egress. - **Bug fix** Allowed ActiveMesh 2.0 migration without disabling Transit FireNet for older releases. R6.3.2364 (03/18/2021) ======================= - **Aviatrix Transit FireNet for GCP** allows you to deploy firewall instances in GCP. For more information, check out `Transit FireNet Workflow <https://docs.aviatrix.com/HowTos/transit_firenet_workflow.html#transit-firenet-workflow-for-aws-azure-and-gcp>`_. - **Segmentation Enhancement** Add the Multi-Cloud Transit segmentation support for CloudN - **Site2Cloud Enhancement** Clear Session option is added in Site2Cloud connection to clear the active connection sessions running through Aviatrix gateways. - **Multi-Cloud Transit Enhancement** New capability to attach managed CloudN with Multi-Cloud Aviatrix Transit without High Performance Encryption (HPE) for Oracle cloud only. - **FlightPath Enhancement** Add support for IP address as a source - **TGW Enhancement** Add support for AWS TGW connect - **Bug fix** Enhanced AWS ENA conntrack data into the syslog - **Bug fix** Improve the route programming mechanism for Spoke VPC to filter the customize CIDRs first before installing into the Spoke VPC route table. - **Bug fix** Fix the Dashboard status display issue for BGP over LAN. - **Bug fix** Fix the Aviatrix Gateways "Polling" status after Controller Backup & Restore and IP migration - **Bug fix** Add the missing parameters in template for "Export to Terraform" feature - **Bug fix** Fix exception for CloudN registration after controller migration. R6.3.2247 (03/01/2021) ======================= - **Bug fix** Race condition causing exception for Aviatrix Transit Gateway peering. - **Bug fix** Fix the TGW attachment deletion issue when customize IAM policy is used in AWS. - **Bug fix** Fix the Site2Cloud diagnostics display issue. - **Bug fix** Missing "Aviatrix-Created-Resource" tag for Aviatrix Gateway keypair in AWS. - **Bug fix** Fix exception for CloudN when eth0 is down. R6.3.2216 (2/22/2021) ======================= - **Enhancement** Significant improvements in failover time through a series of optimization for overlapping networks. - **Enhancement** Add Clear Session capability in Site2Cloud connection to clear all the conntrack sessions entry. - **Enhancement** Add the Active-Standby mode on ActiveMesh 2.0 support for BGP over LAN scenario. - **Enhancement** Add API support to unify programming RFC1918 routes in native egress domain - **Enhancement** New capability to split sending gateway metrics and syslog to different log management systems - **Bug fix** Allow more than 16 network CIDRs in the Site2Cloud configuration. - **Bug fix** Address Route programming failure in OCI VCN route entry in Site2Cloud configuration. - **Bug fix** Unable to launch Palo Alto VM-Series in AWS GovCloud. - **Bug fix** Revert check introduced in 6.3.2092 for ActiveMesh 2.0 that blocks the Aviatrix Transit Peering if ASN# for Aviatrix Transit Gateways are same or not set. - **Bug fix** Fix the long security domain names display issue in Aviatrix Controller. - **Bug fix** Fix exception when using "Export to Terraform" feature for fqdn_tag_rule. - **Bug fix** Fix the route propagation for HPE Aviatrix Transit Gateway eth0 in Azure. - **Bug fix** Update RFC1918 routes in OCI VCN for non-default security list. - **Bug fix** Fix the default route entry removal issue when "Use VPC/VNET DNS Server" feature in-use. - **Bug fix** Security patch for SAML vulnerability R6.3.2092 (1/31/2021) ======================= 1. Multi-Cloud Transit Network -------------------------------- - **Transit in Azure with Express Route** allows you to build an Aviatrix Transit and Transit FireNet solutions while leveraging the native Azure Express Route for on-prem to cloud connectivity and route propagation. One use case is to deploy in an environment where encryption between data center and cloud is not required but using native high performance Express Route is required. Both native Spoke VNet and Aviatrix Spoke Gateways are supported as Spoke attachment. For configuration workflow, follow the `Multi-cloud Transit Integration with Azure Expressroute workflow <https://docs.aviatrix.com/HowTos/integrate_transit_gateway_with_expressroute.html>`_. - **Transit BGP over GRE Tunnel** provides an alternative tunneling protocol to IPSec when connecting Aviatrix Transit Gateway to on-prem. One use case is for an organization that requires high performance but not encryption. With GRE tunneling, Multi-cloud Transit Gateways in AWS connects with on-prem network devices without deploying Aviatrix CloudN appliances. Only available in AWS (Azure and GCP do not support GRE). For configuration information, refer to `Aviatrix Transit Gateway to External Devices <https://docs.aviatrix.com/HowTos/transitgw_external.html#how-to-configure>`_. For end-to-end configuration workflow and performance benchmark, refer to `GRE Tunneling workflow <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_gre_high_performance_workflow.html>`_. - **Transit BGP to LAN** allows Aviatrix Transit Gateways to communicate with other instances in the same VPC or VNet without running any tunneling protocol. One use case is to interoperate with cloud virtual appliances such as a SD-WAN cloud gateway instances that do not have the capability to support BGP over IPSec or GRE protocols. For configuration and performance information, refer to `BGP over LAN in AWS Workflow <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_workflow.html>`_. For Azure, refer to `BGP over LAN in Azure Workflow <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_lan_azure_workflow.html>`_. - **Manual Advertise Routes per BGP Connection** expands the existing gateway based manual advertising routes feature to apply it to each BGP connection. One use case is to have better route advertising control for each remote BGP peer. For configuration details, refer to `Connection Base Manual BGP Advertisement <https://docs.aviatrix.com/HowTos/transit_advanced.html#connection-manual-bgp-advertised-network-list>`_. - **Transit Approval per BGP Connection** expands the existing Aviatrix Transit Gateway based Transit Approval feature to apply it to each on-prem BGP connection for fine grain control of network CIDRs admitted to the cloud network. To configure, go to Multi-cloud Transit -> Approval. Select a Transit Gateway, select Mode Connection and select a connection, enable Learned CIDRs Approval. For more information, refer to `Transit Approval <https://docs.aviatrix.com/HowTos/transit_approval.html>`_. - **Private Transit Gateway Peering with Single-Tunnel Mode** expands the existing Insane Mode Transit Gateway Peering Over Private Network to apply it to single IPSec tunnel. One use case is for low speed encryption between cloud networks (up to 4Gbps). For more information, refer to `Transit Peering in Single-Tunnel mode. <https://docs.aviatrix.com/HowTos/transit_gateway_peering.html#single-tunnel-mode>`_. - **Transit to External Device Using IKEv2** provides an option to run IKEv2 with the on-prem site. For more information, refer to `Aviatrix Transit Gateway to External Devices <https://docs.aviatrix.com/HowTos/transitgw_external.html>`_. - **Client Proxy** allow both the Controller and Aviatrix gateways to use external proxy server for Internet facing API access. One use case is to satisfy compliance requirements where all traffic destined to Internet is required to go through a proxy server. For configuration information, refer to `proxy configuration <https://docs.aviatrix.com/HowTos/advanced_config.html#proxy>`_. - **Improve AWS t3 instances IPSec performance** to up to 6Gbps (MTU 1500 Bytes) for Multi-cloud Transit and Spoke Gateway without additional license charge. The mechanism is to allow Insane Mode to be applied the t3 series without charging the Insane Mode license. For performance details on t3 series, refer to `t3 series Insane Mode performance <https://docs.aviatrix.com/HowTos/insane_mode_perf.html#t3-instance-series-performance>`_. - **Support N2 and C2 instance types on GCP gateways** improves Insane Mode performance on GCP cloud. For new network throughput with these new instance types, refer to `GCP Insane Mode Performance. <https://docs.aviatrix.com/HowTos/insane_mode_perf.html#gcp-performance-test-results>`_ - **Managed CloudN Appliance** supports in GCP. Refer to `Managed CloudN workflow <https://docs.aviatrix.com/HowTos/CloudN_workflow.html>`_. - **License Info** license change to inter-cloud for Aviatrix Transit to AWS VGW connection. 2. FireNet ============= - **FireNet integration with AWS Gateway Load Balancer** provides the capability where adding or removing a firewall to the FireNet does not impact the existing established network sessions. AWS Gateway Load Balancer (GWLB) integration is supported for both TGW based FireNet and Multi-cloud Transit FireNet. For configuration details on TGW based FireNet without Aviatrix FireNet gateways, refer to `Native AWS GWLB Integration <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#b-enable-native-aws-gwlb-for-firenet-function>`_. For configuration details on TGW based FireNet with Aviatrix FireNet gateways, refer to `FireNet with GWLB <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#a-enable-the-aviatrix-gateway-for-firenet-function>`_. For Multi-cloud Transit FireNet GWLB integration, refer to `Enable Transit FireNet <https://docs.aviatrix.com/HowTos/transit_firenet_workflow.html#a-enable-transit-firenet-on-aviatrix-transit-gateway>`_. 3. User VPN ============= - **Download Aviatrix SAML VPN Client from Controller** provides self-service ability for organizations to download Aviatrix SAML VPN Client software from the Controller directly for SAML authenticated users. This simplifies administration for on-boarding new VPN users. To enable, go to OpenVPN -> Advanced -> Global Config -> Download SAML VPN Client to enable. For more information, refer to `Self Service Download SAML Client <https://docs.aviatrix.com/HowTos/openvpn_faq.html#what-is-download-saml-vpn-client>`_. 4. Site2Cloud ============= - **Route based IPSEC with IKEv2** provides an option to run route-based VPN with IKEv2. For more information, refer to `Create Site2Cloud Connection <https://docs.aviatrix.com/HowTos/site2cloud.html#create-site2cloud-connection>`_. - **Change Local Identifier** provides the flexibility to update either gateway's public IP address or private IP address as local identifier. To configure, refer to `Local Identifier <https://docs.aviatrix.com/HowTos/site2cloud.html#local-identifier>`_. - **DPD Parameters** can now be modified through the Controller User Interface in additional to API and Terraform. One use case of modifying DPD parameters is to reduce tunnel failure detection time. To configure, refer to `DPD Configuration <https://docs.aviatrix.com/HowTos/site2cloud.html#dead-peer-detection>`_. - **Event Trigger** is a new mechanism to reduce failure detection time. This is an alternative to the default setting where tunnel status change is detected by a periodic monitoring process running on the gateways. To configure, refer to `Event Triggered HA <https://docs.aviatrix.com/HowTos/site2cloud.html#event-triggered-ha>`_. - **Failover Time Reduction for Overlapping Networks** Significant improvements in failover time reduction through a series of optimization. Refer to `Tuning For Sub-10 Seconds Failover Time in Overlapping Networks. <https://docs.aviatrix.com/HowTos/s2c_overlapping_cidrs_with_fast_convergence.html>`_. 5. Security ============== - **Reduce Email API Blocking** is an enhancement for non HTTP/HTTPS traffic configured on a FQDN gateway where a set of large site's well known IP addresses are pre-populated to the FQDN gateways, thus significantly reducing the probability that applications still cannot make API calls (mostly email services) even though the FQDN rules for these sites are configured. The set of sites are: gmail.com, hotmail.com, microsoft.com, live.com, outlook.com, office.com ad office365.com. The applicable TCP ports are: 25, 465, 587, 143, 993 and 995. - **Edit Stateful Firewall Rules Enhancement** simplifies editing and viewing IP address based stateful firewall rules, allowing large set of rules to be managed easily. To configure, go to Security -> Stateful Firewall -> Policy to edit policies. R6.2.2016 (2/18/2021) ======================= - **Bug fix** Security patch for SAML Vulnerability. R6.2.2003 (2/15/2021) ======================= - **Enhancement** Add API support to turn off Jumbo frame support. - **Bug fix** Allow more than 16 network CIDRs in the Site2Cloud configuration. - **Bug fix** Route programming failure in OCI VCN route entry. - **Bug fix** Unable to launch Palo Alto VM-Series in AWS GovCloud. R6.2.1955 (1/16/2021) ====================== - **Bug fix** GCP Spoke Gateway with SNAT configuration propagates route incorrectly. - **Enhancement** Optimize Spoke Gateway attach/detach functions when "Customize VPC Route table" feature is enabled. - **Enhancement** Improve email authentication mechanism for emails generated by Controller. - **Enhancement** Optimize Multi-cloud transit network failover time. - **Bug fix** Unable to launch Palo Alto VM-Series with version 9.x - **Bug fix** GCP Controller backup and restore fails. R6.2.1925 (12/12/2020) ======================== - **Enhancement** Execute all Azure Spoke VNet programming in parallel. The scope of the enhancement includes individual route entry update and multiple VNet route tables update. The result is a significant reduction in Spoke attachment time and certain failover convergence time. - **Enhancement** Improve Controller daemon process robustness. R6.2.1914 (12/04/2020) ======================== - **Bug fix** Not able to detach a native Spoke VNet when its resource group is deleted on Azure console. - **Bug fix** FQDN crashes when the number of FQDN rules exceed 1000. - **Enhancement** Increase the number of FQDN rules to 1500. R6.2.1891 (11/20/2020) ======================== - **Bug fix** OCI Spoke VCN default route tables not programmed correctly. - **Bug fix** After removing Spoke FQDN, Spoke Gateway route table entries are missing. - **Enhancement** Reduce excessive logging on Controller. - **Enhancement** Add new regions to OCI. - **Enhancement** Performance enhancement when interoperating with Copilot. - **License Info** Site2Cloud license change to inter-cloud for Aviatrix Transit to AWS VGW connection. R6.2.1837 (11/10/2020) ======================= - **Enhancement** Add conntrack_count to syslog. - **Enhancement** FireNet LAN interface keep alive is enhancement with follow up TCP keep alive packets when ICMP ping fails, making the firewall detection more robust. Customer needs to open TCP port 443 from the gateway eth2 IP for this to take effect. No additional configuration required. - **Enhancement** New AWS gateway AMI "hvm-cloudx-aws-102320" with the latest AWS SR-IOV device driver enhancement. - **Bug fix** FQDN feature not working when ports are selected as all. - **Enhancement** on interoperating with co-pilot. - **Enhancement** Add disaster debugging capability when the Controller Apache daemon process fail to start. R6.2.1742 (10/15/2020) ======================== 1. Multi-cloud Transit Network --------------------------------- - **Active-Standby Mode on ActiveMesh 2.0** provides the flexibility on Aviatrix Transit Gateways to connect to on-prem with only one active tunnel and the other one as backup. The use case is a deployment scenario where on-prem device such as firewalls does not support asymmetric routing on two tunnels. When Active-Standby mode is enabled, it applies to both BGP and Static Remote Route Based `External Device Connections <https://docs.aviatrix.com/HowTos/transitgw_external.html>`_ and for each connection, only one tunnel is active in forwarding traffic at any given time. To configure, go to Multi-cloud Transit -> Advanced Config, select the Aviatrix Transit Gateway to enable Active-Standby. For more information, refer to `Active-Standby <https://docs.aviatrix.com/HowTos/transit_advanced.html#active-standby>`_. - **Segmentation based BGP CIDRs Advertisements** advertises only those Spoke CIDRs that have connection policy to a specific on-prem connection. For example, consider a multi-tenant deployment where Aviatrix Transit Gateway connects to multiple on-prem sites over BGP, each site connecting to a set of Spokes through `AWS TGW Edge Segmentation <https://docs.aviatrix.com/HowTos/tgw_faq.html#what-is-edge-segmentation>`_ or `Multi-cloud Segmentation <https://docs.aviatrix.com/HowTos/transit_segmentation_faq.html#what-is-multi-cloud-transit-segmentation>`_. With this new feature, Aviatrix Transit Gateway only advertises Spoke CIDRs that are relevant to the on-prem site. This behavior is enabled as the default when launching a new Transit Gateway. For existing deployment, you can enable it by going to Multi-cloud Transit -> Advanced Config, select an Aviatrix Transit Gateway, scroll down to `Refresh BGP Advertise Network Routes`. - **Multi-cloud Transit Gateway Peering over Private Network** expands Transit Gateway peering over multi-cloud where there is private network connectivity cross cloud. One use case is two Aviatrix Transit Gateways deployed in two different public cloud where each has its private connectivity such as AWS Direct Connect and Azure Express Route connecting to on-prem or a co-location. By building a high performance Transit Gateway private peering, Aviatrix Transit Gateway forwards traffic over the private links to the other Aviatrix Transit Gateway and beyond with encryption for data in motion. To configure, go to Multi-cloud Transit -> Transit Peering -> +Add New. Select the option Peering over Private Network for a new peering connection. For an example configuration, refer to `Multi-cloud Transit Peering over Private Networks <https://docs.aviatrix.com/HowTos/transit_gateway_peering_with_private_network_workflow.html>`_. - **Insane Mode in GCP** is now available for Multi-cloud Transit solution. For performance benchmark, refer to `GCP Insane Mode performance test results <https://docs.aviatrix.com/HowTos/insane_mode_perf.html#gcp-performance-test-results>`_. Insane Mode is enabled when launching a new Aviatrix Transit Gateway or Spoke Gateway in GCP. - **Managed CloudN Appliance** simplifies CloudN configuration and operation by allowing it to be managed by the Controller. Active-Active deployment model supports up to 25Gbps encryption performance. Refer to `Managed CloudN workflow <https://docs.aviatrix.com/HowTos/CloudN_workflow.html>`_. GCP support is in the future release. - **Custom Mapped Site2Cloud in Spoke** solves all issues of overlapping network addresses with remote networks by expanding Site2Cloud `Mapped <https://docs.aviatrix.com/HowTos/site2cloud.html#connection-type-mapped>`_ function in a Spoke. - **TGW with Multicast capability** allows you to launch an AWS TGW with multicast capability. A use case is to support applications running on multicast protocols. API support only. - **Update Attached Spoke VNet CIDR** allows you to update Spoke VNet CIDR when there is a change without having to detach the Spoke and attach again, thus removing any down time or outage. API support only. - **Default Tagging in Azure** adds Aviatrix default tag when Controller creates resources such as launching an Aviatrix gateway, create route entries, load balancer and route tables. - **Enhancement in Creating a VNet** defines public and private subnets and their associated route tables. This helps clarify how Aviatrix Controller manages route table and their programming. For details, refer to `Aviatrix Default Route Handling <https://docs.aviatrix.com/HowTos/default_route_faq.html>`_. - **Default Routing Handling** enforces rules on how Aviatrix Controller handles the propagation and programming of cloud networks. Specifically the Controller only overwrite the default route on private subnets. For details, refer to `Aviatrix Default Route Handling <https://docs.aviatrix.com/HowTos/default_route_faq.html>`_. 2. FireNet ------------- - **FireNet 2-tuple Forwarding Algorithm Support** expands FireNet forwarding algorithm to include forwarding decision based on only the source and destination IP address. One use case is to support an application where multiple TCP sessions are used for an egress Internet service therefore requiring all sessions to go through one firewall with the same source NAT IP address. To configure, go to Firewall Network -> Advanced. Select the FireNet gateway, click the 3 dots skewer, scroll down to Firewall Forwarding, select 2-Tuple. For more information, refer to `Firewall Forwarding Algorithms <https://docs.aviatrix.com/HowTos/firewall_advanced.html#firewall-hashing>`_. - **Centralized FQDN on Azure FireNet** allows Aviatrix FQDN gateways to be deployed in FireNet solution in Azure. One use case is to consolidate egress control to reduce cost with centralized statistical multiplexing. To configure, go to Firewall Network -> Setup -> 7c. For more information, refer to `Launch & Associate Aviatrix FQDN gateway <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#c-launch-associate-aviatrix-fqdn-gateway>`_. - **Bootstrap support in Azure FireNet on Palo Alto Networks VM-Series, Check Point and FortiGate** simplifies FireNet deployment in Azure. For details, refer to `VM-Series bootstrap in Azure <https://docs.aviatrix.com/HowTos/pan_bootstrap_example_azure.html>`_, `Check Point bootstrap in Azure <https://docs.aviatrix.com/HowTos/checkpoint_bootstrap_azure.html>`_ and `FortiGate bootstrap in Azure <https://docs.aviatrix.com/HowTos/fortigate_bootstrap_example_azure.html>`_. - **Bootstrap support in AWS FireNet on Check Point and FortiGate** simplifies FireNet deployment in AWS. For details, refer to `Check Point bootstrap in AWS <https://docs.aviatrix.com/HowTos/checkpoint_bootstrap_azure.html>`_ and `FortiGate bootstrap in AWS <https://docs.aviatrix.com/HowTos/fortigate_bootstrap_example.html>`_. 3. Operations ------------------ - **Discover Unencrypted Flows** is a useful tool to provide visibility on any non TCP port 443 and port 22 traffic running in a VPC in AWS. By running, recording and analyzing VPC flow logs in an on-demand fashion, this tool helps infrastructure engineers to understand application traffic patterns without cost incurring for long running VPC Flow Logs. By excluding TCP port 443 and port 22 traffic, the tool highlights any unencrypted traffic in the network. - **Session Visibility** displays active connection sessions running through Aviatrix gateways. This is useful for troubleshooting connectivity issue. To view sessions, go to Troubleshoot -> Diagnostics -> Gateway -> Session View. Or go to Security -> Stateful Firewall -> Session View. - **16,000,000 Max Connection Session Table Size** This improves the ability of Aviatrix gateways to handle the concurrent sessions going through the gateway. R6.1.1425 (11/9/2020) ========================= - **Bug fix** CloudN failover route selection is not based on best route algorithm. - **Bug fix** Retry when Controller DNS lookup fails intermittently. R6.1.1415 (10/25/2020) ======================== - **Enhancement** Increase the max connection session table size to 16,000,000. Also include connection track entry count in the gateway diagnostics information. R6.1.1409 (10/20/2020) ========================= - **Bug fix** FireNet VPC does not advertise its CIDR to on-prem when FireNet Management is enabled on the Aviatrix Edge Security Domain. - **Bug fix** Custom upgrade is broken. - **Bug fix** Site2Cloud Custom Mapped option becomes unavailable after upgrading. R6.1.1401 (10/4/2020) ====================== - **Bug fix** When attaching an Insane Mode Spoke Gateway to Transit Gateway, the action succeeds even though the underlying cloud provider peering (AWS PCX and Azure VNet Peering) fails. - **Bug fix** Controller does not update the egress default route when Spoke Gateways experience a failover. - **Bug fix** Enabling advertising transit CIDR breaks Azure transit network. - **Bug fix** Single AZ gateway replace function is broken. - **Enhancement** Improve IKEv2 compatibility with Cisco ASA when re-establishing a tunnel after it goes down without restarting the VPN service. - **Enhancement** Enable multi-core processing capability on the Controller to handle co-pilot queries. API support to enable/disable multi-core processing in case of failure. R6.1.1338 (9/24/2020) ====================== - **Bug fix** Aviatrix Transit connecting to external device with 2 different ASNs doesn't work properly - **Bug fix** TGW attaching sometimes fails due to RAM authentication timeout. - **Bug fix** Custom SNAT is not able to select eth0 on Aviatrix Transit Gateway. - **Bug fix** Cannot edit mapped tunnels built before 6.0 R6.1.1309 (9/7/2020) ====================== - **Gateway Rename feature removal** Gateway Rename feature has been removed from UI. - **Account Rename feature removal** Account Rename feature has been removed from UI. - **Enhancement** Consistent Login Banner when custom banner login is enabled. - **Enhancement** Enable multicast option when creating an AWS Transit Gateway (TGW). API support only. - **Bug fix** fix Insane Mode gateway replacement function bug. - **Bug fix** fix Transit Gateway Manual Summarize route bug. - **Bug fix** fix FireNet error programming firewall instances when they go through stop and start process. - **Bug fix** fix gateway launch tag attachment to ensure when a gateway is launched tag is part of the AWS API call. R6.1.1280 (8/17/2020) ======================= - **Bug fix** fix multiple issues with TGW Approval, TGW Peering inspection and FireNet integration. - **Bug fix** Transit Peering with SNAT creates redundant rules. - **Bug fix** FQDN with Edit Source behavior change. - **Enhancement** Add support for Aviatrix gateway certificate import. - **Bug fix** CloudN asymmetric routing for management interface. R6.1.1163 (8/5/2020) ===================== - **Bug fix** fix upgrade issue. R6.1.1162 (8/1/2020) ======================= 1. Multi-cloud Network -------------------------------- - **Scale out Firewalls in Azure FireNet** allows FireNet to support multiple firewall virtual machines in Azure. The use case is to support more than 2 firewall deployment to meet performance requirements. Only new FireNet gateways in Azure supports scale out firewall feature. Refer to `this document <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_azure.html>`_. - **Azure GovCloud** is now supported for both Controller and Aviatrix gateways. Controller can be launched from Azure GovCloud marketplace. Follow `Azure Startup Guide <https://docs.aviatrix.com/StartUpGuides/azure-aviatrix-cloud-controller-startup-guide.html>`_ to get started. - **Prepend ASN on BGP Connection** expands Prepend ASN to specific BGP connection. Previously the ASN prepend applies to the entire Aviatrix Transit Gateway, this feature brings the flexibility to prepend different ASN for different BGP connections. The use case is to provide more flexibility on the Aviatrix Transit Gateway to influence the next hop selection of the upstream BGP neighbour. To configure, go to Multi-Cloud Transit -> Advanced Config. Select an Aviatrix Transit Gateways, scroll down to Connection AS PATH Prepend, select a connection and enter one or more enter AS numbers separated by space. For more details, refer to `Connection AS PATH Prepend <https://docs.aviatrix.com/HowTos/transit_advanced.html#connection-as-path-prepend>`_. - **Multi-cloud Segmentation Enhancement** now handles egress default route in a consistent way by introducing individual route tables for each Security Domain on an Aviatrix Multi-cloud Transit Gateway. This release is not backward compatible to the implementation in Release 6.0. To migrate, `disable Multi-cloud Segmentation <https://docs.aviatrix.com/HowTos/transit_segmentation_workflow.html#disable-aviatrix-transit-gateway-for-segmentation>`_ on each Aviatrix Transit Gateway, upgrade to Release 6.1 and `enable <https://docs.aviatrix.com/HowTos/transit_segmentation_workflow.html#enable-aviatrix-transit-gateway-for-segmentation>`_ again. To learn more on deployment limitation, refer to `this link. <https://docs.aviatrix.com/HowTos/transit_segmentation_faq.html#what-is-the-limitation-of-segmentation>`_ - **FireNet Check Point Integration Enhancement** now support Check Point firewall or security gateway automatic route updates to its routing tables by the Controller. You no longer need to statically configure RFC 1918 or any other routes. - **FireNet for AWS TGW Inter Region Traffic Inspection** allows you to specifically inspect traffic crossing TGW Peering regions. One use case is in certain deployment, it is not desirable to specify all traffic going in and out of a Security Domain, rather the requirement is to only inspect traffic that moves across the regions. For configuration details, refer to `Inspect Inter Region Traffic <https://docs.aviatrix.com/HowTos/tgw_plan.html#inspect-inter-region-traffic>`_. 2. Security ---------------- - **Auto PrivateS3** significantly improves PrivateS3 usability and security by automatically retrieving S3 bucket names for PrivateS3 filtering. One use case is to support large set of S3 buckets owned by organizations without having to manually import into the Controller. The second use case is to prevent accidental or intentional manual input S3 buckets that are not owned by organization. For workflow, check out `PrivateS3 workflow <https://docs.aviatrix.com/HowTos/privateS3_workflow.html>`_. - **Subnets Pass-through** allows you to specify certain subnets in a VPC to bypass any FQDN filter rules. One use case is that certain subnets, for example, are for Dev environment, therefore does not require to be FQDN filtered or logged. To configure, go to Security -> Egress Control -> Egress FQDN Gateway View. Select a gateway, click Actions -> Edit Pass-through. Select subnet or multi select subnets to allow bypass the filter. For more details, refer to `FQDN Source Pass-through <https://docs.aviatrix.com/HowTos/fqdn_viewlog.html#edit-pass-through>`_. - **Exact Port Match** now applies to each FQDN rule. One use case is if you only specify an FQDN rule for TCP port 443, packets with the same FQDN rule for TCP port 80 are dropped unless you have the specific FQDN rule on TCP port 80. This is a bug fix, no configuration required. For more information, refer to `Exact Match <https://docs.aviatrix.com/HowTos/FQDN_Whitelists_Ref_Design.html#exact-match>`_. - **FQDN Option for Exact Match** is a new feature where if a FQDN rule does not have * an exact match is expected. If this global option is not enabled, FQDN rules use regex to match any FQDN names that are subset of the name. For example, if salesforce.com is a rule and Exact Match option is enabled, finance.salesforce.com is not a match and will be dropped. For configuration details, refer to `FQDN Exact Match <https://docs.aviatrix.com/HowTos/FQDN_Whitelists_Ref_Design.html#exact-match>`_. 3. Operations ----------------- - **Account Name Alias** allows you to change the account name after it is created by providing an alias name and allowing it to be modified at any given time. The use case is customers often need to change some account names after the network has been built out to certain scale. By allowing account name alias to be modified without having to delete the account and thus reduces network downtime. To change account name alias, go to Accounts -> Access Accounts, hover the mouse at a specific account, click the Pen icon and start typing. Refer to `this document <https://docs.aviatrix.com/HowTos/aviatrix_account.html#setup-account-name-alias>`_. - **Gateway Name Alias** allow you to change an Aviatrix gateway name after it is created by providing an alias name and allowing it to be modified at any time. The use case is customers often need to change some gateway names after the network has been built out to certain scale. By allowing gateway name alias to be modified without having to delete the gateway and thus reduces network downtime. To change gateway name alias, go to Gateway, hover the mouse at a specific gateway name, click the Pen icon and start typing. Note the original gateway name is still maintained as "Original Name". Refer to `this document <https://docs.aviatrix.com/HowTos/gateway.html#gateway-name-alias>`_. Note this feature does not interoperate with Co-Pilot at this time. For customers who deploy Co-Pilot, making changes the gateway names breaks Co-Pilot. The work around is not to use this feature or change back the gateway name. - **Create a VPC Enhancement** now creates multiple route tables associated with public and private subnets. One use case is to allow traffic load balancing when Aviatrix Spoke Gateways are deployed. To configure, go to Useful Tools -> Create a VPC. For more details, check out `Create a VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_. - **Controller Access Security on Azure** extends the Access Security feature to Azure. When an Aviatrix gateway is launched, security rule is automatically added to the Controller inbound rule. This allows Controller admin to only open inbound TCP port 443 to Aviatrix gateways and no-prem public IP addresses, thus improving Controller security. To configure, go to Settings -> Controller -> Access Security. Select the Controller account and enable. For more details, refer to `Enable Controller Security Group Management <https://docs.aviatrix.com/HowTos/FAQ.html#enable-controller-security-group-management>`_. - **Login Banner** allows you to customize banner text for first time login for compliance. Any user who login for the first time must acknowledge the text before proceeding to Controller. To configure, go to Settings -> Controller -> Login Customization -> Login Banner. For more information, refer to `Login Banner <https://docs.aviatrix.com/HowTos/controller_config.html#login-banner>`_. 4. User VPN -------------- - **Max Routes Pushing to VPN Client** has now been increased to 250. This allow a larger network deployment. Requires Aviatrix VPN client 2.11. No configuration change is needed. - **GeoVPN to use DHCP Setting** for DNS name resolution from the VPC where the VPN gateway is deployed. This reduces latency as DNS service is likely to be closer to the source of the VPN user location. For configuration examples, refer to `VPN Access Gateway Selection by Geolocation of User <https://docs.aviatrix.com/HowTos/GeoVPN.html>`_. R6.0.2483 (8/4/2020) ====================== - **Bug fix** fix upgrade jump version issue. R6.0.2481 (8/1/2020) ====================== - **Bug fix** Latest Chrome browser login issue. R6.0.2466 (7/22/2020) ======================= - **Bug fix** Missing MSS clamping configuration resulted in egress traffic loss. - **Bug fix** Handle VNet UDR routes programming when Azure Netapp service is deployed in the Spoke VNet. - **Bug fix** AWS GovCloud cannot list firewall options. - **Bug fix** Configure the system to prevent memory leak. - **Enhancement** API support for t3a.x gateway instance types. - **Bug fix** Missing configuration parameters in download file for Site2Cloud for Cisco ASA devices. R6.0.2387 (7/10/2020) ====================== - **Bug fix** New gateway launching is missing MSS clamping rule which affects connectivity for potentially different types of traffic including egress and multi region Transit Gateway peering, etc. R6.0.2383 (7/2/2020) ====================== - **Bug fix** for error out when using Diagnostics to force upgrade a gateway. R6.0.2373 (6/30/2020) ======================= - **Enhancement on TGW VPN Approval** improves TGW VPN Approval for overlapping CIDRs to prevent black holing traffic. For details, refer to `this link <https://docs.aviatrix.com/HowTos/tgw_approval.html>`_. For the enhancement to take effect, you need to first disable TGW Approval for each connection, upgrade to 6.0 and enable it again. Note you must first disable Approval before upgrading to 6.0. - **Bug fix** for FQDN thread process stuck. - **Bug fixes** to improve stability and use cases. R6.0.2269 (6/19/2020) ===================== 1. Aviatrix Multi-Cloud Transit ----------------------------------------- - **ActiveMesh 2.0** unifies the Aviatrix Transit Gateway next hop route selection by conforming to BGP next hop selection algorithm for all traffic sources. The use case is to provide a predictable routing path in a multi regions, multi cloud and multi sites environments. All new Transit Network deployed is launched with ActiveMesh 2.0. For a one time migration from the existing deployment, go to Settings -> Migration -> ActiveMesh 2.0 Migration. Click Migrate. To learn more details, check out `ActiveMesh 2.0 Details <https://docs.aviatrix.com/HowTos/activemesh_faq.html#what-is-activemesh-2-0>`_. - **Multi-Cloud Transit Segmentation** allows you to segment the Aviatrix multi-cloud transit network (where Aviatrix Transit Gateways and Spoke Gateways are deployed) by specifying domains and connection policy across all clouds and regions. To learn more, check out `Aviatrix Transit Network Segmentation FAQ <https://docs.aviatrix.com/HowTos/transit_segmentation_faq.html>`_. - **External Device to Support Static Remote Route-Based** provides the interoperability between a route-based Aviatrix Transit Gateway and a remote route-based IPSEC tunnel connection. The use case is to allow the remote site to participate in the ActiveMesh 2.0 route selection in a unified manner. To configure, go to Multi-Cloud Transit -> Setup -> Step 3 -> External Device -> Static Remote Route-Based. - **Dual Transit FireNet** allows you to attach an Aviatrix Spoke Gateway to two Aviatrix Transit Gateways, each with Transit FireNet service enabled but with a different purpose. One carries Egress/Ingress inspection and the other carries East-West and North-South inspection. The use case is to allow different policies to be implemented easily. To configure, go to Multi-Cloud Transit -> Transit FireNet -> `Step 1b. <https://docs.aviatrix.com/HowTos/transit_firenet_workflow.html#b-enable-transit-firenet-on-aviatrix-egress-transit-gateway>`_ - **Aviatrix Transit Gateway ECMP Disable Option** allows you to turn off ECMP for next hop selection. The use case is if on-prem deploy a firewall devices that require symmetric routing. The BGP ECMP is disabled by default. To enable, go to Multi-Cloud Transit -> Advanced Config -> Edit Transit -> BGP ECMP. For more information, refer to `BGP ECMP <https://docs.aviatrix.com/HowTos/transit_advanced.html#bgp-ecmp>`_. - **Advanced NAT Function for Azure and GCP** is now available for Aviatrix Spoke Gateways. The use case is to resolve overlapping network CIDRs between on-prem network and Spoke network. To learn more on Aviatrix advanced SNAT/DNAT functions, check out `Aviatrix Advanced SNAT <https://docs.aviatrix.com/HowTos/gateway.html#source-nat>`_ and `Aviatrix Advanced DNAT <https://docs.aviatrix.com/HowTos/gateway.html#destination-nat>`_. - **GCP Multi Region Transit HA** leverages the GCP capability of multi regions in a single VPC and provide Aviatrix Transit/Spoke Gateway HA in a different region. The use case is to improve regional failure by the ability to failover to a different region. - **Azure Availability Zone Support** allows you to deploy an Aviatrix gateway in Azure in a specified availability zone where it is applicable. Not all regions support availability zones and where it is not, availability set is supported. - **Change Aviatrix Transit Gateway AS Number** provides the ability to change AS number of Aviatrix Transit Gateways. The use case is to avoid human errors when there are multiple BGP connections. To configure, go to Multi-Cloud Transit -> Advanced Config -> Edit Transit -> LOCAL AS NUMBER, enter the desired AS number and click Change. - **Sync Controller Best Routes to Aviatrix Transit Gateway** allows the Controller to reprogram an Aviatrix Transit Gateway route table in case they go out of sync. The use case is to recover the routes from an unforeseeable errors in the deployment. To configure, go to Multi-Cloud Transit -> Advanced Config. Select the Aviatrix Transit Gateway, scroll down to `Sync Controller Best Routes to Transit Gateway`, click Sync Routes. 2. Firewall Network (FireNet) ------------------------------ - **Firewall Instances Health Check Enhancement** checks a firewall instance's health by pinging its LAN interface from the connecting Aviatrix FireNet gateway. This is an alternative option to checking health through firewall's management interface, which improves firewall failure detection time and detection accuracy. Available for both FireNet and Transit FireNet deployment and in both AWS and Azure. To configure, go to Firewall Networks -> Advanced, select the FireNet gateway, click the 3-dot skewer, scroll to Keep Alive via Firewall LAN Interface, click Enable. To learn more, refer to `Firewall Health Check with LAN Interface <https://docs.aviatrix.com/HowTos/firewall_advanced.html#firewall-health-check-and-failover-detection-using-lan-interface>`_. - **FireNet Exclude CIDRs** allows you to exclude a list of network CIDRs to be excluded from going through firewall inspection even though its associated Security Domain or network requires inspection. One use case is to exclude the Aviatrix Controller deployed in the Shared Service VPC to be excluded from inspection while Shared Service VPC traffic is inspected. This improves the Controller reachability by not subjecting the Controller access to unintentional firewall policy errors. For details, check out `Exclude CIDR <https://docs.aviatrix.com/HowTos/firewall_network_faq.html#how-to-exclude-specific-cidrs-from-being-inspected-by-the-firewall>`_. - **Check Point CloudGuard in Azure** is now available in Azure when deploying Aviatrix Transit FireNet. Refer to `this example CheckPoint workflow in Azure <https://docs.aviatrix.com/HowTos/config_CheckPointAzure.html>`_ for more details. - **Fortinet Fortigate in Azure** is now available in Azure when deploying Aviatrix Transit FireNet. - **Check Point Dynamic Route Update** enhances FireNet Check Point integration by dynamically updates CloudGuard route tables by the Controller. The use case is for networks with non-RFC 1918 routes that require specific route table programming on the Check Point appliance. 3. User VPN -------------- - **Signed Cert for SAML Authentication** improves security of User VPN SAML authentication when it authenticates with the IDPs by providing a signed cert. To configure, go to OpenVPN -> Advanced -> SAML -> Add a New SAML Endpoint, select the option "Sign Authn Requests". For SAML login to the Controller, go to Settings -> Controller -> SAML Login -> Add a New SAML Endpoint, select the option "Sign Authn Requests". - **Dashboard to Display user speed** allows you to access individual User VPN client performance. To view the client VPN speed, go to Dashboard, scroll down to the Use VPN section to view. - **Terraform for Attaching a user to profile** allows you to update the user profile in modular fashion. 4. Site2Cloud --------------- - **Route Based IPSEC** provides flexibility to configuration. One use case for selecting route based VPN is to solve overlapping network CIDRs with on-prem as referred in `this example <https://docs.aviatrix.com/HowTos/connect_overlap_cidrs_routebasedipsec.html>`_. To learn more about route based VPN, check out `the FAQ <https://docs.aviatrix.com/HowTos/activemesh_faq.html#what-is-route-based-vpn-and-policy-based-vpn>`_. - **Mapped Configuration for Route Based IPSEC** supports both SNAT and DNAT on the network address ranges. The use case is to connect two IP address overlapping networks, for example a cloud VPC and on-prem, where on-prem cannot implement any network address translation. Comparing with individual IP address based translation, this significantly simplifies configuration. Note this configuration is implemented on route based IPSEC tunnel of an Aviatrix gateway site2cloud connection. To configure, go to Site2Cloud -> Add New. For Connection Type, select `Mapped`. For an example configuration, refer to `Solving Overlapping Networks with Network Mapped IPSec. <https://docs.aviatrix.com/HowTos/connect_overlap_cidrs_routebasedipsec.html>`_ For more complex solutions, read `Overlapping Network Connectivity Solutions <https://docs.aviatrix.com/HowTos/overlapping_network_solutions.html>`_. - **Intelligent Troubleshooting** provides expert analysis to the IPSEC syslog and reduces diagnosis time. To use, go to Site2Cloud -> Diagnostics. Select one connection, select `Run Analysis`. - **Shared the Same Pre-Shared Keys** provides an option for both primary and backup IPSEC tunnel to share the same pre-shared keys. The use case is to reduce the configuration burden for on-prem devices. To configure, go to Site2Cloud -> Add New. Check the option `Same Pre-shared Key as Primary` when creating a connection. For configuration details, check out `Site2Cloud configuration workflow <https://docs.aviatrix.com/HowTos/site2cloud.html#site2cloud-ipsec-vpn-instructions>`_. 5. Egress Control ------------------- - **FQDN Search** supports general search for a specified destination FQDN during a specified period of time. One use case is to troubleshoot on an FQDN tag entry without the need to upload tracelog. - **Disable Caching FQDN Entries** prevents potential data leakage to large domain names that contain unrelated sites. To configure, go to Security -> Egress Control -> Egress FQDN Filter -> Global Configs -> Caching. Click to Disable. 6. Operations ----------------- - **Multi Remote Syslog Servers Support** allows an Aviatrix gateway to forward its syslog to a different remote syslog server than other gateways. The use case is customer may have multiple syslog servers deployed in different regions and Aviatrix gateways deployed in regions should forward syslog data to the server it is assigned to. - **Netflow v9 Support** adds new capability in addition to the current v5 support. - **CloudWatch Customize Configuration** now supports group name customization. The use case is to provide flexibility for customer to name their log folders. To configure, go to Settings -> Logging -> CloudWatch -> Advanced -> Log Group Name, enter a name of your choice. - **New User Interface** aims to reduce web interface screen load time and improve user experience. - **Datadog multi site support** to allow Datadog agent to send syslog to a destination site. To configure, go to Settings -> Logging -> Datadog Agent -> Enable Datadog Agent. Select a site datadoghq.com or datadoghq.eu. 7. AWS Transit Gateway (TGW) ------------------------------- - **Intra Domain Firewall Inspection** allows AWS VPCs in the same Security Domain to be inspected by FireNet. The use case is a Security Domain in which all VPCs can communicate with each other, but all traffic requires logging and inspection. To enable, go to TGW Orchestrator -> List -> TGW Security Domains. Select one Security Domain, click Actions -> Edit Intra Domain Inspection. For additional information, refer to `Edit Intra Domain Firewall Inspection <https://docs.aviatrix.com/HowTos/tgw_list.html#edit-intra-domain-inspection>`_. - **Change Spoke VPC's Security Domains** provides the ability to change a Spoke VPC's Security Domain without detaching the VPC from the TGW. The use case is to reduce Spoke VPC connectivity downtime when it needs to change its associated domains. To configure, go to TGW Orchestrator -> List -> Select the attached Spoke VPC -> Actions -> Switch Security Domain. In the pop up window, select the desired Security Domain to associate. For more information, refer to `Switch Security Domain <https://docs.aviatrix.com/HowTos/tgw_list.html#switch-security-domain>`_. - **Update Spoke VPC Route Tables** provides the ability to update a Spoke VPC route tables without detaching the VPC from TGW. The use case is to reduce Spoke VPC connectivity downtime when its subnets and route tables are added or deleted. To configure, go to TGW Orchestrator -> List -> Select the attached Spoke VPC -> Actions -> Update VPC CIDR. For more information, refer to `Update VPC CIDR <https://docs.aviatrix.com/HowTos/tgw_list.html#update-vpc-cidr>`_. - **Edit Spoke VPC Local Route Propagation** provides the ability to enable and disable attached Spoke VPC local route propagation without detaching the VPC. The use case is to disable local route propagation after a Spoke VPC is attached to TGW. To configure, go to TGW Orchestrator -> List -> Select the attached Spoke VPC -> Actions -> Edit Spoke VPC Local Route Propagation. For more information, refer to `Edit Spoke VPC Local Route Propagation <https://docs.aviatrix.com/HowTos/tgw_list.html#edit-spoke-vpc-local-route-propagation>`_. R5.4.1290 (8/5/2020) ===================== - **Bug fix** fix the issue of jumping versions when upgrading. R5.4.1283 (7/17/2020) ===================== - **Bug fix** upgrade failure from R5.3 to R5.4 R5.4.1281 (7/15/2020) ======================= - **Bug fix** Gateway memory leak when rsyslog is not initialized properly. - **Bug fix** Gateway memory configuration change to allow smaller memory footprint. - **Bug fix** Sometimes firewall instances in FireNet become inaccessible. R5.4.1251 (6/19/2020) ======================== - **Bug fix** nightly cron job hit exception. R5.4.1249 (6/15/2020) ====================== - **Enhancement** to support us-west-4 region in GCP. - **Bug fix** on gateway replacement that has AWS LB deployed. R5.4.1240 (6/1/2020) ===================== - **Bug fix** Insane Mode to support Transit FireNet in Azure has an issue when the FireNet gateway is rebooted. R5.4.1238 (5/27/2020) ====================== - **Enhancement** Insane Mode to support Transit FireNet in Azure. - **Bug fix** CloudN to work with RBAC. R5.4.1234 (5/20/2020) ====================== - **Bug fix** when importing user excel sheet for User VPN. - **Enhancement** to support the new Palo Alto VM-Series Bundle 1 and Bundle 2. R5.4.1232 (5/18/2020) ======================= - **Enhancement to Gateway Syslog Download** allows you to a gateway syslog directly from the Gateway. API support only. - **Bug fix** Aviatrix Transit Gateway update learned routes incorrectly in certain cases. - **Route Update Convergence Enhancement** to improve route propagation and convergence time when routes are changed to the Transit network. R5.4.1204 (5/8/2020) ====================== - **Bug fix** fix API bug in enable_fqdn_cache_global. R5.4.1201 (5/7/2020) ====================== - **Enhancement on FQDN** to disable learned FQDN entry IP address caching. API support only. - **Enhancement on User VPN** to improve page load time by caching VPC tags. - **CloudN Enhancement** to support Netflow to export logs. - **Enhancement to Gateway page** to allow gateway AMI image name to be displayed. This is useful to identify if a gateway runs on older AMI image that needs replacement to newer AMI image. R5.4.1140 (4/21/2020) ====================== - **Support More AWS TGW Peering Regions** Newly available regions of AWS TGW Peering is now supported. - **User VPN Customizing Notification** You can now customize pop up messages after a VPN user is connected. To configure, go to OpenvVPN -> Advanced -> System Use Notification. One use case is for customer to write their own messages for compliance. Please ensure that you are running Aviatrix VPN Client version 2.9 or higher to view the usage notification - **VPN DPD Interval Configuration** allows you to specify DPD interval. API support only. - **Gateway Default Memory Alert Threshold** is changed to 80% to provide earlier warning to the Controller admin. - **Change Gateway Default Size** at launch time to t3.small. - **Bug fix** User VPN to Save Configuration Template to allow multiple gateways to have the same configuration when attached to the same NLB. - **Performance Optimization** in handling the route programming time for large deployment of Aviatrix Transit Gateway peering. - **CloudN Enhancement** in handling tunnel down message with Insane Mode. R5.4.1074 (4/3/2020) ===================== - **Bug fix** Restore a list of APIs that was deleted incorrectly. R5.4.1066 (4/1/2020) ===================== 1. Operations ------------------ - **Role Based Access Control** allows you to both limit access to the Controller functions and enable self-service for users with different permission privileges. Read `RBAC FAQ <https://docs.aviatrix.com/HowTos/rbac_faq.html>`_ for more details. 2. Networking ---------------- - **User VPN Performance Improvements** improves gateway performance when User VPN is enabled on the gateway. To receive enhanced performance, replace an existing gateway or launch a new gateway with `VPN Access <https://docs.aviatrix.com/HowTos/gateway.html#vpn-access>`_ enabled. - **Aviatrix Transit Network Spoke Gateways to Support SNAT/DNAT Functions** enable you to support additional use cases in Aviatrix Transit network. These use cases are `"accessing cloud applications with virtual IP addresses" <https://docs.aviatrix.com/HowTos/transit_for_publicIP.html>`_ and `"connecting overlapping addresses from on-prem to Spoke VPCs in ActiveMesh network" <https://docs.aviatrix.com/HowTos/transit_solution_activemesh_spoke_snat_dnat_rfc1918.html>`_. - **Azure Virtual WAN Integration with CloudWAN** expands Aviatrix CloudWAN solution to allow branch office Cisco IOS routers to automatically connect to Azure Virtual WAN by automatically programming IPSEC and BGP on IOS routers. - **Azure Gateways Enhancement** Azure gateways is now launched by the Controller managed disk option instead of storage account for enhanced security. - **User VPN Profile Multi Attribute Support** allows multiple attributes to be specified in the SAML IDP user database. Simply include a list of the names of User VPN Profiles in the user data profile field at the IDP database. 3. Security Integration ------------------------- - **CheckPoint CloudGuard Integration** now supports CloudGuard All-In-One R80.40. In addition, the initial SSH access process is removed for all CloudGuard AMIs. Check out `CheckPoint CloudGuard Configuration Examples <https://docs.aviatrix.com/HowTos/config_CheckPointVM.html>`_ for more details. - **FortiGate Bootstrap Configuration** is now supported. For details on how to configure, read `Bootstrap Configuration Example for FortiGate Firewall <https://docs.aviatrix.com/HowTos/fortigate_bootstrap_example.html>`_. R5.3.1551 (6/4/2020) ====================== - **Bug fix** Change user password should require login CID. - **Enhancement** Multiple enhancement back porting to 5.3. R5.3.1524 (4/26/2020) ======================== - **Bug fix** Enhancement for Controller migration. - **Bug fix** CloudN missing routes after Transit Gateway is rebooted. R5.3.1516 (4/3/2020) ====================== - **Bug fix** Transit Peering not learning routes correctly when remote transit peering configured static routes. - **Bug fix** Back out auto refresh of BGP sessions after upgrading. - **Enhancement** to the ability to update Aviatrix Transit VPC CIDR. R5.3.1499 (3/17/2020) ======================= - **Bug fix** FQDN statistics on the dashboard could cause the Controller to freeze. - **Bug fix** Cannot edit network CIDRs in Site2Cloud configuration. - **Bug fix** Azure FireNet firewall instance launch with enforcement for username/password. R5.3.1491 (3/11/2020) ======================= - **Bug fix** Gateway launch failure triggered rollback function delete all VPC routes. - **Bug fix** GCP VPN gateway shows in unhealthy state when it is still forwarding traffic. - **Bug fix** Azure gateway floods with IPSEC keep alive messages. R5.3.1468 (3/4/2020) ====================== - **Bug fix** for Controller Migration feature. R5.3.1428 (2/21/2020) ======================= - **Bug fix** AWS GovCloud IAM roles is broken. R5.3.1399 (2/20/2020) ====================== - **Bug fix** CloudWAN gateway instance not programming ingress security group. - **Enhancement** to support Azure Africa region. R5.3.1391 (2/17/2020) ======================== **Important Notice** ---------------------- Release 5.3 is the last software version that supports older Controller AMIs. If your Controller AMI is one of the following, we have provided an `one click migration <https://docs.aviatrix.com/HowTos/controller_migration.html>`_ to migrate to a new Controller after the Controller is upgraded to 5.3. The following Controller AMIs requires migration beyond release 5.3: - Controller AMI ID contains "aviatrix_cloud_services_gateway_081517" - Controller AMI ID contains "aviatrix_cloud_services_gateway_111517" - Controller AMI ID contains "aviatrix_cloud_services_gateway_043018" 1. AWS Transit Gateway (TGW) Orchestrator -------------------------------------------- - **AWS Transit Gateway (TGW) Inter Region Peering** Allows you to connect TGWs deployed in different regions by using the native AWS TGW Inter Region Peering. Aviatrix solution enables you to implement Security Domains in a global fashion where you can specify a Security Domain in one region to connect a Security Domain in a different region. Read more on `TGW Inter Region Peering <https://docs.aviatrix.com/HowTos/tgw_plan.html#tgw-inter-region-peering>`_. - **Update Spoke VPC CIDR** applies to an attached Spoke VPC and allows you to update Spoke VPC CIDR after it is attached to TGW, for example, new subnets or route tables are added to the Spoke VPC. To configure, go to TGW Orchestrator -> List, select the Spoke VPC, click the 3 dots skewer and select Update Spoke VPC CIDR. - **Edit Spoke VPC Customized Routes** allows you to edit Spoke VPC route table entries that target to TGW. To configure, go to TGW Orchestrator -> List, select the Spoke VPC, click the 3 dots skewer and select Edit Spoke VPC Customized Routes. - **Edit Spoke VPC Advertised Routes** allows you to advertise to TGW via Controller a different set of routes other than the default VPC CIDR. To configure, go to TGW Orchestrator -> List, select the Spoke VPC, click the 3 dots skewer and select Edit Spoke VPC Advertised Rotues to edit. - **A Spoke VPC to Attache to Multiple TGWs** allows you to attach a Spoke VPC to multiple TGWs as long as the VPC route tables do not have conflicting route entries. - **Spoke VPC Reachability** shows all VPCs and attachments that a given Spoke VPC can reach by `Connection Policies <https://docs.aviatrix.com/HowTos/tgw_faq.html#what-is-a-connection-policy>`_. To view, go to TGW Orchestrator -> List/Edit, highlight one attachment, select Attachment Reachability at the 3 dots skewer. 2. Networking -------------------- - **CloudWAN Tags** allows you to create a tag (template) that consists of list of CLI configuration commands and applies to routers that are attached to it. The use case is if you need to customize CLI commands that are outside the automated BGP & IPSec configuration by CloudWAN, you can do so by creating one or more tag and apply to the routers at once. To learn more, read `CloudWAN Tags <https://docs.aviatrix.com/HowTos/cloud_wan_workflow.html#configuration-tags>`_. - **CloudWAN Saves & Restore Config Versions** Allows you to save and restore a complete IOS configuration for a branch router. To learn more, go to `Save & Restore Config <https://docs.aviatrix.com/HowTos/cloud_wan_workflow.html#save-config>`_. - **Use NLB to load balance UDP based User VPN** allows you to use AWS Network Loadbalancer for UDP traffic to scale out User VPN solution. The advantage for the deployment is improved throughput performance comparing to TCP based VPN solution. 3. Security -------------- - **PrivateS3** allows you to whitelist S3 buckets access from on-prem over AWS Direct Connect private VIF without data leakage. If you transfer data to/from S3 using the high bandwidth Direct Connect, currently there is no solution to do so without the risk of data being transferred to unauthorized S3 buckets. To learn more, read `PrivateS3 FAQ <https://docs.aviatrix.com/HowTos/privateS3_workflow.html>`_ - **Aviatrix Transit Gateway Edge Segmentation** allows you to specify which `Aviatrix edge VPN connection <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#connect-the-transit-gw-to-aws-vgw>`_ can communicate with which Security Domain in TGW deployment. To learn more, read `Edge Segmentation <https://docs.aviatrix.com/HowTos/tgw_faq.html#what-is-edge-segmentation>`_. - **Aviatrix Transit FireNet for Azure** allows you to deploy firewall instances in Azure. For more information, check out `Transit FireNet FAQ <https://docs.aviatrix.com/HowTos/transit_firenet_faq.html>`_. - **Check Point CloudGuard** can be launched from Aviatrix Controller for FireNet use case. The Controller monitors the firewall instances' health and automatically detach the unhealthy instance and reattach when it becomes healthy. Note static routes need to be programmed on the firewall instances. - **Fortinet FortiGate** can be launched from Aviatrix Controller for FireNet use case. The Controller monitors the firewall instances' health and automatically detach the unhealthy instance and reattach when it becomes healthy. Note static routes need to be programmed on the firewall instances. - **FireNet Fail Close** provides an option to FireNet gateway to drop packets when no firewall instances are attached. To enable, go to Firewall Network -> Advanced, highlight one FireNet gateway, click the 3 dots skewer. At Fail Close, click Enable. 4. Operation ------------- - **Approval for BGP Learned Routes** Enables you to explicitly make a decision if a dynamically learned routes be allowed to propagate to your cloud network. One use case is to apply this feature to a TGW VPN/DXGW that connects with a partner network where you can control which learned routes are allowed to propagate. This feature applies to both AWS TGW and Aviatrix Transit Gateway dynamically learned routes. To learn more, check out `Approval for TGW <https://docs.aviatrix.com/HowTos/tgw_approval.html>`_ and `Aviatrix Encrypted Transit Approval <https://docs.aviatrix.com/HowTos/transit_approval.html>`_. - **FlightPath to support IP address** allows either source or destination to be IP address based. This enables you to troubleshoot connectivity to, for example, on-prem host with a certain IP address. - **FlightPath for Azure** allows you to troubleshoot connectivity issues in Azure in a much faster way by pulling relevant information at once and present in a side by side panels. It also provides expert diagnostics to identify problems. To use, go to Troubleshoot -> FlightPath. - **FlightPath for GCP** allows you to troubleshoot connectivity issues in GCP in a much faster way by pulling relevant information at once and present in a side by side panels. It also provides expert diagnostics to identify problems. To use, go to Troubleshoot -> FlightPath. - **Dynamically display packets while packet capture is on** allows you to view the packet summary on the Controller console while they are being captured. - **User VPN Cert Issue Date** displays the date of a VPN user creation. The display is on the Dashboard page. - **User VPN Client Software Control** allows you to set a minimum Aviatrix VPN client software version that is allowed to connect successfully. To configure, go to OpenVPN -> Edit Config -> MINIMUM VPN CLIENT VERSION to set the Aviatrix VPN client version. - **Migrate Controller** allows you to migrate your Controller AMI image from older opensource OS versions. To migrate, go to Settings -> Maintenance -> Migration. R5.2.2153 (2/7/2020) - **Enhancement** to reduce the number of alert emails. - **Enhancement** to reject an on-prem learned route if it is a subset of cloud network CIDR. R5.2.2122 (1/25/2020) ======================== - **Enhancement** Allow site2cloud gateways to support Active-Active mode where both tunnels are up and packets are routed to both gateways via respective VPC route tables. To enable, go to Site2Cloud, click on the connection, scroll down to Active Active HA and click Enable. - **Enhancement** Allow the service account credential to be re-used by GCP projects. - **Bug fix** Fix Azure gateway memory leak issue. - **Bug fix** Enhancement to FQDN warning messages. - **Bug fix** Fix issue with Spoke VPC with Customized routes on non ActiveMesh encrypted transit network. - **Bug fix** Fix issue with Customized DNS server not restored when after backup/restore. R5.2.2092 (1/15/2020) ======================= - **Bug fix** Aviatrix Active Mesh Transit Gateway takes exception when building Transit Peering. R5.2.2071 (1/10/2020) ========================= - **Bug fix** on-prem adverting the default route 0.0.0.0/0 via TGW DXGW is not propagated through Aviatrix Transit Peering. - **Bug fix** Fix exception when using "Export to Terraform" feature with Aviatrix created VPC resource. - **Enhancement** to reduce failover time for Connected Transit deployment. R5.2.2047 (12/19/2019) ======================== - **Bug fix** Azure China upgraded to upgrade from 5.1 to 5.2. - **Bug fix** Aviatrix Transit Gateway with multiple Spoke Gateways exhibits memory leaks. - **Bug fix** GCP gateway replacement function fails. - **Bug fix** GCP gateway names, VPC route table tables and route entry names can exceed cloud provider's limits. - **Bug fix** Failed to delete IPSec policy when deleting Spoke to Spoke peering. - **Enhancement** Add remote troubleshoot support on CloudN. R5.2.2011 (12/06/2019) ======================== - **Customize Network Filtering of FQDN** Allow configuration to customize the network CIDRS to not be included in FQDN filtering. One use case is if on-prem requires certain network CIDRs to skip FQDN filtering. To configure, go to Security -> Egress Control -> Egress FQDN Filter. Select Customize Network Filtering. R5.2.1991 (12/04/2019) =========================== Security ------------------------------ - **Transit FireNet** Firewall Network for AWS Encrypted Transit VPC. Transit FireNet integrates Firewall Network function into the Aviatrix Transit Gateway function. With this new capability, you can deploy firewall instances into the encrypted transit network to allow security policy management and IDS/IPS functions. To learn more, refer to `Transit FireNet FAQ <https://docs.aviatrix.com/HowTos/transit_firenet_faq.html>`_. - **Public Subnet Filtering** provides the packet filtering capability to instances deployed in AWS VPC public subnets. Leveraging the AWS Ingress Routing service, the Public Subnet Filtering gateway filters out the malicious IP addresses detected by Amazon GuardDuty. Additionally, the filtering gateway provide FQDN functions for Egress traffic from the public instances. To configure, go to Security -> Public Subnets. Refer to `Public Subnet Filtering Gateway FAQ <https://docs.aviatrix.com/HowTos/public_subnet_filtering_faq.html>`_ for more information. - **Independent Verdict for Each Egress Control Rule** allows you to apply Allow or Deny to each FQDN rule. The use case is if you have a large set of FQDN names that should be allowed but only a small subset be denied, you can avoid inputting a large set of rules by creating a Deny rule of the small subset and one Allow rule with wild card for the large set. To configure, go to Security -> Egress Control. Select a tag, click Edit and add new rules. For more information, refer to `Base Policy <https://docs.aviatrix.com/HowTos/FQDN_Whitelists_Ref_Design.html#base-policy>`_. - **FireNet Performance Improvement** FireNet performance achieves 40Gbps throughput. For details, check `this link. <https://docs.aviatrix.com/HowTos/firewall_network_faq.html#what-is-the-maximum-performance-firenet-can-achieve>`_ - **Palo Alto VM-Series Multiple Versions** can be launched from the Aviatrix Controller. The use case is companies with policy of not using the latest software releases. To configure, follow the `Firewall Network Workflow <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html>`_. - **API Support for Stateful Firewall Rules Update** allows individual rule to be inserted, appended and deleted. Networking ------------- - **Aviatrix CloudWAN** provides two capabilities. It centrally manages Cisco IOS routers from the Controller by allowing you to program and edit the IOS CLIs, monitoring the routers' metrics and reachability. It also automatically connects the Cisco IOS routers to the Transit Network with the shortest latency by integrating AWS Global Accelerator. For more information, check out `Cloud WAN FAQ <https://docs.aviatrix.com/HowTos/cloud_wan_faq.html>`_. The use case is to manage and connect the already deployed millions of Cisco IOS routers in the least fiction way and minimum human errors. - **BGP AS_PATH Prepend for Transit Gateway Peering** allows the on-prem learned routes to be propagated to the Transit peering routes along with the AS_PATH information. This feature requires no configuration. - **Consider AS_PATH for Next Hop Decision** enhances the next hop routing decision when the Transit Gateway make decisions. Previously when multiple remote sites advertise the same network CIDRs, Aviatrix Transit Gateway routes with ECMP. With this enhancement, the Transit Gateway selects the shortest AS_PATH length as the preferred routes. Only when remote sites advertises with the same AS_PATH lengths the Transit Gateway routes based on ECMP. This feature requires no configuration. Operations ------------ - **FQDN Dashboard** displays statistics of egress bound destination FQDN names both accepted and rejected. You can further deep dive to see the statistics for each gateways. To view the statistics, go to Dashboard and scroll down to FQDN Stats. - **Flightpath** to include ActiveMesh Spoke Gateways, ActiveMesh Transit Gateways and peering gateways. - **Selective Gateways for Logging** allows to not to have to enable all gateways for logging events. To configure, go to Settings -> Logging, select a log service, click Advanced to edit the list of the gateways to forward the log to the log service. By default, all gateways are included. - **Show Deployment per Access Account** displays what is deployed, for example, the number of encrypted Spoke Gateways, the number of VPC attachment, the number of FQDN gateways and the site2cloud tunnels, deployed for each access account. The use case is to gain visibility of the Aviatrix usage per each account and helps to charge back to teams who are part of the deployment. To view, go to Access Accounts, highlight one access account, click on the three dots skewer, click Show Deployment. - **TGW Route Auditing** allows you to immediately discover the missing routes in Spoke VPC route tables and its associated TGW route tables. To use, go to TGW Orchestrator -> List. Highlight one attachment, click the three dots and click Audit Routes. - **TGW Audit** expands its capability to audit all route entries of attached VPC route tables in addition to route entries in TGW route tables. To use, go to TGW Orchestrator -> Audit. Select one TGW and click Run On-Demand Audit. R5.1.1183 (12/2/2019) ======================= - **Bug fix** BGP learned routes parsing error. - **Bug fix** Transit Peering filter not updating new learned routes. R5.1.1169 (11/25/2019) ======================= - **Bug fix** Transit Gateway filter does not work properly R5.1.1016 (11/21/2019) ======================= - **Bug fix** Fix firewall instance launch failure in AWS Hong Kong region. - **Bug fix** NTP configuration corruption fix. R5.1.989 (11/17/2019) ======================= - **Enhancement** Controller does not allow Transit Gateway peering when multiple Transit Gateways are in the same VPC. - **Bug fix** Gateways fail to forward syslog to remote syslog server when Controller cannot reach the syslog server. - **Terraform enhancement** Add Terraform Export for aviatrix_firewall_instance, aviatrix_firenet_resources, aviatrix_firenet. - **Bug fix** Export to Terraform feature is broken. R5.1.973 (11/6/2019) ====================== - **Bug fix** ActiveMesh does not report tunnel counts to AWS when Metered AMI is deployed. - **Bug fix** Aviatrix Transit Gateway peering does not report tunnel counts to AWS when Metered AMI is deployed. R5.1.969 (11/3/2019) ====================== - **Enhancement** Import VPN users now include user profile field. - **Bug fix** Azure native peering is broken. - **Bug fix** FireNet gateway does not load balance UDP traffic. - **Bug fix** Cannot detach Spoke Gateway when customized CIDRs feature is configured on the Spoke Gateway. - **Bug fix** Fail to import user via CSV file when Geo VPN and SAML are enabled. R5.1.962 (10/29/2019) ========================= - **Bug fix** Aviatrix Controller API calls cause Panorama to become unusable overtime as Panorama fills up its desk space. This is a must fix that impacts all FireNet deployment with Panorama. - **Bug fix** FireNet does not load balance UDP packets correctly. This is a must fix that impacts all FireNet deployment where UDP traffic such as DNS, goes through the FireNet. - **Bug fix** ActiveMesh Transit Gateway stops forwarding packets when forwarding from one VTI interface to another. This is a must fix that impacts all multi sites ActiveMesh Transit Gateway deployment. - **Bug fix** Transit VPC route propagation gets disabled when other Transit VPN connection is deleted. This is a must fix that impacts all multi sites ActiveMesh Transit Gateway deployment. R5.1.943 (10/25/2019) ======================= - **Bug fix** Hostname is blocked in VPN profile policy configuration. Revert the change. - **Bug fix** Transit Gateway peering is missing on dashboard. R5.1.935 (10/19/2019) ========================== Transit Gateway Enhancement ------------------------------ - **Transit Gateway Peering with Network Filter** allows you block route propagation from one Transit Gateway side to the other. This use case is to allow two regions of transit network to connect with each other when there are exact overlapping network CIDRs by blocking on each Transit Gateway these CIDRs. To configure, go to Transit Network -> Transit Peering -> Add New, or Edit an existing peer. For more info, refer to `Filtered CIDRs <https://docs.aviatrix.com/HowTos/transit_gateway_peering.html#filtered-cidrs>`_. - **Route Table Selection** allows VPC route tables to be selected when attaching attaching a Spoke VPC gateway. Only the selected route tables are programmed for learning routes and reprogramming routes at failover time. API support only. - **TGW DXGW and VPN Enhancement** allows DXGW and VPN to be deployed in any Security Domain. One use case is if you have multiple VPN connection and do not wish to have the remote sites to have connectivity with each other, you can now create VPN connections in different Security Domains. - **ASN Path Prepend** adds ASN number when Aviatrix Transit Gateway redistribute routes to its BGP peer. For new Transit connection, the Aviatrix Transit Gateway automatically inserts its ASN number. To insert ASN path in an existing connection, go to Transit Network -> Advanced Config -> Prepend AS Path Security ------------ - **Force_Drop Function** in stateful firewall rule to allow immediate packet dropping on established sessions. - **Stateful Firewall Port Configuration Enhancement** allows you to add multiple port numbers and multiple port ranges separated by comma in the same rule. - **FQDN for non TCP 443 SSL protocol** allows you to execute FQDN filtering function for HTTPS traffic running on non TCP port 443. The use case is for HTTPS based applications that need to access Internet sites on non TCP port 443. To configure, select HTTPS as the protocol and input a specific TCP port. With is feature, you can configure wild card. Operations ------------ - **IAM Policy Auto Update** allows you to update secondary accounts to the latest IAM policy from the Controller console. To configure, go to Accounts -> Access Accounts. Select an account, click the 3 dots skewer and click "Update policy" - **New Dashboard Panel** displays what has been built and if they are healthy. R5.1.845 (10/8/2019) ===================== - **Bug fix** Prevent upgrade from 4.7 to 5.1 directly without going through 5.0 release. - **new API** for selecting firewall instance size. R5.1.842 (10/1/2019) ===================== 1. FireNet Network Enhancement --------------------------------- - **Firewall Network load balancing from TGW** allows both primary gateway and backup gateway to present its ENI interface so that packets initiated from the Spoke VPCs can be forwarded to both gateways in the AZ affinity or nearest AZ affinity fashion. - **Management access from On-Prem** allows on-prem to connect with private IP address of the firewall device deployed in the Native Firewall Domain, Native Egress Domain and Aviatrix Firewall Domain. To enable, go to TGW Orchestrator -> List, highlight the firewall domain, click Edit, click to enable. Note in this release, both accessing from on-prem via Aviatrix Edge Domain and accessing from TGW plus DXGW/VPN are supported. - **Improve FireNet gateway failover time** to be under 16 seconds. 2. Networking ----------------- - **Aviatrix ActiveMesh** is officially available. R5.0.2782 (9/30/2019) ======================= - **Bug fix** Disable Account Audit and Gateway Audit features that cause memory leak in controller. R5.0.2773 (9/20/2019) ======================= - **Bug fix** GovCloud does not support m4.xlarge on Palo Alto Networks VM-Series, fixed the issue with m5.xlarge instance type. - **Bug fix** Multiple gateway security groups can cause gateway audit to generate false alarm. R5.0.2768 (9/18/2019) ======================== - **Bug fix** FQDN process may take 2 to 5 minutes to restart when a new URL rule is updated. R5.0.2754 (9/16/2019) ======================= - **Bug fix** for Oracle Cloud Infrastructure (OCI). R5.0.2667 (9/9/2019) ========================= 1. Automation & Operations ---------------------------- - **Official Terraform Provider** Aviatrix has become the official Terraform provider! Visit `Aviatrix Provider <https://www.terraform.io/docs/providers/aviatrix/index.html>`_. Terraform v0.12 is needed, please visit `Compatibility Chart <https://www.terraform.io/docs/providers/aviatrix/guides/release-compatibility.html>`_, `Terraform Provider 2.x Upgrade Guide <https://www.terraform.io/docs/providers/aviatrix/guides/v2-upgrade-guide.html>`_. - **New API site** visit `api.aviatrix.com <https://api.aviatrix.com/?version=latest>`_ to see our brand new API doc site! - **Access Account Audit** continuously monitors the health of Controller and individual access account. The Controller sends email alert to the admin user and logs the event when errors in the account setting are detected. - **Gateway Audit** continuously monitors the status of gateway cloud credentials and security groups. For AWS, this credential is the gateway's IAM roles and policies. The Controller sends email alert to the admin user and logs the event when errors of gateway cloud credentials are detected. To view the health of the gateway, go to Gateway page and check the field `Audit. <https://docs.aviatrix.com/HowTos/gateway_audit.html>`_ - **Logs display the source IP address when a user login** to improve visibility. - **Logs display the latest at the top of the screen** for ease of use. The logs include Site2Cloud diagnostics messages and command log messages. - **Export VPC Tracker to XML** allows you to download in Excel form all VPCs the Controller retrieves. To download, go to Useful Tools -> VPC Tracker, click the refresh button and then click Export to CSV. - **Bulk import/export VPN Users** Allow onboarding VPN users in volume. - **Gateway restart** is a feature that when Controller detects a gateway goes down and initiates a failover, and in the meantime restart the failed gateway to recover its state. This feature is enabled by default on all gateways. 2. Multi Cloud ----------------- - **Azure Transit with Native Spoke VNet Support** Allows you to build a transit solution without launching an Aviatrix gateway in the Spoke VNet. The solution leverages the Azure native peering capability for the traffic between Spoke VNet and Transit VNet, it also leverages the Controller to propagate learned routes directly to Spoke VNet. Follow the `Transit Network Workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ to get started by launching an Aviatrix Transit GW. Attach a Spoke VNet at `Step 6b <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#b-attach-azure-arm-spoke-vnet-via-native-peering>`_. - **Azure Transit Insane Mode Support** expands our `Insane Mode Encryption Service <https://docs.aviatrix.com/HowTos/insane_mode.html>`_ to Azure networks. The support include Insane Mode encryption over Express Route, Insane Mode for VNet to VNet encrypted peering and Transit Peering connections. Launch an Azure gateway with Insane Mode enabled to get started. - **GCP Transit Gateway Support** expands our `Transit Network Solution <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ to Google GCP. Follow the `Transit Network Solution <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ instruction to get started. - **Oracle Cloud (OCI) Spoke Gateway Support** expands our Transit Network Solution to OCI Spoke Gateways. 3. Networking ---------------- - **IKEv2 support for Site2Cloud connections** expands site2cloud function to support IPSEC IKEv2. Follow the `site2cloud instructions <https://docs.aviatrix.com/HowTos/site2cloud.html>`_ to get started. - **IPv6 Support** enables an Aviatrix gateway to have IPv6 address. One use case is to leverage the unique addressing of IPv6 to solve overlapping network CIDR problem in the cloud networks. IPv6 is supported on User VPN function and Encrypted Peering function. To enable, go to Gateway page, select the gateway, click Edit. Scroll down to IPv6 and click Enable. Refer to `Aviatrix IPv6 <https://docs.aviatrix.com/HowTos/gateway.html#ipv6>`_ for more details. - **Insane Mode over Internet** allows you to leverage the existing high speed Internet to build high performance encryption. - **User VPN Support two way communication** between client and cloud instances by disabling VPN gateway NAT function and program the VPC route table for traffic initiated from VPC to route back to your VPN desktop. 4. Security ------------ - **FQDN Applies to Private Domain Names** allows you to apply FQDN filter on Domain Names that resolve to private IP addresses. The use case is if you have host names that are on the private network and you need to apply whitelist filter. This is a global capability that applies to all FQDN tags. To enable, go to Egress Control -> Egress FQDN Filter, click "Enable Private Network Filter". - **Multi Wildcard for FQDN** allows the FQDN gateway to match more relaxed expressions, such as a-*.b*.com. - **FireNet for GovCloud** is available. Follow the instructions for `Firewall Network workflow <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html>`_ to get started. - **Aviatrix FQDN gateway for FireNet** enables Aviatrix FQDN function to be centrally deployed in AWS Transit Gateway (TGW) environment. One use case is to limit the number of EIPs of egress packets to specific sites that require whitelist of source IP addresses. To enable, follow the `Firewall Network workflow <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html>`_ and deploy Aviatrix FQDN gateway at `Step 7c <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#c-launch-associate-aviatrix-fqdn-gateway>`_. Note only Egress Control for Internet bound traffic is supported. 5. AWS Transit Gateway (TGW) Enhancement ----------------------------------------- - **Disable Spoke VPC local CIDR propagation** is an optional feature that when enabled the Spoke VPC CIDR is not propagated to TGW route table when the Spoke VPC is attached to TGW. One use case is to allow multiple VPCs to be in one Security Domain (share one TGW route table) without the connectivity between them, thus reducing the need to createe a large number of Security Domains in order to build isolation. This optional feature is enable when attaching a VPC at `TGW Build <https://docs.aviatrix.com/HowTos/tgw_build.html>`_. - **Select Spoke VPC route table for programming** is an optional feature that allows you to select which Spoke VPC route tables will be programmed of learned routes propagated from on-prem or other Spoke VPCs. One use case is that certain instances in the VPC do not participate the TGW Orchestrator. - **Management access from On-Prem** allows on-prem to access privately (SSH or HTTPS) the firewall device deployed in the Native Firewall Domain, Native Egress Domain and Aviatrix Firewall Domain. To enable, go to TGW Orchestrator -> List, highlight the firewall domain, click Edit, click to enable.Note in this release, only accessing from on-prem via Aviatrix Edge Domain is supported. Accessing from TGW plus DXGW/VPN are not supported. 6. ActiveMesh and Multi-Site Transit Beta -------------------------------------------- Learn `Aviatrix Transit ActiveMesh Mode <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-a-transit-gateway>`_. Contact Aviatrix sales or support team for preview on ActiveMesh and Multi-site Transit Network. R4.7.590 (8/23/2019) ====================== - **Bug fix** When attaching a Spoke VPC to TGW, VPC route table did not handle the case when there is AWS end point. - **Bug fix** When connecting Transit Gateway to external device, Transit Gateway did not handle the case if on-prem router's advertised routes is a super set to the IPSEC end point IP address. - **Bug fix** The profile attribute handling for SAML user VPN client did not consider error cases when profile attribute is absent or does not produce a match. R4.7.581 (8/11/2019) ======================= - **Transit peering for two Transit Gateways in the same VPC** removes the constraint that Transit Peering can only take place on two Aviatrix Transit Gateway in two different VPCs. The use case is if you have deployed two individual transit networks in the same VPC, now you can connect them by implementing Transit Gateway Peering. R4.7.501 (7/22/2019) ======================= - **Software update for Field Notice 0005** as described in `this document <https://docs.aviatrix.com/HowTos/field_notices.html#field-notice-0005-2019-07-22>`_. This software update applies to all customers who use Aviatrix Client VPN software for SAML authentication, and both Aviatrix Client VPN software and Controller are required to upgrade. If you use Aviatrix Client VPN software for non SAML authentication, you are not affected by the issues described in the Field Notice 0005. R4.7.494 (7/14/2019) ====================== - **Spoke VPC Gateway Attach Behavior** is modified such that when a Spoke Gateway is attached to the Aviatrix Transit GW, RFC 1918 routes are programmed. Conversely when a Spoke VPC gateway is detached from the Aviatrix Transit GW, all learned routes are deleted. Such behavior change simplifies migration process from Aviatrix Encrypted Transit architecture to AWS Transit Gateway (TGW) based transit architecture. Backward compatibility is ensured. - **Azure Gateway Launch** no longer creates a new resource, instead it now re-uses VNET resource. The use case is customers already created a resource group when creating a VNET. - **Add Aviatrix Tag for Cross Account VPC Attachment** allows you to identify in the TGW route table Aviatrix attachment resource when the Spoke VPC is in a different AWS account. - Bug fix that removes the unnecessary restarts of BGP process after software upgrades. R4.7.473 (7/7/2019) ================================================ - **Palo Alto VM-Series Bootstrap function support** allows firewall instance to retrieve initial VM-Series configuration and policies stored in S3 bucket. The use case is to improve automation by allowing the VM-Series to load the initial policy configuration. For more information, refer to `VM-Series Bootstrap integration. <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#example-configuration-for-bootstrap>`_ - **Palo Alto VM-Series Panorama integration** allows firewall instances to be managed by Panorama. The use case is to have Panorama to centrally manage all firewall deployment both on-prem and in the cloud. For more information, refer to `Panorama integration. <https://docs.aviatrix.com/HowTos/paloalto_API_setup.html#managing-vm-series-by-panorama>`_ - **EIP Allocation for Transit Gateway** allows a Transit Gateway to be associated with an already allocated EIP. The use case is to manage the Aviatrix gateway EIP the same way you would manage your EC2 deployment EIPs, as they are all in the same pool. - **Insane Mode Gateway Resizing** allows you to resize Insane Mode gateway after it is launched. This provides the flexibility of to manage instance cost when running Insane Mode. R4.7.419 (6/30/2019) =============================================== - bug fix for "Customize Spoke VPC advertising CIDR". - error checking for TGW VPN configuration parameters. R4.7.378 (6/16/2019) ===================== 1. AWS Transit Gateway Orchestrator ------------------------------------- - **AWS TGW Egress/Ingress Domain** allows you to create a central egress network architecture without requiring to launch Aviatrix FireNet gateway. Aviatrix Orchestrator programs the necessary Spoke VPC route tables and TGW route tables to make sure Internet bound traffic from Spoke VPCs are forwarded to the VPC in egress domain. One use case for native egress domain is to reduce the number of EIPs you may have to whitelist to accessing third party SaaS service. In the egress domain, you can deploy `Aviatrix FQDN gateway <https://docs.aviatrix.com/HowTos/fqdn_faq.html>`_ or a virtual appliance to handle Internet bound traffic. Note in this network architecture, there is no built in scale out and redundancy as it is the case for Aviatrix Firewall Network. To configure, select "Native Egress/Ingress Domain" when `creating a New Security Domain <https://docs.aviatrix.com/HowTos/tgw_plan.html#create-a-new-security-domain>`_ at the TGW Orchestrator Plan. - **AWS TGW Firewall Domain** provides the firewall network architecture without requiring to launch Aviatrix FireNet gateway. Aviatrix Orchestrator programs the necessary Spoke VPC route tables and TGW route tables to make sure traffic that requires inspection is forwarded to the firewall security domain. One use case is to run a virtual appliance for packet inspection. Note in this network architecture, there is no built in scale out and redundancy as it is the case for Aviatrix Firewall Network architecture. To configure, select "Native Firewall Domain" when `creating a New Security Domain <https://docs.aviatrix.com/HowTos/tgw_plan.html#create-a-new-security-domain>`_ at the TGW Orchestrator Plan. - **Customize Spoke VPC Route Table** allows you to program route entries in Spoke VPC route table that points to TGW as target. By default, Aviatrix Orchestrator programs RFC 1918 routes in the VPC route table to point to TGW, any routes that are outside of this range is dynamically programmed into the VPC route table. When you enable this feature, all dynamic route propagation will be stopped. One use case is if you simply want to program the default route to point to TGW. Another use case is if you do not wish Aviatrix Orchestrator to program any VPC routes, in which case you should enter 0.0.0.0/32 for the "Customizing Spoke VPC Rotues" field. To configure, enter a list of comma separated CIDRs at `Attach VPC to TGW <https://docs.aviatrix.com/HowTos/tgw_build.html#attach-vpc-to-tgw>`_ during TGW Orchestrator Build. - **Customize TGW VPN Creation** with additional parameters, such as inside_ip_cidr and pre_shared_key. 2. Insane Mode Enhancement ---------------------------- - **Insane Mode Dynamic Bandwidth Adjustment** significantly reduces Insane Mode tunnel switch over probability by automatically removing the failed encryption lane from the load balancing pool while keeping the remaining encryption lanes to continue to forward the traffic. After the failed lane is brought back up, it is then added back to the load balancing pool. Only when 50% of the lanes fail should the Controller declare the tunnel down and switch over to the backup tunnel. 3. FQDN Enhancement --------------------------------- - **Performance Enhancement** to handle traffic burst. FQDN and system memory pool are significantly increased to handle large burst traffic. R4.6.587 (5/29/2019) ===================== 1. Networking ------------------- - **AWS Transit Gateway Orchestrator for VPN Integration** brings native TGW VPN connection to the Aviatrix Controller Orchestrator. Aviatrix Orchestrator periodically polls TGW route table learned routes from VPN connection and then programs the attach Spoke VPC route tables. One use case is for TGW VPN to connect to on-prem or a third party VPC via IPSec. To configure, follow the `TGW Plan workflow for VPN <https://docs.aviatrix.com/HowTos/tgw_plan.html#setup-aws-transit-gateway-vpn-connection>`_. - **AWS Transit Gateway Orchestrator for Direct Connect Integration** brings native TGW DXGW cocnnection to the Aviatrix Controller Orchestrator. Aviatrix Orchestrator periodically polls TGW route table learned routes from Direct Connect Gateway connection and then programs the attach Spoke VPC route tables. One use case is for TGW DXGW to connect to on-prem. To configure, follow the `TGW Plan workflow for Direct Connect <https://docs.aviatrix.com/HowTos/tgw_plan.html#setup-aws-transit-gateway-direct-connect>`_.` - **Support multiple Firewall Network domains attached for the same TGW**. The use case is to separate VPC to VPC inspection from egress/ingress inspection. There is no User Interface change. To configure, follow the `Firewall Network workflow <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html>`_. Check out `this design pattern <https://docs.aviatrix.com/HowTos/firewall_network_faq.html#firenet-deployment-model-6>`_ for how to use multi Firewall Networks in TGW environment. 2. AWS GovCloud ------------------ - **AWS GovCloud Encrypted Transit** allows you to setup and operate an end-to-end encryption in a transit network. To configure, follow the `Encrypted Transit Network workflow. <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ - **AWS Transit Gateway Orchestrator for GovCloud** allows you to setup and operate AWS Transit Gateway based transit network. To learn more, follow the `AWS Transit Gateway Orchestrator <https://docs.aviatrix.com/HowTos/tgw_faq.html>`_. - **AWS Native Peering for GovCloud** supports AWS native peering in GovCloud. To configure, follow `this link. <https://docs.aviatrix.com/HowTos/peering.html#aws-vpc-peering>`_ - **Backup & Restore for GovCloud** is the best practice to operate Aviatrix solution. Make sure you enable this feature. 3. Compliance -------------- - **FIPS 140-2 Compliant module** allows you to install and operate FIPS 140-2 Crypto Module for SSL library. To learn more, check out `this document. <https://docs.aviatrix.com/HowTos/fips140-2.html>`_ - **Security Patch status display** enhances the Security Patch function by displaying the patch status. R4.3.1275 (Patch release of 4.3 on 5/20/2019) =============================================== - Bug fix for Transit Gateway External Device connection option where on-prem end point uses local link address 169.254.0.0/16. - Bug fix for FQDN HTTP protocol handling. - Bug fix for Transit Peering switch over. R4.3.1262 (Patch release of 4.3 on 5/13/2019) ============================================= - **User Selected Subnet Attachment to TGW** allows you to customize the subnet/AZ of a VPC to attach to TGW. To configure, go to TGW Orchestrator -> Build. Select Advanced and multi select the subnets. For MAC, multi select is "Command + highlight". For Windows, multi select is "Control + highlight". - Bug fix for Transit Gateway peering. - Bug fix for Datadog upgrade for Azure gateway. - Remove TGW VPN background task. R4.3.1230 (5/5/2019) ===================== 1. Networking ---------------- - **Firewall Network (FireNet)** is the new iteration of Transit DMZ for deploying firewall in the cloud. FireNet provides the simplicity, scalability and automation for an optimal network architecture for firewall deployment. Check out the `FireNet FAQ <https://docs.aviatrix.com/HowTos/firewall_network_faq.html>`_ to learn more. Follow `FireNet workflow <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html>`_ to start deploying. - **Transit Peering InsaneMode** allows you to build high performance encrypted connection across AWS regions over AWS private Peering network infrastructure. To configure, first launch the Aviatrix Transit Gateway with InsaneMode enabled, Transit Peering InsaneMode will be automatically enabled when you configure `Transit Gateway Peering. <https://docs.aviatrix.com/HowTos/transit_gateway_peering.html>`_ This feature is only available for AWS deployment. - **User Accelerator Preview** integrates AWS Global Accelerator with Aviatrix User VPN to reduce user access latency. - **Azure Native Peering** supports VNET to VNET native peering in the same Azure subscription. Cross subscription is not supported. To configure, go to Peering -> Azure Peering. - **C5n Instance** is now supported. With C5n.18xlarge, InsaneMode IPSEC performance reaches 25Gbps. - **Select Subnets for TGW Attachment** provides by API the flexibility to select which subnet to attach to AWS Transit Gateway (TGW). - **Reuse Azure Resource Group** provides by API the ability to reuse the VNET resource group when launching an Azure gateway. 2. Routing Policies --------------------- - **Filter Advertised Spoke VPC CIDRs** Supports the ability to exclude certain VPC subnets from advertising to Transit Gateway. One use case is if you have Spoke VPCs that have partial overlapping VPC CIDRs, by excluding the overlapping CIDRs, you can attach your VPC to Aviatrix Transit Gateway without error. This feature is only available for encrypted transit solution. To configure, check out `this link. <https://docs.aviatrix.com/HowTos/gateway.html#filter-advertised-spoke-vpc-cidrs>`_ - **Transit Peers as Backup to On-prem local route** is a routing policy for Transit Gateway with the configuration to instruct all remote Transit Gateway peers not to advertise to their on-prem routes that are learned from the Transit Gateway with the configuration, except when the configured Transit Gateway loses connectivity to its on-prem. One use case is for a connected on-prem network with multiple datacenters where each datacenter is connected to a Transit Gateway and where the Aviatrix Transit Gateways form a mesh backbone. With this policy enabled, datacenters do not learn and advertise conflicting cloud routes to each other. To configure, select the Transit Gateway at the Gateway page, click Edit. Scroll down to "Transit Peers As Backup to On-prem", click Enable. 3. Operation ------------- - **Terraform Exporter** is a tool to learn and build your deployment with Terraform starting from your Aviatrix Controller Console. For example, use Aviatrix Console to deploy a VPN gateway, add a VPN user. You can then download from the Console the Terraform .tf file and instructions. From this point on, you can add more users directly by editing the Terraform file. Great for Terraform beginners and teams who wish to migrate to use code to manage network infrastructure. To download the resources already configured via Console, go to Useful Tools -> Export to Terraform. Check out `this example guide <https://docs.aviatrix.com/HowTos/tf_export.html>`_ to learn how to use the tool. - **SumoLogic Ephemeral Collector** allows any stopped Aviatrix Controller and gateways to remove themselves from the SumoLogic console. - **Datadog version 6 support** If you have already configured Datadog, you can upgrade to version 6 by disable and enable again. To configure, go to Settings -> Logging -> Datadog Agent - **Multiple Endpoints for SAML Login to Controller** allows read_only user to login via SAML authentication. To configure, Settings -> Controller -> SAML Login, to add more endpoint. Check out `this doc <https://docs.aviatrix.com/HowTos/Controller_Login_SAML_Config.html>`_ for instructions. R4.2.764 (Patch release of 4.2 on 4/14/2019) ============================================= - Missing parameters for "skip_rfc1918" for Azure support. - Missing parameters for "skipp_rfc1918" for GCP support. - Bug fix for Transit Peering in handling BGP manual route summary. R4.2.740 (Patch release of 4.2 on 3/31/2019) =============================================== Notable bug fixes: - When attaching a VPC with CIDR 192.168.0.0/16, the system crashes. - When on-prem advertises 0.0.0.0/0, Spoke Gateways in the transit deployment could lose connectivity to the Controller. - FQDN process crashes when certain invalid or corrupted packets are received. - Datadog for gateway in ARM does not work. Fix is a workaround to disable Datadog in ARM. - InsaneMode BGP session goes down after phase-2 negotiation. R4.2.634 (3/19/2019) ====================== 1. Networking ---------------- - **Transit DMZ for Egress/Ingress Traffic Inspection** provides the networking capability to route Internet bound egress traffic from Spoke VPCs to a third party firewall deployed in the Aviatrix Transit DMZ architecture for inspection. Once `Transit DMZ <https://docs.aviatrix.com/HowTos/transit_dmz_workflow.html#>`_ is deployed, go to Transit DMZ -> Advanced, click the Skewer button. Scroll down to enable "Egress through Firewall". - **Transit DMZ for East-West Traffic Inspection** provides the networking capability to route VPC to VPC traffic to a third party firewall deployed in the Aviatrix Transit DMZ architecture for inspection. Once `Transit DMZ <https://docs.aviatrix.com/HowTos/transit_dmz_workflow.html#>`_ is deployed, go to Transit DMZ -> Advanced, click the Skewer button. Scroll down to enable "East-West Traffic Inspection". - **BGP Filtering From Learned Routes** allows you to selectively propagate on-prem routes to Spoke VPCs. When applied to the Aviatrix Transit Gateway, all spoke VPCs are filtered by the same rules. One use case of this feature is for a Spoke VPC that is customer facing and you do not wish your customer to access all your on-prem network CIDRs. For more details, refer to `this link. <https://docs.aviatrix.com/HowTos/gateway.html#filter-routes-to-spoke-vpc>`_ - **Spoke VPC CIDR Customization** allows you to specify what to program to a Spoke VPC route tables and ignore any learned routes propagated from on-prem. One use case of this feature is for a Spoke VPC that is customer facing and your customer is propagating routes that may conflict with your on-prem routes. To learn more, refer to `this link. <https://docs.aviatrix.com/HowTos/gateway.html#customize-spoke-vpc-routes>`_ - **Palo Alto VM-Series instance launch** can be done from the Aviatrix Controller console. This simplifies the VM-Series integration into Transit DMZ. To launch, go to Transit DMZ -> Preparation, follow the instructions to launch VM-Series instance. Note you must first subscribe the VM-Series AMI from AWS Marketplace. 2. Multi Cloud ---------------- - **GCP Spoke Gateway** allows you to launch a GCP gateway in the Aviatrix Next Gen Transit Network workflow. To launch, follow `the Transit VPC workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ to launch a GCP Spoke Gateway. - **GCP FQDN support** allows you to apply Aviatrix FQDN Egress Control to an Aviatrix GCP gateway. Follow `the instructions for FQDN Control <https://docs.aviatrix.com/HowTos/FQDN_Whitelists_Ref_Design.html>`_ to get started. 3. Operation ------------- - **Controller SAML Authentication** Aviatrix administrators can authenticate to the Controller by SAML authentication on an IDP. Follow the `instructions <https://docs.aviatrix.com/HowTos/Controller_Login_SAML_Config.html>`_ to setup authentication with SAML. - **Alert for New Release** sends email to the Controller admin email address to alert you when a major release becomes available. - **Aviatrix Gateway EBS Volume Encryption** allows you to encrypt the AWS gateway EBS volume after the gateway is launched. Learn more at this `link. <https://docs.aviatrix.com/HowTos/gateway.html#encrypt-ebs-volume>`_ - **Connectivity test** From the Aviatrix Controller you can launch two test instances and run a connectivity test in under two minutes time. One use case is to test connectivity two Spoke VPCs attached to Aviatrix Transit Gateway or AWS Transit Gateway. To use, go to the Controller console, Troubleshoot -> Diagnostics -> Network Validation. 4. Security ------------- - **FQDN AZ Affinity Load Balancing** is an optimization to avoid cross AZ traffic charge. If you have two private route tables where each route table is associated with subnets in a separate AZ, the Aviatrix Controller programs the default route (0.0.0.0) in each route table to point to the Aviatrix gateway deployed in the that AZ. Note if you have more than two private route tables and more than two AZs of subnets, cross AZ traffic is still not avoidable for some private subnets. R4.1.946 (Patch release of 4.1 on 2/21/2019) =============================================== Notable field found bug fixes: - Disable OPTIONS HTTP method to pass security scan. - Detach or delete Spoke Gateway when the gateway instance has been deleted from AWS console. - Allow editing manual summarization CIDR when spoke CIDR are either in primary or backup gateway. R4.1.914 (2/9/2019) ===================== 1. Networking --------------- - **Transit Gateway Peering** establishes encrypted tunnels that connect inter region and inter cloud networks by Transit Gateways. This allows you to build a software defined, fully connected global transit network with multiple transit clusters. The spoke VPC/VNet CIDRs and on-prem routes are automatically propagated throughout the network. To configure, follow the `Transit Gateway Peering <https://docs.aviatrix.com/HowTos/transit_gateway_peering.html>`_ instructions. - **Azure Transit Gateway** allows you to launch a Transit Gateway in Azure and build a transit network in Azure the same way for AWS. For configuration instructions, follow the `Global Transit Network Workflow Instructions <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_. "Advertise Transit VNET CIDR" is not supported in 4.1. - **AWS Transit Gateway DMZ** is a Bring Your Own Firewall architecture that seamlessly integrates virtual firewall appliances into the edge of the Next Gen Transit Network. By decoupling firewall functions from the network functions, the architecture allows a scalable firewall deployment that filters traffic between on-prem and cloud. Check out `Transit Gateway FAQ <https://docs.aviatrix.com/HowTos/transit_dmz_faq.html>`_ to learn more. For configuration, follow the `Transit DMZ workflow <https://docs.aviatrix.com/HowTos/transit_dmz_workflow.html>`_.. - **Palo Alto VM-Series Integration** integrates the firewall route updating and health monitoring into the Aviatrix Controller for the AWS Transit Gateway DMZ deployment. The Controller monitors and applies VM-series APIs to the appliance, thus simplifies the operations. For details, read `<https://docs.aviatrix.com/HowTos/transit_dmz_vendors.html>`_. - **External Device support for Transit** allows you to build the Next Gena Transit Network without the constraint of the 100 route limits by AWS VGW. By establishing the IPSEC tunnel directly to your on-prem router over Direct Connect or Internet, VGW no longer carries the routes from on-prem and Spoke VPCs. To configure, follow the `Transit Gateway to external device <https://docs.aviatrix.com/HowTos/transitgw_external.html>`_. Check out the configuration examples for `on-prem ISR/ASR <https://docs.aviatrix.com/HowTos/transitgw_external.html#appendix-2-transit-connection-to-cisco-isr-asr-over-direct-connect>`_. - **Insane Mode Encryption** breaks the 1.25Gbps Transit VPC performance limit and allows you to scale your transit network to 10Gbps throughput with encryption between on-prem and Spoke network. Insane Mode is also supported for Spoke VPCs' connectivities with up to 20Gbps throughput. Follow `Insane Mode <https://docs.aviatrix.com/HowTos/insane_mode.html>`_ to learn more. - **Aviatrix Hardware Appliance CloudN** is the on-prem appliance that enables the Insane Mode Encryption for the Next Gen Transit Network. For details, check out `Aviatrix hardware appliance CloudN <https://docs.aviatrix.com/HowTos/insane_mode.html>`_. 2. OpenVPN® -------------- - **OpenVPN® User Tracking** enables you to quickly correlate a destination IP address access to the specific VPN user. If you select Destination IPs and enter a list of IP addresses, the Aviatrix Controller console returns the list of the VPN user names that communicated with the IP address. If you select Username and enter VPN user names, the console returns all destination IP addresses the user visited. You can further filter on time span and selected VPN gateways. To use the feature, go to Troubleshoot -> Diagnostics -> VPN User. If your VPN configuration is Full Tunnel mode (as opposed to the default Split Tunnel mode), this tool enables the administrator to have complete visibility of your end user activities including Internet browsing. - **OpenVPN® User Diagnostics** improves the speed to troubleshoot if a VPN user has connection problem. Simply enter the user name and discover the errors. To use, go to Troubleshoot -> Diagnostics -> VPN User, enter the VPN user name and click Go. 3. Troubleshoot ---------------- - **Flightpath With Expert Diagnostics** adds expert diagnostics capability to the popular `Flightpath tool <https://docs.aviatrix.com/HowTos/flightpath.html>`_. Flightpath reduces the stress of everyday troubleshooting by pulling together multiple AWS service pages to a single page with side by side display of source and destination information. With the new expert diagnostics, the Aviatrix Controller checks if there are any obvious configuration errors in instance security group rules, VPC route table entries, TGW route table entries and VPC network ACLs. Note this tool is heuristic and cannot replace human experience and judgment. - **Trace Path** is a tool to discover MTU size of devices along the network path. This is useful to help understand if the network devices support Jumbo Frame sizes when you deploy Insane Mode. To use, go to Troubleshoot -> Diagnostics -> Network -> GATEWAY UTILITY. Select the Aviatrix gateway name, outgoing interface, destination IP address or host name, and click Trace Path. - **Packet Capture Enhancement** allows you to see the tunnel interfaces with the gateways names for easy identification. To use, go to Troubleshoot -> Diagnostics -> Network -> PACKET CAPTURE. Select a gateway, Interface, optionally select Host, Port, Duration and Packet length. Click Start to start capturing packets, click Stop to stop the packet capturing. Click Download to download the PCAP file that can be analyzed with Wireshark tools. 4. Security ----------- - **Port Range Configuration on Egress FQDN** allows you to configure TCP/UDP port range for non HTTP/HTTPS ports in a single policy and simplifies the configurations. The maximum port range span is 100 per policy. Configure multiple rules to support larger port range. To configure, go to Security -> Egress Control. 5. Operations --------------- - **Create a VPC** has a new enhancement that allows you to specify "Aviatrix Transit VPC" as an option. This is the best practice for deploying the Next Gen Transit Network, as it creates sufficient number of subnet and route tables. To create, go to Useful Tools -> Create a VPC, select the option "Aviatrix Transit VPC". - **AWS Transit Gateway Audit** is a new function for AWS Transit Gateway Orchestrator that monitors and alerts any out of band changes to AWS Transit Gateway (TGW) related resource, such as route table, route entry, route propagation attribute, VPC attachment and detachment. The out of band change refers to any configuration change that is not initiated from the Aviatrix Controller. To enable, go to the Controller console, TGW Orchestrator -> Audit turn on the auditing capability for each Transit Gateway. - **Display and Download Audit Log** displays on the Aviatrix Controller console who and when accessed the Aviatrix Controller and what commands have been issued. To display audit log, go to Troubleshoot -> Logs -> Display Audit. To filter, type in the search panel and click Display Audit again. To download the log file, click Download Audit. Note all logs are also stored in the syslog that you can export to external log services. - **Splunk Integration Enhancement** allows you to customize Splunk index for inputs.conf improving log analysis visibility. - **Gateway Certificate Import** allows you to import third party signed certificate into Aviatrix gateways. To import, go to Settings -> Advanced -> Security -> IMPORT CERTIFICATE WITH KEY. Select the gateway, upload the CA Certificate and click OK. R4.0 (11/26/2018) ================= 1. Security ------------- - **FQDN Source Filter** enhances egress FQDN function by allowing source IP filtering on any tag and gateway. A given tag can have different source IP filtering applying to different gateways. This provides fine grained configuration control. To configure, click Edit Source on an existing tag and select a gateway to edit. For details, read `Edit Source <https://docs.aviatrix.com/HowTos/FQDN_Whitelists_Ref_Design.html#edit-source>`_. 2. Next Gen Transit Network ----------------------------- - **AWS TGW Orchestrator** is a feature that extends the Aviatrix Transit Network to include AWS Transit Gateway. Key benefits are policy driven network segmentation, no need for Spoke VPC gateway and out-of-box integration with Direct Connect and Internet VPN. For details, check out `Aviatrix TGW Orchestrator FAQ <https://docs.aviatrix.com/HowTos/tgw_faq.html>`_. - **Insane Mode Beta** allows you to build high performance network by deploying Aviatrix hardware appliance in the datacenter. Additional benefits are bypass VGW 100 route limits and high performance encryption over Direct Connect. Contact <EMAIL> to be part of the beta program and learn the use cases for `Insane Mode <https://docs.aviatrix.com/HowTos/insane_mode.html>`_. 3. Operations -------------- - **AWS CloudWatch Log Integration** exports the Aviatrix Controller and gateways logs to AWS CloudWatch Log. If you are already using AWS CloudWatch log service, enable this feature to consolidate the logs from Aviatrix Controller and gateways to the same service. For details, read `AWS CloudWatch Integration <https://docs.aviatrix.com/HowTos/cloudwatch.html>`_. R3.5 (10/7/2018) ================= 1. Security ------------ - **Amazon GuardDuty Integration** adds enforcement functions to Amazon GuardDuty IDS and continuous monitoring service. For example, malicious probes found by GuardDuty can be blocked at the VPC network level automatically orchestrated by Aviatrix Controller. Read `Amazon GuardDuty Integration <https://docs.aviatrix.com/HowTos/guardduty.html>`_ to learn how GuardDuty and Aviatrix integration help securing your AWS deployment. - **Egress FQDN multi tag support** allows you to attach multiple FQDN tags to a gateway. This function simplifies the FQDN rule management. For example, you can create a common base tag of rules for all VPCs and additional tags for specific VPCs. - **Integrated Egress FQDN and NAT function** simplifies deploying FQDN service. Aviatrix Controller automatically replaces the existing AWS NAT Gateway route entry in AWS route table, if there is any, with Aviatrix gateway entry to minimize downtime and simplify deployment when launching FQDN service. - **Egress FQDN and Stateful Firewall interoperability** allows both services to operate together. You can use base Deny All for all your IP address based rules and still use Whitelist FQDN for host name based rules at the same time. 2. Transit Network -------------------- - **Connected Transit** enables all Spoke VPCs to communicate with each other with encryption via the Transit GW in a Transit Network deployment. This effectively builds a full mesh encrypted Transit network without building individual tunnels between Spoke VPCs. Read `Connect Transit <https://docs.aviatrix.com/HowTos/site2cloud.html#connected-transit>`_ for how to enable this function. - **Advertise Transit VPC CIDR** improves flexibility of Transit Network. Now an instance in Transit VPC can communicate with either Spoke and on-prem via Transit GW. For example, you can launch an Aviatrix SSL VPN gateway in the Transit VPC. Read `Advertise Transit VPC CIDR <https://docs.aviatrix.com/HowTos/site2cloud.html#advertise-transit-vpc-network-cidr-s>`_ for more details. 3. Operations -------------- - **Netflow support** enables you to record and log all TCP/UDP sessions flowing through all Aviatrix gateways.This adds more visibility to your network in addition to the existing log forwarding functions for Splunk, SumoLogic, Remote Syslog, DataDog and Logstash. Read `Netflow Integration <https://docs.aviatrix.com/HowTos/netflow.html#netflow-integration>`_ for more details. - **Alert Bell** is a new multi purpose alerting function displayed on the Aviatrix Controller Console. For example, Aviatrix Controller periodically scans your AWS route tables and alerts you if there is any blackhole entry in your AWS route table that needs to be cleaned up as best practice. GuardDuty findings are also recorded by Alert Bell. - **VPC Tracker** has been expanded to include network CIDRs discovered on your Azure accounts, Site2Cloud remote CIDRs and Transit Network on-prem CIDRs. For details, check out `VPC Tracker <https://docs.aviatrix.com/HowTos/vpc_tracker.html>`_. - **Create Azure VNet** allows you to create a fully populated Azure VNet from Aviatrix Controller console. - **Specify an EIP** lets you specify an unassociated EIP in your allocated EIP pool at the gateway launch time. This helps you control what EIP to use for an Aviatrix gateway. - **Aviatrix resource tags support** gives you the option to reduce the Aviatrix required IAM policy scope by restricting actions on these tagged resource. All resources created by the Aviatrix Controller has an identifiable AWS tag. The key value pair of the tag is `Aviatrix-Created-Resource:Do-Not-Delete-Aviatrix-Created-Resource`. Follow information in this `section <https://docs.aviatrix.com/HowTos/customize_aws_iam_policy.html#use-aviatrix-tags-to-limit-resource-deleting-policy-scope>`_ to limit the aviatrix-app-policy. An example IAM policy with Aviatrix tag can be found `here. <https://s3-us-west-2.amazonaws.com/aviatrix-download/aviatrix_customized_IAM_app_policy.txt>`_ R3.4 (8/5/2018) ================ 1. Security ----------- - **Egress FQDN for non HTTP/HTTPS traffic** expands the popular FQDN feature to allow you to control traffic for SFTP, SSH and any other TCP/UDP port using domain names. The new FQDN is backward compatible and auto populates the default protocol and port number (TCP/443) when you configure. For details, check out `Egress Control Filter <https://docs.aviatrix.com/HowTos/FQDN_Whitelists_Ref_Design.html>`_. - **Egress FQDN Import and Export** allows you to download and upload the rules of a FQDN tag in a text file format. This helps you manage large set of rules of multiple tags. For example, you may upload the text file downloaded from `FQDN Discovery <https://docs.aviatrix.com/HowTos/fqdn_discovery.html>`_. You may also download rules from one tag and upload to a different tag to save time from typing. For details, check out `FQDN Export <https://docs.aviatrix.com/HowTos/FQDN_Whitelists_Ref_Design.html#export>`_ and `FQDN Import <https://docs.aviatrix.com/HowTos/FQDN_Whitelists_Ref_Design.html#import>`_. - **FQDN Azure support** is now available. The configuration is the same as for AWS. - **FQDN Exception Rule** provides an option to block SSL request that does not have SNI field. For example, if an application use hard coded destination IP address in its HTTPS request, disabling Exception Rule will block the request, unless the IP address is configured as a rule in the tag. - **Network Address Translation** is significantly expanded to support combinations of SNAT, DNAT with flexible rules to enable new use cases. For example, gateway can now do network translation to a pool of IP addresses, a customized IP addresses and session based translation. This enables gateway to perform complex and customized network address translation requirements. For an example use case, check out `this solution guide. <https://docs.aviatrix.com/Solutions/egress_nat_pool.html>`_ 2. Useful Tools ---------------- - **VPC Tracker** is a tool that provides a "at a glance" view of cloud network CIDR ranges of all your cloud accounts in all regions. No gateway launch required, just add `secondary access accounts on the Controller <https://docs.aviatrix.com/HowTos/aviatrix_account.html>`_, the Controller will retrieve all information for you. The VPC Tracker is also displayed on the Controller Dashboard. You have the option to turn it off. To view all VPC CIDRs, go to "Useful Tools" at the main navigation menu, click "VPC Tracker". To learn more, read the `VPC Tracker <https://docs.aviatrix.com/HowTos/vpc_tracker.html>`_. - **Create VPC** is a tool that creates an AWS VPC with a public subnet and private subnet in each AZ, a public route table, private route table and IGW in a specified account and region. 3. Connectivity ---------------- - **AWS NLB Support for Aviatrix OpenVPN® gateways** allows you to display the remote users' public IP address when they are connected to the gateway. - **Configurable Dead Peer Detection (DPD)** provides the flexibility to work with third security appliance when building the `Site2Cloud <https://docs.aviatrix.com/HowTos/site2cloud.html>`_ tunnels. - **Use Your Own DNS** allows the gateway to use the DNS server configured in the VPC DHCP options.One use case is for Aviatrix gateways to export logs to a private Splunk Server that would like to have its DNS name configured on the `Logging setup <https://docs.aviatrix.com/HowTos/AviatrixLogging.html>`_. For more information, read `the guide. <https://docs.aviatrix.com/HowTos/gateway.html#use-vpc-vnet-dns-server>`_ 4. Operation ------------- - **Controller HA in AWS** is simplified and now supports all types of AMIs in addition to BYOL. Follow the `instructions <https://docs.aviatrix.com/HowTos/controller_ha.html>`_ to enable HA. - **Deployment Scale** is improved. A Controller of t2.large instance can support 500 Aviatrix gateways. R3.3 (6/10/2018) ================= 1. Security ------------ - **Egress FQDN Discovery** enables you to discover what Internet sites (URLs) your Apps in a VPC visit. When enabled on an Aviatrix NAT gateway, the gateways monitors and displays all the destination FQDN names from EC2 instances in the VPC, which helps you build whitelist for FQDN filter. This is a standalone feature, meaning you can use it even for curiosity purpose. To configure `Egress FQDN Discovery <https://docs.aviatrix.com/HowTos/fqdn_discovery.html>`_, go to Security -> Egress Control. Follow Step 1 and Step 2. To turn it off, simply click Stop button. Note FQDN Discovery and FQDN Filter are mutually exclusive on a given gateway. - **Egress FQDN View Log** provides you with a quick way to view gateway FQDN logs when you are curious to view some immediate results. Select a gateway with FQDN enabled, click Download, a compressed log file should be downloaded. Note to log for monitoring and auditing purpose, you should consider a `Logging Integration <https://docs.aviatrix.com/HowTos/AviatrixLogging.html>`_. - **AWS Controller Security Group Management** manages the Controller instance Security Groups to only allow TCP port 443 from Aviatrix gateway EIP. To enable this feature, go to Settings -> Controller -> Security Group Management, select the primary access account that launches the Controller, click Enable. Note this feature is available for AWS Controller only deployment. If you deploy the Controller in other cloud types, this feature is not supported. For information, `read this link. <http://docs.aviatrix.com/HowTos/FAQ.html#enable-controller-security-group-management>`_ 2. Connectivity ---------------- - **Azure Spoke Gateway** is now supported in the Transit Network workflow. To configure, follow the Transit Network workflow `Step 4 <http://docs.aviatrix.com/HowTos/transitvpc_workflow.html#launch-a-spoke-gateway>`_ to launch a Spoke Gateway in Azure. - **Multi-CIDR VPC support** is now available if your VPC has multiple CIDR ranges. - **Destination NAT** on a gateway allows you to change your destination IP address prior to routing. To configure, go to Gateway page, select the gateway, click Edit. Scroll down to DNAT, click Edit/Add. Enter virtual address (mapped), real address, the protocol and port range are the scope of DNAT condition. Click `here <http://docs.aviatrix.com/HowTos/gateway.html#dnat>`_ for more information. - **Configurable Designated Gateway CIDR Range** allows you to add additional CIDRs that are outside of RFC1918. To configure, go to Gateway page, select the gateway, click Edit. Scroll down to "Edit Designated Gateway" to add additional CIDR list separated by comma. This feature is useful if your VPC CIDRs are outside of RFC1918. Click `the link here <http://docs.aviatrix.com/HowTos/gateway.html#designated-gateway>`_ for more information. - **AWS China Support**. Both Controller and gateway can be launched in AWS China. Follow the `AWS China Controller Startup Guide <http://docs.aviatrix.com/StartUpGuides/aviatrix-china-controller-startup-guide.html>`_ to get started. - **Spoke CIDRs Summarization support** allows you to reduce the number of routes advertised by Aviatrix Transit GW to VGW, to overcome the VGW limit of carrying a maximum of 100 routes. Click `here <https://docs.aviatrix.com/HowTos/transitvpc_faq.html#how-to-summarize-spoke-vpc-cidr-ranges>`_ for configuration details. 3. Ease of Use --------------- - **Modular Remote User VPN** enables you to configure or modify all VPN parameters after the VPN gateway is launched. We recommend you not to select any Advanced Option when launching a VPN gateway and configure any specific parameter at later time. - **Workflow for all Use Cases**. Major Aviatrix use cases now have a workflow to guide you through. - **Azure Companion Gateway** is no longer needed to be subscribed. The subscription step has been removed. 4. Operations -------------- - **Source Category** is supported in Sumo Logic specification. To configure, go to Settings -> Logging -> SUMOLOGIC Logging. - **Source Address** is added in FQDN logs. This enables you to see which EC2 instance send packets to a target hostname. - **Access Account Name** is now searchable. - **New APIs** are available for all features in 3.3. - **List Spoke Gateways** allows you to easily see what are the Spoke Gateways are attached to a selected Transit Gateway. To view, scroll down to Step 9 at Transit Network workflow, select a Transit GW and view the attached Spoke Gateways. R3.2 (4/18/2018) ================= 1. Security --------------- - **Gateway Subnet Monitoring** monitors the public subnet where Aviatrix gateway is deployed and automatically stops any user instance in the subnet. This feature ensures unwanted instances are not launched on public subnets in a VPC. To configure, go to Gateway -> Edit -> Monitor Gateway Subnets.If you want to exclude certain user instances from being stopped, you can enter their instance IDs. 2. Operations -------------- - **SSL Certificate Import** allows to import your own key and wildcard certificate for Controller HTTPS access. To import the certificate and key, go to Settings -> Advanced -> Security -> Import Method and select "Import Certificate with Key". - **Disable Admin User Login** allows to disable Controller login as user "admin". To enable/disable it, go to Settings -> Controller -> Login Customization. - **Migrate controller** allows you to migrate among different licenses including Metered, Utility and BYOL through Controller backup and restore. 3. Troubleshooting ------------------- - **Transit Network** can detect overlapping CIDRs between learned on-prem CIDRs and advertised spoke CIDRs. Controller will display these overlapping CIDRs at Site2Cloud -> Edit page in addition to sending email alerts. - **Gateway Replacement** allows to replace a problematic gateway but still keep its configuration. To replace the gateway, go to Troubleshoot -> Diagnostics -> Gateway Replace. - **UCC Controller Public IP Migration** can be used after Controller's public IP is changed. To migrate, go to Troubleshoot -> Diagnostics -> Network -> Migrate. 4. API ------------ - 50 APIs have been added to the Controller. R3.1 (3/6/2018) =============== 1. Connectivity --------------- - **AWS Global Transit Network** is a new workflow that provides a step by step guide to setup `AWS Global Transit Network. <http://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ - **AWS VPC Peering integration** is a 1-click operation to `configure native AWS VPC peering <http://docs.aviatrix.com/HowTos/peering.html>`_ for intra region and inter-region VPC communication. - **BGP dampening** `BGP dampening <http://docs.aviatrix.com/HowTos/advanced_config.html#bgp-dampening>`_ allows you suppress flapping routes. 2. Operations -------------- - **Backup to encrypted S3 bucket** allows you to backup Controller configuration to an `encrypted S3 bucket <http://docs.aviatrix.com/HowTos/controller_backup.html#how-to-backup-configuration-with-aws-encrypted-storage>`_. Check out `this link <http://docs.aviatrix.com/HowTos/controller_backup.html#how-to-backup-configuration-with-aws-encrypted-storage>`_ to enable backup and restore feature. - **Modular NAT configuration** allows you to `enable or disable NAT <http://docs.aviatrix.com/HowTos/gateway.html#nat>`_ function after a gateway instance is launched. - **Gateway Force Upgrade** allows you to force upgrade a specific gateway. This is useful when Controller upgrade fails on some gateways. Go to Troubleshoot -> Diagnostics -> Gateway -> FORCE UPGRADE - **Configurable TLS version** allows you to turn off support for older versions, such as TLSv1.0 and TLSv1.1. TLSv1.2 is supported by default. To configure, go to Settings -> Advanced -> TLS VERSIONS SUPPORT - **Dashboard Logical View** allows you to view VPCs and connection graph. Each dot represents a gateway deployed in a VPC. You can rearrange the graph by dragging the dots. Make sure you click Save to save the changes. - **Gateway Single AZ** is an economic way to improve gateway uptime without running a standby instance. The Aviatrix Controller monitors the gateway's health and when gateway keep alive packets fail to arrive at the Controller, it stops and starts the gateway again. To configure, go to Gateway, select a gateway to Edit, then Enable or Disable Single AZ gateway HA. - **Security patches** for CIS-CAT and Meltdown. - **Terraform provider** is now available for `Transit Network <http://docs.aviatrix.com/HowTos/Setup_Transit_Network_Terraform.html>`_ - **Updated Aviatrix APIs** is now organized by functions and easier to `follow. <http://docs.aviatrix.com/HowTos/Aviatrix_Controller_API.html>`_ R3.0 (12/1/2017) ================ 1. Connectivity --------------- - **BGP** Support BGP interoperability between Aviatrix gateway and AWS VGW. For use case details, check out `the Transit Network with BGP Setup Instructions. <http://docs.aviatrix.com/HowTos/bgp_transitive_instructions.html>`_. - **IPmotion** For AWS migration and DR use case that allows on-prem VMs to migrate to AWS without changing their IP addresses. For use case and details, check out `this link. <http://docs.aviatrix.com/HowTos/ipmotion.html?highlight=ip%20motion>`_. - **AWS ENA** on Aviatrix gateway. 2. Security ----------- - **Tag your security policy** to associate a CIDR with a name tag for a scalable and user friendly. For configuration detail, check `this link. <http://docs.aviatrix.com/HowTos/tag_firewall.html?highlight=tag>`_ - **AES-GCM crypto algorithm**. For IPSEC tunnel connectivity between two Aviatrix gateways, such as Aviatrix peering and IPmotion, the crypto algorithm has been upgraded to AES-GCM. 3. Controller -------------- - **Audit** user actions on the Controller. All commands from web console or API are now logged to syslog and can be forwarded to integrated log services. - **Name your controller** for ease of use. Click "Your controller name goes here" on the Controller console and start typing a new name. Hit return to save the name. - **On demand backup** of the Controller configuration to cloud storage. To configure, go to Settings -> Maintenance -> Backup & Restore -> Backup Now - **Backup multiple copies** of Controller configuration file. You can choose to backup multiple copies of configuration file. To do so, go to Settings -> Maintenance -> Backup & Restore and select Multiple Backup. Up to 3 backup files are stored. You can select any one of them to restore. - **Migrate licenses** from AWS Marketplace Utility image to BYOL. For details, check out `this link. <http://docs.aviatrix.com/HowTos/Migration_From_Marketplace.html>`_ 4. Modular Configuration ------------------------- - **Transitive Peering** supports multiple subnets being configured at the same time. Multiple subnets separated by comma can be added once when configuring transitive peering. - Join Function now support the ability to delete all subnets at once in Join Function gateway. 5. Troubleshooting ------------------- - **FlightPath tool**, an AWS EC2 to EC2 connectivity troubleshooting tool. In the first release, EC2 related resources, such as security groups, route table and Network ACLs are displayed side by side for easy visualization and troubleshooting. 7. Datacenter Extension Features --------------------------------- - **non-RFC1918** on premise network range is now supported. To add, first launch a Datacenter Extension gateway, go to Gateway List, select the gateway and click Edit. At Edit Extended Public CIDR, add one or multiple non-RFC1918 CIDR blocks separated by comma. For example, 172.16.58.3/24,172.16.31.10/24 - **Repair gateway** to replace a gateway in a limbo state. At the Datacenter Extension page, click Replace of specific gateway. R2.7 ========== 1. Controller ------------------- - Console Responsiveness improvements. Significant improvements in page responsiveness when using controller web console. - Support third party signed certificate. You now can import a third party signed certificate to the controller. This should remove the "Not Secure" sign displayed by the browser. To configure, go to Settings -> Advanced -> Certificate -> CERTIFICATE IMPORT. First Enable Certificate Checking. The console will ask you to enter a domain name and generate a CSR file (Certificate Signing Request). Send this CSR to get singed, then import both CA and server certificate. Note if intermediate certificate is one of the return files, use the intermediate certificate file for CA import. 2. Connectivity ------------------- - Support Site2Cloud tunnel on TCP. In addition to run IPSEC tunnel on UDP protocol, you can now run on TCP 443. This option removes the requirements of having to open site firewall ports on UDP 4500/500. To configure, go to Site2Cloud -> Add New. Select TCP for Tunnel Type selection. 3. Scalability --------------- - Support load balancing UDP based OpenVPN® gateways. If your OpenVPN® users experience slow terminal response or long file transfer time, use UDP based VPN gateway can help. This release allows you to create multiple UDP based VPN gateways and load balance them in a round robin fashion by leveraging AWS Route53. To configure, go to OpenVPN® -> Advanced -> UDP Loadbalancer. Note with UDP protocol UDP port 1194 is used. When using from on-prem, firewall port UDP 1194 must be open. - Support Designated Gateway. If you are planning to have a large set of tunnels going through a gateway or are hitting AWS route entry limit, this feature is for you. If "Designated Gateway" option is selected at the gateway launch time, the Controller programs 3 route entries based on RFC1918 for the gateway. Controller will not program additional route entries when configure a VPN tunnel that end on the Designated Gateway. Note if you currently do not have a Designated Gateway and you are hitting route entry limit, launch a new gateway with Designated Gateway enabled and configure future tunnels from the Designated Gateway. Note there can only be one Designated Gateway per VPC. Designated Gateway only supports Gateway HA. 4. Modular Configuration -------------------------- - Allocate New EIP. When this option is selected at new gateway launch time, Controller always allocates a new EIP from AWS and associated it with the gateway. If this option is unchecked, Controller will first look at the EIP pool that belong to the account: if there is allocated but unassociated EIP, Controller will allocate EIP from this pool and associate it with the gateway, otherwise it will select one EIP from the pool and associate it with the gateway. - Support resizing active Gateway without deleting its peering tunnel. You can resize an active gateway when their peering HA configured. The workflow should be: 1) Settings -> Gateways -> select the gateway, select Edit. 2) Select it desired gateway instance size, click Change. As the result of this function, the gateway will be stopped and tunnel switch to backup tunnel. 3) Go to Settings -> Peering, select the peer and click Force Switchover. - Support resizing UDP based OpenVPN® gateway instance. 5. NEW APIs ------------------ - Set VPC Access Base Policy. - Update VPC Access Policy. - Enable Packet Logging. R2.6 =================== Connectivity ------------- - Run encrypted tunnel on TCP port 443. Aviatrix Virtual Appliance CloudN now offers a TCP based secure tunnel connectivity. With this new capability, you do not need to open outbound UDP port 500 and 4500. The encrypted tunnel runs on TCP 443. To configure, go to Datacenter Extension, select TCP for the field Tunnel Type. UDP based encrypted tunnel is still supported. - Reserve on-prem segment for Datacenter Extension feature of CloudN. After deciding how many VPCs you wish to configure during on boarding, you can sub divide the segments to reserve some for on-prem VM deployment. This allows you launch applications where some part of it (such as database) is on-prem and others parts of it (such as web front end) to be in VPC. - Google IDP support. Google IDP is now supported IDP for the Aviatrix SAML VPN solution. Security --------- - FQDN blacklist. In addition to FQDN whitelist, FQDN whitelist is added as a base configuration for each FQDN tag. To configure, go to Advanced Config -> FQDN Filter. After you create a new tag, you can select either White List or Black List. With Black List, the URLs on the Black List will be rejected. API --------- - New APIs are published. list active VPN users, edit Open VPN configuration, backup and restore, list VPC peers, list image. For API details, click `this link. <https://s3-us-west-2.amazonaws.com/aviatrix-download/Cloud-Controller/Cloud+Services+Gateway+Controller+API+reference.pdf>`_ for details. User Interface -------------- - re-organize menu items on Settings. Under Settings -> Maintenance are Upgrade, Backup & Restore and Security Patches. Under Settings -> Controller are System Time, License information, Email settings and controller access method authentication LDAP or DUO configuration.oUnder Settings -> Advanced are tunnel timeout and keepalive configuration, password change and certificate management. - Make a wish. Customers can now send feedback on UI pages regarding features, usability and make a wish on new requirements and enhancements. R2.5 ============================= 1. Security improvements ------------------------- - Provide security patch to upgrade OpenVPN® server to v2.4.3. To apply the patch, go to Settings->Patches and select OpenVPN® 2.4.3 - New Aviatrix VPN client (v1.3.9) for user VPN (Mac, PC and Unix). To download, go to `this link. <http://docs.aviatrix.com/Downloads/samlclient.html>`__ - Hardened password management for "forgot password". - Additional ciphers for site to cloud tunnels for interoperability. To configure, go to Site2Cloud -> "Add New" -> Algorithms. 2. Public cloud specific features ---------------------------------- - AWS China [available in the UCC version only] · - Restful API support for AWS China. For details of the complete APIs, refer to `API Document <https://s3-us-west-2.amazonaws.com/aviatrix-download/Cloud-Controller/Cloud+Services+Gateway+Controller+API+reference.pdf>`__. - Aviatrix cluster peering over AWS peering. To enable it, go to Peering -> "Cluster Encrypted Peering" -> "New Peering" and select "Over AWS Peering". - Aviatrix backup/restore in Google Cloud. To configure back/restore, go to Settings -> "Backup & Restore". - Python script for Google Cloud Controller HA monitoring and restarting. `Follow <https://github.com/AviatrixSystems/Controller-HA-for-GCP>`__ 3. Usability enhancements -------------------------- - Multiple enhancements on User Interface. - Aviatrix product Doc site is now available at http://docs.aviatrix.com - New browser support: IE 11 4. Administration automation ----------------------------- - Cloud-init script to accept input parameters to launch Aviatrix Controller on premises. - Automated Aviatrix Controller deployment in AWS using `Cloudformation: <http://docs.aviatrix.com/StartUpGuides/aviatrix-cloud-controller-startup-guide.html>`__ - GW Resizing API "edit\_gw\_config". - Support proxy setting modification through "Advanced Config" -> "Proxy Settings". - Frictionless install UX [Register Aviatrix on premises Gateway with UCC Controller at the time of install to auto-fetch initial configuration; available for AWS at this time]. 5. Configurable Aviatrix Gateway Failover/HA time -------------------------------------------------- - Support configurable health check frequency between Aviatrix Controller and Gateways for customers to meet their HA failover time constraint. To change the health check frequency, go to Settings -> Keepalive. Select "slow" only when your network is unstable and gateways send too many status alerts. 6. Logs and troubleshooting ---------------------------- - Aviatrix for Splunk has been published on Splunkbase. To download, click `this link <https://splunkbase.splunk.com/app/3585/>`__. For instructions on how to use the app, click `this link <https://github.com/AviatrixSystems/SplunkforAviatrix>`__. - Aviatrix for SumoLogic application is available. To download, click `this link <https://github.com/AviatrixSystems/SumoLogicforAviatrix>`__. - Rsyslog over UDP for customers needing UDP based rsyslog. To configure, go to Settings -> Loggings -> "Remote Syslog" and select UDP for "Protocol". - Configurable gateway debug level. To adjust the debug level, go to Troubleshot -> Diagnostics -> "Gateway Debug Level" and select the appropriate debug level for your gateway. 7. New Aviatrix OVF for VMWare ------------------------------- - Visit download.aviatrix.com UserConnect-031717 ================== Security -------- - First release to white list public Fully Qualified Domain Names (FQDN filtering) for egress HTTP and HTTPS traffic to Internet initiated by instances on private subnets in a VPC. The FQDNs can be specified with regex wild card, such as \*.example.com. A tag is defined as a list of FQDNs and one or more gateways is attached to a tag. Any updates to a tag automatically triggers updates to all gateways attached to the tag. Multiple tags can be defined on the controller. This feature works together with Gateway Security Policy feature where private network, IP address, protocol and ports can be filtered. To configure, go to "Advanced Config" -> "FQDN Filter". The workflow is 1) create a tag, 2) Click Enable to enable the tag, 3) Edit the tag by adding FQDN hostname part of URLs (e.g. `www.aviatrix.com <http://www.aviatrix.com>`__, or \*.google.com), and 4) Attach Gateway. One or more gateways can be attached to a tag. Step 1), 3) and 4) can be done first and then Enable the tag. Once the tag is enabled, HTTP and HTTPS traffic to these FQDN will be allowed, and any destination outside the FQDN will be denied. Note the gateway with FQDN must have NAT enabled for Internet egress traffic. Caveat: in this release FQDN filter is not failover capable when peering HA is configured. Monitor and Troubleshooting --------------------------- - During UCC gateway launch, Controller now reports in text the progress of gateway creation in addition to the progress bar view. - "Dry Run" for system upgrade. Dry Run performs health checks for the Controller and gateways to detect potential upgrade failure without executing the command. Go to Settings -> Upgrade. Optionally, click Dry Run. If it is successful, you may click Upgrade. - Dashboard now displays a summary packet statistics per gateway. Click on a specific gateway, top 10 packet statistics of the gateway are also displayed. - Support test network connectivity. This is useful to troubleshoot any firewall or security policy that blocks connectivity from the controller or gateway. To test, go to Troubleshoot -> Diagnostics -> "Network Connectivity Utility". Select either Controller or one gateway and test if it can reach a specific port of a remote host. - Capability has been added to log tunnel status change notification to syslog (in addition to an email notification with the same content). - Enhancement has been made for tunnel status alert mechanism by allowing users to configure tunnel down detection time. To change the detection time, go to Settings -> Tunnels. The default detection time is 60 seconds. - Capability has been added to check the VPC settings of a specific gateway. VPC settings include security groups, route tables, subnets, Network ACLs, DHCP options. To configure, go to Troubleshoot -> VPC Diagnostics - Splunk forwarder has been upgraded from version 6.2 to version 6.4. Connectivity and High Availability ---------------------------------- - Support multiple independent UDP based VPN gateways (without ELB) within the same VPC. These VPN gateways can have different attributes. For example, one gateway has split tunnel configured while the other one has full tunnel configured. - Support API credential change on controller console for Azure ARM accounts when the credential becomes out of sync with the credential on cloud provider console. For example, the account credentials are changed by the cloud provider or user herself. - HA support has been added to Service Chaining with AWS gateways in different zones. - Support IAM role-based controller and cloud account for AWS GovCloud. The Controller must be in GovCloud to create GovCloud gateways with IAM role-based accounts. - Site2Cloud HA support has been added with CloudN as the on-prem device. To configure it, launch two gateways in the same VPC/VNet with UCC Controller. Then go to Site2Cloud page to create a new connection. Check "Enable HA" and select "Aviatrix" from "Remote Gateway Type" list. After creating the site2cloud connection, select this connection and download configuration with "Aviatrix" as "Vendor". Import the same configuration file at CloudN's Site2Cloud page. Controller Administration ------------------------- - Function has been added to notify admin via admin email when a new release becomes available. - Support has been added to enforce password complexity of account users. To enable it, go to Settings -> Security -> "Password Management". - Support read only (operator) role for Controller management. The read only account has dashboard view, status view and list view, but cannot make modification to any configuration. To create a read only user, go to Accounts -> Account Users -> "New User". Select "read\_only" from the dropdown list of "Account Name". - CloudN's console password can be changed from the default. To do so, type "enable" to enter config mode and then issue "change\_console\_password" command. - Capability has been added for HTTPS certificate check for control traffic between Controller and gateways. To turn on this function, go to Settings -> Security -> "Certificate Checking". - The following APIs have been added. For details of the complete APIs, refer to `API Document <https://s3-us-west-2.amazonaws.com/aviatrix-download/Cloud-Controller/Cloud+Services+Gateway+Controller+API+reference.pdf>`__. - list\_vpcs\_summary - peer\_ha\_switch\_over - upload\_cloudx\_command\_log - upgrade UserConnect-013017 ================== - First release of Service Chaining. Service Chaining capability allows multiple instance based functions to work in tandem to control traffic flow path within an AWS VPC. For example, a firewall instance can be service chained with Aviatrix gateway so that EC2 initiated traffic will first be sent to firewall for inspection before forwarding it to Aviatrix gateway for peering to another VPC. To enable the function, go to "Advanced Config" -> "Service Chaining" to select the route table and enter "Downstream IP". Aviatrix gateway will only modify the selected route table to specify which outgoing traffic needs to go through itself and also route the incoming traffic to the "Downstream IP" address. Normally, the selected route table is associated with the subnet of your firewall's WAN (or untrusted) interface. The "Downstream IP" should be the IP address of your firewall's WAN interface. For details, check out `this <https://s3-us-west-2.amazonaws.com/aviatrix-download/Cloud-Controller/Aviatrix+Service+Chaining+Reference+Design.pdf>`__ reference design. - Within AWS, support has been added to allow deployment of the UCC Controller in VPC's private subnet. To enable this, during the Controller's initial setup, when prompted for "If this controller is being launched on a private subnet, check the box below, otherwise, leave it blank", select "private subnet" and then click the "save" button. Please note that when the Controller is deployed in private subnet it can only create gateways in private subnets. We assume these private subnets in various VPCs can reach each other through AWS peering. - For AWS, account diagnostics have been added. To run these diagnostics, go to Troubleshoot -> Diagnostics -> "Account Diagnostics". This diagnostics command will validate the AWS account credentials and check the status of associated gateways and SQS queues. - There is now support for adding multiple CIDRs separated by commas in "Advanced Config"->"Join Function" -> "Allow Subnet" at CloudN. - Tunnel HA for Azure ARM gateways can now be created through "Advanced Config"->"Join Function". To enable tunnel HA, select a particular gateway on the "Gateway" page and then go to "Gateway for High Availability Tunnel/Peering" to create a backup gateway. - Support has been added to allow the creation of two VPN gateways (without ELB) in the same VPC, one with SAML enabled and the other one with only certification authentication enabled (no MFA method supported on the 2\ :sup:`nd` gateway). - The Dashboard now displays the IPSec tunnels created by site2cloud connection. - Support has been added for enabling NAT on CloudN Controller itself. To enable this, go to Troubleshoot -> Diagnostics -> "NAT Configuration". - With this release, both the actual public IP address of the Controller and the stored public IP address if it is different from the actual public IP are displayed. To view these public IP addresses, go to Troubleshoot -> Diagnostics -> "Controller Public IP". - Proxy server support has been added on the UCC Controller for initial download and ongoing communication. During the Controller's initial setup, when prompted for "If the controller accesses the Internet through a proxy server, provide the following information, otherwise leave the fields blank", enter the server URLs for "HTTP Proxy" and "HTTPS Proxy". If the proxy server issues a self-signed certificate, upload a CA certificate. - The ability to setup proxy server setting for Internet connectivity in CloudN OVA has been added. To configure proxy server support, use "-setup\_network\_only {true\|false}" for clish command setup\_interface\_address and setup\_interface\_static\_address. Use clish command "setup\_network\_options {test\|save\|cancel}" to test/save/remove http/https proxy setting. Currently, "Datacenter Extension" and "Join Function" are not supported when proxy server is enabled. - Traceroute support has been added on gateways. To run "Trace Route", go to Troubleshoot -> Logs -> "Traceroute Utility". - For site2cloud, users can now select the route tables to be modified when "Encryption over ExpressRoute/DirectConnect" is enabled. Only subnets associated with the selected route tables will have tunnel connections to on-prem. To select route tables, go to Site2Cloud -> "Add New" and enable "Encryption over ExpressRoute/DirectConnect". Available route tables will show up in the "Route Tables to Modify" field. - The following APIs have been updated. For details of the complete APIs, refer to `API Document <https://s3-us-west-2.amazonaws.com/aviatrix-download/Cloud-Controller/Cloud+Services+Gateway+Controller+API+reference.pdf>`__. - Added: update\_profile\_policy & add\_admin\_email\_addr - Deprecated: add\_profile\_policy & del\_profile\_policy - Changed: connect\_container & add\_vpn\_user - In the Aviatrix VPN client 1.2.49 release, Linux version AVPN client is now in the supported list. UserConnect-121516 ================== - Add support for three additional AWS regions: Ohio (us-east-2), Canada (ca-central-1) and London (eu-west-2). - Enable load balancer support for Azure ARM VPN gateway creation. - Add packet capture support for both Controller (CloudN only) and gateways. To run "Packet Capture", go to Troubleshoot -> Diagnostics. Select "Local" from "Gateway" list to capture packets on CloudN. Select a gateway name from "Gateway" list to capture packets on the particular gateway. The packet capture files are in .pcap format and can be downloaded for analysis. - Add traceroute support on Controller (CloudN only). To run "Trace Route", go to Troubleshoot -> Logs. - Extend the Peering HA support initiated at 102416 release from AWS to GCloud and Azure ARM. To enable this feature, go to Gateway -> "Gateway for High Availability Peering" to create the backup gateway first and then go to Peering -> "Encrypted Peering" to create the peering with "Enable HA" selected. - Add diagnostics tools for IPSec tunnels created through CloudN "Join Function". Go to "Advanced Config" -> "Join Function". Select the IPSec tunnel to run diagnostics on it. The following options are available: debug, ping, measure latency, restart services and check peering status. - Allow to add VPN users to each individual gateway (with ELB disabled) instead of the whole VPC. Select the gateway name from "LB/Gateway Name" list at OpenVPN® -> "VPN Users" -> "Add New" to add VPN users to that gateway. - Support migrating the same CloudN from one public IP address to another address. Go to Troubleshoot -> Diagnostics -> Migrate to migrate CloudN from its old public IP address to a new one. - Support Controller migration from the old CloudN to a new CloudN. Go to Settings -> "Backup & Restore" to run backup at the old CloudN. Launch a new CloudN with a different public IP. Go to Settings -> "Backup & Restore" to run restore at the new CloudN. The migration function will automatically update the new CloudN with its own public IP. - Support LDAP for Controller login. To enable it, go to Settings -> "Setup LDAP Login" to enable LDAP login first. Then add users at Accounts -> "Account Users" with local passwords. These account users should exist at LDAP server also. With LDAP login enabled, these users can log into Controller with their LDAP passwords. If LDAP login disabled, these users can log into Controller with their local passwords. - Allow credential change for AWS and GCloud accounts when the account credentials are changed by the cloud provider. - Support Okta along with "Client Certificate Sharing" when creating VPN gateways. Select "Okta" from "Two-step Authentication" list and select "Yes" for "Enable Client Certificate Sharing" when launching a new gateway. In previous releases, "Client Certificate Sharing" can't be enabled when Okta is used. - Allow users to customize the email notification (both email content and attachment file name) for VPN client. To configure it, go to OpenVPN® -> Configuration -> "User Defined Email Notification" to edit the file name or email content. The new email format will be used when a VPN certificate is issued. - Add support for the following new APIs. For details of the complete APIs, refer to `API Document <https://s3-us-west-2.amazonaws.com/aviatrix-download/Cloud-Controller/Cloud+Services+Gateway+Controller+API+reference.pdf>`__ - test\_ldap\_bind - get\_gateway\_supported\_size - get\_supported\_region - list\_peer\_vpc\_pairs - peer\_vpc\_pair - unpeer\_vpc\_pair - Aviatrix VPN client 1.1.32 release UserConnect-112816 ================== - Added search capability to the Gateway list page. You can now search for gateways by any of the gateway attributes, such as Name, gateway instance size, account name, etc. - Added search capability to active VPN users list on dashboard. You can now search for active VPN users by all attributes, such as Name, Profile, Landing Gateway, etc. - CloudN "Join" function HA support. Join capability allows you to connect to an existing VPC with an IPSec tunnel. To enable HA, go to the Gateway page, click the gateway, and enable HA. - Remote Syslog enhancement. Enable remote syslog to optionally not be encrypted. To configure, go to Settings -> Loggings -> REMOTE SYSLOG, simply ignore the "cert" option. - Aviatrix SAML VPN client preview for GCloud. The new Aviatrix SAML client provides a seamless user experience when authenticating a VPN user through a SAML IDP. For customers who use SAML based Single Sign On (SSO) for a unified user authentication and access control to their applications, this new capability allows them to treat the Aviatrix VPN solution as another application that authenticates VPN users by an already established mechanism. This preview release has been tested on GCloud. Forgerock is the primarily tested IDP and Okta has been partially verified. The supported platforms for the Aviatrix SAML VPM clients are Mac OSX, Windows 10, and Windows 7. UserConnect-102416 ================== - Scale out encrypted peering support for AWS. You can create a cluster in a VPC that consists of up to 7 gateways, peering between two clusters in two VPCs increases packet throughput. To enable cluster encrypted peering, click Cluster Encrypted Peering under Peering tab. Preliminary iperf performance test shows TCP packet throughput can reach up to 8.5Gbps with bi-directional traffic. For more information, check out `Cluster Peering Reference Design <http://docs.aviatrix.com/HowTos/Cluster_Peering_Ref_Design.html>`__ - Controller HA support. Create a standby controller in any region and any cloud (AWS, Azure ARM and GCloud). When the primary controller goes down, the standby controller takes over and becomes operational. To enable the feature, click Settings -> Controller HA -> Enable. Input the standby controller's public IP address. You also need to input standby controller's admin username and password for authentication purpose. - Enhanced peering HA support. The new peering HA feature reduces failover to a backup peering to under 2 seconds. To enable the feature, click Peering -> Encrypted Peering and enable HA. Note the current gateway HA support will be phased out in the future. - Transitive peering support for Azure ARM, Azure classic, GCloud and Azure China. Built on the earlier release of transitive peering support for AWS, this feature is now covered by all cloud types. This feature enables you to deploy a hub and spoke architecture of multiple VPCs in a simple point and click manner. To enable transitive peering, click Peer -> Transitive Peering. - Peering Diagnostics support. Troubleshooting peering tunnel status is made easy. Click Diag of the specific peer. Options are debug, test latency, ping and restart the tunnel. - Display the public IP address of the controller. This feature is useful for CloudN64 virtual appliance where its public IP address is needed for configuring Site2Cloud capability. To view the controller's public IP address, click Troubleshoot -> Diagnostics -> CONTROLLER PUBLIC IP. - Support all Azure ARM regions. - Support interoperability of Aviatrix gateway Site2Cloud to AWS VGW and Azure VPN Gateway. When configuring Site2Cloud, you can select the specific cloud provider VPN gateways to ensure encrypted tunnel work correctly. - Add API for CloudN64 Join features: allow subnet to VPC and delete subnet to VPC. For the complete APIs, refer to `API Document <https://s3-us-west-2.amazonaws.com/aviatrix-download/Cloud-Controller/Cloud+Services+Gateway+Controller+API+reference.pdf>`__ UserConnect-101016 ================== - Add Mumbai (ap-south-1) to AWS region support list. - Support multiple Splunk indexers by importing Splunk config file. This enables Aviatrix Controller and gateway logs to be integrated with multiple Splunk servers that many enterprises deploy. To configure, go to Settings -> Loggings -> Splunk. Select Import files to import a Splunk configuration file. You may also choose Manual Input, in this case each indexer must be listening on the same port. - Support DataDog agent for both Controller and gateways. To enable, go to Settings -> Loggings -> DataDog, provide an API Key. - Enhancement for VPN user profile editing: when adding a user to a specific profile, only display those who do not belong to the profile. When deleting a user to a specific profile, only displays users who belong to the profile. - Support tooltip for many labels. Move mouse over a label, a detailed explanation displays for the label. UserConnect-092216 ================== - Support encryption over AWS peering. This capability allows two same region VPCs to send encrypted traffic to each other without going over Internet by leveraging AWS peering as underlying infrastructure. This mechanism significantly reduces data transfer cost. To use this feature, customer must configure AWS peering from AWS console between the two VPCs in the same region. To enable this feature, go to Peering -> Encrypted Peering -> New Peering. Check "Over AWS Peering". One use case for this feature is to enable NetApp OnTAP software to run in HA mode. - Support Azure ARM North Europe region. - Support Skyhook for Docker 1.12 release. UserConnect-090416 ================== - Support site2cloud use case where the gateway imports a template configuration file from a different Aviatrix gateway that initiates the configuration. This capability is useful to build IPSEC tunnels between two enterprises where each has its own Aviatrix UCC controller. - Support using Aviatrix CloudN as customer device for site2cloud connection. Follow these steps: 1) use UCC Controller to create a site2cloud connection by entering CloudN's public IP and subnet CIDRs for customer on-prem network. 2) On UCC Controller, select Aviatrix as vendor choice to download this site2cloud configuration file. 3) go to CloudN's site2cloud page and import the downloaded configuration file to establish the site2cloud connection. - Allow users to provide an optional IPSec pre-shared key when creating site2cloud connections. When the filled is left empty, UCC controller will automatically generate a pre-shared key. - Support HA for GCloud gateways with a zone selection option. - Update API to accommodate GUI 2.0 development UserConnect-082116 ================== - Support on GUI 2.0: - Settings -> Change Password - Settings -> Email - Settings -> System Time - OpenVPN® -> Profiles -> Edit -> Add New. Users can select subnets from VPCs/VNets without typing these CIDRs manually. - Gateway -> Click "+" next to the gateway name. Users can display all VMs inside the gateway's VPC/VNet - VPN User list displays user email and associated profile information. - Allow users to setup VPN user license threshold notification. When license usage exceeds the threshold, email notification will be sent out to admin's account. - Azure Aviatrix gateway image is available at marketplace. There is no need to download gateway image to your storage account before launching a gateway. Instead, users need to subscribe to the Aviatrix Companion Gateway in Azure marketplace. This new capability significantly reduces Azure gateway deployment time. The Aviatrix Companion Gateway is free of charge. Please refer to startup guide for details. UserConnect-072216 ================== - GUI 2.0 becomes production. To access GUI 2.0, go to `https://controller\_ip/ <https://controller_ip/preview/>`__. Note: Old GUI is still available at https://controller_ip/v1/. All the new features developed in this release are only available for GUi 2.0. - **(Known issue: After upgrading to UserConnect-072216, the browser does not log out properly. You must type in https://controller_ip to re-login)** - Allow users to specify their own ELB names when creating AWS/GCloud VPN gateways. If no ELB name is specified by users, the Controller will provide a default ELB name. - Support AWS IAM role. When AWS IAM role is used, there is no need to enter AWS access key and secret key when creating a cloud account at Controller. Instead, two IAM roles will be created. Controller will use the role-based temporary security credentials to request access to AWS resources. Cloud account created by IAM role helps to reduce the risk of compromising AWS credentials. Please refer to `Aviatrix IAM role Configuration Guide <http://docs.aviatrix.com/HowTos/HowTo_IAM_role.html>`__ for details. - Support AWS Geo VPN to include other cloud type's ELB DNS name. To configure, go to OpenVPN® -> Configuration to enable AWS Geo VPN first. Then you can add ELB DNS names from other cloud types to Geo VPN. With this capability, VPN gateway in Azure and GCloud can be included as part of Geo VPN solution. - Support gateway resizing without a need to terminate the old gateway and create a new one. This feature is available for AWS, Azure Classic, Azure ARM and GCloud but only on gateways without ELBs. To configure, go to Gateway, select the target gateway and desired size from "Gateway Size" dropdown list", click Change button. - Support an option to select subnet/availability zone when enabling HA for AWS. To configure, go to Gateway, select the target gateway and the desired subnet from "Backup Gateway Subnet" dropdown list, click "Enable HA" button. - Support an option to select ELB name when editing VPN gateway configuration. This feature is useful for GCloud network, which may have multiple ELBs, each in a different subnet. To configure, go to Advanced Config -> Edit Config and select the ELB from "LB Name" dropdown list. - Support to map multiple real CIDRs to multiple virtual CIDRs for site2cloud connection "mapped" connection. The multiple CIDRs need to be separated by a comma. The numbers and masks of the real CIDRs and corresponding virtual CIDRs must match each other. - A new Aviatrix IAM custom policy is provided with more restrictive rules and some additional rules to support role-based IAM. UserConnect-063016 ================== - GUI 2.0 for preview. To access GUI 2.0, go to https://controller_ip/preview/. Note: Old GUI is still available at https://controller_ip. GUI 2.0 doesn't support all the features available at the old GUI at this time. - Note: GUI 2.0 requires the controller to run on a instance with at least 4GB of memory. If your current controller does not meet this requirement, follow the procedure below: - AWS controller: stop the controller instance, change instance type to t2.medium or larger, start the controller instance again. - Azure Classic and Azure ARM controller: you can change the instance dynamically to at least D2 without stopping the instance first. - Google Controller: stop the controller instance, change instance type to n1-standard-2, start the controller instance again. - Support site2cloud connection between customer network and cloud network where the two sides may have overlapping CIDRs. Only GUI 2.0 support this feature. To configure, select "Mapped" for "Connection Type" and assign different virtual subnets to both customer network and cloud network. - GUI 2.0 dashboard displays IPSec tunnel status and link latency of an encrypted peering. When IPSec tunnel status of an encrypted peering flips between up and down, an email notification will be sent to the admin. - GUI 2.0 displays all VPN users added to the controller without selecting VPC ID/VNet name first. VPN users are sorted alphabetically for easy search. UserConnect-052616 ================== - Project Skyhook release: Docker swarm cluster container access support. From your desktop, you now can access Docker containers in a multi-host Docker swarm cluster built on a VXLAN overlay network that may span AWS, Azure and Google. To enable this feature, go to VPC/VNet -> VPN Access -> Skyhook: Docker Container Access. This feature is available on VPN gateways created after upgrade to this release. (If you have enabled ELB, delete the existing gateways and create new one. VPN user database are not affected.) For reference design on how to use this feature to access Docker containers, check out `this link <http://docs.aviatrix.com/HowTos/ContainerAccess.html>`__. Key benefits: a) MFA and user profile based access control apply to containers in the same manner as for instances. b) use the familiar tools such as curl, vim and wget on container without resorting to "docker exec" type of commands. UserConnect-050316 ================== - Enhance stability, manageability and debug ability for gateway launch and encrypted peering functions. - Support one load balancer in each different subnet of the same GCloud network. - Kernel 3.13.0-74 support on new gateway launches. UserConnect-040316 ================== - When VPN gateways are behind ELB, allow to import a new CRL URL without recreating VPN users/profiles or reissuing VPN certificates. To configure, delete all the VPN gateways first and then go to VPC/VNet -> VPN Access -> Certificate Management -> Import Certificates. Make sure that "CA Certificate", "Server Certificate" and "Server Private Key" are the same as before. The new CRL URL can be entered in "CRL Distribution Point URI" field. After finishing certificate management, recreate the VPN gateways behind ELB. - Enhance "Encrypted Peering" by verifying IPSec tunnel connection state after creating the peering. - Provide "Test HA" function for verifying VPC high availability. To test it, go to VPC/VNet -> VPC HA to enable HA for your gateway first and then click "Test HA" button to test HA function. - Enhance gateway creation by only listing the cloud types enabled in cloud accounts. - Allow to modify site2cloud connection and configuration template by editing "Cloud Networks" or "Customer Networks" CIDRs. To use this feature, go to VPC/VNet -> Site2Cloud -> List -> Edit. If changes need to be made for subnets/address spaces in VPC/VNet, select "Cloud Networks" to enter all VPC/VNet CIDRs. If changes need to be made for subnets in on-prem network, select "Customer Networks" to enter all on-prem CIDRs. This feature minimizes the configuration changes on customer sites by not having to delete the existing site2cloud connection. UserConnect-032516 ================== First release for Azure ARM cloud support. If you currently have deployments in Azure Classic, we recommend you skip this release. Azure ARM is the new Azure portal that is significantly different in how API works comparing with Azure Classic. - Support launching gateways in Microsoft Azure Resource Manager (ARM) VNet. Follow the embedded Aviatrix instructions to collect Application Endpoint, Application Client ID and Application Client Secret before creating a cloud account. The main feature supported by ARM in this release is Site2Cloud. Peering with ARM VNet is not supported in this release. - Site2Cloud supports to generate a configuration template for generic customer gateway devices. - Support security patches for both controller and gateways. To apply the software patch, go to Setting -> System -> Security Patches. The patch available for this release is glibc Vulnerability. UserConnect-031016 ================== - Support launching gateways in Microsoft Azure China. Azure China account is required to launch the gateways in Azure China. - Support launching gateways in Amazon AWS GovCloud. AWS GovCloud account is required to launch the gateways in AWS GovCloud. - Support Site2Cloud null encryption. This feature allows you to create an IPSec tunnel without encrypting the packets. To configure, go to VPC/VNet -> Site2Cloud -> Add and then select "Null Encryption". UserConnect-021516 ================== This release consists of a few significant features: GCloud Support, Modular Split Tunnel Configuration, Site to Cloud, Encryption for Azure ExpressRoute, Transitive Peering and VNet route diagnostics, as described below: - Support Google Cloud (GCloud). The following major functions are available on GCloud for this release: - Launch an Aviatrix Controller from GCloud directly. Follow `the instructions <http://docs.aviatrix.com/StartUpGuides/google-aviatrix-cloud-controller-startup-guide.html>`__ to do so. - From AWS/Azure/GCloud controller, you can now launch a gateway in GCloud. - GCloud account creation, editing and deletion - Multiple GCloud projects support - GCloud gateway (with or without ELB, with or without VPN access) creation and deletion - Gateway encrypted peering to other projects in GCloud and with AWS VPC and Azure VNets. - Security policies at GCloud network level. - Edit configuration (LDAP, DHCP, and Split Tunnel) on existing gateway - Support the ability to edit the split tunnel mode on existing VPN gateways. Previously, to make any split tunnel related configuration changes, users have to delete the existing VPN gateways and re-create new ones. With this release, when you add a new VPC/VNet and your VPN users need to access them via VPN, you just modify the CIDRs at "additional CIDRs" field at split tunnel configuration without deleting any existing gateways. To configure, go to VPC/VNet -> Edit Configuration-> Modify Split Tunnel. Note all additional CIDRs (the CIDRs that are not the VPC/VNet CIDR where VPN gateways are deployed) must be entered all together, separated by comma. For example, you have two new VPCs, 10.10.0.0/16 and 10.11.0.0/16, and you like to access them via split tunnel VPN. You must enter at the Modify Split Tunnel field "10.10.0.0/16,10.11.0.0/16" without the quote. In addition, you may need to add encrypted peering with the new VPCs in order for traffic to go through. The changes are effective immediately to the VPN gateway in the VPC/VNet. If there are multiple VPN gateways behind a load balancer, they are all updated at the same time. Active VPN users will be disconnected during this configuration time. - Support Transitive Peering. Transitive Peering enables you to route traffic from instances in Source VPC, encrypted, through a NextHop VPC gateway to reach a destination. Before creating Transitive Peering, you need to make Encrypted Peering between Source VPC and NextHop VPC first. To create/delete Transitive Peering, go to VPC/VNet -> Encrypted Peering -> Transitive Peering. - Support site to cloud IPSec VPN connections. Using this feature, you can create IPSec VPN connections linking your on-prem networks to VPC/VNets in the cloud. To configure, go to VPC/VNet -> Site2Cloud. After adding a site2cloud connection, you can download a configuration template file for your on-prem devices (Only Cisco ASA configuration template is available now). If High Availability (HA) function is enabled, one gateway serves as the primary VPN connection endpoint and the other one serves as the backup. In case on-prem device loses the VPN connection to the primary VPN gateway, it can switch to the backup gateway to recover the VPN connection. Some diagnostic tools for site2cloud are also provided. - Support encryption for Azure ExpressRoute. This feature allows to run IPSec over Azure Express Route to ensure a higher security level. To enable it, first launch a gateway in a subnet dedicated for the gateway, then go to VPC/VNet -> Site2Cloud, click "Add" tab and select "Private Route Encryption". - Support VNet route diagnostics. Go to Settings -> Troubleshooting -> VNet Route Diagnostics to find various VNet routing related diagnostics tools. UserConnect-011316 ================== - Support VPN certificates maintained by a third party PKI system. Third party PKI must be created before any gateway launch. To enable this feature, go to VPC/VNet -> VPN Access -> Certificate Management. Use this feature to import certificates and download VPN configuration files. - Support the ability to edit the LDAP settings on existing VPN gateways. Previously, to make any LDAP related configuration changes, users have to delete the existing VPN gateways and re-create new ones. With this support, you can enable, disable, or modify LDAP configuration on existing VPN gateways without deleting them. To configure, go to VPC/VNet -> Edit Configuration-> Modify LDAP Configuration. UserConnect-121015 ================== - Support remote syslog to a third party or Aviatrix syslog server. The feature allows 24x7 premium customer to forward both controller and gateway events to a customized Aviatrix syslog server for debugging and troubleshooting purpose. This feature improves customers network uptime. To enable this feature, go to Settings -> Setup loggings -> Remote Syslog. - Support the ability to push down to VPN user client the DHCP settings made in AWS VPC Console "Create DHCP Options Set" menu. For example, if you wish to change DNS name after the gateway has been launched, you can use this feature to make changes. The active VPN users will be disconnected when this feature is executed. To configure, go to VPC/VNet -> Edit Configuration -> Reload DHCP Configuration. UserConnect-112415 ================== - Support Sumologic logging collector. When enabled, syslog data from the controller and all gateways will be forwarded to a Sumologic account. To enable, click Settings -> Setup Loggings -> Sumologic - Add LDAP user search capability when Test LDAP Configuration to further test drive the correctness of a LDAP configuration. - Enable the gateway High Availability capability with a pair of gateway instances in active and hot standby mode. To enable, go to VPC/VNet -> VPC HA. - Add Help me! for a drop down display of VPC/VNet in a specific region and cloud account. UserConnect-112015 ================== - Clean up onboarding messages and texts for Azure usage. UserConnect-111015 ================== - Support Geo VPN feature where a VPN user is connected to a nearest VPC. To enable Geo VPN, go to VPC/VNet -> VPN Access -> Geo VPN. UserConnect-110615 ================== - Bug fix to allow multi-AZ and PBR routing configuration scenario. - Added AZ display along with subnet info at gateway create. - Created Reference Designs. UserConnect-102615 ================== - Support 2FA DUO authentication to console log in, in addition to password credentials. The configuration is at Settings -> System -> Setup 2FA Login. UserConnect-101615 ================== - Support multiple controller and gateway clusters in the same VPC. UserConnect-100115 ================== - Support Okta authentication. - Support integration of Elasticsearch on the controller. - Support both allow and deny rules for each VPC security policies. UserConnect-092815 ================== - Support PBR event syslog for NAT translation of every TCP/UDP/ICMP session. The log describes the VPN user virtual IP address, source port and the destination IP address and port. By correlating with VPN username and its assigned virtual IP address, IT admin can uniquely track and identify every VPN user's access activity history to both internal resource and external resource. - Support multiple users in admin privilege. Support multiple users in user account privilege. UserConnect-092115 ================== - Added hard token authentication support on DUO security. Made DUO authentication configuration optional. When "Token" is configured as the Push Mode for all gateways, user must append the 6 digits' token number to their password. **Note: ** 1. **All active VPN users will be disconnected for this upgrade duo to VPN server restart.** 2. **You must log out and log back in again for new features to take effect.** 3. **You need to run upgrade command two times.** - Support VPN user certificate re-issuing. When existing VPN user certificate is re-issued, the current certificate of the user is revoked and a new certificate is sent to the user. - Active VPN user on dashboard display is dynamically refreshed every 5 minutes. UserConnect-082815 ================== - Support launch gateways in Microsoft Azure. UserConnect-082515 ================== - Support backup DUO push. When both LDAP and DUO are enabled, user can type #push1 or #push2 appending to the password field to specify which phone in the DUO device list to be notified for approval. For example, if a user John Smith's password is <PASSWORD>, he can type at password prompt <PASSWORD>#push1 or johnsmith#push2 to specify the first phone or the second phone to be notified. If only password is typed in, the default phone (the first phone on the device list in DUO) will be notified. **Note: You must run upgrade command twice to have the upgrade take effect for this particular upgrade. All VPN users need to be deleted and added again as the existing certificates will not work with the new encryption algorithm. The first upgrade command may generate an exception, just ignore it and run upgrade again. ** Suggested upgrade procedure: delete all existing users. Upgrade once and upgrade again, and then add users back. - Support enhanced encryption algorithms: AES-256-CBC, SHA512, TLS1.2 and TLS-AUTH. - Detailed display of VPC/gateway on Dashboard. Clicking on the gateway name displays the complete configuration of the gateway. - Support API for all CloudOps commands. - Support the option to launch gateway when creating CloudOps VPC pool. - Support CloudOps Access IP address map history and initiator (from Console or from API). - Hash all password. - Add confirmation check when deleting a VPC or gateway. - Dynamically display controller logs on UI. - Bug fixes for out of order gateway command delivery and multiple identical users on the same gateway display. UserConnect-081315 ================== - Support for CloudOps VPC pool creation and CloudOps Read Me First. - Support additional route push to VPN client when split tunnel is enabled. - Disable password caching and credential saving in .onc file for Chromebook users. - Display profile name instead of command name in VPN active user Dashboard. - Fix typos in email notification sent to VPN users. - For UDP connections, send a disconnect message to VPN gateway immediately when the client terminates. - Fix release version alert problem. UserConnect-072815 ================== - Support Diagnostics on controller and gateways. - Added DNS name service for CloudOps Networking feature. - Dashboard performance improvement. - Enhance Chromebook VPN ONC file connection name to be profiled based. - Bug fix for logstash forwarder. UserConnect-071615 ================== - Support upgrades without terminating existing active VPN users unless specifically documented. - Various bug fixings. - General UI look and feel update. UserConnect-070615 ================== - Integrate LDAP configuration with Gateway creation to streamline provisioning process. - Display Profile fields in Active VPN User dashboard. - Support logstash forwarder to forward all syslog and auth log to designated logstash server. - Support software release version visibility. UserConnect-061915 ================== - Support template generation at create gateway and configure VPN access. - Support user activity history UserConnect-061015 ================== - Support operator account where the operator can only access dashboard. - Support disconnect user from dashboard page. UserConnect-060315 ================== - Support capability to manage instances in overlapping CIDRs of VPCs. - Support dashboard for active user display. UserConnect-052615 ================== - LDAP client certificate import facility to support LDAP servers with TLS client verification - Support configurable action parameter in user profile policy - Support forwarding of syslog events to Logstash server UserConnect-051515 ================== - Support LDAP + Duo multi-factor combined authentication. - Support configurable base policy for user profiles. - API to change a VPN user's profile. UserConnect-050915 ================== - Support Chromebook as a VPN client. - Support DUO multi-factor authentication. - Support syslog display with regex filtering capability for each VPN gateway. UserConnect-050215 ================== - Support policy-based routing on the VPN server to allow enterprise to re-direct traffic to its own backbone. UserConnect-042315 ================== - Support user authentication via Google 2-Step Verification process. Support multiple email domain names. UserConnect-041715 ================== - Support for setting the maximum number of connections for each gateway. - Support NAT capability for each gateway. - Support both split tunnel and full tunnel mode for each gateway. - Support gateway size c4.2xlarge. - Support add and delete members on the Profile page. UserConnect-032315 ================== - Support user profile-based security policies. - Support scale out and highly available OpenVPN® solutions for direct access to VPCs. - Support LDAP integration. - Support for Windows, MAC OS, and Chromebook clients. OpenVPN is a registered trademark of OpenVPN Inc. .. disqus:: <file_sep> ================================================================ Transit Advanced Config ================================================================ .. Note:: The advanced configuration applies to each Aviatrix Transit Gateway. To edit a Transit Gateway's advanced configuration, go to Multi-Cloud Transit > Advanced Config. Transit Gateway --------------------------------------- To edit the advanced configuration for any Transit Gateway, click on this dropdown menu and select the Transit Gateway to edit. Local AS Number ------------------------ This option changes the Aviatrix Transit Gateway ASN number before you setup Aviatrix Transit Gateway connection configurations. Connected Transit ------------------------ By default, Aviatrix Spoke VPCs/VNets do not have routing established to communicate with each other via Transit. They are completely segmented. If you would like to build a full mesh network where Spoke VPCs/VNets communicate with each other via Transit GW, you can achieve that by enabling Connected Transit mode. All connections are encrypted. .. Note:: For a Spoke VPC/VNet in a multi-cloud transit to communicate with a Spoke VPC in TGW Orchestrator, connected Transit must be enabled on the Aviatrix Transit Gateway that connects both sides. For software version 4.1 and later, click Multi-Cloud Transit on the left sidebar > Advanced Config > Edit Gateway tab. Select the Transit Gateway for which you want to enable the Connected Transit. Note all Spokes should be either in HA mode or non HA mode. A mixed deployment where some Spokes have HA enabled while others don't work in a normal environment, but does not work when a failover happens on a HA enabled Spoke. Advertise Transit VPC/VNet Network CIDR(s) -------------------------------------- This field is only applicable to Transit GW established by `Transit Network workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_. By default, Aviatrix Transit GW does not advertise Transit VPC/VNet `CIDR <https://www.aviatrix.com/learning/glossary/cidr.php>`_. When this feature is enabled, Aviatrix Transit GW advertises the Transit VPC/VNet CIDR to VGW. The Controller programs the 3 RFC1918 routes in the AWS route table to point to the Transit GW. It also programs the learned routes from VGW into the AWS route table. If you deploy instances in the Transit VPC/VNet, enabling "Advertise Transit VPC CIDR(s) mode allows the instance to communicate both to Spoke VPCs and the on-prem network, assuming the Spoke VPCs are in the RFC1918 range. To enable this option in software version prior to 4.1, click Site2Cloud on the left navigation bar, select the connection established by `Step 3 <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#connect-the-transit-gw-to-aws-vgw>`_, click to edit. Scroll down to Advertise Transit VPC Network CIDR(s) to enable. For software version 4.1 and later, click Multi-Cloud Transit on the left sidebar > Advanced Config > Edit Gateway tab. Select the Transit Gateway you want and scroll down to enable the Advertise Transit VPC Network CIDR(s) option. BGP ECMP ---------------- This option is to enable Equal Cost Multi Path (ECMP) routing for the next hop. For the Aviatrix Transit Gateway next hop routing decision process, refer to `ActiveMesh 2.0 next hop. <https://docs.aviatrix.com/HowTos/activemesh_faq.html#what-is-activemesh-2-0>`_. Click the Slide Bar to enable BGP ECMP. Site2Cloud RX Balancing ---------------------------- .. Note:: This option is only available for Aviatrix Transit Gateways deployed in AWS on C5 and C5n instance types (except for c5.large and c5n.large). The Site2Cloud RX Balancing option can increase forwarding throughput on Aviatrix Transit gateways for BGP-over-GRE `External Device <https://docs.aviatrix.com/HowTos/transitgw_external.html>`_ traffic (a.k.a. Site2Cloud or S2C GRE tunnels), in these situations: * On certain topologies that require high throughput, with External Devices that limit the number of GRE tunnels. * Where maintaining a high number of GRE tunnels increases operational burden. If enabled, this option ensures that the Aviatrix Transit Gateway(s) are configured to maximize RX capacity and distribute ingress GRE tunnel load to all available vCPUs. This is mainly an alternative to `building a large number of GRE tunnels <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_gre_high_performance_workflow.html>`_, but a greater number of tunnels will be needed if the External Device imposes per-tunnel rate limits. A brief (sub-second) period of packet loss may affect the gateway when this setting is enabled or disabled. To maximize the forwarding throughput increase enabled by this setting, consider the following: * The number of vCPUs provisioned for the Aviatrix Transit Gateway(s) should be significantly higher than the number of GRE tunnels (for example, four GRE tunnels to a 16 vCPUs c5n.4xlarge instance). * High Performance Encryption (HPE) should be enabled between Aviatrix Transit Gateways. * BGP ECMP should be enabled, to ensure load balancing of return traffic over multiple tunnels. Active-Standby ------------------- This option is to provide the flexibility on Aviatrix Transit Gateways and Aviatrix BGP Spoke Gateways to connect to on-prem with only one active tunnel and the other one as backup. In addition, this Active-Standby Mode supports ActiveMesh 2.0 only. The use case is a deployment scenario where on-prem device such as firewall does not support asymmetric routing on two tunnels. When Active-Standby mode is enabled, it applies to both BGP and Static Remote Route Based External Device Connections and for each connection, only one tunnel is active in forwarding traffic at any given time. This feature can only be applied to non-HA remote devices in the `External Device section <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#external-device>`_. Click Active-Standby mode to set it to **Enabled**. Preemptive or Non-Preemptive Mode ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ If you enable Active-Standby mode, you can also select the **Preemptive** or **Non-preemptive** radio buttons to determine the network's behavior when the primary gateway goes down and the network switches to the standby gateway. * In Preemptive mode, when the primary gateway for a connection is back up, the network automatically switches back to using that primary gateway. * In Non-preemptive mode, the network continues to use the standby gateway even after the primary gateway is up again, until you initiate a manual switchover using the Switchover button. .. Note:: If you enable Preemptive mode, the Switchover button is grayed out and unclickable because in Preemptive mode, there is no need for a manual switchover back to the primary gateway. Multi-Tier Transit ----------------------- Use the Multi-Cloud Transit Gateway option to implement a hierarchical transit gateway architecture that permits packets to traverse more than 2 Aviatrix transit gateways. In previous releases, full-mesh transit peering was required. You can now connect the two CSPs or regions through one peered connection. You must use ActiveMesh 2.0 to use multi-tier transit gateways, but full-mesh transit peering is not required. Guidelines * You can use Multi-Cloud Transit Gateway option with or without HPE. * Inter and intra-region peering are both supported. * Inter-CSP HPE over Internet is supported between AWS and Azure. * AWS TGW peering is not supported. Gateway Manual BGP Advertised Network List --------------------------------------------------------- This field is only applicable to Transit GW established by `Transit Network workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_. By default, Aviatrix Transit GW advertises individual Spoke VPC/VNet CIDRs to VGW. You can override that by manually entering the intended CIDR list to advertise to VGW. This feature is critical to limit the total number of routes carried by VGW (maximum is 100). To enable this option in software version prior to 4.1, on the left sidebar, select the connection established by `this step <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#connect-the-transit-gw-to-aws-vgw>`_, and click to edit. Scroll down to Manual BGP Advertised Network List to set it to **Enabled**. For software version 4.1 and later, click Multi-Cloud Transit on the left sidebar > Advanced Config > Edit Gateway tab. Select the Transit Gateway you want to enable this feature on, scroll down to the Manual BGP Advertised Network List, and enter the summarized CIDRs that you want to advertise. To disable the option, leave the field blank and click **Change**. Connection Manual BGP Advertised Network List ------------------------------------------------------------- Manual Advertise Routes per BGP Connection expands the existing gateway based manual advertising routes feature to apply it to each BGP connection. One use case is to have better route advertising control for each remote BGP peer. To enable this option on software version 6.3, #. Click Multi-Cloud Transit on the left sidebar > Advanced Config > Edit Transit tab. #. Select the Transit Gateway. #. Find the Connection Manual BGP Advertised Network List panel, select the connection name and fill the CIDRs to advertise in the Advertised Network List field. To disable the option, leave the field blank and click **Change**. Preserve AS Path ----------------- This field is applicable to both Gateway Manual BGP Advertised Network List and Connection Manual BGP Advertised Network List. When disabled, behavior defaults to the AS path being stripped during BGP route advertisements from transit or spoke gateways to neighbors. When enabled, AS Path is preserved. Gateways will not advertise manual BGP advertised CIDRs if the CIDRs are no longer in the best route DB. To enable AS path preservation for a transit gateway: #. Click Multi-Cloud Transit > Advanced Config on the left sidebar. #. On the Edit Transit tab, in the Transit Gateway list select the transit gateway on which to enable this feature. #. Scroll down to Preserve AS Path and set the toggle switch to Enabled. Similarly, to enable AS Path preservation for a spoke gateway, follow the same procedure as above but select the spoke gateway to enable this feature on from the Edit Spoke tab. Scroll down to Preserve AS Path and set the toggle switch to Enabled. Gateway AS Path Prepend ------------------------------------------- You can insert BGP AS_PATH on the Aviatrix Transit Gateway to customize the BGP AP_PATH field when it advertises to VGW or peer devices. For example, enter 65458, 65478 in the input field, these ASN will appear to the remote end. This configuration applies to all BGP peers of the Aviatrix Transit Gateway. If you don't configure this field, Transit Gateway only advertises its own ASN. Connection AS Path Prepend ------------------------------------- Customize AS Path Prepend by specifying AS PATH for each BGP connection. This feature applies to any dynamic connection and Transit Gateway peering connections on a selected Aviatrix Transit Gateway. BGP Polling Time (seconds) ------------------------------------ Aviatrix Transit Gateways report its BGP routes to the Controller periodically. By default, the periodic timer is 50 seconds. This polling time affects BGP route change convergence time. This option changes the default polling time. The range is 10 seconds to 50 seconds. BGP Hold Time (seconds) ---------------------------------- Use the BGP Hold Time option to manually set the BGP holding time for your Aviatrix transit gateway. The hold time specifies how long a router waits for incoming BGP messages before it assumes the neighbor is dead. The Aviatrix Transit Gateway hold time is bound to the Aviatrix keep alive message time, which is always 1/3 of the hold time. By default, the Hold Time is 180 seconds, and the Keep Alive time is 60 seconds. The supported Hold Time range is 12 to 180 seconds. If the remote site has a shorter hold time, the shorter hold time is used for the gateway. Refresh BGP Advertised Routes --------------------------------------- This option reset BGP connection to the remote BGP peers. Use this option to enable new features such as Segmentation based BGP CIDR Advertisements where on-prem receives BGP advertisement for networks on-prem has connection policy or in the same Security Domain. AWS TGW Edge Segmentation --------------------------------------- Refer to `TGW Edge Segmentation <https://docs.aviatrix.com/HowTos/tgw_faq.html#what-is-edge-segmentation>`_ for details. TGW Edge Segmentation can be enabled at given time. Select a connection to enable or disable. Summarize CIDR(s) to AWS TGW ------------------------------------------ * Enable this setting to limit routes propagated to TGW to only 3 RFC1918 CIDRs and specific non-RFC1918 CIDRs. Limiting routes saves route propagation time. * Leave this setting disabled (the default setting) to maintain better segmentation behavior without improving performance. .. |Test| image:: transitvpc_workflow_media/SRMC.png :width: 5.55625in :height: 3.26548in .. |TVPC2| image:: transitvpc_workflow_media/TVPC2.png :scale: 60% .. |HAVPC| image:: transitvpc_workflow_media/HAVPC.png :scale: 60% .. |VGW| image:: transitvpc_workflow_media/connectVGW.png :scale: 50% .. |launchSpokeGW| image:: transitvpc_workflow_media/launchSpokeGW.png :scale: 50% .. |AttachSpokeGW| image:: transitvpc_workflow_media/AttachSpokeGW.png :scale: 50% .. |SpokeVPC| image:: transitvpc_workflow_media/SpokeVPC.png :scale: 50% .. |transit_to_onprem| image:: transitvpc_workflow_media/transit_to_onprem.png :scale: 40% .. |azure_native_transit2| image:: transitvpc_workflow_media/azure_native_transit2.png :scale: 30% .. |transit_approval| image:: transitvpc_workflow_media/transit_approval.png :scale: 30% .. disqus:: <file_sep> ################################### FIPS 140-2 Module ################################### Aviatrix supports the FIPS 140-2 crypto module. The Aviatrix Certificate number is #3475 which you can find from the `NIST site <https://csrc.nist.gov/projects/cryptographic-module-validation-program/certificate/3475>`_. The Aviatrix FIPS 140-2 Security Policy can be found at this `link. <https://csrc.nist.gov/CSRC/media/projects/cryptographic-module-validation-program/documents/security-policies/140sp3475.pdf>`_ Before enabling FIPS 140-2, the FIPS 140-2 Security patch needs to be applied. - To apply FIPS patch go to the Controller Console, Settings -> Maintenance -> Security Patches -> Click FIPS 140-2 - To enable, go to the Controller Console, Settings -> Advanced -> FIPS 140-2. Click Enable. .. note:: OpenVPN services will be restarted and this will cause your VPN clients to disconnect and reconnect to the gateways. .. |gen_csr| image:: controller_certificate_media/gen_csr.png :scale: 30% .. |ca.crt| image:: controller_certificate_media/ca.crt.png :scale: 30% .. |server_crt| image:: controller_certificate_media/server_crt.png :scale: 30% .. |imageRestoreAWS| image:: controller_backup_media/backup_restore_restore_aws.png .. |S3Create| image:: controller_backup_media/S3Create.png .. |S3Properties| image:: controller_backup_media/S3Properties.png :scale: 30% .. |S3SelectDefaultEncryption| image:: controller_backup_media/S3SelectDefaultEncryption.png :scale: 25% .. |S3SelectEncryption| image:: controller_backup_media/S3SelectEncryption.png :scale: 25% .. |KMSKeyCreate| image:: controller_backup_media/KMSKeyCreate.png :scale: 30% :align: middle .. |KMSKeyAddUser| image:: controller_backup_media/KMSKeyAddUser.png :scale: 30% :align: middle .. disqus:: <file_sep> ========================================================================================== GRE Tunneling for Multi-cloud Transit Gateway to On-Prem Workflow ========================================================================================== Introduction ============ Connecting to on-prem network over GRE tunneling protocol in AWS is an alternative to IPsec. When GRE tunneling is used, Aviatrix Multi-cloud Transit Gateways interoperate directly with on-prem network devices over AWS Direct Connect. When on-prem to cloud encryption is not required, using GRE allows you to achieve high performance throughput (10Gbps) without the need to deploy Aviatrix CloudN appliance. The solution is shown in the diagram below, |transit_gateway_external_device_bgp_over_gre_diagram| where Aviatrix Multi-Cloud Transit Gateways connect to an on-prem Edge Router over Direct Connect. This document gives step-by-step instructions on how to build Aviatrix Transit Gateway to External Device using GRE over AWS Direct Connect. In this Tech Note, you learn the following: #. Workflow on `building underlay connectivity with AWS Direct Connect 10 Gbps capacity <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_gre_high_performance_workflow.html#build-underlay-connectivity-with-aws-direct-connect>`_ #. Workflow on `deploying Aviatrix Transit Solution <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_gre_high_performance_workflow.html#deploy-aviatrix-multi-cloud-transit-solution>`_ #. Workflow on `establishing connectivity between Edge Router and Aviatrix Transit Gateway to form GRE tunnel <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_gre_high_performance_workflow.html#build-connectivity-between-edge-router-and-aviatrix-transit-gateway>`_ #. Workflow on `building GRE tunnel and BGP over GRE <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_gre_high_performance_workflow.html#build-gre-tunnel-and-bgp-over-gre>`_ #. Workflow on `enabling ECMP Load Balancing to achieve high performance <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_gre_high_performance_workflow.html#configure-ecmp-load-balancing-for-high-performance>`_ For more information about Multi-Cloud Transit Network and External Device, please see these documents: - `Multi Cloud Global Transit FAQ <https://docs.aviatrix.com/HowTos/transitvpc_faq.html#multi-cloud-global-transit-faq>`_ - `Global Transit Network Workflow Instructions (AWS/Azure/GCP/OCI) <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ - `Aviatrix Transit Gateway to External Devices <https://docs.aviatrix.com/HowTos/transitgw_external.html>`_ - `Transit Network Design Patterns <https://docs.aviatrix.com/HowTos/transitvpc_designs.html>`_ .. important:: - This solution supports only `ActiveMesh 2.0 <https://docs.aviatrix.com/HowTos/activemesh_faq.html#what-is-activemesh-2-0>`_, please check this doc `How to migrate to ActiveMesh 2.0 <https://docs.aviatrix.com/HowTos/activemesh_faq.html#how-to-migrate-to-activemesh-2-0>`_ for migration detail. - This solution is not available to Azure and GCP as they do not support GRE. - Reachability between Transit VPC CIDR and Edge Router is customers' responsibility which is typically done by Colocation data center providers. - Workflow on building underlay connectivity for private network with AWS Direct Connect here is just an example. Please adjust the topology depending on your requirements. The key ideas for this solution are: ---------------------------------------- - The Edge (WAN) Router runs a BGP session to AWS VGW via AWS Direct Connect where the Edge Router advertises its GRE IPs. AWS VGW advertises the AWS Transit VPC CIDR. - Leverage Edge Router BGP ECMP feature. - Configure multiple GRE tunnels for greater aggregate throughput. .. important:: - Reachability between Transit VPC CIDR and Edge Router is the responsibility of customer. Prerequisite ==================== - This feature is available for 6.3 and later. `Upgrade <https://docs.aviatrix.com/HowTos/inline_upgrade.html>`_ Aviatrix Controller to at least version 6.3 - In this example, we are going to deploy the below VPCs in AWS: - AWS Aviatrix Transit VPC (i.e. 10.1.0.0/16) by utilizing Aviatrix feature `Create a VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ with Aviatrix FireNet VPC option enabled - AWS Aviatrix Spoke VPC (i.e. 192.168.1.0/24) by utilizing Aviatrix feature `Create a VPC <https://docs.aviatrix.com/HowTos/create_vpc.html>`_ as the previous step or manually deploying it in each cloud portal. Moreover, feel free to use your existing cloud network. - Edge Router has high throughput supported on hardware interface(s) and GRE tunnel(s) Building Underlay Connectivity with AWS Direct Connect =================================================================================== Building AWS Direct Connect is customer's responsibility. For more information about AWS Direct Connect, please see `Connect Your Data Center to AWS <https://aws.amazon.com/getting-started/projects/connect-data-center-to-aws/>`_. Please adjust the topology depending on your requirements. Building AWS Direct Connect ----------------------------------- See `Equinix ECX Fabric AWS Direct Connect <https://docs.equinix.com/en-us/Content/Interconnection/ECXF/connections/ECXF-aws-direct-connect.htm>`_ if users select Equinix solution. This is just an example here. Make sure to select 10 Gbps capacity. Associating AWS VGW to AWS Transit VPC ----------------------------------------------- 1. Log in to the AWS VPC Portal and select **Virtual Private Gateways** under the Virtual Private Network (VPN) sidebar. 3. Select the Virtual Private Gateway that you have the private virtual interface to AWS Direct Connect 4. Click **Actions**. 5. Select **Attach to VPC**. 6. Select the AWS Transit VPC and click **Yes, Attach**. |aws_vgw_attach| Deploying the Aviatrix Multi-Cloud Transit Solution ================================================= Refer to `Global Transit Network Workflow Instructions <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html>`_ for the steps below. Please adjust the topology depending on your requirements. Step 2.1. Deploy Aviatrix Multi-Cloud Transit Gateway and HA in AWS ------------------------------------------------------------------- - Follow this step `Deploy the Transit Aviatrix Gateway <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html#step-2-deploy-the-transit-aviatrix-gateway>`_ to launch Aviatrix Transit gateway and enable HA with insane mode enabled in AWS Transit VPC - In this example, sizes c5n.2xlarge and c5n.4xlarge are selected to benchmark `performance <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_gre_high_performance_workflow.html#performance-benchmark>`_. Enabling Route Propagation on the Subnet Route Table where Aviatrix Transit Gateway Locates on AWS Portal --------------------------------------------------------------------------------------------------------------------------------------- 1. Log in to the AWS VPC portal and locate the subnet route table where Aviatrix Transit Gateway is located. 2. Select **Route Propagation** tab. 3. Click **Edit route propagation**. 4. Locate the AWS VGW that is associated with this Transit VPC and mark the **Propagate** checkbox. 5. Click **Save**. 6. Check whether the Propagate status is Yes. |aws_route_propagation_status_yes| Deploying Spoke Gateway and HA -------------------------------------- Follow this step `Deploy Spoke Gateways <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html#step-3-deploy-spoke-gateways>`_ to launch Aviatrix Spoke gateway and enable HA with insane mode enabled in AWS Spoke VPC. In this example, sizes c5n.2xlarge and c5n.4xlarge are selected to benchmark `performance <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_gre_high_performance_workflow.html#performance-benchmark>`_. Attaching Spoke Gateways to Transit Network ----------------------------------------------------------- Follow this step `Attach Spoke Gateways to Transit Network <https://docs.aviatrix.com/HowTos/transit_firenet_workflow_aws.html#step-4-attach-spoke-gateways-to-transit-network>`_ to attach Aviatrix Spoke Gateways to Aviatrix Transit Gateways in AWS. Building Connectivity between Edge Router and Aviatrix Transit Gateway ========================================================================================================== Cisco ASR is used as an Edge Router in this example. Checking Whether the Edge Router has Learned AWS Transit VPC CIDR via the BGP Session Between Edge Router and AWS Direct Connect -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- #. Log in to the Edge Router (i.e. Cisco ASR) #. Check whether Edge Router has learned AWS Transit VPC CIDR via the BGP session between Edge Router and AWS Direct Connect by issuing the related "show ip bgp" command Simple Cisco IOS example:: #show ip bgp Preparing IP for GRE source IP on Edge Router ----------------------------------------------------- In this example, we use ASR loopback interface with an unique IP address as a GRE source IP. Create a loopback interface and assign an IP to itself as a GRE source IP. Simple Cisco IOS example:: #configure t (config)#interface Loopback77 (config-if)#ip address 192.168.77.1 255.255.255.255 Advertising that GRE source IP on Edge Router to the BGP Session Between Edge Router and AWS Direct Connect --------------------------------------------------------------------------------------------------------------------------------------------- The purpose of this step is to let AWS VGW learn the GRE source IP on Edge Router via BGP session between Edge Router and AWS Direct Connect, so that Aviatrix Transit Gateway can reach the GRE source IP on Edge Router to form GRE tunnel over AWS Direct Connect. To demonstrate this concept in a simple fashion, we utilize IOS "ip prefix-list" function and apply it on BGP neighbor with direction out function to distribute GRE source IP. Create a prefix list that defines GRE source IP on Edge Router for BGP advertisement. Simple Cisco IOS example:: #configure t (config)#ip prefix-list Router-to-VGW description Advertised GRE source CIDRs 192.168.77.X/32 to build GRE tunnels (config)#ip prefix-list Router-to-VGW seq 10 permit 192.168.77.1/32 Apply this prefix list to outgoing BGP advertisements Simple Cisco IOS example:: #configure t (config)#router bgp 65000 (config-router)#address-family ipv4 (config-router-af)#neighbor 169.254.253.17 prefix-list Router-to-VGW out Notes:: The IP 169.254.253.17 in this example here is the AWS Direct Connect BGP Peer IP. Checking Route Propagation Info on AWS Portal ----------------------------------------------------------- #. Log in to the AWS VPC portal and locate the subnet route table where Aviatrix Transit Gateway is located. #. Select the **Routes** tab. #. Check whether there is a route entry "GRE source IP on Edge Router pointing to AWS VGW." |aws_route_propagation_routing_entry| Confirming that Edge Router and Aviatrix Transit Gateway can Reach to each other IP for GRE Tunnel ------------------------------------------------------------------------------------------------------------------------------- Build GRE tunnel and BGP over GRE ================================================ Configuring GRE tunnel and BGP on Aviatrix Transit Gateway -------------------------------------------------------------------- 1. Log in to your Aviatrix Controller and navigate to Multi-Cloud Transit > Setup > External Device tab. 2. Select option External Device > BGP > GRE. 3. Use the fields below to set up GRE tunnel to Edge Router. +----------------------------------+-------------------------------------------------------------------------------------------------+ | Transit VPC Name | Select the Transit VPC ID where Transit GW was launched. | +----------------------------------+-------------------------------------------------------------------------------------------------+ | Connection Name | Provide a unique name to identify the connection to external device. | +----------------------------------+-------------------------------------------------------------------------------------------------+ | Aviatrix Transit Gateway BGP ASN | Configure a BGP AS number that the Transit GW will use to exchange routes with external device. | +----------------------------------+-------------------------------------------------------------------------------------------------+ | Primary Aviatrix Transit Gateway | Select the Transit GW. | +----------------------------------+-------------------------------------------------------------------------------------------------+ | Enable Remote Gateway HA | Don't check this option in this example. | +----------------------------------+-------------------------------------------------------------------------------------------------+ | Over Private Network | Check this option since AWS Direct Connect is underlay network | +----------------------------------+-------------------------------------------------------------------------------------------------+ | Remote BGP AS Number | Configure a BGP AS number that Edge Router will use to exchange routes with Transit GW | +----------------------------------+-------------------------------------------------------------------------------------------------+ | Local Tunnel IP | Leave it blank in this example. | +----------------------------------+-------------------------------------------------------------------------------------------------+ | Remote Tunnel IP | Leave it blank in this example. | +----------------------------------+-------------------------------------------------------------------------------------------------+ 4. Click **Connect** to generate GRE tunnel and BGP session over it. |aviatrix_transit_externel_device_gre| Downloading the GRE Configuration Sample from Aviatrix Controller --------------------------------------------------------------------------------------- 1. Navigate to Site2Cloud > Setup. 2. Select the connection that you created with “Connection Name” in the previous step 3. Click **Edit**. 4. Select Cisco as Vendor type, ISR, ASR or CSR as Platform, and IOS(XE) as Software for this example. 5. Click **Download Configuration**. Configuring GRE tunnel on Edge Router ----------------------------------------------------- 1. Open the downloaded GRE configuration file. 2. Populate these values as follows based on your setup throughout the Tunnel Interface Configuration. - <tunnel_number1>: the primary GRE tunnel interface number connecting Aviatrix Transit Primary Gateway (i.e. 11) - <tunnel_number2>: the secondary GRE tunnel interface number connecting Aviatrix Transit HA Gateway (i.e. 12) - <ios_wan_interface1>: the IP which is assigned on the Loopback interface as an GRE source IP (i.e. 192.168.77.1) - <ios_wan_interface2>: the IP which is assigned on the Loopback interface as an GRE source IP (i.e. 192.168.77.1) 3. Copy and paste the updated Tunnel Interface Configuration into Edge Router Simple Cisco IOS example:: interface Tunnel 11 ip address 169.254.61.205 255.255.255.252 ip mtu 1436 ip tcp adjust-mss 1387 tunnel source 192.168.77.1 tunnel destination 10.1.0.185 ip virtual-reassembly no keepalive exit interface Tunnel 12 ip address 169.254.173.77 255.255.255.252 ip mtu 1436 ip tcp adjust-mss 1387 tunnel source 192.168.77.1 tunnel destination 10.1.1.27 ip virtual-reassembly no keepalive exit Configuring BGP over GRE tunnel on Edge Router --------------------------------------------------------------------- 1. Open the downloaded GRE configuration file and copy and paste the BGP Routing Configuration into Edge Router. Simple Cisco IOS example:: router bgp 65000 bgp log-neighbor-changes neighbor 169.254.61.206 remote-as 65212 neighbor 169.254.61.206 timers 10 30 30 neighbor 169.254.173.78 remote-as 65212 neighbor 169.254.173.78 timers 10 30 30 ! address-family ipv4 redistribute connected neighbor 169.254.61.206 activate neighbor 169.254.61.206 soft-reconfiguration inbound neighbor 169.254.173.78 activate neighbor 169.254.173.78 soft-reconfiguration inbound maximum-paths 4 exit-address-family 2. Create a prefix list that defines CIDR where server locates in on-prem/co-location for BGP advertisement. Simple Cisco IOS example:: #configure t (config)#ip prefix-list Router-To-Transit-GRE description Advertised on-prem CIDRs 10.220.5.0/24 (config)#ip prefix-list Router-To-Transit-GRE seq 10 permit 10.220.5.0/24 3. Apply the prefix list to outgoing BGP advertisements. Simple Cisco IOS example:: #configure t (config)#router bgp 65000 (config-router)#address-family ipv4 (config-router-af)#neighbor 169.254.61.206 prefix-list Router-To-Transit-GRE out (config-router-af)#neighbor 169.254.173.78 prefix-list Router-To-Transit-GRE out Verifying GRE Tunnel Status on Aviatrix Controller ---------------------------------------------------------- 1. Navigate back to Aviatrix Controller and open Site2Cloud > Setup. 2. Find the connection that you created with Connection Name in the previous step. 3. Check the Tunnel Status. |aviatrix_gre_status_1| 4. Go to Multi-Cloud Transit > List. 5. Select the Transit Primary Gateway that was created in the previous step. 6. Click **Details/Diag**. 7. Scroll down to Connections > On-prem Connections. 8. Find the connection that you created with Connection Name in the previous step and check the Tunnel Status. |aviatrix_gre_status_2| Verifying BGP session status on Aviatrix Controller ---------------------------------------------------------- 1. Go to Multi-Cloud Transit > BGP. 2. Find the connection that you created with Connection Name in the previous step and check the BGP Status. |aviatrix_gre_bgp_status| Configuring ECMP Load Balancing for High Performance ===================================================================== Building Multiple GRE tunnels between Edge Router and Aviatrix Transit Gateway ------------------------------------------------------------------------------------------------------- 1. Building multiple GRE tunnels by repeating `"Build connectivity between Edge Router and Aviatrix Transit Gateway" <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_gre_high_performance_workflow.html#build-connectivity-between-edge-router-and-aviatrix-transit-gateway>`_. 2. Build multiple BGP over GRE tunnels by repeating `"Build GRE tunnel and BGP over GRE" <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_gre_high_performance_workflow.html#build-gre-tunnel-and-bgp-over-gre>`_. In this example, we build up to 4 pairs of GRE connections (total up to 8 tunnels) to benchmark `performance <https://docs.aviatrix.com/HowTos/transit_gateway_external_device_bgp_over_gre_high_performance_workflow.html#performance-benchmark>`_. |aviatrix_multiple_gre| Enabling BGP ECMP feature on Aviatrix Transit Gateway ------------------------------------------------------------- 1. Navigate back to Aviatrix Controller 2. Go to Multi-Cloud Transit > Advanced Config > Edit Transit Tab. 3. Select the Transit Gateway that was created in the previous step. 4. Scroll down to `BGP ECMP <https://docs.aviatrix.com/HowTos/transit_advanced.html#bgp-ecmp>`_ and enable it. |aviatrix_gre_bgp_ecmp_function| Verifying BGP ECMP feature on Aviatrix Controller ---------------------------------------------------------------- 1. Go to Multi-Cloud Transit > List. 2. Select the Transit Primary Gateway that was created in the previous step. 3. Click **DETAILS/DIAG**. 4. Scroll down to Gateway Routing Table. 5. Click **Refresh**. 6. Search for the on-prem CIDR in the Destination column. 7. Check whether there are multiple GRE tunnels with same Metric and Weight under the same route entry. |aviatrix_gre_bgp_verify_ecmp_function| Enabling the BGP ECMP feature on Edge Router ----------------------------------------------------------------- Configure "maximum-paths" with higher number of equal-cost routes in BGP settings so that BGP will install in the routing table. In this example, we configure "maximum-paths 8" to achieve high performance over multiple GRE tunnels. Simple Cisco IOS example:: #configure t (config)#router bgp 65000 (config-router)#address-family ipv4 (config-router-af)#maximum-paths 8 - Modify ECMP Load Balancing algorithm depending on traffic type. Simple Cisco IOS example:: #configure t (config)#ip cef load-sharing algorithm include-ports source destination Verifying the BGP ECMP feature on Edge Router ------------------------------------------------------------- Check whether BGP install equal-cost routes in the routing table by issuing the related command "show ip bgp." |asr_gre_bgp_verify_ecmp_function| Ready to Go ================= At this point, run connectivity and performance test to ensure everything is working correctly. Performance Benchmarks =========================== End-to-End traffic via Aviatrix <-> Cisco ASR --------------------------------------------- Multiple flows result by using iperf3 tool with TCP 128 connections ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +-----------------------+---------------------------------------------+---------------------------------------------+ | Aviatrix Gateway size | 3 pairs of GRE connections (total 6 tunnels)| 4 pairs of GRE connections (total 8 tunnels)| +-----------------------+---------------------------------------------+---------------------------------------------+ | C5n.2xlarge | 8.0 - 8.3 (Gbps) | 8.3 - 9.1 (Gbps) | +-----------------------+---------------------------------------------+---------------------------------------------+ | C5n.4xlarge | 9.0 - 9.3 (Gbps) | 9.2 - 9.3 (Gbps) | +-----------------------+---------------------------------------------+---------------------------------------------+ Single flow result by using iperf3 tool with TCP 1 connection: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1.6 - 2.4 (Gbps) for both sizes C5n.2xlarge and C5n.4xlarge .. |transit_gateway_external_device_bgp_over_gre_diagram| image:: transit_gateway_external_device_bgp_over_gre_high_performance_workflow_media/transit_gateway_external_device_bgp_over_gre_diagram.png :scale: 50% .. |aws_vgw_attach| image:: transit_gateway_external_device_bgp_over_gre_high_performance_workflow_media/aws_vgw_attach.png :scale: 50% .. |aws_route_propagation_status_yes| image:: transit_gateway_external_device_bgp_over_gre_high_performance_workflow_media/aws_route_propagation_status_yes.png :scale: 50% .. |aws_route_propagation_routing_entry| image:: transit_gateway_external_device_bgp_over_gre_high_performance_workflow_media/aws_route_propagation_routing_entry.png :scale: 50% .. |aviatrix_transit_externel_device_gre| image:: transit_gateway_external_device_bgp_over_gre_high_performance_workflow_media/aviatrix_transit_externel_device_gre.png :scale: 50% .. |aviatrix_gre_status_1| image:: transit_gateway_external_device_bgp_over_gre_high_performance_workflow_media/aviatrix_gre_status_1.png :scale: 50% .. |aviatrix_gre_status_2| image:: transit_gateway_external_device_bgp_over_gre_high_performance_workflow_media/aviatrix_gre_status_2.png :scale: 50% .. |aviatrix_gre_bgp_status| image:: transit_gateway_external_device_bgp_over_gre_high_performance_workflow_media/aviatrix_gre_bgp_status.png :scale: 50% .. |aviatrix_gre_bgp_ecmp_function| image:: transit_gateway_external_device_bgp_over_gre_high_performance_workflow_media/aviatrix_gre_bgp_ecmp_function.png :scale: 50% .. |aviatrix_gre_bgp_verify_ecmp_function| image:: transit_gateway_external_device_bgp_over_gre_high_performance_workflow_media/aviatrix_gre_bgp_verify_ecmp_function.png :scale: 30% .. |asr_gre_bgp_verify_ecmp_function| image:: transit_gateway_external_device_bgp_over_gre_high_performance_workflow_media/asr_gre_bgp_verify_ecmp_function.png :scale: 70% .. |aviatrix_multiple_gre| image:: transit_gateway_external_device_bgp_over_gre_high_performance_workflow_media/aviatrix_multiple_gre.png :scale: 30% .. disqus:: <file_sep> ################################### Error Messages ################################### This document records Aviatrix error messages, possible root causes and solutions. --------------------------------------------------------------------------------------- :: [Aviatrix Error] Egress-FireNet-oregon enables East-west inspection. It conflicts with tgw-0af3e281d06d363d4 existing firewall policy. If there are multiple Firewall domains or Transit DMZ that enable traffic inspection, please make sure egress_domain is completely isolated from the other firewall domain. This is probably caused by two firewall domains both wanting to inspect the same VPC traffic. Only one firewall domain can inspect east-west traffic the other inspects egress. You can fix this by going to Firewall Network -> Advanced. Select the firewall domain, disable "Traffic Inspection, and enable "Egress through Firewall". Then go back and execute Step 6 in Firewall Network workflow. ------------------------------------------------------------------------------------- :: [Aviatrix Error] Only VPN BGP is supported. Go to AWS Console -> VPC -> Site-to-Site VPN Connections to download the configuration file. TGW VPN configuration downloading is not supported from the Aviatrix Controller console. You can download the configuration by going to the AWS Console -> VPC -> Site-to-Site VPN Connections to download the configuration file. Once the file is downloaded, use the information in the file to configure the remote end of the IPSec VPN. ------------------------------------------------------------------------------------ :: Error: [Aviatrix Error] Peerings detected. Please delete them before terminating the gateway. You must go to the Peering page to delete the peering first before you can delete the gateway. -------------------------------------------------------------------------------- :: [Aviatrix Error] Failed to deliver msg to gw oregon-spoke1-server: HTTPSConnectionPool(host='192.168.3.11', port=443): Max retries exceeded with url: /cloudxaws/launch.py?action=gateway_diag (Caused by ConnectTimeoutError(, 'Connection to 192.168.3.11 timed out. (connect timeout=10)')) It's possible the named gateway is stopped or a security group rule blocked access from the Controller. --------------------------------------------------------------------------------- :: Error: [Aviatrix Error] For rule:[{u'port': u'22-220', u'fqdn': u'www.amazon.com', u'proto': u'tcp'}] port[22-220] range must be within the caped limit of:100. Syntax:[port | fromport-toport]. Range "fromport" to "toport" inclusive. The maximum port range is 100. --------------------------------------------------- :: Error: Exception CloudxErrExt Context:message:Failed to assume role to your aviatrix-role-app. The policy associated with the role must include AssumeRole. class:CloudxErrExt cloud_type:[1] account_name:[GreatCall_DevOps_Account] It is likely that the Controller was launched not by the CloudFormation script provided by Aviatrix. Follow the `Aviatrix Controller Startup guide <https://docs.aviatrix.com/StartUpGuides/aviatrix-cloud-controller-startup-guide.html>`_. ---------------------------------------------------------------------------------- :: Error: [Aviatrix Error] BGP connection can only be deleted from Transit Network page. A Site2Cloud connection established from `Transit Network workflow <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#connect-the-transit-gw-to-aws-vgw>`_ can only be deleted by the `delete section <https://docs.aviatrix.com/HowTos/transitvpc_workflow.html#remove-transit-gw-to-vgw-connection>`_ in the workflow. ----------------------------------------------------------------------------------- :: [Aviatrix Error] Primary gateway virginia-transit is not up. Bring up the Primary gateway and try again. It is likely your gateway is in a stopped state. Go to AWS Console to start the gateway instance. ------------------------------------------------------------------------------------ :: [Aviatrix Error] Failed to enable route propagation for route table rtb-00e04eeae563a1713, vgw vgw-058b6dbb20155c6b2 - EC2ResponseError: 403 Forbidden UnauthorizedOperationYou are not authorized to perform this operation.16b84b8a-f5cd-4a25-9c61-bdf8f52a08f1 One likely cause is that your Aviatrix IAM policy (aviatrix-app-policy) does not contain the privilege for this operation. Follow the instruction in this link to update the aviatrix-app-policy. https://docs.aviatrix.com/HowTos/iam_policies.html#updating-iam-policies (If this is not clear, go to docs.aviatrix.com and search the matching error string for resolution.) One likely cause is that your Aviatrix IAM policy (aviatrix-app-policy) does not contain the privilege for this operation. Follow the instruction in this link to update the aviatrix-app-policy. https://docs.aviatrix.com/HowTos/iam_policies.html#updating-iam-policies Follow the instructions `here <https://docs.aviatrix.com/HowTos/iam_policies.html>`_ to update the IAM policy on this account. ---------------------------------------------------------------------------------- :: [Aviatrix Error] oregon-transit with size t2.micro only support 2 interfaces. Cannot create DMZ interface. Please increase gateway size (suggest t3.medium) Transit DMZ deployment requires 3 Ethernet interfaces. t2.micro has only 2. At the Aviatrix Controller console, go to Gateway. Highlight the transit gateway with the size error, click Edit. Scroll down to Gateway Resize. In the drop down menu, select t3.large or a more powerful instance size. For instance size charts, refer to `this AWS guide <https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html>`_. ------------------------------------------------------------------------------------ :: Error: [Aviatrix Error] Peerings detected. Please delete them before terminating the gateway. Go to Peering page to delete the peer first. ----------------------------------------------------------------------------------- :: Error: [Aviatrix Error] Detach virginia-spoke-1 from virginia-transit in Transit Network page... The peering relationship was most likely established by the Transit Network workflow attaching a Spoke VPC to the Transit Gateway, therefore you should detach the Spoke VPC from the Transit VPC to delete the peering. ------------------------------------------------------------------------------------ :: Error: Failed to create TGW Infra-TGW in us-east-1 - An error occurred (UnauthorizedOperation) when calling the CreateTransitGateway operation: You are not authorized to perform this operation. It is likely you need to update IAM policies. Follow the instructions `here. <https://docs.aviatrix.com/HowTos/iam_policies.html>`_ ----------------------------------------------------------------------------------- :: [Aviatrix Error] Legal terms have not been accepted for this item on this subscription. To accept legal terms, please go to the Azure portal ..... and configure programmatic deployment for the Marketplace item or create it there for the first time If you see this error message when you launch an Azure ARM gateway, chances are you have not subscribed to the Aviatrix gateway during the Azure onboarding process. Either go back to the onboarding page and follow the instructions there, or click `this link <https://s3-us-west-2.amazonaws.com/aviatrix-download/Cloud-Controller/How+to+subscribe+to+Aviatrix+companion+gateway.pdf>`__ for guidance. --------------------------------------------------------------------------------- :: [Aviatrix Error] Exception CloudxErrExt Context:message:EC2ResponseError: 401 Unauthorized AuthFailureAWS was not able to validate the provided access credentialsf67841bc-cb94-4cfd-a990-05d27d11f540 If you see this error message when launching an AWS gateway, the potential root causes are: - If you used AWS IAM roles for the Aviatrix account, it is likely that your IAM role policies are not up to date. Follow `this link <https://docs.aviatrix.com/HowTos/iam_policies.html#updating-iam-policies>`_ to update both IAM policies on both your primary account and secondary account. - If you used an AWS access key and secret ID for the Aviatrix account, it is possible that this pair of credentials is incorrect. Re-enter these two fields. ------------------------------------------------------------------------------------ :: [Aviatrix Error] Detach before you delete AWS TGW. To detach Aviatrix Transit GW vpc-873db7e2 using "TGW Orchestrator > Plan > Step 7". This error message says you must first detach the Aviatrix Transit GW from the TGW before you can delete the gateway. -------------------------------------------------------------------------------------- :: [Aviatrix Error] VPC creation failed with error EC2ResponseError: 400 Bad Request VpcLimitExceededThe maximum number of VPCs has been reached You may have exceeded AWS VPC limits on this account. You can file a support ticket to increase the limit. ------------------------------------------------------------------------------------ :: Error: [Aviatrix Error] Failed to deliver msg to gw virginia-client: HTTPSConnectionPool(host='172.16.17.32', port=443): Max retries exceeded with url: /cloudxaws/launch.py?action=gateway_diag (Caused by ConnectTimeoutError(, 'Connection to 172.16.17.32 timed out. (connect timeout=10)')) The gateway instance is either stopped or a security group rule of the gateway instance was added that prevents the Controller from reaching the gateway. ------------------------------------------------------------------------------------ :: Error: [Aviatrix Error] Failed to launch vpc virginia-client due to Failed to create instance. Error code: Unsupported, message: Your requested instance type (c5.2xlarge) is not supported in your requested Availability Zone (us-east-1e). Please retry your request by not specifying an Availability Zone or choosing us-east-1b, us-east-1d, us-east-1a, us-east-1f, us-east-1c.. Could be the Gateway size c5.2xlarge is not supported in the region us-east-1 This instance size is not supported in the AZ you selected. Select a different one. ------------------------------------------------------------------------------------ :: Error: [Aviatrix Error] Failed to allocate EIP, The maximum number of addresses has been reached. You have reached your AWS EIP limit. Release some of your unallocated EIPs from the AWS EC2 Console or submit a support ticket to AWS to increase the limit. ----------------------------------------------------------------- :: Error: [Aviatrix Error] Peerings detected. Please delete them before terminating the gateway. You should go to Peering page to delete all peerings on the gateway before you can delete the gateway. -------------------------------------------------------------- :: Error: [Aviatrix Error] Only C5 instances are allowed when Insane Mode is enabled. Insane Mode only supports AWS C5 series. For performance, check `this link <https://docs.aviatrix.com/HowTos/insane_mode.html#instance-sizes-and-ipsec-performance>`_. -------------------------------------------------------------------- :: Error: [Aviatrix Error] Primary transit gateway insane2-main is not active gateway. Please force switchover gateway back to primary before enabling Connected Transit Mode. Your primary Aviatrix Transit Gateway is not the active one. Please follow the steps below to switchover from backup Transit Gateway to primary Transit Gateway: - For DMZ Main Transit Gateway, go to "Transit DMZ" -> "Advanced". At "Main gateway" section, click "Switchover" button and make sure "HA Status" of primary Main Gateway is in "Active" state. - For a Transit Gateway with BGP connections, go to "Troubleshoot" -> "Diagnostics" -> "BGP", click "Switch Over" button along with backup Transit Gateway (gateway name with "hagw" postfix). -------------------------------------------------------------------- :: Error: [Aviatrix Error] Gateway instance create failed Reason:Quota 'IN_USE_ADDRESSES' exceeded. Limit: 8.0 in region us-central1. You may have exceeded GCP IN_USE_ADDRESSES limits on this account. By default in GCP, the in-use IP address of a region is 8 (Different GCP project has different quotas limit setting), you can ask for a new quota limit by following `this GCP instruction <https://cloud.google.com/compute/quotas#request_quotas>`_. -------------------------------------------------------------------- :: Error: [Aviatrix Error] LAN interface is not in demo1-oregon-firenet-gw firewall subnet subnet-09f70b0922e5878ce. When you try to associate firewall instance to FireNet gateway, the firewall's LAN instance must stay in the same subnet with FireNet gateway's firewall subnet. It is recommended to use Aviatrix controller to launch and associate firewall, which guarentee all the subnets and interfaces are correct. If you launch your own firewall, you need to make sure the firewall interfaces are correct. The firewall subnets/interfaces are created when enable FireNet function on the gateway. If you create firewall instance before enable FireNet function, those instances can not associate with gateway due to mismatched interface. One way to solve this is to use API to enable FireNet function, and provide existing subnets as option. Please refer to API doc. -------------------------------------------------------------------- :: Error: TCP: connect to [AF_INET] failed, will try again in 5 seconds: The system tried to join a drive to a directory on a joined drive. This error may be found in Aviatrix VPN Client logs. It will be returned in the event a TCP OpenVPN Gateway is deployed behind an AWS NLB, but port 943 is not open to the preserved source IP's. We recommend opening port 943 to 0.0.0.0/0 to prevent connectivity issues like this. Please refer to the following documentation for OpenVPN required ports: https://docs.aviatrix.com/Support/support_center_openvpn_gateway.html#which-ports-should-i-have-open-in-my-firewall-to-allow-openvpn-users-to-come-in -------------------------------------------------------------------- :: Error: [Aviatrix Error] An error occurred (InsufficientFreeAddressesInSubnet) when calling the CreateTransitGatewayVpcAttachment operation: Insufficient Free IP Addresses in subnet. This error will be returned when there are 0 available IP addresses in a subnet that is being attached to the TGW. You must have at least one available IP address in each subnet that will be attached. -------------------------------------------------------------------- :: Error: [Aviatrix Error] Gateway instance create failed Reason:Quota 'IN_USE_ADDRESSES' exceeded. Limit: 8.0 in region us-central1. You may have exceeded GCP IN_USE_ADDRESSES limits on this account. By default in GCP, the In-use IP address of a region is 8 (Different GCP project has different quotas limit setting), you can ask for a new quota limit by following `this GCP instruction <https://cloud.google.com/compute/quotas#request_quotas>`_. -------------------------------------------------------------------- :: Error: [Aviatrix Error] [AVXERR-GATEWAY-####] Failed to resize Gateway *Gateway_Name*. Azure Error: NetworkInterfaceCountExceeded Message: The number of network interfaces for virtual machine *Virtual_Machine_Name* exceeds the maximum allowed for the virtual machine size Standard_B1ms. The number of network interfaces is 3 and the maximum allowed is 2. This issue occurs because the gateway you attempted to downsize does not have enough network interfaces or NICs (Network Interface Cards) for the size of your Azure virtual machine with Aviatrix FireNet enabled. Azure virtual machines with the Standard_B1 size can have up to 2 NICs. However, when you use Aviatrix Transit FireNet for a gateway, you need 3 NICs. To resolve this issue, you can either: * Resize the Azure virtual machine to Standard-B2 or larger. * Disable Transit FireNet on this gateway. In your Controller, go to Firewall Network > Setup > Detach > Disable Transit Firenet Function for Aviatrix Transit Gateway > select the gateway > click **Disable**. .. disqus:: <file_sep> ================================================================= Bootstrap Configuration Example for FortiGate Firewall in Azure ================================================================= Using the bootstrap option significantly simplifies Fortinet FortiGate initial configuration setup. In this document, we provide a bootstrap example to set up an "Allow All" firewall policy, firewall health check policy and static routes for the FortiGate to validate that traffic is indeed sent to the FortiGate for VNet-to-VNet traffic inspection. For a manual setup, follow `manual setup example <https://docs.aviatrix.com/HowTos/config_FortiGateAzure.html>`_. There are two ways to configure Fortinet Fortigate via Bootstrap Configuration: Method 1: Configuring Fortigate Firewall via User Data ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Follow the Aviatrix Firewall Network (FireNet) workflow to `this step <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#launching-and-associating-firewall-instance>`_ to launch the firewall instance. To Configure FortiGate using Custom Data, go to the Aviatrix Controller > Firewall Network > Setup > Launch & Associate Firewall Instance. Fill in the required fields. Click **Advanced**. Fill in the following parameters. ================================ ====================== **Advanced Field** **Example Value** ================================ ====================== User Data Bootstrap Configuration ================================ ====================== Sample Fortigate Bootstrap Configuration to configure firewall "Allow-all" policy, health check policy and RFC 1918 static routes is shown below: :: # Simple Example Fortigate Bootstrap Configuration # Not Necessary Fulfill the Requirement for any Customer # Login Username and Password config system admin edit admin set password <<PASSWORD>> end # System Hostname config system global set hostname myhost set timezone 04 end # Important HTTPS needs to be allowed on LAN interface for Firewall Health Check config system interface edit port2 set allowaccess https next end #RFC 1918 Routes and Subnet Default Gateway config router static edit 1 set dst 10.0.0.0 255.0.0.0 set gateway 10.26.0.81 set device port2 next edit 2 set dst 192.168.0.0 255.255.0.0 set gateway 10.26.0.81 set device port2 next edit 3 set dst 172.16.0.0 255.240.0.0 set gateway 10.26.0.81 set device port2 next # LoadBalancer IP edit 4 set dst 192.168.127.12 255.255.255.255 set gateway 10.26.0.81 set device port2 next end # Firewall Allow All Policy Example config firewall policy edit 1 set name allow_all set srcintf port2 set dstintf port2 set srcaddr all set dstaddr all set action accept set schedule always set service ALL next end |fortigate_bootstrap_example| Launch the instance. Wait for 15 minutes for it to boot up and initialize. Log in to the HTTPS interface of the public IP with username "admin" and the password specified in the example Fortigate Bootstrap Configuration. For initial Fortigate login information, go to `Credentials for FortiGate Initial Login <https://aviatrix.zendesk.com/hc/en-us/articles/4417531104781>`_. You must be registered to access the Aviatrix Customer Support website. If you are not already registered, you can sign-up at https://support.aviatrix.com. Method 2: Configure Fortigate Using Azure Blob ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Creating Storage Account and Private Container ------------------------------------------------------------ Log in to Azure's console and create a storage account, and private container in the Azure blob for bootstrap with a **unique** name, for example "bootstrap-fortigate", using this `guide <https://docs.fortinet.com/document/fortigate/6.0.0/deploying-fortigate-on-azure/61731/bootstrapping-the-fortigate-cli-and-byol-license-at-initial-boot-up-using-user-data>`_ Step 2 and 3 with the following structure: :: Storage Account Container fortigatebootstrap/ init.txt license.txt Uploading Config Files --------------------------------- 1. The example init.conf file contains the "Allow All" setup. To download the file, click :download:`init.txt <fortigate_bootstrap_example_media/init-azure.txt>`. 2. For the example license.lic file (optional), click :download:`license.txt <fortigate_bootstrap_example_media/license.lic>`. 3. Upload these two files in the blob. Please follow Step 4 in `this <https://docs.fortinet.com/document/fortigate/6.0.0/deploying-fortigate-on-azure/61731/bootstrapping-the-fortigate-cli-and-byol-license-at-initial-boot-up-using-user-data>`_ guide. Launching the Fortigate Instance -------------------------------------------- First follow `Step 5 <https://docs.fortinet.com/document/fortigate/6.0.0/deploying-fortigate-on-azure/61731/bootstrapping-the-fortigate-cli-and-byol-license-at-initial-boot-up-using-user-data>`_ to get the SAS URL for Configuration and License. Follow the Aviatrix Firewall Network (FireNet) workflow to `this step <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#launching-and-associating-firewall-instance>`_. Fill in the required fields. Click **Advanced**. Fill in the following parameters. ================================ ====================== **Advanced Field** **Example Value** ================================ ====================== Bootstrap Storage Name Azure Storage Name (e.g. transitbootstrapsotrage) Container Folder Private Container Name (e.g. fortigatebootstrap) SAS URL Config SAS Config URL (Follow the given guide) SAS URL License SAS License URL (Follow the given guide) ================================ ====================== Example Screenshot: |fortigate_method2_example| Launch the instance. Wait for 15 minutes for it to boot up and initialize. Please make sure to verify the RFC 1918 and Internet static route in Fortigate firewall. Log in to the HTTPS interface of the public IP with username "admin" and the password specified in the example Fortigate Bootstrap Configuration. For initial Fortigate login information, go to `ZENDESK_TITLE <ZENDESK_TITLE>`_. You must be registered to access the Aviatrix Customer Support website. If you are not already registered, you can sign-up at https://support.aviatrix.com. Ready to Go ~~~~~~~~~~~~~~~ Now your firewall instance is ready to receive packets. Next step is to validate your configurations and polices using FlightPath and Diagnostic Tools (ping, traceroute etc.). Launch one instance in PROD Spoke VNet and DEV Spoke VNet. Start ping packets from a instance in DEV Spoke VNet to the private IP of another instance in PROD Spoke VNet. The ICMP traffic should go through the firewall and be inspected in firewall. .. |fortigate_bootstrap_example| image:: fortigate_bootstrap_example_media/fortigate_bootstrap_example.png :scale: 40% .. |fortigate_method2_example| image:: fortigate_bootstrap_example_media/fortigate_method2_example.png :scale: 40% .. disqus:: <file_sep> ========================================================= AWS Ingress Firewall Setup Solution ========================================================= This document illustrates a simple architecture for Ingress traffic inspection firewall that leverages AWS Load Balancers, `Aviatrix TGW Orchestrator <https://docs.aviatrix.com/HowTos/tgw_faq.html>`_ and `Aviatrix Firewall Network <https://docs.aviatrix.com/HowTos/firewall_network_faq.html>`_. The solution also allows you to view the client IP address. The deployment is shown as the diagram below. |ingress_firewall| The key idea is from FireNet point of view, the ingress inspection is simply a VPC-to-VPC traffic inspection. This is accomplished by a. Placing an Internet-facing AWS ALB/NLB in a spoke VPC in a separate domain (in the diagram, this domain is called Ingress domain.) from the domains where applications reside (Application domain). #. Build a connection policy to connect the Ingress domain with the Application domain. #. Connect the Application domain traffic that requires inspection with the Aviatrix Firewall Domain. In this unified architecture, firewalls can be used for Ingress, Egress, North-South and VPC-to-VPC filtering. The solution does not need AWS ALB/NLB to directly attach to firewall instances which then requires firewall instances to source NAT the incoming traffic from the Internet. Firewall instances can scale out as applications scale for all traffic types. .. Note:: This architecture works for both `AWS Network Load Balancer <https://docs.aws.amazon.com/elasticloadbalancing/latest/network/introduction.html>`_ and `AWS ALB. <https://docs.aws.amazon.com/elasticloadbalancing/latest/application/create-application-load-balancer.html>`_. NLB is used for illustration purpose. You can create multiple load balancers in the Ingress VPC. 1. Prerequisite Setup -------------------------------- - Follow `Aviatrix Firewall Network workflow <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html>`_ to launch FireNet gateways and firewall instances. Enable `Egress <https://docs.aviatrix.com/HowTos/firewall_network_faq.html#how-do-i-enable-egress-inspection-on-firenet>`_ if desired. - Follow `Aviatrix TGW Orchestrator workflow <https://docs.aviatrix.com/HowTos/tgw_plan.html>`_ to: - Create an Ingress domain (this domain can be named something else and can be an existing domain, just make sure it is in a different domain than Application domain). - Build Connection policy between the Ingress domain and the Application domain. - Build Connection policy between Application domain and Firewall domain so that traffic in and out of the domain is inspected. - Attach the Application domain VPC (Spoke-2 in the diagram) to the TGW. - Attach the Ingress domain VPC (Spoke-1 in the diagram) to the TGW. 2. Create AWS NLB ------------------------------------- In Ingress domain VPC (Spoke-1), create an AWS NLB, make sure you select the following. - Select **Internet-facing**. - Routing Target group should be IP. 3. Ready to go! --------------- - From the AWS Console, make sure NLB target group is in healthy state. - Run a https request on the NLB DNS name - The application can also reach Internet through firewall instances if you enable Egress on the FireNet. 4. Capturing Client IP ------------------------- 4.1 Using AWS ALB ^^^^^^^^^^^^^^^^^^ AWS ALB automatically preserves client IP address, you can find the client IP address in the HTTP header field "X-Forwarded-For". To view the client IP address in the access log, follow the instructions in `How to save client IP in access logs <https://aws.amazon.com/premiumsupport/knowledge-center/elb-capture-client-ip-addresses/>`_. 4.2 Using AWS NLB ^^^^^^^^^^^^^^^^^^^^ When NLB uses IP address as target group, the client IP address of the packet reaching to the application is one of the NLB node private IP address. If you like to get the original client IP address, you need to enable function `proxy_protocol_v2.enabled under Target Group Attributes <https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-target-groups.html#target-group-attributes>`_ on the NLB. Review the section "Enable Proxy Protocol" in the above AWS document or follow the same steps as below to enable this function on NLB using the AWS console. 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. #. On the navigation pane, under Load Balancing, select **Target Groups**. #. Select the target group. #. Choose Description > Edit attributes. #. Select **Enable proxy protocol v2**, and then click **Save**. Also, you need to configure/support Proxy Protocol feature on your web server to retrieve the client original IP address. Please follow the steps below which are referring to the AWS document `How do I capture client IP addresses in my ELB access logs? <https://aws.amazon.com/premiumsupport/knowledge-center/elb-capture-client-ip-addresses/>`_. - Take Apache/2.4.41 (Ubuntu) for example. - Find and open Apache configuration file. :: /etc/apache2/apache2.conf - Edit/add remoteip module configuration into Apache configuration file as below: :: LoadModule remoteip_module /usr/lib/apache2/modules/mod_remoteip.so - https://httpd.apache.org/docs/2.4/mod/mod_remoteip.html - https://httpd.apache.org/docs/2.4/mod/mod_remoteip.html#remoteipproxyprotocol - Confirm that the mod_remoteip module loads by issuing command as below :: $sudo apachectl -t -D DUMP_MODULES | grep -i remoteip - Review the output and verify that it contains a line similar to: :: remoteip_module (shared) - Notes: If you are not able to view the prompt message, please make sure that your apache version support that module or attempt to load that module into the apache configuration. - Configure the following line to your Apache configuration file (take /etc/apache2/sites-available/000-default.conf for example) to enable Proxy Protocol support. :: RemoteIPProxyProtocol On - To view client IP address in the access log, edit/add commands into LogFormat section as below: :: LogFormat "%h %p %a %{remote}p %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined - Save the changes - Reload the Apache service by issuing command. :: #systemctl reload apache2 - Open the Apache access logs on your Apache server. - Verify that client IP addresses are now recorded under the X-Forwarded-For header. - Notes: - Commands and file location varies by configuration - For other OSs and web services, please find detail in the document `How do I capture client IP addresses in my ELB access logs? <https://aws.amazon.com/premiumsupport/knowledge-center/elb-capture-client-ip-addresses/>`_ .. |ingress_firewall| image:: ingress_firewall_example_media/ingress_firewall.png :scale: 30% .. disqus:: <file_sep> ============================================ Aviatrix Gateway to Juniper SRX ============================================ This document describes how to build an IPsec tunnel-based Site2Cloud connection between an Aviatrix Gateway and a JuniperSRX Firewall. The network setup is as follows: **VPC/VNet-multicloudvpc1 (with Aviatrix Gateway)** *VPC/VNet CIDR: 10.1.1.0/16* *VPC/VNet Subnet CIDR (public in AWS, GCP, or OCI): 10.1.1.0/24* *VPC/VNet Private Subnet CIDR: 10.1.2.0/24* **On-Prem (with Juniper SRX Firewall)** *On-Prem Network CIDR: 10.0.0.0/16* *On-prem Public Network CIDR: 10.0.3.0/24* *On-prem Private Network CIDR: 10.0.2.0/24* Creating a Site2Cloud Connection at the Aviatrix Controller ====================================================== 1. Go to **Gateway > New Gateway** to launch an Aviatrix Gateway at the subnet of VPC/VNet-multicloudvpc1 (public subnet for AWS, GCP, or OCI). Collect Gateway's public IP addresses (172.16.17.32 in this example). |image1| 2. Go to the **Site2Cloud** page and click **Add New** to create a Site2Cloud connection. =============================== ================================================================= **Field** **Value** =============================== ================================================================= VPC ID/VNet Name Choose VPC ID/VNet of VPC/VNet- multicloudvpc1 Connection Type Unmapped Connection Name Arbitrary (e.g. avx-SRX-S2C) Remote Gateway Type Generic Tunnel Type UDP Algorithms Unmark this checkbox Encryption over Direct Connect Unmark this checkbox Enable HA Unmark this checkbox Primary Cloud Gateway Select Aviatrix Gateway created above Remote Gateway IP Address Public IP of Juniper SRX WAN port (172.16.31.10 in this example) Pre-shared Key Optional (auto-generated if not entered) Remote Subnet 10.0.2.0/16 (On-Prem Private Network CIDR) Local Subnet 10.1.2.0/24 (VPC-multicloudvpc1 private subnet) =============================== ================================================================= 3. Go to the **Site2Cloud** page. From the Site2Cloud connection table, select the connection created above (e.g. avx-SRX-S2C). - Select **Generic** from the **Vendor** dropdown menu. - Click the **Download Configuration** button to download the SRX Site2Cloud configuration. - Save the configuration file as a reference for configuring your Juniper SRX. |image2| The following is an SRX sample configuration based on the Site2Cloud configuration above. |image3| Configuring JuniperSRX ======================= Apply the following configuration to your SRX: .. raw:: html <iframe src="https://s3-us-west-2.amazonaws.com/aviatrix-download/docs/srx_site2cloud.txt" height="300px" width="100%"></iframe> Troubleshooting and Verifying at the Aviatrix Controller ======================================================== 1. At the Aviatrix Controller, select **Site2Cloud** from the left sidebar. Verify that the status of the Site2Cloud connection is up. |image4| 2. At the Site2Cloud - Diagnostics page, run various diagnostics commands. =============================== ================================================================= **Field** **Value** =============================== ================================================================= VPC ID/VNet Name VPC/VNet- multicloudvpc1 (Aviatrix Gateway VPC/VNet) ID Connection Name of the Site2Cloud connection created above Gateway Name of the Aviatrix Gateway Action One of the supported diagnostics commands =============================== ================================================================= .. |image1| image:: ./site2cloud_JuniperSRX_media/JuniperS2C1.png :width: 100% .. |image2| image:: ./site2cloud_JuniperSRX_media/JuniperS2C2.png :width: 100% .. |image3| image:: ./site2cloud_JuniperSRX_media/JuniperS2C3.png :width: 100% .. |image4| image:: ./site2cloud_JuniperSRX_media/JuniperS2C4.png :width: 100% <file_sep> ========================================================= Example Config for FortiGate VM in AWS ========================================================= In this document, we provide an example to set up the Fortigate Next Generation Firewall instance for you to validate that packets are indeed sent to the Fortigate Next Generation Firewall for VPC-to-VPC and from VPC to Internet traffic inspection. The Aviatrix Firewall Network (FireNet) workflow launches a Fortigate Next Generation Firewall instance at `this step <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#launching-and-associating-firewall-instance>`_. After the launch is complete, the console displays the Fortigate Next Generation Firewall instance with its public IP address of management/egress interface and allows you either to download the .pem file for SSH access to the instance or to access the FortiGate web page. Here is the Firewall information in this example for your reference. Please adjust it depending on your requirements. ========================================== ========== **Example setting** **Example value** ========================================== ========== Firewall Image Fortinet FortiGate Next-Generation Firewall Firewall Image Version 6.2.3 Firewall Instance Size c5.xlarge Egress Interface Subnet Select the subnet whose name contains "FW-ingress-egress." Key Pair Name (Optional) The .pem file name for SSH access to the firewall instance. Attach Check ========================================== ========== .. note:: Fortigate Next Generation Firewall instance has 2 interfaces as described below. Additionally, firewall instance eth1 is on the same subnet as FireNet gateway eth2 interface. ======================================================== =============================== ================================ **Fortigate VM instance interfaces** **Description** **Inbound Security Group Rule** ======================================================== =============================== ================================ eth0 (on subnet -Public-FW-ingress-egress-AZ-a) Egress or Untrusted interface Allow ALL eth1 (on subnet -dmz-firewall) LAN or Trusted interface Allow ALL (Do not change) ======================================================== =============================== ================================ Below are the steps for initial setup. Downloading Fortigate Next Generation Firewall Access Key ------------------------------------------------------------------------------ After `this step <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#launching-and-associating-firewall-instance>`_ in the workflow is completed, click **Download** to download the .pem file. If you get a download error, usually it means the Fortigate Next Generation Firewall instance is not ready. Wait until it is ready, refresh the browser and then try again. |v2_avx_pem_file_download| Logging in to the Fortigate Next Generation Firewall -------------------------------------------------------------------- 1. Go back to the Aviatrix Controller. 2. Go to `this step <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#launching-and-associating-firewall-instance>`_ of the Firewall Network workflow. Click on the Management UI. It takes you to the Fortigate Next Generation Firewall you just launched. |v2_avx_management_UI| .. note:: Please try to use browser Firefox if the Management UI link is not able to open on your default browser. Resetting Fortigate Next Generation Firewall Password --------------------------------------------------------------------- Once logged in with the default password, it will ask you to set a new password. .. note:: Log in with Username "admin." The default password is the instance-id. Configuring Fortigate Next Generation Firewall port1 with WAN --------------------------------------------------------------------------------- After logging in with the new password, go to the page "Network -> Interfaces" to configure Physical Interface port1 as the following screenshot. 1. Select the interface with port 1 and click **Edit**. 2. Enter an Alias (i.e.: WAN) for the interface. 3. Specify appropriate role (WAN). 4. Enable DHCP to ensure FW retrieve private IP information from the AWS console. 5. Enable **Retrieve default gateway from server**. |v2_fortigate_interface_wan| Configure Fortigate Next Generation Firewall port2 with LAN ------------------------------------------------------------------------------- Go to the page Network > Interfaces to configure Physical Interface port2 as the following screenshot. 1. Select the interface with port 2 and click **Edit**. 2. Enter an Alias (i.e.: LAN) for the interface. 3. Specify appropriate role (LAN). 4. Enable DHCP to ensure FW retrieve private IP information from AWS console. 5. Enable Administrative Access: IPv4 > HTTPS. 6. Disable **Retrieve default gateway from server**. |v2_fortigate_interface_lan| Creating Static Routes for Routing of Traffic VPC to VPC -------------------------------------------------------------------- Packets to and from TGW VPCs, as well as on-premises, will be hairpinned off of the LAN interface. As such, we will need to configure appropriate route ranges that you expect traffic for packets that need to be forward back to TGW. For simplicity, you can configure the FW to send all RFC 1918 packets to LAN port, which sends the packets back to the TGW. In this example, we configure all traffic for RFC 1918 to be sent out of the LAN interface. Go to **Network -> Static Routes** to create a Static Route as the following screenshot. 1. Click **Create New**. 2. Enter the destination route in **Destination**. 3. In **Gateway Address**, you will need to enter the AWS default gateway IP on subnet -dmz-firewall. .. note:: i.e. The subnet CIDR for -dmz-firewall is 10.66.0.96/28, thus the AWS default gateway IP on this subnet is 10.66.0.97. 4. The interface will be the LAN (port2). 5. Configure an appropriate admin distance if you expect overlapping routes that need to be prioritized. 6. Enter comments as necessary. 7. Repeat the steps above for RFC 1918 routes. |v2_fortigate_static_routes| Those static routes also could be reviewed by navigating to Monitor > Routing Monitor. |v2_fortigate_static_routes_review| (Optional) Firewall Vendor Integration ------------------------------------------------------ Integrating a FortiGate firewall with the Aviatrix Controller enables the controller to make automatic route updates to the FortiGate routing tables. You may also manually enable the integration with your CSP management tools. FortiGate integration is supported in AWS, Azure, and GCP clouds. Integrate the FortiGate firewall with the Aviatrix Controller. 1. Generate a Firewall API Token from FortiGate. This token is required to integrate the FortiGate firewall with the Controller. 2. In the FortiGate GUI, go to System > Admin Profiles > Create New. 3. Enable the Read/Write option for Network and click **OK**. 4. Navigate to System > Administrators > Create New > REST API Admin. 5. Supply a Username and choose the Admin Profile from the previous step, and press **OK**. 6. Copy the generated token. It will only be displayed once. 7. Go to Aviatrix Controller > Firewall Network > Vendor Integration. 8. Enter the vendor firewall information into the Controller. 9. Click **Save**, then **Show**, then **Sync** to enable the Aviatrix Controller and FortiGate firewall integration. The Aviatrix Controller is now enabled to make automatic route updates to the FortiGate routing tables. Configuring Basic Traffic Policy to Allow Traffic VPC-to-VPC ---------------------------------------------------------------------------- In this step, we will configure a basic traffic security policy that allows traffic to pass through the firewall. Given that Aviatrix Gateways will only forward traffic from the TGW to the LAN port of the Firewall, we can simply set our policy condition to match any packet that is going in/out of LAN interface. Navigate to Policy & Objects > IPv4 Policy > Create New / Edit to configure the policy as shown in the following screenshot. ================== =============================================== **Field** **Value** ================== =============================================== Name Configure any name for this policy Incoming Interface LAN (port2) Outgoing Interface LAN (port2) Source Click on the + sign and add all Destination Click on the + sign and add all Schedule always Service ALL Action ACCEPT NAT Disabled ================== =============================================== |v2_fortigate_policy_vpc_to_vpc| After validating that your TGW traffic is being routed through your firewall instances, you can customize the security policy to tailor to your requirements. [Optional] Configuring Basic Traffic Policy to Allow Traffic VPC to Internet --------------------------------------------------------------------------------------------- In this step, we will configure a basic traffic security policy that allows Internet traffic to pass through the firewall. Given that Aviatrix Gateways will only forward traffic from the TGW to the LAN port of the Firewall, we can simply set our policy condition to match any packet that is going in of LAN interface and going out of WAN interface. .. important:: Enable `Egress inspection <https://docs.aviatrix.com/HowTos/firewall_network_faq.html#how-do-i-enable-egress-inspection-on-firenet>`_ feature on FireNet First, go back to the Aviatrix Controller. 1. Navigate to Firewall Network > Advanced. 2. Click the skewer/three dot button. 3. Scroll down to Egress through Firewall and click **Enable**. 4. Verify the Egress status on the page Firewall Network > Advanced. |v2_avx_egress_inspection| Second, go back to the Fortigate Next Generation Firewall console and navigate to Policy & Objects > IPv4 Policy > Create New / Edit to configure policy as the following screenshot. ================== =============================================== **Field** **Value** ================== =============================================== Name Configure any name for this policy Incoming Interface LAN (port2) Outgoing Interface WAN (port1) Source Click on the + sign and add all Destination Click on the + sign and add all Schedule always Service ALL Action ACCEPT NAT Enable ================== =============================================== .. important:: NAT function needs to be enabled on this VPC to Internet policy. |v2_fortigate_policy_vpc_to_internet| After validating that your TGW traffic is being routed through your firewall instances, you can customize the security policy to tailor to your requirements. Ready to Go --------------------- Now your firewall instance is ready to receive packets. The next step is to specify which Security Domain needs packet inspection by defining a connection policy that connects to the firewall domain. This operation is done by `this step <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#specify-security-domain-for-firewall-inspection>`_ in the Firewall Network workflow. In addition, attach VPC to TGW by `Step 1 <https://docs.aviatrix.com/HowTos/tgw_build.html#aws-transit-gateway-orchestrator-build>`_ in the TGW Orchestrator Build workflow. For example, deploy Spoke-1 VPC in Security_Domain_1 and Spoke-2 VPC in Security_Domain_2. Build a connection policy between the two domains. Build a connection between Security_Domain_2 to Firewall Domain. Viewing the Traffic Log ------------------------------------ You can view if traffic is forwarded to the firewall instance by logging in to the Fortigate Next Generation Firewall console. Go to FortiView > Destinations. For VPC-to-VPC traffic: *********************** Launch one instance in Spoke-1 VPC and Spoke-2 VPC. Start ping packets from a instance in Spoke-1 VPC to the private IP of another instance in Spoke-2 VPC where one or both of Security Domains are connected to Firewall Network Security Domain. The ICMP traffic should go through and be inspected on firewall. |v2_fortigate_view_traffic_log_vpc_to_vpc| [Optional] For VPC to Internet traffic: *************************************** Launch a private instance in the Spoke VPC (i.e. Spoke-2 VPC) where the Security Domain (i.e. Security_Domain_2) is connected to Firewall Network Security Domain. Start ping packets from the private instance to Internet service to verify egress function. The ICMP traffic should go through and be inspected on firewall. |v2_fortigate_view_traffic_log_vpc_to_internet| .. |v2_avx_pem_file_download| image:: config_FortiGate_media/v2_pem_file_download.png :scale: 40% .. |v2_avx_management_UI| image:: config_FortiGate_media/v2_avx_management_UI.png :scale: 40% .. |v2_fortigate_interface_wan| image:: config_FortiGate_media/v2_fortigate_interface_wan.png :scale: 40% .. |v2_fortigate_interface_lan| image:: config_FortiGate_media/v2_fortigate_interface_lan.png :scale: 40% .. |v2_fortigate_static_routes| image:: config_FortiGate_media/v2_fortigate_static_routes.png :scale: 40% .. |v2_fortigate_static_routes_review| image:: config_FortiGate_media/v2_fortigate_static_routes_review.png :scale: 40% .. |v2_fortigate_policy_vpc_to_vpc| image:: config_FortiGate_media/v2_fortigate_policy_vpc_to_vpc.png :scale: 40% .. |v2_fortigate_policy_vpc_to_internet| image:: config_FortiGate_media/v2_fortigate_policy_vpc_to_internet.png :scale: 40% .. |v2_avx_egress_inspection| image:: config_FortiGate_media/v2_avx_egress_inspection.png :scale: 40% .. |v2_fortigate_view_traffic_log_vpc_to_vpc| image:: config_FortiGate_media/v2_fortigate_view_traffic_log_vpc_to_vpc.png :scale: 40% .. |v2_fortigate_view_traffic_log_vpc_to_internet| image:: config_FortiGate_media/v2_fortigate_view_traffic_log_vpc_to_internet.png :scale: 40% .. disqus:: <file_sep> ========================================================================== Configuring an AWS Load Balancer with SSL in front of Aviatrix Controller ========================================================================== Overview -------- The Aviatrix Controller supports adding an SSL certificate. However, sometimes you may prefer to put an ALB in front of the Controller. This gives you the ability to associate it with a WAF, for example. |imageArchitecture| Step-by-Step Deployment Guide ----------------------------- Follow the steps below to put the Aviatrix Controller behind an AWS ALB: #. Login to the `AWS console <https://console.aws.amazon.com/>`__ #. Go to `Load Balancers` for EC2 service in the region where your Aviatrix Controller is running #. Create a new load balancer .. note:: See `this guide <https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/load-balancer-getting-started.html>`__ for more information on AWS load balancing. #. Select `Application Load Balancer` and click `Create` #. Configure the load balancer. Be sure to select `internet-facing` Scheme and `HTTPS` for the `Load Balancer Protocol` of the only listener. |imageConfigureStep1| #. Configure the `Security Settings` by selecting your SSL certificate and security policy. |imageConfigureStep2| #. Select the appropriate security group. This security group should allow traffic on port 443 from your desired source network(s). #. Configure the routing with a new target group. The `Target group` should be configured with `HTTPS` protocol on port `443` and a `Target type` of `instance`. The Health check should use `HTTPS` Protocol and `/` Path. |imageConfigureRouting| .. note:: You may adjust the `Interval` to be larger than 30 seconds to lower the burden on your Controller. #. Find the Aviatrix Controller instance to register in the target group. |imageConfigureRegisterTarget1| After `Add to registered` is clicked you will see this: |imageConfigureRegisterTarget2| #. Review and Create the load balancer |imageConfigureReview| #. Collect the `DNS name` from the load balancer |imageLBDNSName| #. Create a DNS CNAME record pointing your desired name to the load balancer's `DNS name` .. note:: The DNS CNAME record must match the name used in the SSL cert or you will receive a warning in the browser. .. tip:: Here is an example setting up the entry in Route53: |imageRoute53Example| #. The Controller's security groups should have inbound allow policy for port 443 for the VPC CIDR, so that the ELB can talk to the Controller .. |imageConfigureStep1| image:: controller_ssl_elb_media/configure_lb_step1.png :scale: 75% .. |imageConfigureStep2| image:: controller_ssl_elb_media/configure_lb_security.png :scale: 75% .. |imageConfigureRouting| image:: controller_ssl_elb_media/configure_lb_routing.png :scale: 75% .. |imageConfigureRegisterTarget1| image:: controller_ssl_elb_media/configure_lb_add_controller_to_target.png :scale: 75% .. |imageConfigureRegisterTarget2| image:: controller_ssl_elb_media/configure_lb_controller_register.png :scale: 75% .. |imageConfigureReview| image:: controller_ssl_elb_media/configure_lb_review.png :scale: 50% .. |imageLBDNSName| image:: controller_ssl_elb_media/lb_get_dns.png :scale: 75% .. |imageBrowser| image:: controller_ssl_elb_media/browser.png :scale: 50% .. |imageRoute53Example| image:: controller_ssl_elb_media/route53entry.png :scale: 75% .. |imageArchitecture| image:: controller_ssl_elb_media/highlevel.png :scale: 50% .. note:: If you have enabled controller HA, you can point your Auto Scaling Group to Target Group of your ELB for auto registration in the event of a failover. However, please note that Max value should be always 1. Having more than 1 active controller for any given set of services is not supported as documented `here <https://docs.aviatrix.com/HowTos/controller_ha.html>`_, if it is deployed behind an ELB <file_sep> ========================================================= Example Config for FortiGate VM in AWS ========================================================= The goal of this document is to provide a step by step guide to launch and configure one or more Fortigate Next Generation Firewall instances to be integrated with Aviatrix Firewall Network. This setup will include basic “allow-all” policies to serve as initial configuration to validate that intended traffic is passing through the firewall instance. Fortinet’s documentation should be consulted for the configuration of security policies and features. Setup details -------------- The instance will have to be launched in a Firewall Network VPC and appropriate subnets based on the availability zone. Each FW instance will have 3 interfaces that will have the following roles: - Eth0 → Management Interface - Eth1 → Transit Gateways traffic - Eth2 → Internet ingress/egress traffic 1. Setup Firewall Network (FireNet) --------------------------------------- Complete steps 1-5 of the Firewall Network Workflow in Aviatrix controller to prepare your Firewall VPC (FireNet VPC). This will also set up the subnets that you will need for launching your Fortigate instance. 2. Deploy Fortigate Instance from AWS Marketplace ---------------------------------------------------- Launch Fortigate from AWS Marketplace, with the appropriate subscription level. The type of subscription and/or version does not affect the functionality from an Aviatrix perspective. However, it may affect the steps outline from FortiGate's UI. - Step 1: Choose an appropriate image from Marketplace - Step 2: Choose an Instance Type: Chose any appropriate instance type - Step 3: Configure Instance Details. Below, you will find launch configuration details that will be needed for firewall network. All other options can be left on default or modified as required. |launch-step-2| Note: Primary interface (Eth0): Assign this interface to a public subnet of the FireNet VPC that is designated for management. If you created this subnet using the Aviatrix VPC creator, the subnet is named in this format: *<VPC Name>-Public-gateway-and-firewall-mgmt-<AvailabilityZone>* - Step 4/5: Configure as appropriate - Step 6: Configure Security Group for management interface 3. Configure Dataplane interfaces ------------------------------------------ - Using the AWS console, create two additional Network Interfaces in the AWS console with the following subnet association (Naming is optional): - “WAN” Port (Eth1) Subnet: Designated Egress Public Subnet. This interface will be used for Egress/Ingress to and from the internet. Therefore, it is either going to be talking to a load balancer or Internet gateway. If you created this subnet using the Aviatrix VPC creator, the subnet is named in this format: *<VPC Name>-Public-FW-ingress-egress-<AvailabilityZone>* Security Groups: Allow inbound traffic to a supernet for your VPC and OnPrem CIDRs - “LAN” Port (Eth2) Subnet: This interface will be facing Aviatrix GW Eth2. This subnet is automatically created by Aviatrix Controller with following naming format: *<Gateway Name>-dmz-firewall* Security Groups: Ensure we allow appropriate inbound traffic if Ingress is to be used. Note: If you need further clarification on FireNet subnets, please see this link: `FireNet Subnets <https://www.lucidchart.com/publicSegments/view/f0bbe123-cbf7-4339-88df-a51eee2da631/image.pdf>`_ - Using the AWS console, assign an Elastic IP address to Management and WAN interfaces (Eth0 and Eth2) 4. Login to Firewall and configure interfaces ------------------------------------------------ - Using a web browser, connect to the management IP of the instance with HTTPS. You should see a login prompt as seen below, continue to login. |login| :: At the time of this writing, default login for Fortigate is admin as username and instance ID as the password - To configure both Port1 and Port2, go to "Interfaces" tab: - Select an interface and click on "Edit". Enter the following details: - Enter an Alias (i.e: LAN/WAN) for the interface - Enable DHCP to ensure FW retrieve private IP information from AWS console - Disable “Retrieve default gateway from server" - Specify appropriate role (LAN/WAN) |editInterface| 5. Create static routes for routing of traffic VPC to VPC ------------------------------------------------------------ Go to Network -> State Routes to create A Static Route -> click on "Create New" |createStaticRoute| Packets to and from TGW VPCs, as well as on-premises, will be hairpinned off of the LAN interface. As such, we will need to configure appropriate route ranges that you expect traffic for packets that need to be forward back to TGW. For simplicity, you can configure the FW to send all RFC 1918 packets to LAN port, which sends the packets back to the TGW. In this example, we configure all traffic for 172.16.0.0/12 to be sent out of the LAN interface. Go to Network -> Static Routes -> Create new In the Edit dialog, you need to enter the following: - Enter the destination route in the "Destination" box. - In the "Gateway" box, you will need to enter the IP address of the Eth2 interface of the Aviatrix gateway that this firewall will be attached to. - Interface will be the LAN port. - Configure an appropriate admin distance if you expect overlapping routes that need to be prioritized - Enter comments as necessary. |editStaticRoute| 6. Configure basic traffic policy to allow traffic ----------------------------------------------------------- In this step, we will configure a basic traffic security policy that allows traffic to pass through the firewall. Given that Aviatrix gateways will only forward traffic from the TGW to the LAN port of the Firewall, we can simply set our policy condition to match any packet that is going in/out of LAN interface. Go to Policy & Objects -> IPv4 Policy -> Create New / Edit In the Edit Policy dialogue, you need to enter the following: - Name: Configure any name for this policy - Incoming Interface: LAN - Outgoing Interface: LAN - Source: Click on the + sign and add all - Destination: Click on the + sign and add all - Schedule: always - Service: ALL - Action: Accept After validating that your TGW traffic is being routed through your firewall instances, you can customize the security policy to tailor to your requirements. |editPolicy| 7. Ready to go! --------------- Now your firewall instance is ready to receive packets! The next step is specifying which Security Domain needs packet inspection by defining a connection policy that connects to the firewall domain. This is done by `Step 8 <https://docs.aviatrix.com/HowTos/firewall_network_workflow.html#specify-security-domain-for-firewall-inspection>`_ in the Firewall Network workflow. For example, deploy Spoke-1 VPC in Security_Domain_1 and Spoke-2 VPC in Security_Domain_2. Build a connection policy between the two domains. Build a connection between Security_Domain_2 to Firewall Domain. Launch one instance in Spoke-1 VPC and one in Spoke-2 VPC. From one instance, ping the other instance. The ping should go through. 8. View Traffic Log ---------------------- You can view if traffic is forwarded to firewall instance by going to FortiView |showTraffic| .. |launch-step-2| image:: config_FortiGate_media/launch-step-2.png :scale: 40% .. |login| image:: config_FortiGate_media/login.png :scale: 40% .. |Interfaces.png| image:: config_FortiGate_media/Interfaces.png.png :scale: 40% .. |editInterface| image:: config_FortiGate_media/editInterface.png :scale: 40% .. |editPolicy| image:: config_FortiGate_media/editPolicy.png :scale: 40% .. |createStaticRoute| image:: config_FortiGate_media/createStaticRoute.png :scale: 40% .. |editStaticRoute| image:: config_FortiGate_media/editStaticRoute.png :scale: 40% .. |editStaticRoute| image:: config_FortiGate_media/editStaticRoute.png :scale: 40% .. |showTraffic| image:: config_FortiGate_media/showTraffic.png :scale: 40% .. disqus:: <file_sep> ============================================= Aviatrix Gateway to Palo Alto Firewall ============================================= This document describes how to build an IPsec tunnel based Site2Cloud connection between an Aviatrix Gateway and a Palo Alto Networks Firewall. To simulate an on-prem Firewall, we use a VM-Series in an AWS VPC. .. note:: If you do not have access to AWS, you can simulate an on-prem Firewall by deploying the Palo Alto Firewall in any other cloud (such as Microsoft Azure, Google Cloud Platform, or Oracle Cloud Infrastructure). The network setup is as follows: **VPC1 (with Aviatrix Gateway)** *VPC1 CIDR: 10.0.0.0/16* *VPC1 Public Subnet CIDR: 10.0.1.0/24* *VPC1 Private Subnet CIDR: 10.0.2.0/24* **VPC2 (with Palo Alto Networks VM-series)** *VPC2 CIDR: 10.13.0.0/16* *VPC2 Public Subnet CIDR: 10.13.0.0/24* *VPC2 Private Subnet CIDR: 10.13.1.0/24* Certificate-Based Authentication ================================ If you want to use certificate-based authentication when establishing a Site2Cloud connection with your Palo Alto VM-Series firewall, you must do the following: 1. Generate a certificate from your Palo Alto VM-Series firewall. See steps `here <#creating-and-generating-a-self-signed-root-certificate>`_. #. Export your certificate in PEM format. See steps `here <#creating-and-generating-a-self-signed-root-certificate>`_. #. In the Aviatrix Controller, upload the CA certificate generated from your Palo Alto VM-Series firewall under Site2Cloud > Certificate > CA Certificate. See `here <https://docs.aviatrix.com/HowTos/site2cloud-cacert.html>`_ for details. #. Create your Site2Cloud connection as described `here <#setting-up-site2cloud-connection>`_. #. After creating the Site2Cloud connection, `download the resulting configuration <https://docs.aviatrix.com/HowTos/site2cloud.html#download-configuration>`_. #. Download the Aviatrix CA certificate from Site2Cloud > CA Certificate. #. Upload the Aviatrix CA certificate to your on-prem Palo Alto VM-Series firewall. See steps `here <#importing-the-aviatrix-ca-certificate>`_. #. In the Palo Alto VM-Series UI, use the information from the downloaded configuration file to configure your tunnels/interfaces. See steps `here <#adding-a-tunnel-interface>`_. #. In the Palo Alto VM-Series UI, configure the `IKE Gateway <#setting-up-ike-crypto-profile-and-ike-gateways>`_ depending on if you are using PSK or certificate-based authentication. Configuration Workflow ====================== If you are not using certificate-based authentication in your Site2Cloud connection with your Palo Alto firewall, you can skip these sections: - Creating and Generating a Self-Signed Root Certificate - Importing the Aviatrix CA Certificate Also, in the "Setting up IKE Crypto Profile and Gateways" section, you follow the PSK configuration steps instead of the certificate-based authentication steps. Creating and Generating a Self-Signed Root Certificate ------------------------------------------------------ If you are creating a Site2Cloud connection between your Palo Alto VM-Series firewall and your Aviatrix gateway in the cloud and want to use cert-based authentication, you must generate a CA certificate in the firewall UI that you will upload to the Aviatrix Controller under Site2Cloud > CA Certificate. See `this URL <https://docs.paloaltonetworks.com/pan-os/9-1/pan-os-admin/certificate-management/obtain-certificates/create-a-self-signed-root-ca-certificate>`_ for more information on certificates in Palo Alto. 1. In the Palo Alto VM-Series firewall UI, navigate to Device > Certificate Management > Certificates > Device Certificates. #. Click Generate at the bottom of the window. The Generate Certificate dialog displays. #. Fill out the following information: - Certificate Name: a name that makes sense to you, such as PAN-CA - Common Name: a descriptor that makes sense to you, such as pan-to-avx.com - Signed By: select ‘Certificate Authority’ - Cryptographic Settings: - Select Elliptic Curve DSA (ECDSA); this is currently the only algorithm supported by Site2Cloud cert-based authentication. - Select 256 bits - Select sha256 digest |image11| 4. Click Generate. This creates the root CA certificate that will be used to sign the PAN to Aviatrix certificate you will create in the next step. #. Under Device > Certificate Management > Certificates > Device Certificates, generate another certificate (signed by the PAN-CA root you created) and populate as follows: - Certificate Name: a name that makes sense to you, such as pan-to-avx-cert - Common Name: a name that makes sense to you, such as pan-device.com - Signed by: PAN-CA (created in above steps) - Cryptographic Settings: Elliptic Curve DSA algorithm; 256 bits; sha256 digest - Certificate Attributes: refer to the aforementioned Palo Alto Networks URL for information on attributes to use for device certificate creation 6. Click Generate. #. Export the PAN-CA certificate for uploading to the Site2Cloud > CA Certificate page in the Aviatrix Controller. #. See the `CA Certificate page <https://docs.aviatrix.com/HowTos/site2cloud_cert.html>`_ for details on uploading this certificate. Setting up Site2Cloud Connection -------------------------------- 1. Launch a Palo Alto Networks VM-series with at least two network interfaces. One interface serves as a WAN port and is in VPC2's public subnet. The other interface serves as a LAN port and is in VPC2's private subnet. Collect the public IP address of the WAN port. #. In the Aviatrix Controller, navigate to Gateway > New Gateway to launch an Aviatrix Gateway at VPC1's public subnet. Collect both the public and private IP address of the Gateway. #. In the Aviatrix Controller, navigate to Site2Cloud and click **Add New** to create a Site2Cloud connection using the following values (selecting either PSK or certificate-based authentication): =============================== ========================================= **Field** **Value** =============================== ========================================= VPC ID/VNet Name Choose VPC ID of VPC1 Connection Type Unmapped Connection Name Arbitrary (e.g. avx-pan-s2c) Remote Gateway Type Generic Tunnel Type UDP Algorithms Uncheck this box Encryption over Direct Connect Uncheck this box Enable HA Uncheck this box Primary Cloud Gateway Select Aviatrix Gateway created above Remote Gateway IP Address Public IP of Palo Alto Networks VM Series WAN port Pre-shared Key Optional (auto-generated if not entered) Remote Subnet 10.13.1.0/24 (VPC2 private subnet) Local Subnet 10.0.2.0/24 (VPC1 private subnet) =============================== ========================================= #. After the connection is created, select the connection you just created in the table on the Site2Cloud page (for example, avx-pan-s2c). #. Select **Generic** from the **Vendor** dropdown list and click the **Download Configuration** button to download the Site2Cloud configuration. Use this configuration file to configure the tunnels and interfaces in your Palo Alto Network VM-Series firewall. Importing the Aviatrix CA Certificate ------------------------------------- If you are creating a Site2Cloud connection between your Palo Alto VM-Series firewall and your Aviatrix gateway, you must download the Aviatrix CA certificate as per the instructions on the `CA Certificate <https://docs.aviatrix.com/HowTos/site2cloud-cacert.html>`_ page, and then upload it to your Palo Alto VM-Series UI as follows: 1. In the Palo Alto VM-Series UI, navigate to Device > Certificate Management > Certificates > Device Certificates. #. At the bottom of the window, click Import. #. In the Import Certificate dialog, enter the following information: - Certificate Name: a name that makes sense to you - Certificate File: click Browse to navigate to the location of the Aviatrix CA certificate - File Format: select Base64 Encoded Certificate (PEM). 4. Click OK. #. Navigate to Device > Certificate Management > Certificate Profile. In the Certificate Profile dialog enter the following: - Name: enter a name for the profile (such as AVX-CA). - CA Certificates: click Add and select AVX-CERT (or whatever name you gave to the imported Aviatrix CA certificate) from the CA Certificate list. 6. Click OK. #. Click OK again on the main Certificate Profile dialog. Adding a Tunnel Interface ------------------------- #. Log into the Palo Alto Networks VM Series UI. #. Navigate to Network > Interface > Tunnel and click **Add** to create a new tunnel interface and assign the following parameters. |image0| =============================== ====================================== **Field** **Value** =============================== ====================================== Interface Name tunnel.1 Virtual Router Select the existing **default** virtual router Security Zone Select the layer 3 internal zone from which traffic originates =============================== ====================================== .. note:: If the tunnel interface is in a zone different from the one where the traffic will originate, a policy needs to be created to allow the traffic to flow from the source zone to the zone containing the tunnel interface. Setting up IKE Crypto Profile and IKE Gateways ---------------------------------------------- 1. In the Palo Alto VM-Series UI, navigate to to Network > Network Profiles > IKE Crypto, click **Add** and define the IKE Crypto profile (IKEv1 Phase-1) parameters. |image1| #. If using PSK (Pre-shared Key) for authentication with Site2Cloud: a. Navigate to Network > Network Profiles > IKE Gateways to configure the IKE Phase-1 Gateway. These parameters should match the Site2Cloud configuration downloaded under "Setting up Site2Cloud Connection". |image2| =============================== ========================================= **Field** **Value** =============================== ========================================= Interface Palo Alto Networks WAN port Peer IP Address Aviatrix Gateway public IP Pre-shared Key Key from Site2Cloud configuration downloaded at Step 4 Peer Identification Peer public IP Address (if the controller version is below 5.0, it should be peer private IP) =============================== ========================================= According to the Palo Alto Networks official documents, it is not necessary to add Peer Identification. However, Aviatrix recommends adding it, to make sure the tunnel is working. In the event that IPsec tunnel is up but traffic is not passing between the Cloud and on-prem, you may want to enable NAT-T in the Palo Alto Networks Firewall. |image3| =============================== ========================================= **Field** **Value** =============================== ========================================= IKE Crypto Profile Select the profile created at Step 5.2 =============================== ========================================= b. Under Network > Network Profiles > IPsec Crypto, click **Add** to create a new profile. Define the IPsec crypto profile (IKEv1 Phase-2). These parameters should match on the Site2Cloud configuration downloaded at Step 4. |image4| c. Under Network > IPsec Tunnels, click **Add** to create a new IPsec Tunnel. At the **General** window: |image5| =============================== ========================================= **Field** **Value** =============================== ========================================= Tunnel Interface Tunnel interface created at Step 5.1 IKE Gateway IKE gateway created at Step 5.3 IPsec Crypto Profile IPsec crypto profile created at Step 5.4 =============================== ========================================= d. At **Proxy IDs** window: |image6| =============================== ================================================================= **Field** **Value** =============================== ================================================================= Local VPC2 private subnet CIDR Remote VPC1 private subnet CIDR Protocol Any =============================== ================================================================= e. Under Network > Virtual Routers, click on the virtual router profile, then click Static Routes > default, add a new route destinating to VPC1 private subnet. |image7| =============================== ================================================================= **Field** **Value** =============================== ================================================================= Destination VPC1 private subnet CIDR Interface Tunnel interface created at Step 5.1 =============================== ================================================================= f. Commit the configuration. And, you will see the IPsec tunnel status become green. |image10| 3. If using certificate-based authentication with Site2Cloud: a. Go to Network > Network Profiles > IKE Gateways. These parameters should match the Site2Cloud configuration downloaded at Step 5 under "Setting up Site2Cloud Connection". b. In the IKE Gateway dialog enter the following: +----------------------+-------------------------------------------------------+ | **Field** | **Value** | +----------------------+-------------------------------------------------------+ | Name | A name that makes sense to you | +----------------------+-------------------------------------------------------+ | Version | IKEv2 only mode | +----------------------+-------------------------------------------------------+ | Interface | ethernet 1/1 | +----------------------+-------------------------------------------------------+ | Local IP Address | IP address of on-prem | +----------------------+-------------------------------------------------------+ | Peer IP Address Type | IP | +----------------------+-------------------------------------------------------+ | Peer Address | IP address of cloud gateway | +----------------------+-------------------------------------------------------+ | Authentication | Certificate | +----------------------+-------------------------------------------------------+ | Local Certificate | the device certificate you created earlier | +----------------------+-------------------------------------------------------+ | Local Identification | FQDN (hostname) such as pan-device.com | +----------------------+-------------------------------------------------------+ | Peer Identification | FQDN (hostname) such as gw-spoke.aviatrix.network.com | +----------------------+-------------------------------------------------------+ | Peer ID Check | Exact | +----------------------+-------------------------------------------------------+ | Certificate Profile | select the certificate profile you created in the | | | previous section | +----------------------+-------------------------------------------------------+ c. Click OK. d. Navigate to Device > Certificate Management > Device Certificates > PAN-CA and export this certificate as a PEM file. e. You must now import this certificate in on the CA Certificate page in the Aviatrix Controller, to use when setting up the Site2Cloud connection between the Aviatrix Controller and the Palo Alto VM-Series firewall. Finishing the Configuration --------------------------- 1. In the AWS portal, configure the VPC Route Table associated with the private subnet of VPC2. Add a route that has a destination of the VPC1 private subnet with the Palo Alto Networks VM LAN port as the gateway. #. Send traffic between VPC1's and VPC2's private subnets. In the Aviatrix Controller, go to the Site2Cloud page to verify the Site2Cloud connection status. |image8| To troubleshoot, navigate to Site2Cloud > Diagnostics and select commands from **Action** drop down list. |image9| .. |image0| image:: s2c_gw_pan_media/Create_Tunnel_Interface.PNG :width: 5.55625in :height: 3.26548in .. |image1| image:: s2c_gw_pan_media/IKE_Crypto_Profile.PNG :width: 5.55625in :height: 3.26548in .. |image2| image:: s2c_gw_pan_media/ike-gw-1.png :width: 5.55625in :height: 3.26548in .. |image3| image:: s2c_gw_pan_media/ike-gw-2.png :width: 5.55625in :height: 3.26548in .. |image4| image:: s2c_gw_pan_media/IPSec_Crypto_Profile.PNG :width: 5.55625in :height: 3.26548in .. |image5| image:: s2c_gw_pan_media/IPSec_Tunnel_1.PNG :width: 5.55625in :height: 3.26548in .. |image6| image:: s2c_gw_pan_media/IPSec_Tunnel_2.PNG :width: 5.55625in :height: 3.26548in .. |image7| image:: s2c_gw_pan_media/Static_Route.PNG :width: 5.00000in :height: 3.26548in .. |image8| image:: s2c_gw_pan_media/Verify_S2C.PNG :width: 5.55625in :height: 2.96548in .. |image9| image:: s2c_gw_pan_media/Troubleshoot_S2C.PNG :width: 7.00000 in :height: 4.50000 in .. |image10| image:: s2c_gw_pan_media/IPSecTunnelStatus.png :width: 7.00000 in :height: 0.60000 in .. |image11| image:: s2c_gw_pan_media/generate-cert.png .. disqus:: <file_sep> =========================================================================================== AWS Network Limits and Limitations =========================================================================================== It is good to know about the AWS network limits both for planning and troubleshooting: you can build your architecture to allow you to overcome these limits and it saves you time of troubleshooting when there is a failure or downtime in your network. For example, an AWS VGW carries a hard limit of 100 BGP routes in total. When the BGP prefixes exceed 100, VGW randomly resets the BGP session, leading to unpredictable potential network downtime. AWS publishes VPC limits at `this link. <https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html>`_ In addition to limits, there are limitations in functionality. Below is a list of commonly asked limits and limitations by network engineers. ======================================== =============== ===================== Functions Limits Comments ======================================== =============== ===================== VPC Peering Limit per VPC 125 default limit is 50. Constrained also by route limit of 100 VPC Route entries in a route table 100 default is 50. Performance impact on 100 routes. BGP prefix total on VGW 100 exceeding the limit results in random BGP resets VGW instance size scaling reset BGP trigger a BGP downtime DNAT function in VGW not available SNAT function in VGW not available NAT Gateway policies not available VPN connections per VPC 10 VPN traffic initiation from on-prem traffic must be initiated from on-prem to establish a VPN tunnel with VGW VIF per Direct Connect 50 Inter region peering MTU size 1500 bytes unlike intra region peering, there is no jumbo frame support, therefore inter region performance is maxed out at 5Gbps. Outgoing SMTP traffic on port 25 throttled you can send a request to lift the throttle. ======================================== =============== ===================== .. |survey| image:: opstools_survey_media/survey.png :scale: 30% .. disqus::
d2ef81b9e505305a3851b7932b7f1f48f6834a49
[ "reStructuredText", "JavaScript", "Markdown", "Text", "Shell" ]
333
reStructuredText
AviatrixSystems/Docs
1cf6e64dac41e3286c312cd8a66c6ca3101c05c1
54993081dabd25391c8272254f984681c1af7285
refs/heads/master
<repo_name>kyam3235/OpenGLTraining<file_sep>/OpenGLTraining/OpenGLTraining.cpp // OpenGLTraining.cpp : アプリケーションのエントリ ポイントを定義します。 // //OpenGLを使ってグラフィック処理を行ってみるためのアプリ //参考 //THe Program Ported to Windows //https://msdn.microsoft.com/ja-jp/library/windows/desktop/dd369065%28v=vs.85%29.aspx #include "stdafx.h" #include "OpenGLTraining.h" #include <gl\GL.h> #include <gl\GLU.h> //#include <GL/glut.h> HDC ghDC; HGLRC ghRC; #define SWAPBUFFERS SwapBuffers(ghDC) #define BLACK_INDEX 0 #define RED_INDEX 13 #define GREEN_INDEX 14 #define BLUE_INDEX 16 #define WIDTH 300 #define HEIGHT 200 GLfloat latitude, longitude, latinc, longinc; GLdouble radius; #define GLOBE 1 #define CYLINDER 2 #define CONE 3 //プロトタイプ宣言 GLvoid Resize(GLsizei, GLsizei); GLvoid InitializeGL(GLsizei, GLsizei); GLvoid DrawScene(GLvoid); BOOL BSetupPixelFormat(HDC); void PolarView(GLdouble, GLdouble, GLdouble, GLdouble); #define MAX_LOADSTRING 100 // グローバル変数: HINSTANCE hInst; // 現在のインターフェイス TCHAR szTitle[MAX_LOADSTRING]; // タイトル バーのテキスト TCHAR szWindowClass[MAX_LOADSTRING]; // メイン ウィンドウ クラス名 // このコード モジュールに含まれる関数の宣言を転送します: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: ここにコードを挿入してください。 MSG msg; HACCEL hAccelTable; // グローバル文字列を初期化しています。 LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_OPENGLTRAINING, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // アプリケーションの初期化を実行します: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_OPENGLTRAINING)); // メイン メッセージ ループ: while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int) msg.wParam; } // // 関数: MyRegisterClass() // // 目的: ウィンドウ クラスを登録します。 // ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_OPENGLTRAINING)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = MAKEINTRESOURCE(IDC_OPENGLTRAINING); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } // // 関数: InitInstance(HINSTANCE, int) // // 目的: インスタンス ハンドルを保存して、メイン ウィンドウを作成します。 // // コメント: // // この関数で、グローバル変数でインスタンス ハンドルを保存し、 // メイン プログラム ウィンドウを作成および表示します。 // BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd; hInst = hInstance; // グローバル変数にインスタンス処理を格納します。 hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } // // 関数: WndProc(HWND, UINT, WPARAM, LPARAM) // // 目的: メイン ウィンドウのメッセージを処理します。 // // WM_COMMAND - アプリケーション メニューの処理 // WM_PAINT - メイン ウィンドウの描画 // WM_DESTROY - 中止メッセージを表示して戻る // // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; RECT rect; switch (message) { case WM_CREATE: ghDC = GetDC(hWnd); if (!BSetupPixelFormat(ghDC)) PostQuitMessage(0); ghRC = wglCreateContext(ghDC); GetClientRect(hWnd, &rect); InitializeGL(rect.right, rect.bottom); break; case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // 選択されたメニューの解析: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); // TODO: 描画コードをここに追加してください... EndPaint(hWnd, &ps); break; case WM_SIZE: GetClientRect(hWnd, &rect); Resize(rect.right, rect.bottom); break; case WM_CLOSE: if (ghRC) wglDeleteContext(ghRC); if (ghDC) ReleaseDC(hWnd, ghDC); ghRC = 0; ghDC = 0; DestroyWindow(hWnd); break; case WM_DESTROY: if (ghRC) wglDeleteContext(ghRC); if (ghDC) ReleaseDC(hWnd, ghDC); PostQuitMessage(0); break; case WM_KEYDOWN: switch (wParam) { case VK_LEFT: longinc += 0.5f; break; case VK_RIGHT: longinc -= 0.5f; break; case VK_UP: longinc += 0.5f; break; case VK_DOWN: longinc -= 0.5f; break; default: break; } default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // バージョン情報ボックスのメッセージ ハンドラーです。 INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; } BOOL BSetupPixelFormat(HDC hdc) { PIXELFORMATDESCRIPTOR pfd, *ppfd; int pixelformat; ppfd = &pfd; ppfd->nSize = sizeof(PIXELFORMATDESCRIPTOR); ppfd->nVersion = 1; ppfd->dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; ppfd->dwLayerMask = PFD_MAIN_PLANE; ppfd->iPixelType = PFD_TYPE_COLORINDEX; ppfd->cColorBits = 8; ppfd->cAccumBits = 0; ppfd->cStencilBits = 0; pixelformat = ChoosePixelFormat(hdc, ppfd); if ((pixelformat = ChoosePixelFormat(hdc, ppfd)) == 0) { //MessageBox(NULL, "ChoosePixelFormat failed", "Error", MB_OK); return FALSE; } if (SetPixelFormat(hdc, pixelformat, ppfd) == FALSE) { //MessageBox(NULL, "SetPixelFormat failed", "Error", MB_OK); return FALSE; } return TRUE; } //OpenGL code GLvoid Resize(GLsizei width, GLsizei height) { GLfloat aspect; glViewport(0, 0, width, height); aspect = (GLfloat)width / height; glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45.0, aspect, 3.0, 7.0); glMatrixMode(GL_MODELVIEW); } GLvoid CreateObjects() { GLUquadricObj *quadObj; glNewList(GLOBE, GL_COMPILE); quadObj = gluNewQuadric(); gluQuadricDrawStyle(quadObj, GLU_LINE); gluSphere(quadObj, 1.5, 16, 16); glEndList(); glNewList(CONE, GL_COMPILE); quadObj = gluNewQuadric(); gluQuadricDrawStyle(quadObj, GLU_FILL); gluQuadricNormals(quadObj, GLU_SMOOTH); gluCylinder(quadObj, 0.3, 0.0, 0.6, 15, 10); glEndList(); glNewList(CYLINDER, GL_COMPILE); glPushMatrix(); glRotatef((GLfloat)90.0, (GLfloat)1.0, (GLfloat)0.0, (GLfloat)0.0); glTranslatef((GLfloat)0.0, (GLfloat)0.0, (GLfloat)-1.0); quadObj = gluNewQuadric(); gluQuadricDrawStyle(quadObj, GLU_FILL); gluQuadricNormals(quadObj, GLU_SMOOTH); gluCylinder(quadObj, 0.3, 0.3, 0.6, 12, 2); glPopMatrix(); glEndList(); } GLvoid InitializeGL(GLsizei width, GLsizei height) { GLfloat maxObjectSize, aspect; GLdouble nearPlane, farPlane; glClearIndex((GLfloat)BLACK_INDEX); glClearDepth(1.0); glEnable(GL_DEPTH_TEST); glMatrixMode(GL_PROJECTION); aspect = (GLfloat)width / height; gluPerspective(45.0, aspect, 3.0, 7.0); glMatrixMode(GL_MODELVIEW); nearPlane = 3.0; farPlane = 7.0; maxObjectSize = 3.0f; radius = nearPlane + maxObjectSize / 2.0; latitude = 0.0f; longitude = 0.0f; latinc = 6.0f; longinc = 2.5f; CreateObjects(); } void PolarView(GLdouble radius, GLdouble twist, GLdouble latitude, GLdouble longitude) { glTranslated(0.0, 0.0, -radius); glRotated(-twist, 0.0, 0.0, 1.0); glRotated(-latitude, 1.0, 0.0, 0.0); glRotated(longitude, 0.0, 0.0, 1.0); } GLvoid DrawScene(GLvoid) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glPushMatrix(); latitude += latinc; longitude += longinc; PolarView(radius, 0, latitude, longitude); glIndexi(RED_INDEX); glCallList(CONE); glIndexi(BLUE_INDEX); glCallList(GLOBE); glIndexi(GREEN_INDEX); glPushMatrix(); glTranslatef(0.8f, -0.65f, 0.0f); glCallList(CYLINDER); glPopMatrix(); glPopMatrix(); SWAPBUFFERS; } <file_sep>/DrawingCurveSample/Main.cpp /* * Example of a Windows OpenGL program. * The OpenGL code is the same as that used in * the X Window System sample */ #include <windows.h> //#include <GL/gl.h> //#include <GL/glu.h> #include <GL/glut.h> /* Windows globals, defines, and prototypes */ CHAR szAppName[] = "Win OpenGL"; HWND ghWnd; HDC ghDC; HGLRC ghRC; #define SWAPBUFFERS SwapBuffers(ghDC) #define BLACK_INDEX 0 #define RED_INDEX 13 #define GREEN_INDEX 14 #define BLUE_INDEX 16 #define WIDTH 300 #define HEIGHT 200 LONG WINAPI MainWndProc(HWND, UINT, WPARAM, LPARAM); BOOL bSetupPixelFormat(HDC); /* OpenGL globals, defines, and prototypes */ GLfloat latitude, longitude, latinc, longinc; GLdouble radius; #define GLOBE 1 #define CYLINDER 2 #define CONE 3 GLvoid resize(GLsizei, GLsizei); GLvoid initializeGL(GLsizei, GLsizei); GLvoid drawScene(GLvoid); void polarView(GLdouble, GLdouble, GLdouble, GLdouble); //static const int order = 3; //static const int n = 4; //static const int knotn = 4 + 3; //n + order //static const int knotn = 4 + 2; //n + order //GLfloat ctrlPoint[4][4] = { // {-0.5, 0., 0., 1.}, // {-0.25, 0.5, 0., 1.}, // {0.25, -0.5, 0., 1.}, // {0.5, 0., 0., 1.} //}; static const int order = 2; //線の次数(2〜) //static const int n = 5; //線を描画する時のプロット数 //static const int knotn = 5 + 2; //n + order → knotベクトルの要素数 static const int stride = 4; //GLfloat knot[7] = { 0., 1., 2., 3., 4., 5., 6. }; //次数が高いほど曲線の表現力が高い //GLfloat ctrlPoint[5][4] = { // { -1.0, 0., 0., 1. }, // { -0.25, 0.5, 0., 1. }, // { 0.25, -0.5, 0., 1. }, // { 0.5, 0., 0., 1. }, // { 1.0, 0.3, 0., 1. } //}; static const int n = 50000; static int knotn = 50000 + 2; GLfloat knot[50002]; GLfloat ctrlPoint[50002][4]; static GLUnurbsObj *nurbs; void nurbsError(GLenum); int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { MSG msg; WNDCLASS wndclass; /* Register the frame class */ wndclass.style = 0; wndclass.lpfnWndProc = (WNDPROC)MainWndProc; wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.hInstance = hInstance; wndclass.hIcon = LoadIcon(hInstance, szAppName); wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); wndclass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wndclass.lpszMenuName = szAppName; wndclass.lpszClassName = szAppName; if (!RegisterClass(&wndclass)) return FALSE; /* Create the frame */ ghWnd = CreateWindow(szAppName, "Generic OpenGL Sample", WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, CW_USEDEFAULT, CW_USEDEFAULT, WIDTH, HEIGHT, NULL, NULL, hInstance, NULL); /* make sure window was created */ if (!ghWnd) return FALSE; /* show and update main window */ ShowWindow(ghWnd, nCmdShow); UpdateWindow(ghWnd); /* animation loop */ while (1) { /* * Process all pending messages */ while (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE) == TRUE) { if (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } else { return TRUE; } } drawScene(); } } /* main window procedure */ LONG WINAPI MainWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { LONG lRet = 1; PAINTSTRUCT ps; RECT rect; switch (uMsg) { case WM_CREATE: ghDC = GetDC(hWnd); if (!bSetupPixelFormat(ghDC)) PostQuitMessage(0); ghRC = wglCreateContext(ghDC); wglMakeCurrent(ghDC, ghRC); GetClientRect(hWnd, &rect); initializeGL(rect.right, rect.bottom); break; case WM_PAINT: BeginPaint(hWnd, &ps); EndPaint(hWnd, &ps); break; case WM_SIZE: GetClientRect(hWnd, &rect); resize(rect.right, rect.bottom); break; case WM_CLOSE: if (ghRC) wglDeleteContext(ghRC); if (ghDC) ReleaseDC(hWnd, ghDC); ghRC = 0; ghDC = 0; DestroyWindow(hWnd); break; case WM_DESTROY: if (ghRC) wglDeleteContext(ghRC); if (ghDC) ReleaseDC(hWnd, ghDC); PostQuitMessage(0); break; case WM_KEYDOWN: switch (wParam) { case VK_LEFT: longinc += 0.5F; break; case VK_RIGHT: longinc -= 0.5F; break; case VK_UP: latinc += 0.5F; break; case VK_DOWN: latinc -= 0.5F; break; } default: lRet = DefWindowProc(hWnd, uMsg, wParam, lParam); break; } return lRet; } BOOL bSetupPixelFormat(HDC hdc) { PIXELFORMATDESCRIPTOR pfd, *ppfd; int pixelformat; ppfd = &pfd; ppfd->nSize = sizeof(PIXELFORMATDESCRIPTOR); ppfd->nVersion = 1; ppfd->dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; ppfd->dwLayerMask = PFD_MAIN_PLANE; ppfd->iPixelType = PFD_TYPE_COLORINDEX; ppfd->cColorBits = 8; ppfd->cDepthBits = 16; ppfd->cAccumBits = 0; ppfd->cStencilBits = 0; pixelformat = ChoosePixelFormat(hdc, ppfd); if ((pixelformat = ChoosePixelFormat(hdc, ppfd)) == 0) { MessageBox(NULL, "ChoosePixelFormat failed", "Error", MB_OK); return FALSE; } if (SetPixelFormat(hdc, pixelformat, ppfd) == FALSE) { MessageBox(NULL, "SetPixelFormat failed", "Error", MB_OK); return FALSE; } return TRUE; } /* OpenGL code */ GLvoid resize(GLsizei width, GLsizei height) { GLfloat aspect; glViewport(0, 0, width, height); aspect = (GLfloat)width / height; glMatrixMode(GL_PROJECTION); glLoadIdentity(); //gluPerspective(45.0, aspect, 3.0, 7.0); gluPerspective(0.0, aspect, 3.0, 7.0); glMatrixMode(GL_MODELVIEW); } GLvoid createObjects() { GLUquadricObj *quadObj; nurbs = gluNewNurbsRenderer(); gluNurbsProperty(nurbs, GLU_SAMPLING_METHOD, GLU_PATH_LENGTH); gluNurbsProperty(nurbs, GLU_SAMPLING_TOLERANCE, 10.); gluNurbsProperty(nurbs, GLU_DISPLAY_MODE, GLU_FILL); gluNurbsProperty(nurbs, GLU_AUTO_LOAD_MATRIX, GL_TRUE); //gluNurbsProperty(nurbs, GLU_ERROR, (void *)nurbsError); for (int i = 0; i < 50002; i++){ knot[i] = i; } for (int i = 0; i < 50002; i++){ ctrlPoint[i][0] = (i - 25001.0) / 25001.0; ctrlPoint[i][1] = (rand() - (RAND_MAX / 2.)) / (RAND_MAX / 2.); ctrlPoint[i][2] = 0.; ctrlPoint[i][3] = 1.; } } GLvoid initializeGL(GLsizei width, GLsizei height) { GLfloat maxObjectSize, aspect; GLdouble near_plane, far_plane; glClearIndex((GLfloat)BLACK_INDEX); glClearDepth(1.0); glEnable(GL_DEPTH_TEST); glMatrixMode(GL_PROJECTION); aspect = (GLfloat)width / height; //gluPerspective(45.0, aspect, 3.0, 7.0); gluPerspective(0.0, aspect, 3.0, 7.0); glMatrixMode(GL_MODELVIEW); createObjects(); } GLvoid drawScene(GLvoid) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glPushMatrix(); gluBeginCurve(nurbs); gluNurbsCurve(nurbs, knotn, knot, stride, &ctrlPoint[0][0], order, GL_MAP1_VERTEX_4); gluEndCurve(nurbs); glPopMatrix(); SWAPBUFFERS; } void nurbsError(GLenum error) { exit(0); }
6ae9a1f3ae3073f04ccec0d13b7be09e5ecb85ed
[ "C++" ]
2
C++
kyam3235/OpenGLTraining
4a425253f6c9c47c04f7418ad17186b44518e274
2a2225d2657bde9a322e0babf0f81226f37f5ad2
refs/heads/master
<repo_name>JimzyLui/pre-immersive-challenges<file_sep>/insert-dashes/insertDashes.js module.exports = function insertDashes(num) { // write your code in here var str = num.toString(); var result = str[0]; var isEven = x => { return x % 2 == 0; }; for (var i = 0; i < str.length - 1; i++) { if (isEven(str[i]) && isEven(str[i + 1])) { result += "-" + str[i + 1]; } else { result += str[i + 1]; } } return result; }; <file_sep>/find-the-longest-word/findTheLongestWord.js module.exports = function findTheLongestWord(sen) { // write your code in here /* Plan: use .reduce comparing the string length */ var reducer = (longest, word) => { return longest.length > word.length ? longest : word; }; return sen.reduce(reducer); }; <file_sep>/move-the-zeros/moveTheZeros.js module.exports = function moveTheZeros(arrNum, isRight) { // write your code here /* Plan: count the zeros while pushing the number into an empty array then add the zeros into the new array depending on location */ "use strict"; var arr = []; var zeroCtr = 0; for (var i = 0; i < arrNum.length; i++) { if (arrNum[i] === 0) { zeroCtr++; } else { arr.push(arrNum[i]); } } // console.log("zeroCtr: " + zeroCtr); var arrZ = new Array(zeroCtr).fill(0); // console.log("arrZ: " + arrZ); if (isRight) { return arr.concat(arrZ); } else { return arrZ.concat(arr); } }; <file_sep>/check-ascending-order/checkAscOrder.js module.exports = function checkAscOrder(numArray) { // write your code in here for (let i = 0; i <= numArray.length - 2; i++) { if (numArray[i] > numArray[i + 1]) { return false; } } return true; }; <file_sep>/acceptable-sequence/acceptableSequence.js module.exports = function acceptableSequence(str) { // write your code here var regex = /[a-zA-Z]/; if (regex.test(str[0]) || regex.test(str[str.length - 1])) { return false; } for (let x = 0; x <= str.length - 3; x++) { const sample = str.substring(x, x + 3); if (regex.test(sample[1])) { // middle char is alpha regex = /\+[a-zA-Z]\+/; if (!regex.test(sample)) { return false; } } } return true; }; <file_sep>/reverse-message/reverseMessage.js module.exports = function reverseMessage(str) { // write your code in here /* Plan: split into array map lowercase, backwards, cap join with spaces */ var result = str .split(" ") .map(x => x.toLowerCase()) .reverse() .map(x => x .split("") .reverse() .join("") ) .map(x => x.charAt(0).toUpperCase() + x.slice(1)) .join(" "); return result; }; <file_sep>/double-str-chars/doubleStrChars.js module.exports = function doubleStrChars(str) { // write your code in here if (typeof str !== "string") { return "not a string!"; } /* Plan: str --> array apply double to each arry join the array */ return str .split("") .map(x => x.repeat(2)) .join(""); }; <file_sep>/even-ladder-pattern/evenLadderPattern.js module.exports = function evenLadderPattern(num) { // write your code in here if (typeof num !== "number") { return ""; } if (num < 2) { return ""; } var str = ""; for (var x = 2; x <= num; x += 2) { str += x.toString().repeat(x) + "\n"; } return str.trim(); }; <file_sep>/how-many-litres/howManyLitres.js module.exports = function howManyLitres(hours) { // write your code in here return Math.floor(hours * 0.5); }; <file_sep>/descending-order/descendingOrder.js module.exports = function descendingOrder(number) { // write code in here // console.log("type: " + typeof number); if (typeof number !== "number") { return "not a number!"; } // cast as string... toString() // conv to array... split('') // sort backward... sort(fx) //w/ fx b-a // join into string... join('') // convert back to int... parseInt() var arr = number.toString().split(""); var sortRev = (a, b) => { return b - a; }; var arrR = arr.sort(sortRev); return parseInt(arrR.join("")); }; <file_sep>/cookie-problem/cookieProblem.js module.exports = function cookieProblem(array) { // write your code in here let iMax = Math.max(...array); // console.log("iMax: " + iMax); let iCookieCount = 0; for (let i = 0; i < array.length; i++) { iCookieCount += iMax - array[i]; // console.log("iCookieCount: " + iCookieCount); } return iCookieCount; };
f099908dd9c6122ee23039233ad110554b316bb4
[ "JavaScript" ]
11
JavaScript
JimzyLui/pre-immersive-challenges
f33dc7cdb28400e9408c824e2241cc1b7dc9e1d0
8eeeb9aa690ff9d9a4200aeea47a48aff0d6e828
refs/heads/master
<file_sep>from django.db import models # Create your models here. class Author(models.Model): full_name = models.CharField(max_length=160, verbose_name='Имя') birth_year = models.SmallIntegerField(verbose_name='Дата рождения') country = models.CharField(max_length=2, verbose_name='Страна рождения') def __str__(self): return self.full_name class Publisher(models.Model): name = models.CharField(max_length=160, verbose_name='Название') def __str__(self): return self.name class Book(models.Model): ISBN = models.CharField(max_length=13) title = models.CharField(max_length=160, verbose_name='Заголовок') description = models.TextField(verbose_name='Описание') year_release = models.SmallIntegerField(verbose_name='Дата издания') author = models.ForeignKey(Author, on_delete=models.CASCADE, verbose_name='Автор') price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='Цена') copy_count = models.SmallIntegerField(default=1) publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE, verbose_name='Издательство', null=True, blank=True, related_name='books') friend = models.ForeignKey('Friend', on_delete=models.CASCADE, related_name='books', verbose_name='Другу отдана', null=True, blank=True) image = models.ImageField(upload_to='book_photos/', blank=True, null=True, verbose_name='Фото') @property def get_image_url(self): if self.image and hasattr(self.image, 'url'): return self.image.url else: return "/media/book_photos/book_default.jpg" def __str__(self): return self.title class Friend(models.Model): full_name = models.CharField(max_length=200, verbose_name='Имя') phone = models.CharField(max_length=20, blank=True, verbose_name='Номер телефона') def __str__(self): return self.full_name <file_sep>Проект сайта домашней библиотеки Есть возможность добавление автора и книги Можно редактировать и создавать издательства Запуск сайта командой - python manage.py runserver Несколько примеров адресов: http://127.0.0.1:8000/friends - информация о друзьях http://127.0.0.1:8000/author/create - добавление автора http://127.0.0.1:8000/publishers - информация об издательствах<file_sep># Generated by Django 2.2.6 on 2021-02-17 18:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('p_library', '0007_auto_20210217_2241'), ] operations = [ migrations.AlterField( model_name='book', name='image', field=models.ImageField(blank=True, null=True, upload_to='../media/book_photos/', verbose_name='Фото'), ), ] <file_sep>from django.contrib import admin from django.urls import path from .views import * urlpatterns = [ path('author/create', AuthorEdit.as_view(), name='author_create'), path('authors', AuthorList.as_view(), name='author_list'), path('author/create_many', author_create_many, name='author_create_many'), path('author_book/create_many', books_authors_create_many, name='author_book_create_many'), path('friends', FriendList.as_view(), name='friend_list'), path('friend/create', FriendEdit.as_view(), name='friend_create'), path('book/create', BookEdit.as_view(), name='book_create'), path('books', BookList.as_view(), name='book_list') ]<file_sep># Generated by Django 2.2.6 on 2021-02-16 18:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('p_library', '0005_auto_20210216_2352'), ] operations = [ migrations.AlterField( model_name='book', name='image', field=models.ImageField(blank=True, default='book_photos/book_default.jpg', null=True, upload_to='book_photos/%Y/%m/%d', verbose_name='Фото'), ), ] <file_sep># Generated by Django 2.2.6 on 2021-02-10 20:05 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('p_library', '0001_initial'), ] operations = [ migrations.CreateModel( name='Friend', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('full_name', models.CharField(max_length=160, verbose_name='Имя')), ('phone', models.CharField(blank=True, max_length=20, verbose_name='Номер телефона')), ], ), migrations.AlterField( model_name='author', name='birth_year', field=models.SmallIntegerField(verbose_name='Дата рождения'), ), migrations.AlterField( model_name='author', name='country', field=models.CharField(max_length=2, verbose_name='Страна рождения'), ), migrations.AlterField( model_name='author', name='full_name', field=models.TextField(verbose_name='Имя'), ), migrations.AlterField( model_name='book', name='author', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='p_library.Author', verbose_name='Автор'), ), migrations.AlterField( model_name='book', name='description', field=models.TextField(verbose_name='Описание'), ), migrations.AlterField( model_name='book', name='price', field=models.DecimalField(blank=True, decimal_places=2, max_digits=10, null=True, verbose_name='Цена'), ), migrations.AlterField( model_name='book', name='publisher', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='books', to='p_library.Publisher', verbose_name='Издательство'), ), migrations.AlterField( model_name='book', name='title', field=models.TextField(verbose_name='Заголовок'), ), migrations.AlterField( model_name='book', name='year_release', field=models.SmallIntegerField(verbose_name='Дата издания'), ), migrations.AlterField( model_name='publisher', name='name', field=models.CharField(max_length=160, verbose_name='Название'), ), migrations.AddField( model_name='book', name='friend', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='books', to='p_library.Friend', verbose_name='Друг'), ), ] <file_sep># Generated by Django 2.2.6 on 2021-02-16 18:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('p_library', '0003_auto_20210211_2345'), ] operations = [ migrations.AddField( model_name='book', name='photo', field=models.ImageField(blank=True, null=True, upload_to='book_photos'), ), migrations.AlterField( model_name='author', name='full_name', field=models.CharField(max_length=160, verbose_name='Имя'), ), migrations.AlterField( model_name='book', name='title', field=models.CharField(max_length=160, verbose_name='Заголовок'), ), migrations.AlterField( model_name='friend', name='full_name', field=models.CharField(max_length=200, verbose_name='Имя'), ), ]
ee119ecf22862bbbaeab1d796af3a1842765dea6
[ "Markdown", "Python" ]
7
Python
Joly-Roman/D6_HM-RRR
46f992f387d2e86d072df87e988abc6c66bf54b5
35cce9cb2eb43b91c55d4c5de5b2d0155166b5f3
refs/heads/main
<repo_name>Eteye77/HR_database_analysis-using-SQL<file_sep>/sorting_and_grouping.sql # Sorting-and-Grouping CREATE TABLE EMPLOYEES ( EMP_ID CHAR(9) NOT NULL, F_NAME VARCHAR(15) NOT NULL, L_NAME VARCHAR(15) NOT NULL, SSN CHAR(9), B_DATE DATE, SEX CHAR, ADDRESS VARCHAR(30), JOB_ID CHAR(9), SALARY DECIMAL(10,2), MANAGER_ID CHAR(9), DEP_ID CHAR(9) NOT NULL, PRIMARY KEY (EMP_ID)); CREATE TABLE JOB_HISTORY ( EMPL_ID CHAR(9) NOT NULL, START_DATE DATE, JOBS_ID CHAR(9) NOT NULL, DEPT_ID CHAR(9), PRIMARY KEY (EMPL_ID,JOBS_ID)); CREATE TABLE JOBS ( JOB_IDENT CHAR(9) NOT NULL, JOB_TITLE VARCHAR(15) , MIN_SALARY DECIMAL(10,2), MAX_SALARY DECIMAL(10,2), PRIMARY KEY (JOB_IDENT)); CREATE TABLE DEPARTMENTS ( DEPT_ID_DEP CHAR(9) NOT NULL, DEP_NAME VARCHAR(15) , MANAGER_ID CHAR(9), LOC_ID CHAR(9), PRIMARY KEY (DEPT_ID_DEP)); CREATE TABLE LOCATIONS ( LOCT_ID CHAR(9) NOT NULL, DEP_ID_LOC CHAR(9) NOT NULL, PRIMARY KEY (LOCT_ID,DEP_ID_LOC)); SELECT * FROM EMPLOYEES; SELECT * FROM JOB_HISTORY; SELECT * FROM JOBS; SELECT * FROM DEPARTMENTS; SELECT * FROM LOCATIONS; --- Query1 --- SELECT F_NAME, L_NAME from EMPLOYEES WHERE ADDRESS LIKE '%ELGIN,IL%'; --- Query2 --- SELECT F_NAME, L_NAME from EMPLOYEES WHERE B_DATE LIKE '%197%'; --- Query3 --- select * from EMPLOYEES where (SALARY BETWEEN 60000 and 70000) and DEP_ID = 5 ; --- Query4 --- SELECT * from EMPLOYEES ORDER BY DEP_ID; --- Query5 --- SELECT F_NAME, L_NAME, DEP_ID from EMPLOYEES ORDER BY DEP_ID DESC, L_NAME DESC; --- Query6 --- SELECT DEP_ID, COUNT(DEP_ID) AS COUNT FROM EMPLOYEES GROUP BY DEP_ID; --- Query7 --- SELECT DEP_ID, AVG(SALARY), COUNT(DEP_ID) AS COUNT FROM EMPLOYEES GROUP BY DEP_ID; --- Query8 --- SELECT DEP_ID, AVG(SALARY) AS 'AVG_SALARY', COUNT(DEP_ID) AS 'NUM_EMPLOYEES' FROM EMPLOYEES GROUP BY DEP_ID; --- Query9 --- SELECT DEP_ID, AVG(SALARY) AS 'AVG_SALARY', COUNT(DEP_ID) AS 'NUM_EMPLOYEES' FROM EMPLOYEES GROUP BY DEP_ID ORDER BY AVG_SALARY; --- Query10 --- SELECT DEP_ID, AVG(SALARY) AS 'AVG_SALARY', COUNT(DEP_ID) AS 'NUM_EMPLOYEES' FROM EMPLOYEES GROUP BY DEP_ID HAVING COUNT(DEP_ID) < 4; --- Query11 --- SELECT F_NAME, L_NAME, DEP_ID from EMPLOYEES ORDER BY DEP_ID DESC, L_NAME DESC; --- Query12 --- SELECT EMP_ID, SALARY, (SELECT AVG(SALARY) FROM EMPLOYEES) AS AVG_SALARY FROM EMPLOYEES; --- Query13 --- SELECT * FROM(SELECT EMP_ID, F_NAME, L_NAME, DEP_ID FROM EMPLOYEES) AS EMP4ALL; --- Query14 --- SELECT * FROM EMPLOYEES WHERE DEP_ID IN (SELECT DEPT_ID_DEP FROM DEPARTMENTS); --- Query15 --- select * from employees where DEP_ID IN ( select DEPT_ID_DEP from departments where LOC_ID = 'L0002'); --- Query16 --- select DEPT_ID_DEP, DEP_NAME from departments where DEPT_ID_DEP IN ( select DEP_ID from employees where SALARY > 70000 ); --- Query17 --- select D.DEP_NAME , E.F_NAME, E.L_NAME from EMPLOYEES as E, DEPARTMENTS as D where E.DEP_ID = D.DEPT_ID_DEP; --- Query18 --- select E.F_NAME,E.L_NAME, JH.START_DATE from EMPLOYEES as E INNER JOIN JOB_HISTORY as JH on E.EMP_ID=JH.EMPL_ID where E.DEP_ID ='5'; --- Query19 --- select E.F_NAME,E.L_NAME, JH.START_DATE, J.JOB_TITLE from EMPLOYEES as E INNER JOIN JOB_HISTORY as JH on E.EMP_ID=JH.EMPL_ID INNER JOIN JOBS as J on E.JOB_ID=J.JOB_IDENT where E.DEP_ID ='5'; --- Query 20 --- select E.EMP_ID,E.L_NAME,E.DEP_ID,D.DEP_NAME from EMPLOYEES AS E LEFT OUTER JOIN DEPARTMENTS AS D ON E.DEP_ID=D.DEPT_ID_DEP; --- Query 21 --- select E.EMP_ID,E.L_NAME,E.DEP_ID,D.DEP_NAME from EMPLOYEES AS E LEFT OUTER JOIN DEPARTMENTS AS D ON E.DEP_ID=D.DEPT_ID_DEP where YEAR(E.B_DATE) < 1980; --- alt Query 22 --- select E.EMP_ID,E.L_NAME,E.DEP_ID,D.DEP_NAME from EMPLOYEES AS E INNER JOIN DEPARTMENTS AS D ON E.DEP_ID=D.DEPT_ID_DEP where YEAR(E.B_DATE) < 1980; --- Query 23 --- select E.EMP_ID,E.L_NAME,E.DEP_ID,D.DEP_NAME from EMPLOYEES AS E LEFT OUTER JOIN DEPARTMENTS AS D ON E.DEP_ID=D.DEPT_ID_DEP AND YEAR(E.B_DATE) < 1980; --- Query 24 --- select E.F_NAME,E.L_NAME,D.DEP_NAME from EMPLOYEES AS E FULL OUTER JOIN DEPARTMENTS AS D ON E.DEP_ID=D.DEPT_ID_DEP; --- Query 25 --- select E.F_NAME,E.L_NAME,D.DEPT_ID_DEP, D.DEP_NAME from EMPLOYEES AS E FULL OUTER JOIN DEPARTMENTS AS D ON E.DEP_ID=D.DEPT_ID_DEP AND E.SEX = 'M'; --- alt Query 26 --- select E.F_NAME,E.L_NAME,D.DEPT_ID_DEP, D.DEP_NAME from EMPLOYEES AS E LEFT OUTER JOIN DEPARTMENTS AS D ON E.DEP_ID=D.DEPT_ID_DEP AND E.SEX = 'M';
1d668438e54512d85b21325fc9162f1ffd421500
[ "SQL" ]
1
SQL
Eteye77/HR_database_analysis-using-SQL
e044a2eaa5da45c9d5902d5b769528156021bb22
abc184f2f58454b1ad837bfc7397e4538eda49e7
refs/heads/master
<repo_name>serpent5/SO53654020<file_sep>/README.md # SO53654020 Sample repository for configuring ASP.NET Core to support Google's OAuth login process without using ASP.NET Core Identity, in response to a Stack Overflow question [here](https://stackoverflow.com/questions/53654020/how-to-implement-google-login-in-net-core-without-an-entityframework-provider). It consists of a Razor Page (`Index`) that requires authorisation in order to show the signed-in user's claims. The authentication process is handled in `AccountController`, a standard MVC controller implementation. The sample should run mostly as is, but requires setting the Google `ClientId`/`ClientSecret` pair in [`Startup.cs`](Startup.cs#L24). <file_sep>/Startup.cs using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using SO53654020.Infrastructure; namespace SO53654020 { public class Startup { public void ConfigureServices(IServiceCollection serviceCollection) { serviceCollection .AddAuthentication(o => { o.DefaultScheme = Constants.ApplicationScheme; o.DefaultSignInScheme = Constants.SignInScheme; }) .AddCookie(Constants.ApplicationScheme) .AddCookie(Constants.SignInScheme) .AddGoogle(o => { o.ClientId = "..."; o.ClientSecret = "..."; }); serviceCollection.AddMvc() .AddRazorPagesOptions(o => o.Conventions.AuthorizePage("/Index")); } public void Configure(IApplicationBuilder applicationBuilder) { applicationBuilder.UseDeveloperExceptionPage(); applicationBuilder.UseHttpsRedirection(); applicationBuilder.UseRouting(); applicationBuilder.UseAuthentication(); applicationBuilder.UseAuthorization(); applicationBuilder.UseEndpoints(endpointRouteBuilder => { endpointRouteBuilder.MapDefaultControllerRoute(); endpointRouteBuilder.MapRazorPages(); }); } } } <file_sep>/Infrastructure/Constants.cs namespace SO53654020.Infrastructure { internal static class Constants { public const string ApplicationScheme = "Application"; public const string SignInScheme = "External"; } } <file_sep>/Controllers/AccountController.cs using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Google; using Microsoft.AspNetCore.Mvc; using SO53654020.Infrastructure; namespace SO53654020.Controllers { public class AccountController : Controller { public IActionResult Login(string returnUrl) => new ChallengeResult( GoogleDefaults.AuthenticationScheme, new AuthenticationProperties { RedirectUri = Url.Action(nameof(LoginCallback), new { returnUrl }) }); public async Task<IActionResult> LoginCallback(string returnUrl) { var authenticateResult = await HttpContext.AuthenticateAsync(Constants.SignInScheme); if (!authenticateResult.Succeeded) return BadRequest(); var claimsIdentity = new ClaimsIdentity(Constants.ApplicationScheme); claimsIdentity.AddClaim(authenticateResult.Principal.FindFirst(ClaimTypes.Name)); claimsIdentity.AddClaim(authenticateResult.Principal.FindFirst(ClaimTypes.Email)); await HttpContext.SignInAsync( Constants.ApplicationScheme, new ClaimsPrincipal(claimsIdentity), new AuthenticationProperties { IsPersistent = true }); // IsPersistent will set a cookie that lasts for two weeks (by default). return LocalRedirect(returnUrl); } } }
1a81d68c5a05b062ae08745c8efbbf5bcc25a5bf
[ "Markdown", "C#" ]
4
Markdown
serpent5/SO53654020
bc8d5083b96c9d6f4c84ce34cabfb7471221e9d5
e6704f9149c7089977e8bff66d5174bfb9c1e529
refs/heads/master
<repo_name>RoterFuchs/photoweb<file_sep>/src/HTW/PhotoWebBundle/Component/Authentication/Handler/LoginFailureHandler.php <?php namespace HTW\PhotoWebBundle\Component\Authentication\Handler; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationFailureHandler; use Symfony\Component\Security\Http\HttpUtils; class LoginFailureHandler extends DefaultAuthenticationFailureHandler { public function onAuthenticationFailure(Request $request, AuthenticationException $exception) { if ($request->isXmlHttpRequest()) { $json = array( 'error' => true, 'message' => $exception->getMessage() ); return new Response(json_encode($json)); } return parent::onAuthenticationFailure($request, $exception); } }<file_sep>/src/HTW/PhotoWebBundle/Controller/StaticPageController.php <?php namespace HTW\PhotoWebBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Request; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Symfony\Component\Validator\Constraints as Assert; class StaticPageController extends Controller { /** * @Route("/privacy") * @Template("HTWPhotoWebBundle:StaticPage:privacy.html.twig") */ public function privacyAction() { return array(); } /** * @Route("/imprint") * @Template("HTWPhotoWebBundle:StaticPage:imprint.html.twig") */ public function imprintAction() { return array(); } /** * @Route("/contact") * @Template("HTWPhotoWebBundle:StaticPage:contact.html.twig") */ public function contactAction(Request $request) { $form = $this->createFormBuilder() ->add('name', 'text', array( 'label' => 'Ihr Name', 'constraints' => array( new Assert\NotBlank(), ) )) ->add('email', 'email', array( 'label' => 'Ihre E-Mail Adresse', 'constraints' => array( new Assert\NotBlank(), new Assert\Email(array( 'message' => 'Die Adresse "{{ value }}" ist keine valide E-Mail Adresse.', 'checkMX' => false, )) ) )) ->add('message', 'textarea', array( 'label' => 'Ihre Nachricht an uns', 'constraints' => array( new Assert\NotBlank() ) )) ->add('send', 'submit', array('label' => 'Nachricht abschicken')) ->getForm(); $form->handleRequest($request); if ($form->isValid()) { $data = $form->getData(); $message = \Swift_Message::newInstance() ->setSubject('Neue Nachricht von '. $data['name'] .' über Fotoweb!') ->setFrom(array('<EMAIL>' => 'FotoWeb')) ->setReplyTo(array($data['email'] => $data['name'])) ->setTo('<EMAIL>') ->setBody($data['message']); $this->get('mailer')->send($message); $this->get('session')->getFlashBag()->add( 'success', 'Vielen Dank, Ihre Nachricht wurde entgegen genommen.' ); return $this->redirect($this->generateUrl('htw_photoweb_staticpage_contact')); } return array('form' => $form->createView()); } } <file_sep>/src/HTW/PhotoWebBundle/Controller/PhotoController.php <?php namespace HTW\PhotoWebBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Request; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use HTW\PhotoWebBundle\Entity\Photo; class PhotoController extends Controller { /** * @Route("/upload") */ public function uploadAction(Request $request) { $user = $this->getUser()->getId(); $photo = new Photo($user); $form = $this->createFormBuilder($photo) ->add('name', 'text') ->add('description', null, array('label' => 'Beschreibung')) ->add('file', null, array('label' => 'Datei')) ->add('format', 'choice', array( 'choices' => array( 1 => 'Quadratisch', 2 => 'Hochformat', 3 => 'Querformat', 4 => 'Panorama' ) )) ->add('color', 'choice', array( 'choices' => array( '1' => 'Farbe', '2' => 'Schwarzweiß', ), 'label' => 'Farbe', )) ->add('width', 'text', array('label' => 'Breite in px', 'required' => false)) ->add('height', 'text', array('label' => 'Höhe in px', 'required' => false)) ->add('save', 'submit', array('attr'=> array('class'=>'test'), 'label' => 'Hinzufügen')) ->add('saveAndAdd', 'submit', array('label' => 'Hinzufügen und weiteres Foto anlegen')) ->getForm(); $form->handleRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($photo); $em->flush(); $this->get('session')->getFlashBag()->add('notice', 'Das Bild wurde erfolgreich hinzugefügt!'); // Stay on the upload page if second button is clicked if($form->get('saveAndAdd')->isClicked()) { return $this->redirect($this->generateUrl('htw_photoweb_photo_upload')); } return $this->redirect($this->generateUrl('htw_photoweb_myarea_index')); } return $this->render('HTWPhotoWebBundle:Photo:upload.html.twig', array('form' => $form->createView())); } /** * @Route("/export.xml") * @Method("GET") */ public function exportAction() { $userID = $this->getUser()->getId(); $repository = $this->getDoctrine() ->getRepository('HTWPhotoWebBundle:Photo'); $query = $repository->createQueryBuilder('p') ->where('p.user = :userID') ->setParameter('userID', $userID) ->getQuery(); $templating = $this->get('templating'); $content = $templating->render( 'HTWPhotoWebBundle:Photo:export.html.twig', array( 'photos' => $query->getResult(), 'formats' => array( 1 => 'Quadratisch', 2 => 'Hochformat', 3 => 'Querformat', 4 => 'Panorama' ), 'colors' => array( 1 => 'Farbe', 2 => 'Schwarzweiß', ) )); $response = new Response($content); $response->headers->set('Content-Type', 'application/xml'); return $response; } } <file_sep>/src/HTW/PhotoWebBundle/Controller/SearchController.php <?php namespace HTW\PhotoWebBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Request; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; class SearchController extends Controller { /** * @Route("/old") */ public function resultsAction() { return $this->render('HTWPhotoWebBundle:Search:search.html.twig'); } /** * @Route("/form") */ public function formAction(Request $request, $originalRequest = null) { $defaultValues = array(); if($originalRequest != null) { $defaultValues['name'] = $originalRequest->query->get('name'); $defaultValues['format'] = $originalRequest->query->get('format'); $defaultValues['color'] = $originalRequest->query->get('color'); $defaultValues['width'] = $originalRequest->query->get('width'); $defaultValues['height'] = $originalRequest->query->get('height'); } $form = $this->createFormBuilder($defaultValues) ->setAction($this->generateUrl('htw_photoweb_search_form')) ->add('name', 'text', array('required' => false)) ->add('format', 'choice', array( 'choices' => array( '1' => 'Quadratisch', '2' => 'Hochformat', '3' => 'Querformat', '4' => 'Panorama' ), 'required' => false, 'empty_value' => 'Alle', 'empty_data' => null, )) ->add('color', 'choice', array( 'choices' => array( '1' => 'Farbe', '2' => 'Schwarzweiß', ), 'label' => 'Farbe', 'empty_value' => 'Alle', 'empty_data' => null, 'required' => false, )) ->add('width', 'text', array('label' => 'Breite in px', 'required' => false)) ->add('height', 'text', array('label' => 'Höhe in px', 'required' => false)) ->add('search', 'submit', array('label' => 'Suchen')) ->getForm(); $form->handleRequest($request); if ($form->isValid()) { $data = $form->getData(); return $this->redirect($this->generateUrl('htw_photoweb_search_search', array( 'name' => $data['name'], 'format' => $data['format'], 'color' => $data['color'], 'width' => $data['width'], 'height' => $data['height'], ))); } return $this->render('HTWPhotoWebBundle:Search:form.html.twig', array('form' => $form->createView())); } /** * @Route("/") */ public function searchAction(Request $request) { $name = $request->query->get('name') ? $request->query->get('name') : '%'; $format = $request->query->get('format') ? $request->query->get('format') : '%'; $color = $request->query->get('color') ? $request->query->get('color') : '%'; $width = $request->query->get('width') ? $request->query->get('width') : '%'; $height = $request->query->get('height') ? $request->query->get('height') : '%'; $repository = $this->getDoctrine() ->getRepository('HTWPhotoWebBundle:Photo'); $query = $repository->createQueryBuilder('p') ->where('LOWER(p.name) LIKE LOWER(:name) OR LOWER(p.description) LIKE LOWER(:desc)') ->andWhere('p.format LIKE :format OR p.format IS NULL') ->andWhere('p.color LIKE :color OR p.color IS NULL') ->andWhere('p.width LIKE :width OR p.width IS NULL') ->andWhere('p.height LIKE :height OR p.height IS NULL') ->setParameter('name', '%'.$name.'%') ->setParameter('desc', '%'.$name.'%') ->setParameter('format', '%'.$format.'%') ->setParameter('color', '%'.$color.'%') ->setParameter('width', '%'.$width.'%') ->setParameter('height', '%'.$height.'%') ->orderBy('p.id', 'DESC') ->getQuery(); $paginator = $this->get('knp_paginator'); $pagination = $paginator->paginate( $query, $this->get('request')->query->get('page', 1), 16 ); return $this->render('HTWPhotoWebBundle:Search:results.html.twig', array('pagination' => $pagination)); } } <file_sep>/src/HTW/PhotoWebBundle/Controller/MyAreaController.php <?php namespace HTW\PhotoWebBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Request; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; class MyAreaController extends Controller { /** * @Route("/") * @Method("GET") * @Template("HTWPhotoWebBundle:MyArea:index.html.twig") */ public function indexAction() { $userID = $this->getUser()->getId(); $repository = $this->getDoctrine() ->getRepository('HTWPhotoWebBundle:Photo'); $query = $repository->createQueryBuilder('p') ->where('p.user = :userID') ->setParameter('userID', $userID) ->orderBy('p.id', 'DESC') ->getQuery(); //return array('photos' => $query->getResult()); $paginator = $this->get('knp_paginator'); $pagination = $paginator->paginate( $query, $this->get('request')->query->get('page', 1), 18 ); return $this->render('HTWPhotoWebBundle:MyArea:index.html.twig', array('pagination' => $pagination)); } } <file_sep>/src/HTW/PhotoWebBundle/Component/Authentication/Handler/LoginSuccessHandler.php <?php namespace HTW\PhotoWebBundle\Component\Authentication\Handler; use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationSuccessHandler; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\SecurityContext; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\Routing\Router; class LoginSuccessHandler extends DefaultAuthenticationSuccessHandler { public function onAuthenticationSuccess(Request $request, TokenInterface $token) { if ($request->isXmlHttpRequest()) { $json = array( 'error' => false, ); return new Response(json_encode($json)); } return parent::onAuthenticationSuccess($request, $token); } }<file_sep>/src/HTW/PhotoWebBundle/HTWPhotoWebBundle.php <?php namespace HTW\PhotoWebBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class HTWPhotoWebBundle extends Bundle { } <file_sep>/src/HTW/PhotoWebBundle/Entity/Photo.php <?php // src/HTW/PhotoWebBundle/Entity/Photo.php namespace HTW\PhotoWebBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; use Symfony\Component\HttpFoundation\File\UploadedFile; /** * @ORM\Entity * @ORM\HasLifecycleCallbacks */ class Photo { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ public $id; /** * @ORM\Column(type="string", length=255) * @Assert\NotBlank */ public $name; /** * @ORM\Column(type="string", length=255, nullable=true) */ public $path; /** * @ORM\Column(type="text", nullable=true) */ public $description; /** * @ORM\Column(type="integer") */ public $user; /** * @ORM\Column(type="integer") */ public $album; /** * @ORM\Column(type="integer", nullable=true) */ public $format; /** * @ORM\Column(type="integer", nullable=true) */ public $color; /** * @ORM\Column(type="integer", nullable=true) */ public $width; /** * @ORM\Column(type="integer", nullable=true) */ public $height; /** * @Assert\NotBlank * @Assert\Image(maxSize="6000000", * mimeTypes = {"image/png", "image/jpeg", "image/gif"}, * mimeTypesMessage = "Please upload a valid image. Possible extensions are: jpeg, png, gif" * ) */ private $file; private $temp; public function __construct($user = null) { $this->user = $user; $this->album = 0; } public function getAbsolutePath() { return null === $this->path ? null : $this->getUploadRootDir().'/'.$this->path; } public function getWebPath() { return null === $this->path ? null : $this->getUploadDir().'/'.$this->path; } protected function getUploadRootDir() { // the absolute directory path where uploaded // documents should be saved return __DIR__.'/../../../../web/'.$this->getUploadDir(); } protected function getUploadDir() { // get rid of the __DIR__ so it doesn't screw up // when displaying uploaded doc/image in the view. return 'uploads/photos'; } /** * Sets file. * * @param UploadedFile $file */ public function setFile(UploadedFile $file = null) { $this->file = $file; // check if we have an old image path if (isset($this->path)) { // store the old name to delete after the update $this->temp = $this->path; $this->path = null; } else { $this->path = 'initial'; } } /** * Get file. * * @return UploadedFile */ public function getFile() { return $this->file; } /** * @ORM\PrePersist() * @ORM\PreUpdate() */ public function preUpload() { if (null !== $this->getFile()) { // do whatever you want to generate a unique name $filename = sha1(uniqid(mt_rand(), true)); $this->path = $filename.'.'.$this->getFile()->guessExtension(); } } /** * @ORM\PostPersist() * @ORM\PostUpdate() */ public function upload() { if (null === $this->getFile()) { return; } // if there is an error when moving the file, an exception will // be automatically thrown by move(). This will properly prevent // the entity from being persisted to the database on error $this->getFile()->move($this->getUploadRootDir(), $this->path); // check if we have an old image if (isset($this->temp)) { // delete the old image unlink($this->getUploadRootDir().'/'.$this->temp); // clear the temp image path $this->temp = null; } $this->file = null; } /** * @ORM\PostRemove() */ public function removeUpload() { if ($file = $this->getAbsolutePath()) { unlink($file); } } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set name * * @param string $name * @return Photo */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Set path * * @param string $path * @return Photo */ public function setPath($path) { $this->path = $path; return $this; } /** * Get path * * @return string */ public function getPath() { return $this->path; } /** * Set description * * @param string $description * @return Photo */ public function setDescription($description) { $this->description = $description; return $this; } /** * Get description * * @return string */ public function getDescription() { return $this->description; } /** * Set user * * @param integer $user * @return Photo */ public function setUser($user) { $this->user = $user; return $this; } /** * Get user * * @return integer */ public function getUser() { return $this->user; } /** * Set album * * @param integer $album * @return Photo */ public function setAlbum($album) { $this->album = $album; return $this; } /** * Get album * * @return integer */ public function getAlbum() { return $this->album; } /** * Set format * * @param integer $format * @return Photo */ public function setFormat($format) { $this->format = $format; return $this; } /** * Get format * * @return integer */ public function getFormat() { return $this->format; } /** * Set color * * @param integer $color * @return Photo */ public function setColor($color) { $this->color = $color; return $this; } /** * Get color * * @return integer */ public function getColor() { return $this->color; } /** * Set width * * @param integer $width * @return Photo */ public function setWidth($width) { $this->width = $width; return $this; } /** * Get width * * @return integer */ public function getWidth() { return $this->width; } /** * Set height * * @param integer $height * @return Photo */ public function setHeight($height) { $this->height = $height; return $this; } /** * Get height * * @return integer */ public function getHeight() { return $this->height; } } <file_sep>/src/HTW/PhotoWebBundle/Controller/UserController.php <?php namespace HTW\PhotoWebBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Request; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use HTW\PhotoWebBundle\Entity\User; class UserController extends Controller { /** * @Route("/") * @Method("GET") * @Template("HTWPhotoWebBundle:User:list.html.twig", vars={"users"}) */ public function listAction() { $users = $this->getDoctrine() ->getRepository('HTWPhotoWebBundle:User') ->findAll(); return array('users' => $users); } /** * @Route("/{user}") * @ParamConverter("user", class="HTWPhotoWebBundle:user") * @Method("GET") * @Template("HTWPhotoWebBundle:User:show.html.twig", vars={"user"}) */ public function showAction() {} }
8bcf2a8ecdc406bc54e734a3f75c7fe9cda0a663
[ "PHP" ]
9
PHP
RoterFuchs/photoweb
0cdd5d321a1d6f29e62273922caaa883cc8ff3d8
8862f5b3ac00b005dbb85d8cacd5848c982f4b14
refs/heads/master
<file_sep>import 'dotenv/config'; //this needs to come before other imports if they need access to the details // import express from 'express'; import cors from 'cors'; import uuidv4 from 'uuid/v4'; import bodyParser from 'body-parser'; // import models from './models'; import routes from './routes'; import models, { sequelize } from './models'; const express = require('express'); // const bodyParser = require('body-parser'); const app = express(); console.log(process.env.MY_SECRET); app.use(cors()); app.use(bodyParser.json()); app.use( bodyParser.urlencoded({ extended: true, }) ); app.use((req, res, next) => { req.context = { models, me: models.users[1], }; next(); }); // app.use(async (req, res, next) => { // req.context = { // models, // me: await models.users.findByLogin('jacob'), // }; // next(); // }); app.use('/session', routes.session); app.use('/messages', routes.message); app.use('/users', routes.user); // app.get('/', (req, res) => { // res.json({ info: 'Node.js, Express, and PostGres API' }) // }); // app.get('/users', (req, res) => { // return res.send(Object.values(req.context.models.users)); // }); // app.get('/users/:userId', (req, res) => { // return res.send(req.context.models.users[req.params.userId]); // }); // app.get('/messages', (req, res) => { // return res.send(Object.values(req.context.models.messages)); // }); // app.get('/session', (req, res) => { // return res.send(req.context.models.users[req.context.me.id]); // }); // app.get('/messages/:messageId', (req, res) => { // return res.send(req.context.models.messages[req.params.messageId]); // }); // // return res.text(); // app.post('/messages', (req,res) => { // console.log(req.body.text); // const id = uuidv4(); // const message = { // id, // text: req.body.text, // userId: req.context.me.id, // }; // req.context.models.messages[id] = message; // return res.send(message); // }); // app.delete('/messages/:messageId', (req, res) => { // const { // [req.params.messageId]: message, // ...othermessages // } = req.context.models.messages; // req.context.models.messages = othermessages; // return res.send(message); // }) sequelize.sync().then(() => { app.listen(process.env.port, () => { console.log(`App is listening on port ${process.env.port}.`) }); });
fd93666dec55a1c1cbf3045c2023c01cea0dc5f8
[ "JavaScript" ]
1
JavaScript
jhuiet/express-routing
fc1144a89b70f253a1713252057ddaef13b4241c
fe2517a7b8c302087060b279033b8fbf2920e75c
refs/heads/master
<repo_name>annawinther/DOM-II<file_sep>/js/index.js // Your code goes here // Making variables const body = document.querySelector('body'); // const navCont = document.querySelector('.nav-container'); const link1 = document.querySelector(' a:nth-child(1)'); const link2 = document.querySelector(' a:nth-child(2)'); const link3 = document.querySelector(' a:nth-child(3)'); const link4 = document.querySelector(' a:nth-child(4)'); const h2 = document.querySelector('h2'); const h1 = document.querySelector('h1'); const bottomContent = document.querySelectorAll('.destination > p'); const h2All = document.querySelectorAll('h2'); const img = document.querySelectorAll("img"); const button = document.querySelectorAll('.btn'); // navCont.addEventListener('mouseover', event =>{ // event.target.style = "background-color: red"; // }) // navCont.addEventListener('mouseout', event =>{ // event.target.style = "background-color: white"; // }) h1.addEventListener('focus', (event) => { event.target.style.backgroun = "pink"; console.log('this should be focused') }); h2All.forEach(element => element.addEventListener('mousedown', event => event.target.style = "color: red")); h2All.forEach(element => element.addEventListener('mouseup', event => event.target.style = "color: pink")); button.forEach(element => element.addEventListener('click', event => event.target.style = "background-color: pink")); // KEY UP KEY DOWN window.addEventListener('keydown', (event)=>{ event.target.style ="color:red"; }); window.addEventListener('keyup', (event)=>{ event.target.style ="color: black"; }); // bottomContent.forEach((element) => { // element.addEventListener('click', // event => event.target.style = "background-color: lightblue"); // console.log('blue') // }) bottomContent.forEach(p => p.addEventListener("mouseover", greyscale)); bottomContent.forEach(p => p.addEventListener("mouseout", resetColor)); function greyscale(event){ event.target.style.filter = "greyscale(100%)"; } function resetColor( event){ event.target.style.filter ="inherit"; } // NAV const navBar = document.querySelectorAll('a'); navBar.forEach( (element) => { element.addEventListener("mousemove", event => event.target.style = "color: purple"); ; }) // EVENT FOR EACH NAV BAR ELEMENT WHEN MOUSE HOVER OVER. // link1.addEventListener('mouseover', (event) =>{ // console.log('MOUSE OVER HOME'); // }) // link2.addEventListener('mouseover', ()=>{ // console.log('MOUSE OVER ABOUT US') // }) // link3.addEventListener('mouseover', ()=>{ // console.log('MOUSE OVER BLOG'); // }) // link4.addEventListener('mouseover', ()=>{ // console.log('MOUSE OVER CONTACT'); // }) // EVENT WHEN HOVER OVER -> PRINTS OUT FOR ALL OF THEM link1.addEventListener('mouseover', listener, {capture: false}); link2.addEventListener('mouseover', listener, { capture: false }); link3.addEventListener('mouseover', event => { console.log('ABOUT TO SHORT-CIRCUIT BUBBLING'); event.stopPropagation(); }); link4.addEventListener('mouseover', listener, {capture: false }); function listener (event){ console.log('MOUSE OVER HOME', event.target); console.log('MOUSE OVER ABOUT US', event.target); console.log('MOUSE OVER BLOG', event.currentTarget); console.log('MOUSE OVER CONTACT', event.currentTarget); } // Create event listeners h2.addEventListener('click', (event) => { event.target.style = "color: green"; console.log('H2 CLICKED'); }); // IMAGES img.forEach(image => image.addEventListener("mouseover", grayscale)); img.forEach(image => image.addEventListener("mouseout", resetColor)); // Callbacks function grayscale (event) { event.target.style.filter = "grayscale(60%)"; } function resetColor (event) { event.target.style.filter = "inherit"; } window.addEventListener('resize', (event) =>{ //event.target.style = 'background-color:grey'; console.log('SUPER RESIZE ME'); }) window.addEventListener('scroll', () =>{ console.log('THEY SEE ME SCROLLING, THEY HATING'); }) window.addEventListener('beforeprint', () => { console.log('USER PRESSED PRINT'); }) window.addEventListener('afterprint', () => { console.log('USER CLOSED PRINT DIALOG'); }) window.addEventListener('load', () => { console.log('ITS LOADING'); }) let heading = document.querySelector(".text-content"); heading.addEventListener('select', (event) => { event.target.style = "color: red"; })
a82ce2160560e7fbe89c47da8ab248bb6529e721
[ "JavaScript" ]
1
JavaScript
annawinther/DOM-II
80330fa32125852d50e1eb788bd80417b635ebda
31e3ce96ff9d800be9487b56444789393b8baff6
refs/heads/master
<repo_name>rohits-sirpi/plumberExamples<file_sep>/inst/plumber/18-logging/plumber.R ## ---- logging library(plumber) library(logger) library(glue) # Path for log files log_path <- "logs" # Create log file directory if it doesn't exist if (!fs::dir_exists(log_path)) fs::dir_create(log_path) # Send logs both to stdout and the log directory log_appender(appender_tee(tempfile("plumber_", log_path, ".log"))) #* @apiTitle Plumber Logging Example #* Echo back the input #* @param msg The message to echo #* @get /echo function(msg = "") { list(msg = paste0("The message is: '", msg, "'")) } #* Plot a histogram #* @serializer png #* @post /plot function() { rand <- rnorm(100) hist(rand) } #* @plumber function(pr) { pr %>% pr_hook("postserialize", function(req, res) { if (class(res$body) == "json") { res_size <- length(charToRaw(res$body)) } else { res_size <- length(res$body) } req_size <- length(charToRaw(req$postBody)) log_info('{req$REMOTE_ADDR} "{req$HTTP_USER_AGENT}" {req$HTTP_HOST} {req$REQUEST_METHOD} {req$PATH_INFO} {res$status} {req_size} {res_size}') }) } <file_sep>/inst/plumber/22-parsers/plumber.R ## ---- parsers library(plumber) #* @post /json function(req, res) { list( message = "Body parsed as JSON", body = req$body ) } #* @parser csv #* @post /csv function(req, res) { list( message = "Body parsed as CSV", body = req$body ) } <file_sep>/inst/plumber/15-openapi-spec/README.md <!-- README.md is generated from README.Rmd. Please edit that file --> # OpenAPI Spec This API demonstrates how to manipulate the OpenAPI spec file used to generated the Plumber UI. ## Endpoints - `/sum`: Return the sum of the provided array of values ## Definition ### [plumber.R](plumber.R) ``` r library(plumber) #* @get /sum function(num) { num_parsed <- unlist(strsplit(num, ",")) sum(as.integer(num_parsed)) } #* @plumber function(pr) { pr %>% pr_set_api_spec(function(spec) { spec$paths[["/sum"]]$get$summary <- "Sum numbers" spec$paths[["/sum"]]$get$parameters <- list(list( "description" = "numbers", "required" = TRUE, "in" = "query", "name" = "num", "schema" = list("type" = "array", "items" = list("type" = "integer"), "minItems" = 1), "style" = "form", "explode" = FALSE )) spec }) } ``` <file_sep>/inst/plumber/05-static/plumber.R ## ---- static-files #* @assets ./files list() #* @assets ./files /static list() #* @get / #* @json(auto_unbox = TRUE) function() { "static file server at './files'" } <file_sep>/inst/plumber/10-welcome/README.Rmd --- output: github_document --- <!-- README.md is generated from README.Rmd. Please edit that file --> ```{r, include = FALSE} knitr::opts_chunk$set( eval = FALSE, collapse = TRUE, comment = "#>" ) knitr::read_chunk("plumber.R") ``` # Welcome A simple API with a single endpoint that returns HTML indicating Plumber is running. ## Endpoints - `/`: HTML indicating plumber is alive ## Definition ### [plumber.R](plumber.R) ```{r welcome} ``` <file_sep>/inst/plumber/20-simple-model/model-training.Rmd --- title: "Cars Model Training" output: html_notebook --- Build simple model from mtcars dataset. ```{r} # Model ---- (insert fancy model here) cars_model <- lm(mpg ~ cyl + hp, data = mtcars) # Save model ---- saveRDS(cars_model,"cars-model.rds") ``` <file_sep>/inst/plumber/07-mailgun/README.Rmd --- output: github_document --- <!-- README.md is generated from README.Rmd. Please edit that file --> ```{r, include = FALSE} knitr::opts_chunk$set( eval = FALSE, collapse = TRUE, comment = "#>" ) knitr::read_chunk("plumber.R") ``` # Mailgun Example of manipulating global state. Each request to `/mail` adds an entry to the `emails` dataframe. `/tail` can be used to see the most recent 5 emails. ## Endpoints - `/mail`: Submit an email with `from` and `subject` parameters - `/tail`: Return the last 5 recorded emails ## Definition ### [plumber.R](plumber.R) ```{r mailgun} ``` <file_sep>/inst/plumber/07-mailgun/README.md <!-- README.md is generated from README.Rmd. Please edit that file --> # Mailgun Example of manipulating global state. Each request to `/mail` adds an entry to the `emails` dataframe. `/tail` can be used to see the most recent 5 emails. ## Endpoints - `/mail`: Submit an email with `from` and `subject` parameters - `/tail`: Return the last 5 recorded emails ## Definition ### [plumber.R](plumber.R) ``` r emails <- data.frame(from=character(0), time=character(0), subject=character(0), stringsAsFactors = FALSE) #* @param from #* @param subject #* @post /mail function(from, subject){ emails <<- rbind(emails, data.frame(from=from, time=date(), subject=htmltools::htmlEscape(subject), stringsAsFactors=FALSE)) TRUE } #* @get /tail function(){ tail(emails[,-1], n=5) } ``` <file_sep>/inst/plumber/03-github/README.Rmd --- output: github_document --- <!-- README.md is generated from README.Rmd. Please edit that file --> ```{r, include = FALSE} knitr::opts_chunk$set( eval = FALSE, collapse = TRUE, comment = "#>" ) knitr::read_chunk("plumber.R") ``` # GitHub This example highlights how a Plumber API can be used in connection with a GitHub webhook to automatically update the Plumber package anytime an update a pushed to the GitHub repository. Note this requires a valid GitHub key stored as `github-key.txt` in order to properly work. ## Endpoints * `/version`: Return information about the currently installed version of Plumber * `/update`: Checks to ensure the incoming request is an authenticated GitHub request, then updates the system installed version of Plumber. ## Definition ### [plumber.R](plumber.R) ```{r github} ``` <file_sep>/inst/plumber/06-sessions/plumber.R ## ---- session #* Example using req$cookies #* @get /counter function(req, res) { count <- 0 if (!is.null(req$cookies$visitcounter)) { count <- as.numeric(req$cookies$visitcounter) } # Most people won't need to concern themselves with the path argument. # I do because of some peculiarities in how I'm hosting the examples. res$setCookie("visitcounter", count+1, path="/") return(paste0("This is visit #", count)) } #* Example using req$session #* @get /sessionCounter function(req){ count <- 0 if (!is.null(req$session$counter)){ count <- as.numeric(req$session$counter) } req$session$counter <- count + 1 return(paste0("This is visit #", count)) } #* @assets static list() #* @plumber function(pr) { pr %>% pr_hooks(session_cookie("secret", "cookieName")) } <file_sep>/inst/plumber/21-ui/README.md <!-- README.md is generated from README.Rmd. Please edit that file --> # User Interface The default user interface for Plumber APIs is [Swagger](https://swagger.io/). Since Plumber APIs are based on the OpenAPI Specification, other common interfaces can be used. Two additional interfaces that are currently supported are [ReDoc](https://github.com/Redocly/redoc) and [RapiDoc](https://mrin9.github.io/RapiDoc/). There are in-development GitHub packages that make using these interfaces with Plumber fairly straightforward: - ReDoc: <https://github.com/meztez/redoc> - RapiDoc: <https://github.com/meztez/rapidoc> ## Endpoints - `/echo`: Echo back the input - `/plot`: Return a histogram of 100 random normal values - `/sum`: Return the sum of 2 values ## Definition ### [plumber.R](plumber.R) ``` r library(plumber) library(rapidoc) #* @apiTitle RapiDoc UI #* Echo back the input #* @param msg The message to echo #* @get /echo function(msg = "") { list(msg = paste0("The message is: '", msg, "'")) } #* Plot a histogram #* @serializer png #* @get /plot function() { rand <- rnorm(100) hist(rand) } #* Return the sum of two numbers #* @param a The first number to add #* @param b The second number to add #* @post /sum function(a, b) { as.numeric(a) + as.numeric(b) } #* @plumber function(pr) { pr %>% pr_set_docs("rapidoc") } ``` <file_sep>/inst/plumber/15-openapi-spec/README.Rmd --- output: github_document --- <!-- README.md is generated from README.Rmd. Please edit that file --> ```{r, include = FALSE} knitr::opts_chunk$set( eval = FALSE, collapse = TRUE, comment = "#>" ) knitr::read_chunk("plumber.R") ``` # OpenAPI Spec This API demonstrates how to manipulate the OpenAPI spec file used to generated the Plumber UI. ## Endpoints - `/sum`: Return the sum of the provided array of values ## Definition ### [plumber.R](plumber.R) ```{r openapi-spec} ``` <file_sep>/inst/plumber/09-content-type/plumber.R ## ---- content-type #* @serializer pdf #* @get /pdf function(){ plot(1:10, type="b") text(4, 8, "PDF from plumber!") } #* @serializer text #* @get /text function(){ "just plain text here..." } #* @serializer html #* @get /html function(){ "<html><h1>HTML!</h1>HTML here!</html>" } #* Download a binary file. #* @serializer contentType list(type="application/octet-stream") #* @get /download-binary function(res){ # TODO: Stream the data into the response rather than loading it all in memory # first. # Create a temporary example RDS file x <- list(a=123, b="hi!") tmp <- tempfile(fileext=".rds") saveRDS(x, tmp) # This header is a convention that instructs browsers to present the response # as a download named "mydata.Rds" rather than trying to render it inline. res$setHeader("Content-Disposition", "attachment; filename=mydata.Rds") # Read in the raw contents of the binary file bin <- readBin(tmp, "raw", n=file.info(tmp)$size) # Delete the temp file file.remove(tmp) # Return the binary contents bin } <file_sep>/inst/plumber/15-openapi-spec/plumber.R ## ---- openapi-spec library(plumber) #* @get /sum function(num) { num_parsed <- unlist(strsplit(num, ",")) sum(as.integer(num_parsed)) } #* @plumber function(pr) { pr %>% pr_set_api_spec(function(spec) { spec$paths[["/sum"]]$get$summary <- "Sum numbers" spec$paths[["/sum"]]$get$parameters <- list(list( "description" = "numbers", "required" = TRUE, "in" = "query", "name" = "num", "schema" = list("type" = "array", "items" = list("type" = "integer"), "minItems" = 1), "style" = "form", "explode" = FALSE )) spec }) } <file_sep>/inst/plumber/14-future/plumber.R ## ---- future library(plumber) library(promises) library(future) future::plan("multiprocess") # use all available cores # future::plan(future::multiprocess(workers = 2)) # only two cores # Quick manual test: # Within 10 seconds... # 1. Visit /future # 2. While /future is loading, visit /sync many times # /future will not block /sync from being able to be loaded. #' @serializer json list(auto_unbox = TRUE) #' @get /sync function() { # print route, time, and worker pid paste0("/sync; ", Sys.time(), "; pid:", Sys.getpid()) } #' @contentType list(type = "text/html") #' @serializer json list(auto_unbox = TRUE) #' @get /future function() { future({ # perform large computations Sys.sleep(10) # print route, time, and worker pid paste0("/future; ", Sys.time(), "; pid:", Sys.getpid()) }) } # Originally by @antoine-sachet from https://github.com/rstudio/plumber/issues/389 #' @get /divide #' @serializer json list(auto_unbox = TRUE) #' @param a number #' @param b number function(a = NA, b = NA) { future({ a <- as.numeric(a) b <- as.numeric(b) if (is.na(a)) stop("a is missing") if (is.na(b)) stop("b is missing") if (b == 0) stop("Cannot divide by 0") a / b }) } #' @get /divide-catch #' @serializer json list(auto_unbox = TRUE) #' @param a number #' @param b number function(a = NA, b = NA) { future({ a <- as.numeric(a) b <- as.numeric(b) if (is.na(a)) stop("a is missing") if (is.na(b)) stop("b is missing") if (b == 0) stop("Cannot divide by 0") a / b }) %>% # Handle `future` errors promises::catch(function(error) { # handle error here! if (error$message == "b is missing") { return(Inf) } # rethrow original error stop(error) }) } <file_sep>/inst/plumber/02-filters/README.Rmd --- output: github_document --- <!-- README.md is generated from README.Rmd. Please edit that file --> ```{r, include = FALSE} knitr::opts_chunk$set( eval = FALSE, collapse = TRUE, comment = "#>" ) knitr::read_chunk("plumber.R") ``` # Plumber filters This examples show how Plumber filters work by implementing a rudimentary authentication mechanism. ## Endpoints * `/me`: Returns the identity of the user, as defined in the `username` query string parameter. Users are "authenticated" against a set list. * `/about`: This endpoint preempts the authentication endpoint and is therefore available to all users, whether they are valid or not. ## Definition ### [plumber.R](plumber.R) ```{r filter} ``` <file_sep>/inst/plumber/06-sessions/README.Rmd --- output: github_document --- <!-- README.md is generated from README.Rmd. Please edit that file --> ```{r, include = FALSE} knitr::opts_chunk$set( eval = FALSE, collapse = TRUE, comment = "#>" ) knitr::read_chunk("plumber.R") ``` # Sessions This API demonstrates how values can be stored across essions. ## Endpoints - `/counter`: Return visit count stored via cookies - `/sessionCounter`: Return visit count stored within session object ## Definition ### [plumber.R](plumber.R) ```{r session} ``` <file_sep>/inst/plumber/11-car-inventory/README.Rmd --- output: github_document --- <!-- README.md is generated from README.Rmd. Please edit that file --> ```{r, include = FALSE} knitr::opts_chunk$set( eval = FALSE, collapse = TRUE, comment = "#>" ) knitr::read_chunk("plumber.R") ``` # Car Inventory A collection of endpoints that all relate to an inventory of cars. This example illustrates typical CRUD API design with each endpoint related to a specific action performed against the car inventory list. ## Endpoints - GET `/car`: List all cars - GET `/car/id`: Lookup a car by id - POST `/car`: Add a car to the inventory - PUT `/car`: Update a car in the inventory - DELETE `/car/id`: Delete a car from the inventory ## Definition ### [plumber.R](plumber.R) ```{r car-inventory} ``` <file_sep>/inst/plumber/01-append/README.Rmd --- output: github_document --- <!-- README.md is generated from README.Rmd. Please edit that file --> ```{r, include = FALSE} knitr::opts_chunk$set( eval = FALSE, collapse = TRUE, comment = "#>" ) knitr::read_chunk("plumber.R") ``` # Appender This API highlights how to use the global environment to keep track of API state. The [managing state](https://www.rplumber.io/articles/execution-model.html#managing-state-1) section of the Plumber documentation contains further details. ## Endpoints * `/append`: Append a value to a global set of values * `/tail`: Return the last n values of the global value store * `/graph`: Return a plot of the values contained in the global value store ## Definition ### [plumber.R](plumber.R) ```{r append} ``` <file_sep>/inst/plumber/14-future/README.Rmd --- output: github_document --- <!-- README.md is generated from README.Rmd. Please edit that file --> ```{r, include = FALSE} knitr::opts_chunk$set( eval = FALSE, collapse = TRUE, comment = "#>" ) knitr::read_chunk("plumber.R") ``` # Future Example for using the [future](https://github.com/HenrikBengtsson/future) package for asynchronous execution with Plumber ## Endpoints - `/sync`: Print route, time, and worker PID - `/future`: Sleep for 10 seconds, then print route, time, and worker PID - `/divide`: Divide a by b in a future process - `/divide-catch`: Divide a by b in a future process and handle errors ## Definition ### [plumber.R](plumber.R) ```{r future} ``` <file_sep>/inst/plumber/11-car-inventory/README.md <!-- README.md is generated from README.Rmd. Please edit that file --> # Car Inventory A collection of endpoints that all relate to an inventory of cars. This example illustrates typical CRUD API design with each endpoint related to a specific action performed against the car inventory list. ## Endpoints - GET `/car`: List all cars - GET `/car/id`: Lookup a car by id - POST `/car`: Add a car to the inventory - PUT `/car`: Update a car in the inventory - DELETE `/car/id`: Delete a car from the inventory ## Definition ### [plumber.R](plumber.R) ``` r inventory <- read.csv("inventory.csv", stringsAsFactors = FALSE) #* @apiTitle Auto Inventory Manager #* @apiDescription Manage the inventory of an automobile #* store using an API. #* @apiTag cars Functionality having to do with the management of #* car inventory. #* List all cars in the inventory #* @get /car/ #* @tag cars listCars <- function(){ inventory } #* Lookup a car by ID #* @param id The ID of the car to get #* @get /car/<id:int> #* @response 404 No car with the given ID was found in the inventory. #* @tag cars getCar <- function(id, res){ car <- inventory[inventory$id == id,] if (nrow(car) == 0){ res$status <- 404 } car } validateCar <- function(make, model, year){ if (missing(make) || nchar(make) == 0){ return("No make specified") } if (missing(model) || nchar(model) == 0){ return("No make specified") } if (missing(year) || as.integer(year) == 0){ return("No year specified") } NULL } #* Add a car to the inventory #* @post /car/ #* @param make:character The make of the car #* @param model:character The model of the car #* @param edition:character Edition of the car #* @param year:int Year the car was made #* @param miles:int The number of miles the car has #* @param price:numeric The price of the car in USD #* @response 400 Invalid user input provided #* @tag cars addCar <- function(make, model, edition, year, miles, price, res){ newId <- max(inventory$id) + 1 valid <- validateCar(make, model, year) if (!is.null(valid)){ res$status <- 400 return(list(errors=paste0("Invalid car: ", valid))) } car <- list( id = newId, make = make, model = model, edition = edition, year = year, miles = miles, price = price ) inventory <<- rbind(inventory, car) getCar(newId) } #* Update a car in the inventory #* @param id:int The ID of the car to update #* @param make:character The make of the car #* @param model:character The model of the car #* @param edition:character Edition of the car #* @param year:int Year the car was made #* @param miles:int The number of miles the car has #* @param price:numeric The price of the car in USD #* @put /car/<id:int> #* @tag cars updateCar <- function(id, make, model, edition, year, miles, price, res){ valid <- validateCar(make, model, year) if (!is.null(valid)){ res$status <- 400 return(list(errors=paste0("Invalid car: ", valid))) } updated <- list( id = id, make = make, model = model, edition = edition, year = year, miles = miles, price = price ) if (!(id %in% inventory$id)){ stop("No such ID: ", id) } inventory[inventory$id == id, ] <<- updated getCar(id) } #* Delete a car from the inventory #* @param id:int The ID of the car to delete #* @delete /car/<id:int> #* @tag cars deleteCar <- function(id, res){ if (!(id %in% inventory$id)){ res$status <- 400 return(list(errors=paste0("No such ID: ", id))) } inventory <<- inventory[inventory$id != id,] } ``` <file_sep>/inst/plumber/05-static/README.md <!-- README.md is generated from README.Rmd. Please edit that file --> # Static File Server This example sets up two static file servers. One at the default path (`/public`), and another at an explicit path (`/static`). You should be able to access the two files in the `./files` directory at either of those paths. So try `http://localhost:8000/static/b.txt` or `http://localhost:8000/public/a.html`. ## Endpoints - `/`: Information about the static file server - `/static/a.html`: The contents of `./files/a.html` - `/static/b.txt`: The contents of `./files/b.txt` - `/public/a.html`: The contents of `./files/a.html` - `/public/b.txt`: The contents of `./files/b.txt` ## Definition ### [plumber.R](plumber.R) ``` r #* @assets ./files list() #* @assets ./files /static list() #* @get / #* @json(auto_unbox = TRUE) function() { "static file server at './files'" } ``` <file_sep>/inst/plumber/03-github/README.md <!-- README.md is generated from README.Rmd. Please edit that file --> # GitHub This example highlights how a Plumber API can be used in connection with a GitHub webhook to automatically update the Plumber package anytime an update a pushed to the GitHub repository. Note this requires a valid GitHub key stored as `github-key.txt` in order to properly work. ## Endpoints - `/version`: Return information about the currently installed version of Plumber - `/update`: Checks to ensure the incoming request is an authenticated GitHub request, then updates the system installed version of Plumber. ## Definition ### [plumber.R](plumber.R) ``` r #* Get information about the currently available #* @get /version function(){ desc <- read.dcf(system.file("DESCRIPTION", package="plumber")) resp <- list( version = unname(desc[1,"Version"]), built = unname(desc[1,"Built"]) ) if ("GithubSHA1" %in% colnames(desc)){ resp["sha1"] <- unname(desc[1,"GithubSHA1"]) } resp } #* Give GitHub Webhook a way to alert us about new pushes to the repo #* https://developer.github.com/webhooks/ #* @post /update function(req, res){ secret <- readLines("./github-key.txt")[1] hm <- digest::hmac(secret, req$postBody, algo="sha1") hm <- paste0("sha1=", hm) if (!identical(hm, req$HTTP_X_HUB_SIGNATURE)){ res$status <- 400 res$body <- "invalid GitHub signature." return(res) } # DO... devtools::install_github("rstudio/plumber") TRUE } ``` <file_sep>/inst/plumber/02-filters/plumber.R ## ---- filter library(plumber) users <- data.frame( id = 1:2, username = c("joe", "kim"), groups = c("users", "admin,users") ) #* Filter that grabs the "username" querystring parameter. #* You should, of course, use a real auth system, but #* this shows the principles involved. #* @filter auth-user function(req, username=""){ # Since username is a querystring param, we can just # expect it to be available as a parameter to the # filter (plumber magic). if (username == ""){ # No username provided } else if (username %in% users$username){ # username is valid req$user <- users[users$username == username,] } else { # username was provided, but invalid stop("No such username: ", username) } # Continue on forward() } #* Now require that all users must be authenticated. #* @filter require-auth function(req, res){ # Check if the user is logged in # Check if the request is being made to OpenAPI - allow the UI to render if (is.null(req$user) & !grepl("docs|swagger|openapi", tolower(req$PATH_INFO))){ # User isn't logged in and request isn't going to Swagger res$status <- 401 # Unauthorized list(error="You must login to access this resource.") } else { # user is logged in. Move on... forward() } } #* @get /me function(req){ # Safe to assume we have a user, since we've been # through all the filters and would have gotten an # error earlier if we weren't. list(user=req$user) } #* Get info about the service. We preempt the #* require-auth filter because we want authenticated and #* unauthenticated users alike to be able to access this #* endpoint. #* @preempt require-auth #* @get /about function(){ list(descript="This is a demo service that uses authentication!") } <file_sep>/inst/plumber/17-arguments/README.Rmd --- output: github_document --- <!-- README.md is generated from README.Rmd. Please edit that file --> ```{r, include = FALSE} knitr::opts_chunk$set( eval = FALSE, collapse = TRUE, comment = "#>" ) knitr::read_chunk("plumber.R") ``` # Arguments This example highlights challenges that can occur when you depend solely on Plumber to automatically parse request arguments. Since arguments can be presented in a variety of different ways as part of a request, it is best practice to manually parse the arguments in the manner you expect to receive them. ## Endpoints - `/bad-practice/<a>/<b>`: List back the parsed arguments - `/good-practice/<a>/<b>`: List various arguments as represented by the `req` object` ## Definition ### [plumber.R](plumber.R) ```{r arguments} ``` <file_sep>/inst/plumber/09-content-type/README.Rmd --- output: github_document --- <!-- README.md is generated from README.Rmd. Please edit that file --> ```{r, include = FALSE} knitr::opts_chunk$set( eval = FALSE, collapse = TRUE, comment = "#>" ) knitr::read_chunk("plumber.R") ``` # Content Type Examples for serializing responses to different content types ## Endpoints - `/pdf`: Return a PDF - `/text`: Return plain text - `/html`: Return simple HTML content - `/download-binary`: Return a binary file ## Definition ### [plumber.R](plumber.R) ```{r content-type} ``` <file_sep>/inst/plumber/10-welcome/plumber.R ## ---- welcome #* @serializer html #* @get / function(){ "<html><body><h1>Plumber is alive!</h1></body></html>" } <file_sep>/inst/plumber/08-identity/plumber.R ## ---- identity #* @get /name function(){ Sys.info()[["nodename"]] } <file_sep>/inst/plumber/06-sessions/README.md <!-- README.md is generated from README.Rmd. Please edit that file --> # Sessions This API demonstrates how values can be stored across essions. ## Endpoints - `/counter`: Return visit count stored via cookies - `/sessionCounter`: Return visit count stored within session object ## Definition ### [plumber.R](plumber.R) ``` r #* Example using req$cookies #* @get /counter function(req, res) { count <- 0 if (!is.null(req$cookies$visitcounter)) { count <- as.numeric(req$cookies$visitcounter) } # Most people won't need to concern themselves with the path argument. # I do because of some peculiarities in how I'm hosting the examples. res$setCookie("visitcounter", count+1, path="/") return(paste0("This is visit #", count)) } #* Example using req$session #* @get /sessionCounter function(req){ count <- 0 if (!is.null(req$session$counter)){ count <- as.numeric(req$session$counter) } req$session$counter <- count + 1 return(paste0("This is visit #", count)) } #* @assets static list() #* @plumber function(pr) { pr %>% pr_hooks(session_cookie("secret", "cookieName")) } ``` <file_sep>/inst/plumber/05-static/README.Rmd --- output: github_document --- <!-- README.md is generated from README.Rmd. Please edit that file --> ```{r, include = FALSE} knitr::opts_chunk$set( eval = FALSE, collapse = TRUE, comment = "#>" ) knitr::read_chunk("plumber.R") ``` # Static File Server This example sets up two static file servers. One at the default path (`/public`), and another at an explicit path (`/static`). You should be able to access the two files in the `./files` directory at either of those paths. So try `http://localhost:8000/static/b.txt` or `http://localhost:8000/public/a.html`. ## Endpoints - `/`: Information about the static file server - `/static/a.html`: The contents of `./files/a.html` - `/static/b.txt`: The contents of `./files/b.txt` - `/public/a.html`: The contents of `./files/a.html` - `/public/b.txt`: The contents of `./files/b.txt` ## Definition ### [plumber.R](plumber.R) ```{r static-files} ``` <file_sep>/inst/plumber/09-content-type/README.md <!-- README.md is generated from README.Rmd. Please edit that file --> # Content Type Examples for serializing responses to different content types ## Endpoints - `/pdf`: Return a PDF - `/text`: Return plain text - `/html`: Return simple HTML content - `/download-binary`: Return a binary file ## Definition ### [plumber.R](plumber.R) ``` r #* @serializer pdf #* @get /pdf function(){ plot(1:10, type="b") text(4, 8, "PDF from plumber!") } #* @serializer text #* @get /text function(){ "just plain text here..." } #* @serializer html #* @get /html function(){ "<html><h1>HTML!</h1>HTML here!</html>" } #* Download a binary file. #* @serializer contentType list(type="application/octet-stream") #* @get /download-binary function(res){ # TODO: Stream the data into the response rather than loading it all in memory # first. # Create a temporary example RDS file x <- list(a=123, b="hi!") tmp <- tempfile(fileext=".rds") saveRDS(x, tmp) # This header is a convention that instructs browsers to present the response # as a download named "mydata.Rds" rather than trying to render it inline. res$setHeader("Content-Disposition", "attachment; filename=mydata.Rds") # Read in the raw contents of the binary file bin <- readBin(tmp, "raw", n=file.info(tmp)$size) # Delete the temp file file.remove(tmp) # Return the binary contents bin } ``` <file_sep>/inst/plumber/22-parsers/README.md <!-- README.md is generated from README.Rmd. Please edit that file --> # Parsers [Body parses](https://www.rplumber.io/reference/parsers.html) transform the request body received by the API into an R object that can be used by each endpoint. ## Endpoints - `/json`: Parse JSON from request - `/csv`: Parse CSV from request ## Definition ### [plumber.R](plumber.R) ``` r library(plumber) #* @post /json function(req, res) { list( message = "Body parsed as JSON", body = req$body ) } #* @post /csv function(req, res) { list( message = "Body parsed as CSV", body = req$body ) } ``` <file_sep>/inst/plumber/14-future/README.md <!-- README.md is generated from README.Rmd. Please edit that file --> # Future Example for using the [future](https://github.com/HenrikBengtsson/future) package for asynchronous execution with Plumber ## Endpoints - `/sync`: Print route, time, and worker PID - `/future`: Sleep for 10 seconds, then print route, time, and worker PID - `/divide`: Divide a by b in a future process - `/divide-catch`: Divide a by b in a future process and handle errors ## Definition ### [plumber.R](plumber.R) ``` r library(promises) library(future) future::plan("multiprocess") # use all available cores # future::plan(future::multiprocess(workers = 2)) # only two cores # Quick manual test: # Within 10 seconds... # 1. Visit /future # 2. While /future is loading, visit /sync many times # /future will not block /sync from being able to be loaded. #' @serializer json list(auto_unbox = TRUE) #' @get /sync function() { # print route, time, and worker pid paste0("/sync; ", Sys.time(), "; pid:", Sys.getpid()) } #' @contentType list(type = "text/html") #' @serializer json list(auto_unbox = TRUE) #' @get /future function() { future({ # perform large computations Sys.sleep(10) # print route, time, and worker pid paste0("/future; ", Sys.time(), "; pid:", Sys.getpid()) }) } # Originally by @antoine-sachet from https://github.com/rstudio/plumber/issues/389 #' @get /divide #' @serializer json list(auto_unbox = TRUE) #' @param a number #' @param b number function(a = NA, b = NA) { future({ a <- as.numeric(a) b <- as.numeric(b) if (is.na(a)) stop("a is missing") if (is.na(b)) stop("b is missing") if (b == 0) stop("Cannot divide by 0") a / b }) } #' @get /divide-catch #' @serializer json list(auto_unbox = TRUE) #' @param a number #' @param b number function(a = NA, b = NA) { future({ a <- as.numeric(a) b <- as.numeric(b) if (is.na(a)) stop("a is missing") if (is.na(b)) stop("b is missing") if (b == 0) stop("Cannot divide by 0") a / b }) %>% # Handle `future` errors promises::catch(function(error) { # handle error here! if (error$message == "b is missing") { return(Inf) } # rethrow original error stop(error) }) } ``` <file_sep>/inst/plumber/19-reticulate/README.md <!-- README.md is generated from README.Rmd. Please edit that file --> # Reticulated Plumber The `reticulate` package enables enables interoperability between Python and R. This example sources a [python script](add.py) and makes the Python function available in a Plumber API endpoint. ## Endpoints - `/sum`: Return the sum of 2 values ## Definition ### [plumber.R](plumber.R) ``` r library(plumber) library(reticulate) source_python("add.py") #* @apiTitle Reticulated Plumber API #* Return the sum of two numbers #* @param a The first number to add #* @param b The second number to add #* @post /sum function(a, b) { a <- as.numeric(a) b <- as.numeric(b) add(a, b) } ``` <file_sep>/inst/plumber/12-entrypoint/myplumberapi.R ## ---- plumber #* @get /counter function(req){ count <- 0 if (!is.null(req$session$counter)){ count <- as.numeric(req$session$counter) } req$session$counter <- count + 1 return(paste0("This is visit #", count)) } <file_sep>/inst/plumber/10-welcome/README.md <!-- README.md is generated from README.Rmd. Please edit that file --> # Welcome A simple API with a single endpoint that returns HTML indicating Plumber is running. ## Endpoints - `/`: HTML indicating plumber is alive ## Definition ### [plumber.R](plumber.R) ``` r #* @serializer html #* @get / function(){ "<html><body><h1>Plumber is alive!</h1></body></html>" } ``` <file_sep>/inst/plumber/08-identity/README.md <!-- README.md is generated from README.Rmd. Please edit that file --> # Identity A simple API that returns information about the system it’s running on. ## Endpoints - `/name`: The `nodename` of the server receiving the request ## Definition ### [plumber.R](plumber.R) ``` r #* @get /name function(){ Sys.info()[["nodename"]] } ``` <file_sep>/inst/plumber/08-identity/README.Rmd --- output: github_document --- <!-- README.md is generated from README.Rmd. Please edit that file --> ```{r, include = FALSE} knitr::opts_chunk$set( eval = FALSE, collapse = TRUE, comment = "#>" ) knitr::read_chunk("plumber.R") ``` # Identity A simple API that returns information about the system it's running on. ## Endpoints - `/name`: The `nodename` of the server receiving the request ## Definition ### [plumber.R](plumber.R) ```{r identity} ``` <file_sep>/inst/plumber/19-reticulate/README.Rmd --- output: github_document --- <!-- README.md is generated from README.Rmd. Please edit that file --> ```{r, include = FALSE} knitr::opts_chunk$set( eval = FALSE, collapse = TRUE, comment = "#>" ) knitr::read_chunk("plumber.R") ``` # Reticulated Plumber The `reticulate` package enables enables interoperability between Python and R. This example sources a [python script](add.py) and makes the Python function available in a Plumber API endpoint. ## Endpoints * `/sum`: Return the sum of 2 values ## Definition ### [plumber.R](plumber.R) ```{r reticulate} ``` <file_sep>/inst/plumber/11-car-inventory/plumber.R ## ---- car-inventory inventory <- read.csv("inventory.csv", stringsAsFactors = FALSE) #* @apiTitle Auto Inventory Manager #* @apiDescription Manage the inventory of an automobile #* store using an API. #* @apiTag cars Functionality having to do with the management of #* car inventory. #* List all cars in the inventory #* @get /car/ #* @tag cars listCars <- function(){ inventory } #* Lookup a car by ID #* @param id The ID of the car to get #* @get /car/<id:int> #* @response 404 No car with the given ID was found in the inventory. #* @tag cars getCar <- function(id, res){ car <- inventory[inventory$id == id,] if (nrow(car) == 0){ res$status <- 404 } car } validateCar <- function(make, model, year){ if (missing(make) || nchar(make) == 0){ return("No make specified") } if (missing(model) || nchar(model) == 0){ return("No make specified") } if (missing(year) || as.integer(year) == 0){ return("No year specified") } NULL } #* Add a car to the inventory #* @post /car/ #* @param make:character The make of the car #* @param model:character The model of the car #* @param edition:character Edition of the car #* @param year:int Year the car was made #* @param miles:int The number of miles the car has #* @param price:numeric The price of the car in USD #* @response 400 Invalid user input provided #* @tag cars addCar <- function(make, model, edition, year, miles, price, res){ newId <- max(inventory$id) + 1 valid <- validateCar(make, model, year) if (!is.null(valid)){ res$status <- 400 return(list(errors=paste0("Invalid car: ", valid))) } car <- list( id = newId, make = make, model = model, edition = edition, year = year, miles = miles, price = price ) inventory <<- rbind(inventory, car) getCar(newId) } #* Update a car in the inventory #* @param id:int The ID of the car to update #* @param make:character The make of the car #* @param model:character The model of the car #* @param edition:character Edition of the car #* @param year:int Year the car was made #* @param miles:int The number of miles the car has #* @param price:numeric The price of the car in USD #* @put /car/<id:int> #* @tag cars updateCar <- function(id, make, model, edition, year, miles, price, res){ valid <- validateCar(make, model, year) if (!is.null(valid)){ res$status <- 400 return(list(errors=paste0("Invalid car: ", valid))) } updated <- list( id = id, make = make, model = model, edition = edition, year = year, miles = miles, price = price ) if (!(id %in% inventory$id)){ stop("No such ID: ", id) } inventory[inventory$id == id, ] <<- updated getCar(id) } #* Delete a car from the inventory #* @param id:int The ID of the car to delete #* @delete /car/<id:int> #* @tag cars deleteCar <- function(id, res){ if (!(id %in% inventory$id)){ res$status <- 400 return(list(errors=paste0("No such ID: ", id))) } inventory <<- inventory[inventory$id != id,] } <file_sep>/inst/plumber/23-tidy-plumber/README.md <!-- README.md is generated from README.Rmd. Please edit that file --> # Tidy Plumber Version 1.0.0 of Plumber introduced a “tidy interface” for Plumber APIs that dramatically simplifies programmatically building APIs. ## Endpoints - `/echo`: Echo back the input - `/plot`: Return a histogram of 100 random normal values - `/sum`: Return the sum of 2 values ## Definition ### [plumber.R](plumber.R) ``` r library(plumber) #* @plumber function(pr) { pr %>% pr_get(path = "/echo", handler = function(msg = "") { list(msg = paste0("The message is: '", msg, "'")) }) %>% pr_get(path = "/plot", handler = function() { rand <- rnorm(100) hist(rand) }, serializer = serializer_png()) %>% pr_post(path = "/sum", handler = function(a, b) { as.numeric(a) + as.numeric(b) }) } ``` <file_sep>/inst/plumber/04-mean-sum/README.md <!-- README.md is generated from README.Rmd. Please edit that file --> # Mean and Sum Simple examples showing two numeric API endpoints. ## Endpoints - `/mean`: Return the mean of `n` random samples from a normal distribution - `/sum`: Return the sum of two values. ## Definition ### [plumber.R](plumber.R) ``` r #* @get /mean normalMean <- function(samples=10){ data <- rnorm(samples) mean(data) } #* @post /sum addTwo <- function(a, b){ as.numeric(a) + as.numeric(b) } ``` <file_sep>/inst/plumber/04-mean-sum/README.Rmd --- output: github_document --- <!-- README.md is generated from README.Rmd. Please edit that file --> ```{r, include = FALSE} knitr::opts_chunk$set( eval = FALSE, collapse = TRUE, comment = "#>" ) knitr::read_chunk("plumber.R") ``` # Mean and Sum Simple examples showing two numeric API endpoints. ## Endpoints * `/mean`: Return the mean of `n` random samples from a normal distribution * `/sum`: Return the sum of two values. ## Definition ### [plumber.R](plumber.R) ```{r mean-and-sum} ``` <file_sep>/inst/plumber/20-simple-model/plumber.R ## ---- simple-model library(plumber) # Read in previously trained model model <- readRDS("cars-model.rds") #* @apiTitle Simple ML Model #* API Health Check #* @get /health-check function() { list( "timestamp" = Sys.time(), "api-status" = "listening") } validate_data <- function(data) { length(intersect(names(data), c("cyl", "hp"))) == 2 } #* Predict on input values #* @post /predict function(req, res) { if (!validate_data(req$body)) { res$status <- 400 return(list(error = "No data submitted")) } predict(model, req$body) } <file_sep>/inst/plumber/22-parsers/README.Rmd --- output: github_document --- <!-- README.md is generated from README.Rmd. Please edit that file --> ```{r, include = FALSE} knitr::opts_chunk$set( eval = FALSE, collapse = TRUE, comment = "#>" ) knitr::read_chunk("plumber.R") ``` # Parsers [Body parses](https://www.rplumber.io/reference/parsers.html) transform the request body received by the API into an R object that can be used by each endpoint. ## Endpoints - `/json`: Parse JSON from request - `/csv`: Parse CSV from request ## Definition ### [plumber.R](plumber.R) ```{r parsers} ``` <file_sep>/inst/plumber/16-attachment/README.md <!-- README.md is generated from README.Rmd. Please edit that file --> # Attachment This API demonstrates how to make responses availalbe as attachments. ## Endpoints - `/name`: Download an attachment as a named text file - `/no-name`: Download an attachment as the name of the route - `/inline`: No attachment - display the result in browser ## Definition ### [plumber.R](plumber.R) ``` r #* Save a file with a particular file name. Ex: `time.txt` #* @serializer text #* @get /name function() { as_attachment(Sys.time(), "time.txt") } #* Save a file as the route. Ex: `no_name` #* @serializer text #* @get /no_name function() { as_attachment(Sys.time()) } #* Display within browser. Possible as the mime type is `text/plain` #* @serializer text #* @get /inline function() { Sys.time() } ``` <file_sep>/inst/plumber/20-simple-model/README.Rmd --- output: github_document --- <!-- README.md is generated from README.Rmd. Please edit that file --> ```{r, include = FALSE} knitr::opts_chunk$set( eval = FALSE, collapse = TRUE, comment = "#>" ) knitr::read_chunk("plumber.R") ``` # Simple ML Model This example is a simplified example of the version in [sol-eng/plumber-model](https://github.com/sol-eng/plumber-model), which demonstrates how to build a Plumber endpoint for a machine learning model. ## Endpoints * `/health-check`: Verify API is up and running * `/predict`: Generate predictions based on a provided set of input values ## Definition ### [plumber.R](plumber.R) ```{r simple-model} ``` <file_sep>/inst/plumber/20-simple-model/README.md <!-- README.md is generated from README.Rmd. Please edit that file --> # Simple ML Model This example is a simplified example of the version in [sol-eng/plumber-model](https://github.com/sol-eng/plumber-model), which demonstrates how to build a Plumber endpoint for a machine learning model. ## Endpoints - `/health-check`: Verify API is up and running - `/predict`: Generate predictions based on a provided set of input values ## Definition ### [plumber.R](plumber.R) ``` r library(plumber) # Read in previously trained model model <- readRDS("cars-model.rds") #* @apiTitle Simple ML Model #* API Health Check #* @get /health-check function() { list( "timestamp" = Sys.time(), "api-status" = "listening") } validate_data <- function(data) { length(intersect(names(data), c("cyl", "hp"))) == 2 } #* Predict on input values #* @post /predict function(req, res) { if (!validate_data(req$body)) { res$status <- 400 return(list(error = "No data submitted")) } predict(model, req$body) } ``` <file_sep>/README.md <!-- README.md is generated from README.Rmd. Please edit that file --> # plumberExamples This package provides a collection of example APIs built in R using the [Plumber](https://rplumber.io) package. These examples are meant to highlight common patterns and best practices. They can be used as compelling starting points when getting started with Plumber. ## Installation You can install the development version of plumberExamples from GitHub with: ``` r remotes::install_github("sol-eng/plumberExamples") ``` ## Usage There are two main uses cases for this package: running example APIs and examining their source code. Example APIs can be run using the `plumb_api()` function: ``` r library(plumber) plumb_api(package = "plumberExamples", name = "00-hello") %>% pr_run() ``` To view the source code associated with the API, add `edit = TRUE` to the function call: ``` r plumb_api(package = "plumberExamples", name = "00-hello", edit = TRUE) ``` ## Examples There are currently 23 examples in this package. Each example is located in [`/inst/plumber`](inst/plumber) and can be accessed using the previously described `plumb_api()` function: | Example | Path | |:-----------------|:---------------------------------------------------------------| | 00-hello-world | [inst/plumber/00-hello-world](inst/plumber/00-hello-world) | | 01-append | [inst/plumber/01-append](inst/plumber/01-append) | | 02-filters | [inst/plumber/02-filters](inst/plumber/02-filters) | | 03-github | [inst/plumber/03-github](inst/plumber/03-github) | | 04-mean-sum | [inst/plumber/04-mean-sum](inst/plumber/04-mean-sum) | | 05-static | [inst/plumber/05-static](inst/plumber/05-static) | | 06-sessions | [inst/plumber/06-sessions](inst/plumber/06-sessions) | | 07-mailgun | [inst/plumber/07-mailgun](inst/plumber/07-mailgun) | | 08-identity | [inst/plumber/08-identity](inst/plumber/08-identity) | | 09-content-type | [inst/plumber/09-content-type](inst/plumber/09-content-type) | | 10-welcome | [inst/plumber/10-welcome](inst/plumber/10-welcome) | | 11-car-inventory | [inst/plumber/11-car-inventory](inst/plumber/11-car-inventory) | | 12-entrypoint | [inst/plumber/12-entrypoint](inst/plumber/12-entrypoint) | | 13-promises | [inst/plumber/13-promises](inst/plumber/13-promises) | | 14-future | [inst/plumber/14-future](inst/plumber/14-future) | | 15-openapi-spec | [inst/plumber/15-openapi-spec](inst/plumber/15-openapi-spec) | | 16-attachment | [inst/plumber/16-attachment](inst/plumber/16-attachment) | | 17-arguments | [inst/plumber/17-arguments](inst/plumber/17-arguments) | | 18-logging | [inst/plumber/18-logging](inst/plumber/18-logging) | | 19-reticulate | [inst/plumber/19-reticulate](inst/plumber/19-reticulate) | | 20-simple-model | [inst/plumber/20-simple-model](inst/plumber/20-simple-model) | | 21-ui | [inst/plumber/21-ui](inst/plumber/21-ui) | | 22-parsers | [inst/plumber/22-parsers](inst/plumber/22-parsers) | <file_sep>/inst/plumber/12-entrypoint/entrypoint.R ## ---- entrypoint pr <- plumb("myplumberapi.R") pr$registerHook("preroute", sessionCookie("secret", "cookieName")) pr <file_sep>/inst/plumber/16-attachment/plumber.R ## ---- attachment #* Save a file with a particular file name. Ex: `time.txt` #* @serializer text #* @get /name function() { as_attachment(Sys.time(), "time.txt") } #* Save a file as the route. Ex: `no_name` #* @serializer text #* @get /no_name function() { as_attachment(Sys.time()) } #* Display within browser. Possible as the mime type is `text/plain` #* @serializer text #* @get /inline function() { Sys.time() } <file_sep>/inst/plumber/18-logging/README.Rmd --- output: github_document --- <!-- README.md is generated from README.Rmd. Please edit that file --> ```{r, include = FALSE} knitr::opts_chunk$set( eval = FALSE, collapse = TRUE, comment = "#>" ) knitr::read_chunk("plumber.R") ``` # Plumber Logging This is a simplified version of the example in [sol-eng/plumber-logging](https://github.com/sol-eng/plumber-logging). This example highlights how Plumber APIs can be built with additional logging in order to capture information about incoming requests. ## Endpoints - `/echo`: Echo back the input - `/plot`: Return a histogram of 100 random normal values ## Definition ### [plumber.R](plumber.R) ```{r logging} ``` <file_sep>/inst/plumber/17-arguments/README.md <!-- README.md is generated from README.Rmd. Please edit that file --> # Arguments This example highlights challenges that can occur when you depend solely on Plumber to automatically parse request arguments. Since arguments can be presented in a variety of different ways as part of a request, it is best practice to manually parse the arguments in the manner you expect to receive them. ## Endpoints - `/bad-practice/<a>/<b>`: List back the parsed arguments - `/good-practice/<a>/<b>`: List various arguments as represented by the `req` object\` ## Definition ### [plumber.R](plumber.R) ``` r #* Plumber allows for things like URI paths to be accessed via named R function arguments, but this is generally considered bad practice (see the examples below) #* @serializer print #* @post /bad-practice/<a>/<b> function(a, b) { list(a = a, b = b) } #* Since URI paths, query params, and body arguments can have conflicting names, it's better practice to access arguments via the request object #* If more information is needed from the body (such as filenames), inspect `req$body` for more information #* @serializer print #* @post /good-practice/<a>/<b> function(req, res) { list( args = req$args, argsQuery = req$argsQuery, argsPath = req$argsPath, argsBody = req$argsBody, body = req$body ) } # Test this api... ### In an R session... ### Run plumber API # plumb_api("plumber", "17-arguments") %>% print() %>% pr_run(port = 1234) ### In a terminal... ### Curl API ## Fails (conflicting variable `a`) # curl --data '' '127.0.0.1:1234/bad-practice/1/2?a=3' # curl --data 'a=3' '127.0.0.1:1234/bad-practice/1/2' # curl --data 'a=4' '127.0.0.1:1234/bad-practice/1/2?a=3' ## Works (but missing variable `d`) # curl --data '' '127.0.0.1:1234/bad-practice/1/2?d=3' #> $a #> [1] "1" #> #> $b #> [1] "2" ## Works (but missing variable `d`) # curl --data 'd=3' '127.0.0.1:1234/bad-practice/1/2' #> $a #> [1] "1" #> #> $b #> [1] "2" ## Safe endpoint setup # curl --data 'a=5&b=6' '127.0.0.1:1234/good-practice/3/4?a=1&b=2&d=10' #> $args #> $args$req #> <environment> #> #> $args$res #> <PlumberResponse> #> #> $args$a #> [1] "1" #> #> $args$b #> [1] "2" #> #> $args$d #> [1] "10" #> #> $args$a #> [1] "3" #> #> $args$b #> [1] "4" #> #> $args$a #> [1] "5" #> #> $args$b #> [1] "6" #> #> #> $argsQuery #> $argsQuery$a #> [1] "1" #> #> $argsQuery$b #> [1] "2" #> #> $argsQuery$d #> [1] "10" #> #> #> $argsPath #> $argsPath$a #> [1] "3" #> #> $argsPath$b #> [1] "4" #> #> #> $argsBody #> $argsBody$a #> [1] "5" #> #> $argsBody$b #> [1] "6" #> #> #> $body #> $body$a #> [1] "5" #> #> $body$b #> [1] "6" ``` <file_sep>/inst/plumber/13-promises/plumber.R ## ---- promises # Visit /async # While /async is loading, visit /sync many times library(promises) sleep_count <- 5 # add 5 seconds of sleep time add_async_sleep <- function(p) { n <- 20 for (i in 1:(sleep_count * n)) { p <- then(p, function(value) { Sys.sleep(1/n) "" # return value }) } p } # use name_ as a placeholder for name when there are extra args time <- function(name_, name = name_) { paste0(name, ": ", Sys.time()) } new_promise <- function() { promise(function(resolve, reject){ resolve(NULL) }) } #' @get /async function() { new_promise() %>% add_async_sleep() %...>% time("async") } #' @get /sync function() { time("sync") } #' @get /sync-slow function() { Sys.sleep(sleep_count) time("sync-slow") } #' @get /async-bad function() { new_promise() %>% add_async_sleep() %...>% stop("async-bad - expected error here") %>% add_async_sleep() %...>% time("async-bad") } #' @get /sync-bad function() { stop("sync-bad - expected error here") } <file_sep>/inst/plumber/18-logging/README.md <!-- README.md is generated from README.Rmd. Please edit that file --> # Plumber Logging This is a simplified version of the example in [sol-eng/plumber-logging](https://github.com/sol-eng/plumber-logging). This example highlights how Plumber APIs can be built with additional logging in order to capture information about incoming requests. ## Endpoints - `/echo`: Echo back the input - `/plot`: Return a histogram of 100 random normal values ## Definition ### [plumber.R](plumber.R) ``` r library(plumber) library(logger) library(glue) # Path for log files log_path <- "logs" # Create log file directory if it doesn't exist if (!fs::dir_exists(log_path)) fs::dir_create(log_path) # Send logs both to stdout and the log directory log_appender(appender_tee(tempfile("plumber_", log_path, ".log"))) #* @apiTitle Plumber Logging Example #* Echo back the input #* @param msg The message to echo #* @get /echo function(msg = "") { list(msg = paste0("The message is: '", msg, "'")) } #* Plot a histogram #* @serializer png #* @post /plot function() { rand <- rnorm(100) hist(rand) } #* @plumber function(pr) { pr %>% pr_hook("postserialize", function(req, res) { if (class(res$body) == "json") { res_size <- length(charToRaw(res$body)) } else { res_size <- length(res$body) } req_size <- length(charToRaw(req$postBody)) log_info('{req$REMOTE_ADDR} "{req$HTTP_USER_AGENT}" {req$HTTP_HOST} {req$REQUEST_METHOD} {req$PATH_INFO} {res$status} {req_size} {res_size}') }) } ``` <file_sep>/inst/plumber/16-attachment/README.Rmd --- output: github_document --- <!-- README.md is generated from README.Rmd. Please edit that file --> ```{r, include = FALSE} knitr::opts_chunk$set( eval = FALSE, collapse = TRUE, comment = "#>" ) knitr::read_chunk("plumber.R") ``` # Attachment This API demonstrates how to make responses availalbe as attachments. ## Endpoints - `/name`: Download an attachment as a named text file - `/no-name`: Download an attachment as the name of the route - `/inline`: No attachment - display the result in browser ## Definition ### [plumber.R](plumber.R) ```{r attachment} ``` <file_sep>/README.Rmd --- output: github_document --- <!-- README.md is generated from README.Rmd. Please edit that file --> ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.path = "man/figures/README-", out.width = "100%" ) # Count number of examples n_examples <- length(dir("inst/plumber")) ``` # plumberExamples This package provides a collection of example APIs built in R using the [Plumber](https://rplumber.io) package. These examples are meant to highlight common patterns and best practices. They can be used as compelling starting points when getting started with Plumber. ## Installation You can install the development version of plumberExamples from GitHub with: ```{r, eval=FALSE} remotes::install_github("sol-eng/plumberExamples") ``` ## Usage There are two main uses cases for this package: running example APIs and examining their source code. Example APIs can be run using the `plumb_api()` function: ```{r, eval = FALSE} library(plumber) plumb_api(package = "plumberExamples", name = "00-hello") %>% pr_run() ``` To view the source code associated with the API, add `edit = TRUE` to the function call: ```{r, eval = FALSE} plumb_api(package = "plumberExamples", name = "00-hello", edit = TRUE) ``` ## Examples There are currently `r n_examples` examples in this package. Each example is located in [`/inst/plumber`](inst/plumber) and can be accessed using the previously described `plumb_api()` function: ```{r, echo = FALSE, results='asis'} knitr::kable(data.frame( Example = list.dirs("inst/plumber", full.names = FALSE, recursive = FALSE), Path = paste0("[", list.dirs("inst/plumber", full.names = TRUE, recursive = FALSE), "](", list.dirs("inst/plumber", full.names = TRUE, recursive = FALSE), ")" ) )) ``` <file_sep>/inst/plumber/12-entrypoint/README.md <!-- README.md is generated from README.Rmd. Please edit that file --> # Entrypoint **Note: As of verison 1.0.0, `entrypoint.R` is deprecated in favor of using `#* @plumber` tags in a standard Plumber definition file.** `entrypoint.R` can be used to further modify an existing Plumber API router. ## Endpoints - `/counter`: Return visit count ## Definition ### [myplumberapi.R](myplumberapi.R) ``` r #* @get /counter function(req){ count <- 0 if (!is.null(req$session$counter)){ count <- as.numeric(req$session$counter) } req$session$counter <- count + 1 return(paste0("This is visit #", count)) } ``` ### [entrypoint.R](entrypoint.R) ``` r pr <- plumb("myplumberapi.R") pr$registerHook("preroute", sessionCookie("secret", "cookieName")) pr ``` <file_sep>/inst/plumber/13-promises/README.Rmd --- output: github_document --- <!-- README.md is generated from README.Rmd. Please edit that file --> ```{r, include = FALSE} knitr::opts_chunk$set( eval = FALSE, collapse = TRUE, comment = "#>" ) knitr::read_chunk("plumber.R") ``` # Promises Example for using [promises](https://rstudio.github.io/promises/) with Plumber ## Endpoints - `/async`: Asynchronous endpoint - `/sync`: Synchronous endpoint - `/sync-slow`: Synchronous endpoint with delay - `/async-bad`: Asynchronous endpoint with error - `/sync-bad`: Synchronous endpont with error ## Definition ### [plumber.R](plumber.R) ```{r promises} ``` <file_sep>/inst/plumber/19-reticulate/plumber.R # ---- reticulate library(plumber) library(reticulate) source_python("add.py") #* @apiTitle Reticulated Plumber API #* Return the sum of two numbers #* @param a The first number to add #* @param b The second number to add #* @post /sum function(a, b) { a <- as.numeric(a) b <- as.numeric(b) add(a, b) } <file_sep>/inst/plumber/02-filters/README.md <!-- README.md is generated from README.Rmd. Please edit that file --> # Plumber filters This examples show how Plumber filters work by implementing a rudimentary authentication mechanism. ## Endpoints - `/me`: Returns the identity of the user, as defined in the `username` query string parameter. Users are “authenticated” against a set list. - `/about`: This endpoint preempts the authentication endpoint and is therefore available to all users, whether they are valid or not. ## Definition ### [plumber.R](plumber.R) ``` r library(plumber) users <- data.frame( id = 1:2, username = c("joe", "kim"), groups = c("users", "admin,users") ) #* Filter that grabs the "username" querystring parameter. #* You should, of course, use a real auth system, but #* this shows the principles involved. #* @filter auth-user function(req, username=""){ # Since username is a querystring param, we can just # expect it to be available as a parameter to the # filter (plumber magic). if (username == ""){ # No username provided } else if (username %in% users$username){ # username is valid req$user <- users[users$username == username,] } else { # username was provided, but invalid stop("No such username: ", username) } # Continue on forward() } #* Now require that all users must be authenticated. #* @filter require-auth function(req, res){ # Check if the user is logged in # Check if the request is being made to OpenAPI - allow the UI to render if (is.null(req$user) & !grepl("docs|swagger|openapi", tolower(req$PATH_INFO))){ # User isn't logged in and request isn't going to Swagger res$status <- 401 # Unauthorized list(error="You must login to access this resource.") } else { # user is logged in. Move on... forward() } } #* @get /me function(req){ # Safe to assume we have a user, since we've been # through all the filters and would have gotten an # error earlier if we weren't. list(user=req$user) } #* Get info about the service. We preempt the #* require-auth filter because we want authenticated and #* unauthenticated users alike to be able to access this #* endpoint. #* @preempt require-auth #* @get /about function(){ list(descript="This is a demo service that uses authentication!") } ``` <file_sep>/inst/plumber/17-arguments/plumber.R ## ---- arguments #* Plumber allows for things like URI paths to be accessed via named R function arguments, but this is generally considered bad practice (see the examples below) #* @serializer print #* @post /bad-practice/<a>/<b> function(a, b) { list(a = a, b = b) } #* Since URI paths, query params, and body arguments can have conflicting names, it's better practice to access arguments via the request object #* If more information is needed from the body (such as filenames), inspect `req$body` for more information #* @serializer print #* @post /good-practice/<a>/<b> function(req, res) { list( args = req$args, argsQuery = req$argsQuery, argsPath = req$argsPath, argsBody = req$argsBody, body = req$body ) } # Test this api... ### In an R session... ### Run plumber API # plumb_api("plumber", "17-arguments") %>% print() %>% pr_run(port = 1234) ### In a terminal... ### Curl API ## Fails (conflicting variable `a`) # curl --data '' '127.0.0.1:1234/bad-practice/1/2?a=3' # curl --data 'a=3' '127.0.0.1:1234/bad-practice/1/2' # curl --data 'a=4' '127.0.0.1:1234/bad-practice/1/2?a=3' ## Works (but missing variable `d`) # curl --data '' '127.0.0.1:1234/bad-practice/1/2?d=3' #> $a #> [1] "1" #> #> $b #> [1] "2" ## Works (but missing variable `d`) # curl --data 'd=3' '127.0.0.1:1234/bad-practice/1/2' #> $a #> [1] "1" #> #> $b #> [1] "2" ## Safe endpoint setup # curl --data 'a=5&b=6' '127.0.0.1:1234/good-practice/3/4?a=1&b=2&d=10' #> $args #> $args$req #> <environment> #> #> $args$res #> <PlumberResponse> #> #> $args$a #> [1] "1" #> #> $args$b #> [1] "2" #> #> $args$d #> [1] "10" #> #> $args$a #> [1] "3" #> #> $args$b #> [1] "4" #> #> $args$a #> [1] "5" #> #> $args$b #> [1] "6" #> #> #> $argsQuery #> $argsQuery$a #> [1] "1" #> #> $argsQuery$b #> [1] "2" #> #> $argsQuery$d #> [1] "10" #> #> #> $argsPath #> $argsPath$a #> [1] "3" #> #> $argsPath$b #> [1] "4" #> #> #> $argsBody #> $argsBody$a #> [1] "5" #> #> $argsBody$b #> [1] "6" #> #> #> $body #> $body$a #> [1] "5" #> #> $body$b #> [1] "6" <file_sep>/inst/plumber/07-mailgun/plumber.R ## ---- mailgun emails <- data.frame(from=character(0), time=character(0), subject=character(0), stringsAsFactors = FALSE) #* @param from #* @param subject #* @post /mail function(from, subject){ emails <<- rbind(emails, data.frame(from=from, time=date(), subject=htmltools::htmlEscape(subject), stringsAsFactors=FALSE)) TRUE } #* @get /tail function(){ tail(emails[,-1], n=5) } <file_sep>/inst/plumber/13-promises/README.md <!-- README.md is generated from README.Rmd. Please edit that file --> # Promises Example for using [promises](https://rstudio.github.io/promises/) with Plumber ## Endpoints - `/async`: Asynchronous endpoint - `/sync`: Synchronous endpoint - `/sync-slow`: Synchronous endpoint with delay - `/async-bad`: Asynchronous endpoint with error - `/sync-bad`: Synchronous endpont with error ## Definition ### [plumber.R](plumber.R) ``` r # Visit /async # While /async is loading, visit /sync many times library(promises) sleep_count <- 5 # add 5 seconds of sleep time add_async_sleep <- function(p) { n <- 20 for (i in 1:(sleep_count * n)) { p <- then(p, function(value) { Sys.sleep(1/n) "" # return value }) } p } # use name_ as a placeholder for name when there are extra args time <- function(name_, name = name_) { paste0(name, ": ", Sys.time()) } new_promise <- function() { promise(function(resolve, reject){ resolve(NULL) }) } #' @get /async function() { new_promise() %>% add_async_sleep() %...>% time("async") } #' @get /sync function() { time("sync") } #' @get /sync-slow function() { Sys.sleep(sleep_count) time("sync-slow") } #' @get /async-bad function() { new_promise() %>% add_async_sleep() %...>% stop("async-bad - expected error here") %>% add_async_sleep() %...>% time("async-bad") } #' @get /sync-bad function() { stop("sync-bad - expected error here") } ``` <file_sep>/inst/plumber/01-append/README.md <!-- README.md is generated from README.Rmd. Please edit that file --> # Appender This API highlights how to use the global environment to keep track of API state. The [managing state](https://www.rplumber.io/articles/execution-model.html#managing-state-1) section of the Plumber documentation contains further details. ## Endpoints - `/append`: Append a value to a global set of values - `/tail`: Return the last n values of the global value store - `/graph`: Return a plot of the values contained in the global value store ## Definition ### [plumber.R](plumber.R) ``` r values <- 15 MAX_VALS <- 50 #* Append to our values #* @param val:int value to append #* @post /append function(val, res){ v <- as.numeric(val) if (is.na(v)){ res$status <- 400 res$body <- "val parameter must be a number" } values <<- c(values, val) if (length(values) > MAX_VALS){ values <<- tail(values, n=MAX_VALS) } list(result="success") } #* Get the last few values #* @get /tail function(n="10", res){ n <- as.numeric(n) if (is.na(n) || n < 1 || n > MAX_VALS){ res$status <- 400 res$body <- "parameter 'n' must be a number between 1 and 100" } list(val=tail(values, n=n)) } #* Get a graph of the values #* @png #* @get /graph function(){ plot(values, type="b", ylim=c(1,100), main="Recent Values") } ``` <file_sep>/inst/plumber/12-entrypoint/README.Rmd --- output: github_document --- <!-- README.md is generated from README.Rmd. Please edit that file --> ```{r, include = FALSE} knitr::opts_chunk$set( eval = FALSE, collapse = TRUE, comment = "#>" ) knitr::read_chunk("myplumberapi.R") knitr::read_chunk("entrypoint.R") knitr::read_chunk("tidy-plumber.R") ``` # Entrypoint **Note: As of verison 1.0.0, `entrypoint.R` is deprecated in favor of using `#* @plumber` tags in a standard Plumber definition file.** `entrypoint.R` can be used to further modify an existing Plumber API router. ## Endpoints - `/counter`: Return visit count ## Definition ### [myplumberapi.R](myplumberapi.R) ```{r plumber} ``` ### [entrypoint.R](entrypoint.R) ```{r entrypoint} ``` ### [Tidy Plumber](tidy-plumber.R) ```{r tidy-plumber} ``` <file_sep>/inst/plumber/23-tidy-plumber/plumber.R ## ---- tidy-plumber library(plumber) #* @plumber function(pr) { pr %>% pr_get(path = "/echo", handler = function(msg = "") { list(msg = paste0("The message is: '", msg, "'")) }) %>% pr_get(path = "/plot", handler = function() { rand <- rnorm(100) hist(rand) }, serializer = serializer_png()) %>% pr_post(path = "/sum", handler = function(a, b) { as.numeric(a) + as.numeric(b) }) } <file_sep>/inst/plumber/00-hello-world/README.md <!-- README.md is generated from README.Rmd. Please edit that file --> # Hello World, Plumber This is the default starter example for Plumber APIs. ## Endpoints - `/echo`: Echo back the input - `/plot`: Return a histogram of 100 random normal values - `/sum`: Return the sum of 2 values ## Definition ### [plumber.R](plumber.R) ``` r # # This is a Plumber API. You can run the API by clicking # the 'Run API' button above. # # Find out more about building APIs with Plumber here: # # https://www.rplumber.io/ # library(plumber) #* @apiTitle Plumber Example API #* Echo back the input #* @param msg The message to echo #* @get /echo function(msg = "") { list(msg = paste0("The message is: '", msg, "'")) } #* Plot a histogram #* @serializer png #* @get /plot function() { rand <- rnorm(100) hist(rand) } #* Return the sum of two numbers #* @param a The first number to add #* @param b The second number to add #* @post /sum function(a, b) { as.numeric(a) + as.numeric(b) } ```
19a9bd828af72248d556a13acc6191e68b31b655
[ "Markdown", "R", "RMarkdown" ]
68
R
rohits-sirpi/plumberExamples
865f936fb1a5dfb8841b71f5c4ccc8c29244aba8
31d3ca11988df10245db6c6a9e76c45a3866c753
refs/heads/master
<file_sep> // testDlg.cpp: 实现文件 // #include "pch.h" #include "framework.h" #include "test.h" #include "testDlg.h" #include "afxdialogex.h" #include <TlHelp32.h> #include "newprocess.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // 用于应用程序“关于”菜单项的 CAboutDlg 对话框 class CAboutDlg : public CDialogEx { public: CAboutDlg(); // 对话框数据 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_ABOUTBOX }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // CtestDlg 对话框 CtestDlg::CtestDlg(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_TEST_DIALOG, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CtestDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_LIST2, m_list); } BEGIN_MESSAGE_MAP(CtestDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(Btn_Refresh, &CtestDlg::OnBnClickedButton1) ON_BN_CLICKED(Btn_CloseProcess, &CtestDlg::OnBnClickedCloseprocess) ON_BN_CLICKED(Btn_CreateProcess, &CtestDlg::OnBnClickedCreateprocess) END_MESSAGE_MAP() // CtestDlg 消息处理程序 //对话框初始化 BOOL CtestDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // 将“关于...”菜单项添加到系统菜单中。 // IDM_ABOUTBOX 必须在系统命令范围内。 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != nullptr) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 #pragma region 设置列表格式 //给列表添加列 左对齐 m_list.InsertColumn(0, _T("编号"), LVCFMT_LEFT, 100); m_list.InsertColumn(1, _T("进程名称"), LVCFMT_LEFT, 200); m_list.InsertColumn(2, _T("PID"), LVCFMT_LEFT, 200); //设置拓展风格,添加网格线 m_list.SetExtendedStyle(LVS_EX_GRIDLINES|LVS_EX_FULLROWSELECT); #pragma endregion //遍历进程 BrowserProcess(); return TRUE; // 除非将焦点设置到控件,否则返回 TRUE } void CtestDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::OnSysCommand(nID, lParam); } } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。 对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void CtestDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 用于绘制的设备上下文 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 使图标在工作区矩形中居中 int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 绘制图标 dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } //当用户拖动最小化窗口时系统调用此函数取得光标 //显示。 HCURSOR CtestDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } //遍历进程 void CtestDlg::BrowserProcess() { HANDLE hProcessSnap=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); //获取快照失败,返回 if (hProcessSnap == INVALID_HANDLE_VALUE) { return; } //枚举进程 PROCESSENTRY32 pe32; pe32.dwSize = sizeof(PROCESSENTRY32); BOOL bMore=Process32First(hProcessSnap, &pe32); //此变量用于记录编号 int i = 0; //此变量用于最终呈现编号 CString NO; //此变量用于呈现PID CString PID; while (bMore) { NO.Format(_T("%d"), i+1); //编号插入列表 m_list.InsertItem(i, NO); //进程名插入列表 m_list.SetItemText(i, 1, pe32.szExeFile); //PID插入列表 PID.Format(_T("%d"), pe32.th32ProcessID); m_list.SetItemText(i, 2, PID); bMore=Process32Next(hProcessSnap, &pe32); i++; } } void CtestDlg::OnBnClickedButton1() { m_list.DeleteAllItems(); BrowserProcess(); } void CtestDlg::OnBnClickedCloseprocess() { // TODO: 在此添加控件通知处理程序代码 int nselect=m_list.GetSelectionMark(); //没选,返回 if (nselect < 0) { return; } CString strPID=m_list.GetItemText(nselect, 2); DWORD dwPID = _wtoi(strPID); //打开PID进程,搞到进程句柄 HANDLE hProcess=OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwPID); if (hProcess == NULL) { MessageBox(L"打开进程失败!"); return; } //关闭进程 TerminateProcess(hProcess,0); //刷新进程列表 OnBnClickedButton1(); } void CtestDlg::OnBnClickedCreateprocess() { // TODO: 在此添加控件通知处理程序代码 newprocess cp; cp.DoModal(); } <file_sep>// newprocess.cpp: 实现文件 // #include "pch.h" #include "test.h" #include "newprocess.h" #include "afxdialogex.h" // newprocess 对话框 IMPLEMENT_DYNAMIC(newprocess, CDialogEx) newprocess::newprocess(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_DIALOG1, pParent) { } newprocess::~newprocess() { } void newprocess::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, Input_Process, m_input); DDX_Control(pDX, IDC_STATIC_ID1, m_PID1); DDX_Control(pDX, IDC_STATIC_ID2, m_PID2); } BEGIN_MESSAGE_MAP(newprocess, CDialogEx) ON_BN_CLICKED(IDOK, &newprocess::OnBnClickedOk) END_MESSAGE_MAP() // newprocess 消息处理程序 CString dwprocessid; CString dwThreadId; //创建新进程 void CreateNewProcess(CString processname) { LPWSTR szCommandLine = processname.GetBuffer(); STARTUPINFO si = { sizeof(si) }; PROCESS_INFORMATION pi; si.dwFlags = STARTF_USESHOWWINDOW; //制定wShowWindow成员 si.wShowWindow = TRUE; //为真,显示进程的主窗口 BOOL bRet = ::CreateProcess( NULL,//不在此指定可执行文件的文件名 szCommandLine, //命令行参数 NULL,//默认进程的安全性 NULL,//默认线程的安全性 FALSE,//指定当前进程内的句柄不可以被子进程继承 CREATE_NEW_CONSOLE,//为新进程创建一个新的控制台窗口 NULL,//使用本进程的环境变量 NULL,//使用本进程的驱动器和目录 &si, &pi); if (bRet) { //既然我们不使用两个句柄,最好是立刻将他们关闭 ::CloseHandle(pi.hThread); ::CloseHandle(pi.hProcess); dwprocessid.Format(_T("%d"), pi.dwProcessId); dwThreadId.Format(_T("%d"), pi.dwThreadId); /*printf("新的进程的进程ID号:%d\n", pi.dwProcessId); printf("新进程的主线程ID号:%d\n", pi.dwThreadId);*/ } } void newprocess::OnBnClickedOk() { // TODO: 在此添加控件通知处理程序代码 CString processname; m_input.GetWindowText(processname); CreateNewProcess(processname); m_PID1.SetWindowTextW(dwprocessid); m_PID2.SetWindowTextW(dwThreadId); } <file_sep>#pragma once // newprocess 对话框 class newprocess : public CDialogEx { DECLARE_DYNAMIC(newprocess) public: newprocess(CWnd* pParent = nullptr); // 标准构造函数 virtual ~newprocess(); // 对话框数据 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_DIALOG1 }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: CEdit m_input; afx_msg void OnBnClickedOk(); // CStatic m_text1; // CStatic m_text2; CStatic m_PID1; CStatic m_PID2; }; <file_sep>//{{NO_DEPENDENCIES}} // Microsoft Visual C++ 生成的包含文件。 // 供 test.rc 使用 // #define IDM_ABOUTBOX 0x0010 #define IDD_ABOUTBOX 100 #define IDS_ABOUTBOX 101 #define IDD_TEST_DIALOG 102 #define IDR_MAINFRAME 128 #define IDD_DIALOG1 133 #define IDC_LIST2 1001 #define Btn_Refresh 1002 #define Btn_CloseProcess 1004 #define Btn_CreateProcess 1006 #define IDCANCEL 1007 #define Input_Process 1008 #define IDC_STATIC1 1009 #define IDC_STATIC2 1010 #define text_pid2 1012 #define IDC_STATIC3 1013 #define IDC_STATIC_ID1 1014 #define IDC_STATIC_ID2 1015 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 135 #define _APS_NEXT_COMMAND_VALUE 32771 #define _APS_NEXT_CONTROL_VALUE 1016 #define _APS_NEXT_SYMED_VALUE 104 #endif #endif
33a33d0b8e703fb23f539c78723584745d4e57bc
[ "C", "C++" ]
4
C++
Kafuu-Chino-GYZ/-
6246fd0a111310ef457f957ed114452771564b57
524f6329bbbbd21fb89dca5c05ce47fd45c825cb
refs/heads/master
<repo_name>mbrotos/DailyCodingProblem---Python<file_sep>/src/Problem4.py """ Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree. For example, given the following Node class class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right The following test should pass: node = Node('root', Node('left', Node('left.left')), Node('right')) assert deserialize(serialize(node)).left.left.val == 'left.left' """ class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def serialize(root_node): string = [] def serializer(root): if root is None: string.append("-1") return string.append(root.val) serializer(root.left) serializer(root.right) serializer(root_node) return string index = 0 def deserialize(array): global index if index == len(array) or array[index] == "-1": index += 1 return None root = Node(array[index]) index += 1 root.left = deserialize(array) root.right = deserialize(array) return root node = Node('root', Node('left', Node('left.left')), Node('right')) assert deserialize(serialize(node)).left.left.val == 'left.left'
097d302c5d976a335518d2cca65ca585695577f7
[ "Python" ]
1
Python
mbrotos/DailyCodingProblem---Python
0109a6e717b90625b5277f9e8dd759064a3ad423
2b6643ae7064affd35d1d90a1cb2cc7422a0d989
refs/heads/master
<repo_name>egus032/testproject_3-master<file_sep>/src/main/frontend/gulpfile.js var gulp = require("gulp"), runSequence = require("run-sequence"), // inject mainBowerFiles = require("main-bower-files"), inject = require("gulp-inject"), // minify concat = require("gulp-concat"), uglify = require("gulp-uglify"), sourcemaps = require("gulp-sourcemaps"), htmlmin = require("gulp-htmlmin"), csso = require("gulp-csso"), ngAnnotate = require("gulp-ng-annotate"), // hints htmlhint = require("gulp-htmlhint"), csslint = require("gulp-csslint"), jshint = require("gulp-jshint"), //files path = require("path"), crypto = require("crypto"), fs = require("fs"), //utils gulpFilter = require("gulp-filter"), gulpif = require("gulp-if"), util = require("gulp-util"); // Paths var dirs = { target: "../../../target/" + util.env.target, webapp: "../webapp", static: "static" }, mask = { js: ["js/vendors/**/*.js", "app/app.js", "app/*.js", "app/**/*.js", "js/*.js" ], css: ["css/*.css", "app/common/**/*.css"], html: ["app/**/*.html"] }; // Help var isProduction = (util.env.asset == "production"), isDevelopment = (util.env.asset == "development"), getSources = function () { var pathNames = mask.js.concat(mask.css).concat(mask.html); for (pathName in pathNames) { pathNames[pathName] = path.join(dirs.webapp, dirs.static, pathNames[pathName]); } return pathNames; }, copyBowerFiles = function () { return gulp.src(mainBowerFiles()) .pipe(gulp.dest(path.join(dirs.target, dirs.static, "/bower_components"))); }, hash = function hash(filePath) { return crypto .createHash("sha1") .update(fs.readFileSync(path.join(filePath), {encoding: "utf8"})) .digest("hex") }; gulp.task("inject", function () { var transform = function (filepath, file, i, length) { if (filepath.slice(-3) === ".js") { var async = filepath.slice(-13) === "production.js"; filepath += "?v=" + hash(path.join(dirs.target, filepath)); return "<script src=\"" + filepath + "\"" + (async ? " async" : "") + "></script>"; } filepath += "?v=" + hash(path.join(dirs.target, filepath)); return inject.transform.apply(inject.transform, arguments); }, getOptions = function (name, ignorePath) { return {ignorePath: ignorePath, addRootSlash: false, name: name, transform: transform}; }, getProductionSources = function () { return [path.join(dirs.target, dirs.static, "production.js"), path.join(dirs.target, dirs.static, "css/production.css")]; }; var target = gulp.src([path.join(dirs.target, "**/stylesheets.ftl"), path.join(dirs.target, "**/javascripts.ftl")]); target .pipe(gulpif(isDevelopment, inject(copyBowerFiles(), getOptions("bower", dirs.target)))) .pipe(gulpif(isDevelopment, inject(gulp.src(getSources(), {read: false}), getOptions("inject", dirs.webapp)))) .pipe(gulpif(isProduction, inject(gulp.src(getProductionSources(), {read: false}), getOptions("inject", dirs.target)))) .pipe(gulp.dest(dirs.target)); }); // Sequences gulp.task("development", function () { runSequence(["validate-client", "inject"]); }); gulp.task("production", function () { runSequence(["validate-client", "html-compress", "concat-compress-js", "concat-compress-css"], "inject"); }); // Tasks gulp.task("concat-compress-css", function () { return gulp.src(mainBowerFiles().concat(getSources())) .pipe(gulpFilter("**/*.css")) .pipe(concat("css/production.css")) .pipe(csso()) .pipe(gulp.dest(path.join(dirs.target, dirs.static))); }); gulp.task("concat-compress-js", function () { return gulp.src(mainBowerFiles().concat(getSources())) .pipe(gulpFilter("**/*.js")) .pipe(sourcemaps.init()) .pipe(ngAnnotate()) .pipe(concat("production.js")) .pipe(uglify()) .pipe(sourcemaps.write("./")) .pipe(gulp.dest(path.join(dirs.target, dirs.static))); }); gulp.task("html-compress", function () { return; // remove, if html views doesn't use Freemarker return gulp.src(getSources()) .pipe(gulpFilter("**/*.html")) .pipe(htmlmin({collapseWhitespace: false})) .pipe(gulp.dest(path.join(dirs.target, dirs.static, "app"))); }); gulp.task("validate-client", function () { runSequence(["html-hint", "js-hint", "css-lint"]); }); gulp.task("html-hint", function () { return gulp.src(getSources()) .pipe(gulpFilter("**/*.html")) .pipe(htmlhint({"doctype-first": false})) .pipe(htmlhint.reporter()); }); gulp.task("js-hint", function () { return gulp.src(getSources()) .pipe(gulpFilter("**/*.js")) .pipe(jshint({expr: true})) .pipe(jshint.reporter("jshint-stylish")); }); gulp.task("css-lint", function () { return gulp.src(getSources()) .pipe(gulpFilter("**/*.css")) .pipe(csslint({ "box-sizing": false, "adjoining-classes": false, "fallback-colors": false, "unqualified-attributes": false, "important": false })) .pipe(csslint.reporter()); }); <file_sep>/src/main/java/com/mgames/testproject/scheduler/Tasks.java package com.mgames.testproject.scheduler; import com.mgames.testproject.resolvers.EmailSenderResolver; import com.mgames.testproject.Variables; import com.mgames.testproject.dao.CommonsDao; import com.mgames.utils.email.Email; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * * @author den */ @Component public class Tasks { private static final Logger log = LoggerFactory.getLogger(Tasks.class.getName()); private static final SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyy"); @Autowired private CommonsDao commonsDao; @Autowired private EmailSenderResolver emailSenderResolver; @Autowired private Variables variables; public void setCommonsDao(CommonsDao commonsDao) { this.commonsDao = commonsDao; } public void setVariables(Variables variables) { this.variables = variables; } public void sendLogbackEmailsJob() { List<String> emails = new ArrayList<>(); emails.addAll(Arrays.asList(variables.LOGBACK_REPORT_EMAILS.split(","))); if (!emails.isEmpty()) { sendEmails(commonsDao.getLogbackPerDay(), emails); } } private void sendEmails(JSONObject logbackJSONObject, List<String> emails) { try { JSONArray errorsJSONArray = logbackJSONObject.getJSONArray("errors"); if (errorsJSONArray.length() == 0) { return; } StringBuilder message = new StringBuilder("<h1 style=\"color: black;\">Отчет ошибок проекта '" + variables.HOST + "' за " + sdf.format(new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24)) + "</h1><br/>"); message.append("<span style=\"color:black;\">"); for (int i = 0; i < errorsJSONArray.length(); i++) { message.append("<p>") .append("EVENT_ID: ").append(errorsJSONArray.getJSONObject(i).getLong("event_id")).append("<br/>") .append("CALLER_CLASS: ").append(errorsJSONArray.getJSONObject(i).getString("caller_class")).append("<br/>") .append("CALLER_METHOD: ").append(errorsJSONArray.getJSONObject(i).getString("caller_method")).append("<br/>") .append("CALLER_LINE: ").append(errorsJSONArray.getJSONObject(i).getString("caller_line")).append("<br/>") .append("FORMATTED_MESSAGE: ").append(errorsJSONArray.getJSONObject(i).getString("formatted_message")).append("<br/>") .append("TIMESTMP: ").append(new Date(errorsJSONArray.getJSONObject(i).getLong("timestmp")).toString()).append("<br/>") .append("DESCRIPTION: ").append(errorsJSONArray.getJSONObject(i).getJSONArray("description").optString(0)).append("<br/>") .append("</p><br/><br/>"); } message.append("</span>"); emailSenderResolver.get().sendEmail(new Email.EmailBuilder("Logback report for " + variables.HOST, "<EMAIL>"). addRecipients(emails).withHtmlPart(message.toString()).build()); } catch (JSONException ex) { log.error("", ex); } } } <file_sep>/src/main/webapp/static/app/common/social/sign.js /* global angular, user, VK, FB, _ */ (function () { "use strict"; angular.module("sign", ["openapi", "oauth", "ngCookies"]) .provider("signSettings", function () { var settings = { autologin: true }; this.$get = function () { return settings; }; }) .run(function ($injector, thirdPartyCookieEnabled, settings) { if (!user && isIframe) { settings.THIRD_PARTY_COOKIE_FIX && thirdPartyCookieEnabled(function (enabled) { if (!enabled) { window.top.location = window.location.protocol + settings.HOST + "api/auth/third_party_cookie_fix.html?redirect=" + encodeURIComponent(document.referrer); } }); document.referrer.contains("://vk.com/") && $injector.get("signVKIframe")(); document.referrer.contains("://ok.ru/") && $injector.get("signOKIframe")(); document.referrer.startsWith("https://apps.facebook.com") && $injector.get("signFB")(); } }) .factory("signVKIframe", function ($rootScope, vkapi, AuthApi, utils, signSettings) { return function () { vkapi.call("users.get", {fields: "sex,bdate,photo_100"}, function (r) { AuthApi.openapiSignIn({net: "vk"}, { session: utils.serializeUrlParams(), user_info: r.response[0] }, function (r) { $rootScope.user = r.user; $rootScope.$broadcast(NG_EVENTS.SIGN.IN, $rootScope.user); }); }); }; }) .factory("signOKIframe", function ($rootScope, okapi, AuthApi, utils, signSettings) { return function () { okapi.call("users.getCurrentUser", {fields: "first_name,last_name,birthday,gender,pic128x128"}, function (r) { AuthApi.openapiSignIn({net: "ok"}, { user_info: r, session_key: utils.serializeUrlParams().session_key, auth_sig: utils.serializeUrlParams().auth_sig }, function (r) { $rootScope.user = r.user; $rootScope.$broadcast(NG_EVENTS.SIGN.IN, $rootScope.user); }); }); }; }) .factory("signVK", function ($rootScope, vkapi, AuthApi, signSettings) { return function () { vkapi.call("users.get", {fields: "sex,bdate,photo_100"}, function (r) { AuthApi.openapiSignIn({net: "vk"}, { session: VK.Auth.getSession(), user_info: r.response[0], autologin: signSettings.autologin }, function (r) { $rootScope.user = r.user; $rootScope.$broadcast(NG_EVENTS.SIGN.IN, $rootScope.user); }); }); }; }) .directive("signVkBtn", function (signVK) { return { restrict: "A", scope: {}, link: function (scope, elem) { elem.on("click", function () { signVK(); }); } }; }) .factory("signFB", function ($rootScope, fbapi, AuthApi, signSettings) { return function () { fbapi.call("/me", {}, function (r) { AuthApi.openapiSignIn({net: "fb"}, { access_token: FB.getAuthResponse().accessToken, autologin: signSettings.autologin }, function (r) { $rootScope.user = r.user; $rootScope.$broadcast(NG_EVENTS.SIGN.IN, $rootScope.user); }); }); }; }) .directive("signFbBtn", function (signFB) { return { restrict: "A", scope: {}, link: function (scope, elem) { elem.on("click", function () { signFB(); }); } }; }) .factory("signOut", function ($rootScope, AuthApi) { return function () { $rootScope.$evalAsync(function () { AuthApi.signOut({}); var tmpUser = $rootScope.user; $rootScope.user = _.noop(); $rootScope.$broadcast(NG_EVENTS.SIGN.OUT, tmpUser); }); }; }) .directive("signOutBtn", function (signOut) { return { restrict: "A", scope: {}, link: function (scope, elem) { elem.on("click", function () { signOut(); }); } }; }) .directive("signVkOauth2Btn", function ($rootScope, AuthApi, utils, vkoauth2, signSettings) { return { restrict: "A", scope: {}, link: function (scope, elem) { elem.on("click", function () { vkoauth2.loginDialog(function () { AuthApi.oauthSignIn({net: "vk"}, {}, function (r) { $rootScope.user = r.user; $rootScope.$broadcast(NG_EVENTS.SIGN.IN, $rootScope.user); }); }); }); } }; }) .directive("signFbOauth2Btn", function ($rootScope, AuthApi, utils, fboauth2, signSettings) { return { restrict: "A", scope: {}, link: function (scope, elem) { elem.on("click", function () { fboauth2.loginDialog(function () { AuthApi.oauthSignIn({net: "fb"}, {}, function (r) { $rootScope.user = r.user; $rootScope.$broadcast(NG_EVENTS.SIGN.IN, $rootScope.user); }); }); }); } }; }) .directive("signOkOauth2Btn", function ($rootScope, AuthApi, utils, okoauth2, signSettings) { return { restrict: "A", scope: {}, link: function (scope, elem) { elem.on("click", function () { okoauth2.loginDialog(function () { AuthApi.oauthSignIn({net: "ok"}, {}, function (r) { $rootScope.user = r.user; $rootScope.$broadcast(NG_EVENTS.SIGN.IN, $rootScope.user); }); }); }); } }; }) .controller("SignUpCtrl", function ($scope, AuthApi, $rootScope) { $scope.master = {}; $scope.submit = function () { if ($scope.form.$invalid) return; AuthApi.signUp({ lname: $scope.master.lname, fname: $scope.master.fname, sname: $scope.master.sname, email: $scope.master.email, phone: $scope.master.phone, repeatPhone: $scope.master.repeatPhone, password: md5($<PASSWORD>), autologin: $scope.master.autologin, bdate: $scope.master.bdate, sex: '1', region: '1', city: $scope.master.city }, function (r) { $rootScope.user = r.user; $rootScope.$broadcast(NG_EVENTS.SIGN.UP, $rootScope.user); $rootScope.$broadcast(NG_EVENTS.SIGN.IN, $rootScope.user); $scope.master = {}; $scope.form.$setPristine(); }, function (e) { switch (e.data.error.code) { case 9: $scope.form.email.$setValidity("already_exists", false); $scope.form.email.$parsers.push(function (value) { $scope.form.email.$setValidity("already_exists", true); return value; }); break; } }); }; }) .controller("SignInCtrl", function ($scope, AuthApi, $rootScope, mgPopup) { $scope.master = {}; $scope.submit = function () { if ($scope.form.$invalid) return; AuthApi.signIn({ email: $scope.master.email, password: <PASSWORD>), autologin: $scope.master.autologin, }, function (r) { $rootScope.user = r.user; $rootScope.$broadcast(NG_EVENTS.SIGN.IN, $rootScope.user); $scope.master = {}; $scope.form.$setPristine(); }, function (e) { switch (e.data.error.code) { case 1: mgPopup("Неверная комбинация e-mail и пароля"); break; } }); }; }) .service("AuthApi", function ($resource) { return $resource("/api/auth/", null, { signIn: {method: "PUT", url: "/api/auth/sign_in"}, signUp: {method: "POST", url: "/api/auth/sign_up"}, signOut: {method: "DELETE", url: "/api/auth/sign_out"}, getUser: {method: "GET", url: "/api/auth/get_user"}, openapiSignIn: {method: "PUT", url: "/api/auth/openapi/sign_in/:net"}, oauthSignIn: {method: "PUT", url: "/api/auth/oauth2/sign_in/:net"} }); }); })();<file_sep>/src/main/webapp/static/app/app.events.js (function () { "use strict"; window.NG_EVENTS = { SIGN: { UP: "SIGN.UP", // регистрация IN: "SIGN.IN", // авторизация OUT: "SIGN.OUT" // де-авторизация }, POPUP: { CLOSED: "POPUP.CLOSED", OPENED: "POPUP.OPENED" }, CUSTOM: { } }; })();<file_sep>/src/main/java/com/mgames/testproject/models/UserInfo.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mgames.testproject.models; import java.sql.Timestamp; import java.time.LocalDate; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p> * @author <NAME> */ public class UserInfo { private static final Logger log = LoggerFactory.getLogger(UserInfo.class.getName()); private final Timestamp birthday; private final String email; private final String lname; private final String fname; private final String sname; private final String phone; private final String repeatPhone; private final String password; private final String region; private final String city; private final String photo; private final int sex; private final String socialId; protected UserInfo(String socialId, String firstName, String lastName, String secondName, String email, String phone, String repeatPhone, String password, Timestamp birthday, int sex, String region, String city, String photo ) { this.socialId = socialId; this.fname = firstName; this.lname = lastName; this.sname = secondName; this.email = email; this.phone = phone; this.repeatPhone = repeatPhone; this.password = <PASSWORD>; this.birthday = birthday; this.sex = sex; this.region = region; this.city = city; this.photo = photo; } public Timestamp getBirthday() { return birthday; } public String getEmail() { return email; } public String getFname() { return fname; } public String getLname() { return lname; } public String getSname() { return sname; } public String getPassword() { return password; } public String getRegion() { return region; } public String getCity() { return city; } public String getPhone() { return phone; } public String getRepeatPhone() { return repeatPhone; } public String getPhoto() { return photo; } public int getSex() { return sex; } public String getSocialId() { return socialId; } public static class UserInfoBuilder { public static UserInfoBuilder email(String lastName, String firstName, String secondName, String email, String phone, String repeatPhone, String password, Timestamp birthday, int sex, String region, String city) { UserInfoBuilder builder = new UserInfoBuilder(); builder.socialId = "email_" + email; builder.lname = lastName; builder.fname = firstName; builder.sname = secondName; builder.email = email; builder.phone = phone; builder.repeatPhone = repeatPhone; builder.password = <PASSWORD>; builder.birthday = birthday; builder.sex = sex; builder.region = region; builder.city = city; return builder; } public static UserInfoBuilder fb(String uid) { UserInfoBuilder builder = new UserInfoBuilder(); builder.socialId = "fb_" + uid; return builder; } public static UserInfoBuilder ok(String uid) { UserInfoBuilder builder = new UserInfoBuilder(); builder.socialId = "ok_" + uid; return builder; } public static UserInfoBuilder vk(String uid) { UserInfoBuilder builder = new UserInfoBuilder(); builder.socialId = "vk_" + uid; return builder; } private Timestamp birthday; private String email; private String lname; private String fname; private String sname; private String phone; private String repeatPhone; private String password; private String region; private String city; private String photo; private int sex = 0; private String socialId; protected UserInfoBuilder() { } public UserInfo build() { return new UserInfo(socialId, fname, lname, sname, email, phone, repeatPhone, password, birthday, sex, region, city, photo); } public UserInfoBuilder withBirthday(Timestamp birthday) { this.birthday = birthday; return this; } public UserInfoBuilder withBirthday(String birthday, String pattern) { if (birthday != null) { try { this.birthday = new Timestamp(LocalDate.parse(birthday, DateTimeFormatter.ofPattern(pattern)).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()); } catch (DateTimeParseException ex) { log.warn("Unparsable date {} with pattern {}", birthday, pattern); } } return this; } public UserInfoBuilder withFirstName(String firstName) { this.fname = firstName; return this; } public UserInfoBuilder withLastName(String lastName) { this.lname = lastName; return this; } public UserInfoBuilder withPhoto(String photo) { this.photo = photo; return this; } public UserInfoBuilder withSex(int sex) { this.sex = sex; return this; } public UserInfoBuilder withSexMaleFemale(String maleOrfemale) { int sex = 0; switch (maleOrfemale) { case "male": withSex(2); break; case "female": withSex(1); break; default: withSex(0); } return this; } } } <file_sep>/src/main/webapp/static/app/removeit/img-cropper/img-cropper.js (function () { "use strict"; angular.module("removeit.imgCropper", []) .controller("removeit.imgCropper.Ctrl", function ($scope) { $(function () {//for img crop 'use strict'; var $image = $('#image'); var options = { aspectRatio: 16 / 9, preview: '.img-preview', checkCrossOrigin: false, //attention viewMode: 2, dragMode: 'move', responsive: true, restore: true, modal: true, guides: true, center: true, highlight: true, background: true, autoCrop: true, autoCropArea: .5, movable: true, rotatable: true }; // Cropper $image.on().cropper(options); // Methods for buttons work $('.docs-buttons').on('click', '[data-method]', function () { var $this = $(this); var data = $this.data(); var $target; var result; if ($this.prop('disabled') || $this.hasClass('disabled')) { return; } if ($image.data('cropper') && data.method) { data = $.extend({}, data); // Clone a new one if (typeof data.target !== 'undefined') { $target = $(data.target); if (typeof data.option === 'undefined') { try { data.option = JSON.parse($target.val()); } catch (e) { console.log(e.message); } } } result = $image.cropper(data.method, data.option, data.secondOption); switch (data.method) { case 'scaleX': case 'scaleY': $(this).data('option', -data.option); break; case 'getCroppedCanvas': if (result) { // Bootstrap's Modal $('#getCroppedCanvasModal').modal().find('.modal-body').html(result); // if (!$download.hasClass('disabled')) { // $download.attr('href', result.toDataURL()); // } } break; } if ($.isPlainObject(result) && $target) { try { $target.val(JSON.stringify(result)); } catch (e) { console.log(e.message); } } } }); // Methods for import image var $inputImage = $('#inputImage'); var URL = window.URL || window.webkitURL; var blobURL; if (URL) { $inputImage.change(function () { var files = this.files; var file; if (!$image.data('cropper')) { return; } if (files && files.length) { file = files[0]; if (/^image\/\w+$/.test(file.type)) { blobURL = URL.createObjectURL(file); $image.one('built.cropper', function () { // Revoke when load complete URL.revokeObjectURL(blobURL); }).cropper('reset').cropper('replace', blobURL); $inputImage.val(''); } else { window.alert('Please choose an image file.'); } } }); } else { $inputImage.prop('disabled', true).parent().addClass('disabled'); } }); }); })();<file_sep>/src/main/java/com/mgames/testproject/models/User.java package com.mgames.testproject.models; import com.mgames.testproject.models.interfaces.JsonConvertible; import java.sql.Timestamp; import java.time.LocalDateTime; import org.apache.commons.codec.digest.DigestUtils; import org.json.JSONException; import org.json.JSONObject; /** * <p> * @author MalyanovDmitry */ public class User implements JsonConvertible { public static String generateSha256Password(String password, String salt) { return DigestUtils.sha256Hex(salt + DigestUtils.sha256Hex(salt + password)); } private LocalDateTime birthday; private final String email; private String fname; private String sname; private final int id; private String lname; private final String password; private String photo; private final String salt; private final int sex; private String region; private String city; private String phone; private String repeatPhone; private final String socialId; public User(int id, String socialId, String firstName, String lastName, String secondName, String email, String phone, String repeatPhone, String password, Timestamp birthday, int sex, String region, String city, String salt, String photo) { this.id = id; this.socialId = socialId; this.fname = firstName; this.lname = lastName; this.sname = secondName; this.email = email; this.phone = phone; this.repeatPhone = repeatPhone; this.password = <PASSWORD>; this.birthday = birthday != null ? birthday.toLocalDateTime() : null; this.sex = sex; this.photo = photo; this.region = region; this.city = city; this.salt = salt; } public boolean checkPassword(String password) { return this.password.equals(generateSha256Password(password, salt)); } public int getId() { return id; } public String getSocialId() { return socialId; } @Override public JSONObject toJson() throws JSONException { return new JSONObject() .put("social_id", socialId) .put("lname", lname) .put("fname", fname) .put("sname", sname) .put("phone", phone) .put("repeatPhone", repeatPhone) .put("birthday", birthday) .put("sex", sex) .put("region", region) .put("city", city) .put("photo", photo); } @Override public String toString() { return "User{" + "email=" + email + ", firstName=" + fname + ", id=" + id + ", lastName=" + lname + ", secondName=" + sname + ", socialId=" + socialId + ", password=" + <PASSWORD> + ", phone=" + phone + ", repeatPhone=" + repeatPhone + ", birthday=" + birthday + ", sex=" + sex + ", region=" + region + ", city=" + city + '}'; } public void update(UserInfo userInfo) { this.lname = userInfo.getLname(); this.fname = userInfo.getFname(); this.sname = userInfo.getSname(); this.phone = userInfo.getPhone(); this.repeatPhone = userInfo.getRepeatPhone(); this.birthday = userInfo.getBirthday() != null ? userInfo.getBirthday().toLocalDateTime() : null; } } <file_sep>/src/main/webapp/static/js/frontend.js (function () { "use strict"; // Верстальщик, пиши код здесь! })();<file_sep>/src/main/java/com/mgames/testproject/controllers/response/OkResponse.java package com.mgames.testproject.controllers.response; import java.util.Map; import org.json.JSONObject; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; /** * * @author <NAME> */ public class OkResponse extends Response { public OkResponse() { this(new JSONObject()); } public OkResponse(JSONObject answer) { super(answer.toString(), HttpStatus.OK); } public OkResponse(Map answer) { this(new JSONObject(answer)); } public OkResponse(JSONObject answer, HttpHeaders customHeaders) { super(answer.toString(), HttpStatus.OK, customHeaders); } public OkResponse(Map answer, HttpHeaders customHeaders) { this(new JSONObject(answer), customHeaders); } } <file_sep>/src/main/webapp/static/js/jcf.main.js $(document).ready(function(){ jcf.replaceAll(); }); <file_sep>/src/main/webapp/static/app/removeit/removeit.js (function () { "use strict"; angular.module("removeit", [ "removeit.authorization", "removeit.api", "removeit.share", "removeit.imgCropper" ]) .config(function ($stateProvider) { $stateProvider.state("removeitAuthorizationJavascript", { url: "/removeit-authorization-javascript", templateUrl: "static/app/removeit/authorization/javascript/javascript.html" }); $stateProvider.state("removeitAuthorizationOauth", { url: "/rm/removeit-authorization-oauth", templateUrl: "static/app/removeit/authorization/oauth/oauth.html" }); $stateProvider.state("removeitAuthorizationEmail", { url: "/removeit-authorization-email", templateUrl: "static/app/removeit/authorization/email/email.html" }); $stateProvider.state("removeitAuthorizationLogin", { url: "/removeit-authorization-login", templateUrl: "static/app/removeit/authorization/login/login.html" }); $stateProvider.state("removeitAuthorizationReg", { url: "/removeit-authorization-reg", templateUrl: "static/app/removeit/authorization/reg/reg.html" }); $stateProvider.state("removeitApiVk", { url: "/removeit-api-vk", templateUrl: "static/app/removeit/api/vk/vk.html", controller: "removeit.api.vk.Ctrl" }); $stateProvider.state("removeitApiFacebook", { url: "/removeit-api-facebook", templateUrl: "static/app/removeit/api/facebook/facebook.html", controller: "removeit.api.facebook.Ctrl" }); $stateProvider.state("removeitApiOk", { url: "/removeit-api-ok", templateUrl: "static/app/removeit/api/ok/ok.html", controller: "removeit.api.ok.Ctrl" }); $stateProvider.state("removeitShare", { url: "/removeit-share", templateUrl: "static/app/removeit/share/share.html", controller: "removeit.share.Ctrl" }); $stateProvider.state("removeitImgCropper", { url: "/removeit-img-cropper", templateUrl: "static/app/removeit/img-cropper/img-cropper.html", controller: "removeit.imgCropper.Ctrl" }); }); })();<file_sep>/src/main/webapp/static/app/removeit/api/facebook/facebook.js (function () { "use strict"; angular.module("removeit.api.facebook", ["openapi", "oauth", "mgPopup"]) .controller("removeit.api.facebook.Ctrl", function ($scope, fbapi, fboauth2) { $scope.master = { method: "me", params: JSON.stringify({fields: "id,first_name,last_name,birthday,gender,email"}) }; $scope.js = function () { if ($scope.form.$invalid) return; fbapi.call($scope.master.method, JSON.parse($scope.master.params), function (r) { showDialog($scope.master.method, r); }); }; $scope.oauth2 = function () { if ($scope.form.$invalid) return; fboauth2.call($scope.master.method, JSON.parse($scope.master.params), function (r) { showDialog($scope.master.method, r); }); }; function showDialog(title, body) { $scope.response = JSON.stringify(body, null, 2); showPopup("responsePopup"); $scope.form.$setPristine(); } }); })();<file_sep>/src/main/webapp/static/app/removeit/share/share.js (function () { "use strict"; angular.module("removeit.share", []) .controller("removeit.share.Ctrl", function ($scope) { $scope.master = { url: "http://google.com/", title: "Это тестовый заголовок", description: "Это тестовое описание", image: "http://placehold.it/150x150" }; }); })();<file_sep>/src/main/java/com/mgames/testproject/controllers/RestController.java package com.mgames.testproject.controllers; import com.mgames.testproject.Strings; import com.mgames.testproject.Variables; import com.mgames.testproject.controllers.response.ErrorResponse; import com.mgames.testproject.controllers.response.ErrorResponse.Error; import com.mgames.testproject.controllers.response.OkResponse; import com.mgames.testproject.controllers.response.Response; import com.mgames.testproject.managers.UsersManager; import com.mgames.testproject.resolvers.FileSaverResolver; import com.mgames.utils.filesaver.FileSaver; import com.mgames.utils.filesaver.SavingPreset; import java.io.IOException; import org.joda.time.DateTime; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; /** <p> @author <NAME> */ @Controller @RequestMapping("api") public class RestController extends BaseController { private static final Logger log = LoggerFactory.getLogger(RestController.class.getName()); @Autowired private FileSaverResolver fileSaverResolver; @Autowired private Strings strings; @Autowired private UsersManager usersManager; @Autowired private Variables vars; @RequestMapping(value = "/multipart", method = RequestMethod.POST) public ResponseEntity<String> multipart(@RequestParam(value = "textparam", required = false) final String textparam, @RequestParam(value = "fileparam", required = false) final MultipartFile file) { HttpHeaders customHeaders = new HttpHeaders(); // for IE customHeaders.add("Content-Type", "text/plain; charset=utf-8"); customHeaders.add("X-XSS-Protection", "0"); customHeaders.set("P3P", "CP=\"IDC DSP COR ADM DEVi TAIi PSA` PSD IVAi IVDi CONi HIS OUR IND CNT\""); if (textparam.isEmpty()) { return new ErrorResponse(Error.PARSE_ARGUMENTS_ERROR, "Поле textparam не заполнено. Пример обработки ошибки на сервере"); } try { SavingPreset preset = SavingPreset.newBuilder() .folder("my_avas") .build(); FileSaver fileSaver = fileSaverResolver.get(); String filename = fileSaver.getHttpPath(fileSaverResolver.get().save(file.getInputStream(), file.getOriginalFilename(), preset), preset); return new OkResponse(new JSONObject() .put("textparam", textparam) .put("new_file", filename), customHeaders); } catch (JSONException ex) { log.error("", ex); return new ErrorResponse(Error.JSON_EXCEPTION); } catch (IOException ex) { log.error("", ex); return new ErrorResponse(Error.INTERNAL_ERROR); } } @RequestMapping(value = "/ping", method = RequestMethod.GET) public Response ping() { try { return new OkResponse(new JSONObject() .put("response", "Hello world!") .put("time", new DateTime().toString())); } catch (JSONException ex) { log.error("", ex); return new ErrorResponse(Error.JSON_EXCEPTION); } } @RequestMapping(value = "/reload_cache", method = RequestMethod.GET) public Response reload_cache() { try { vars.reload(); strings.reload(); usersManager.clear(); return new OkResponse(new JSONObject() .put("response", "cache reloaded") .put("time", new DateTime().toString())); } catch (JSONException ex) { log.error("", ex); return new ErrorResponse(Error.JSON_EXCEPTION); } } } <file_sep>/src/main/webapp/static/app/removeit/authorization/authorization.js (function () { "use strict"; angular.module("removeit.authorization", ["removeit.authorization.javascript", "removeit.authorization.oauth", "removeit.authorization.email", "removeit.authorization.reg", "removeit.authorization.login"]); })();<file_sep>/src/main/webapp/static/app/common/swf/swf.js /* global angular, swfobject, buildNumber */ (function () { "use strict"; angular.module("swf", []) .service("embedSwf", function () { return function (elementId, swfPath, width, height, flashvars, params, attributes) { var el = document.getElementById(elementId); !flashvars && (flashvars = { }); !params && (params = { menu: "false", scale: "noScale", allowFullscreen: "true", allowScriptAccess: "always", bgcolor: "", wmode: "opaque" // can cause issues with FP settings & webcam }); !attributes && (attributes = {}); swfobject.embedSWF(swfPath + "?" + buildNumber, el, width, height, "10.0.0", "static/expressInstall.swf", flashvars, params, attributes); }; }) .service("getSwfObject", function () { return function (elementId) { var M$ = navigator.appName.indexOf("Microsoft") != -1; return (M$ ? window : document)[elementId]; }; }); });<file_sep>/src/main/webapp/static/app/removeit/api/api.js (function () { "use strict"; angular.module("removeit.api", ["removeit.api.vk", "removeit.api.facebook", "removeit.api.ok"]); })();<file_sep>/src/main/webapp/static/app/common/analytics.js /* global angular, _ */ (function () { "use strict"; var firstView = false, firstState; angular.module("analytics", []) .provider("analytics", function () { var useYandexMetrika = false; var yaCounterId; this.setYandexMetrikaId = function (id) { useYandexMetrika = true; yaCounterId = id; }; this.useYandexMetrika = function (value) { if (value && !yaCounterId) return; useYandexMetrika = !!value; }; var useGoogleAnalytics = false; this.useGoogleAnalytics = function (value) { useGoogleAnalytics = !!value; }; var useGoogleTagManager = false; this.useGoogleTagManager = function (value) { useGoogleTagManager = !!value; }; this.$get = ["$log", "$window", "$location", function ($log, $window, $location) { return { event: function (category, event) { if (useGoogleAnalytics) { try { $window.ga("send", "event", category, event); $log.debug("Track GA event: Category: {0}. Event: {1}".format(category, event)); } catch (e) { $log.error("Cannot track GA event"); } } if (useYandexMetrika) { try { $window["yaCounter" + yaCounterId].reachGoal(category, {event: event}); $log.debug("Track Yandex.Metrika event: Category: {0}. Event: {1}".format(category, event)); } catch (e) { $log.error("Cannot track Yandex.Metrika event"); } } if (useGoogleTagManager) { try { $window.dataLayer.push({"title": category, "event": event}); $log.debug("Track GTM event: Title: {0}. Event: {1}".format(category, event)); } catch (e) { $log.error("Cannot track GTM event"); } } }, pageView: function (toState, fromState) { if (useGoogleAnalytics) { $window.ga("send", "pageview", {page: toState.url}); } if (useYandexMetrika) { $window["yaCounter" + yaCounterId].hit(toState.url, toState.name, fromState.name ? fromState.url : _.noop()); } if (useGoogleTagManager) { $window.dataLayer.push({event: "virtualPageView", virtualUrl: toState.url}); } } }; }]; }) .run(function ($rootScope, analytics) { $rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) { if (!fromState.name) { firstState = toState; } }); $rootScope.$on("$stateChangeSuccess", function (event, toState, toParams, fromState, fromParams) { if (firstState == toState && !firstView) { firstView = true; return; } analytics.pageView(toState, fromState); }); }); })(); <file_sep>/src/main/java/com/mgames/testproject/controllers/response/JsonpResponse.java /* */ package com.mgames.testproject.controllers.response; /** * * @author <NAME> */ public class JsonpResponse extends Response { public JsonpResponse(Response response, String callback) { super(";" + callback + "(" + response.getBody() + ");", response.getStatusCode()); } } <file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.mgames</groupId> <artifactId>testproject</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>${project.artifactId}</name> <profiles> <profile> <id>development</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <datasource>jdbc/${project.artifactId}DS</datasource> <profile>development</profile> </properties> </profile> <profile> <id>production</id> <properties> <datasource>jdbc/${project.artifactId}DS</datasource> <profile>production</profile> <debug>false</debug> </properties> <build> </build> </profile> <profile> <id>archetype</id> <build> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>2.6.1</version> <configuration> <filesets> <fileset> <directory>src/main/frontend/node</directory> </fileset> <fileset> <directory>src/main/frontend/node_modules</directory> </fileset> <fileset> <directory>src/main/frontend/bower_components</directory> </fileset> </filesets> </configuration> </plugin> </plugins> </build> </profile> </profiles> <properties> <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <netbeans.hint.deploy.server>Tomcat</netbeans.hint.deploy.server> <spring.version>4.1.5.RELEASE</spring.version> <buildNumber>${maven.build.timestamp}</buildNumber> <maven.build.timestamp.format>yyMMddHHmmssSSS</maven.build.timestamp.format> <debug>true</debug> </properties> <dependencies> <!--Other libs--> <dependency> <groupId>org.liquibase</groupId> <artifactId>liquibase-core</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-web-api</artifactId> <version>6.0</version> <scope>provided</scope> </dependency> <!-- MGames libs --> <dependency> <groupId>com.mgames</groupId> <artifactId>mgAdminFramework</artifactId> <version>0.6.16</version> </dependency> <dependency> <groupId>com.mgames</groupId> <artifactId>mgSocialLib</artifactId> <version>1.1.52</version> <type>jar</type> </dependency> <!-- SPRING --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <!--VAADIN--> <dependency> <groupId>ru.xpoft.vaadin</groupId> <artifactId>spring-vaadin-integration</artifactId> <version>3.1</version> </dependency> </dependencies> <repositories> <repository> <id>vaadin-addons</id> <url>http://maven.vaadin.com/vaadin-addons</url> </repository> </repositories> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>1.8</source> <target>1.8</target> <compilerArguments> <endorseddirs>${endorsed.dir}</endorseddirs> </compilerArguments> <debug>true</debug> </configuration> </plugin> <plugin> <groupId>com.github.eirslett</groupId> <artifactId>frontend-maven-plugin</artifactId> <version>0.0.25</version> <configuration> <workingDirectory>src/main/frontend</workingDirectory> </configuration> <executions> <execution> <id>install node and npm</id> <goals> <goal>install-node-and-npm</goal> </goals> <phase>generate-resources</phase> <configuration> <nodeVersion>v0.12.2</nodeVersion> <npmVersion>2.8.4</npmVersion> </configuration> </execution> <execution> <id>npm install</id> <goals> <goal>npm</goal> </goals> <phase>generate-resources</phase> <configuration> <arguments>install</arguments> </configuration> </execution> <execution> <id>bower prune</id> <goals> <goal>bower</goal> </goals> <phase>generate-resources</phase> <configuration> <arguments>prune</arguments> </configuration> </execution> <execution> <id>bower update</id> <goals> <goal>bower</goal> </goals> <phase>generate-resources</phase> <configuration> <arguments>update</arguments> </configuration> </execution> <execution> <id>gulp build</id> <goals> <goal>gulp</goal> </goals> <phase>package</phase> <configuration> <arguments>${profile} --target=${project.build.finalName} --asset=${profile}</arguments> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> <configuration> <useCache>true</useCache> <failOnMissingWebXml>false</failOnMissingWebXml> <warName>${project.artifactId}</warName> </configuration> <executions> <execution> <!-- First step is to disable the default-war build step. --> <id>default-war</id> <phase>none</phase> </execution> <execution> <!-- Second step is to create an exploded war. Done in prepare-package --> <id>war-exploded</id> <phase>prepare-package</phase> <configuration> <webResources> <resource> <filtering>true</filtering> <directory>src/main/webapp</directory> <includes> <include>ftl/javascripts.ftl</include> <include>WEB-INF/*</include> <include>META-INF/context.xml</include> </includes> </resource> <resource> <filtering>true</filtering> <directory>src/main/resources</directory> <targetPath>WEB-INF/classes</targetPath> <includes> <include>settings.properties</include> <include>logback.xml</include> </includes> </resource> </webResources> </configuration> <goals> <goal>exploded</goal> </goals> </execution> <execution> <!-- Last step is to make sure that the war is built in the package phase --> <id>custom-war</id> <phase>package</phase> <goals> <goal>war</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>2.8</version> <executions> <execution> <phase>validate</phase> <goals> <goal>copy</goal> </goals> <configuration> <outputDirectory>${endorsed.dir}</outputDirectory> <silent>true</silent> <artifactItems> <artifactItem> <groupId>javax</groupId> <artifactId>javaee-endorsed-api</artifactId> <version>6.0</version> <type>jar</type> </artifactItem> </artifactItems> </configuration> </execution> </executions> </plugin> </plugins> </build> </project> <file_sep>/src/main/webapp/static/app/common/mg-popup/mg-popup.js /* global angular */ (function () { "use strict"; angular.module("mgPopup", []) .directive("mgPopup", function ($rootScope, $timeout, $window, $q) { $rootScope.showPopup = $window.showPopup = function (id) { return $q(function (resolve, reject) { var $elem = _.isString(id) ? $("#" + id) : $(id), $directive = $elem.parents(".wrapper-outer").parent(), $wrapperOuter = $directive.children(".wrapper-outer"), $wrapperInner = $wrapperOuter.children(".wrapper-inner"), $overlap = $directive.children(".overlap"); $elem.addClass("show"); $wrapperInner.scrollTop(0); $overlap.addClass("show"); $("html").css("overflow-y", "hidden"); $wrapperOuter.addClass("show"); $timeout(function () { $overlap.addClass("anim"); $wrapperInner.off("click"); $elem.on("click", function (e) { e.stopPropagation(); e.preventDefault(); }); $wrapperInner.on("click", function (e) { e.stopPropagation(); e.preventDefault(); $window.closePopup(id); }); $($window).on("keydown", function (e) { if ((e.keyCode ? e.keyCode : e.which) === 27) $window.closePopup(id); }); $elem.addClass("anim-in"); resolve(); $rootScope.$broadcast(NG_EVENTS.POPUP.OPENED, $elem.attr("id")); }, 100); $wrapperInner.focus(); }); }; $rootScope.closePopup = $window.closePopup = function (id) { return $q(function (resolve) { var $elem = _.isString(id) ? $("#" + id) : $(id), $directive = $elem.parents(".wrapper-outer").parent(), $wrapperOuter = $directive.children(".wrapper-outer"), $overlap = $directive.children(".overlap"); $elem.addClass("anim-out"); $overlap.removeClass("anim"); $timeout(function () { $elem.removeClass("show anim-in anim-out"); $("html").css("overflow-y", "auto"); $wrapperOuter.removeClass("show"); $overlap.removeClass("show"); resolve(); $rootScope.$broadcast(NG_EVENTS.POPUP.CLOSED, $elem.attr("id")); }, 500); }); }; return { restrict: "A", templateUrl: "static/app/common/mg-popup/mg-popup.html", transclude: true, scope: { id: "@mgPopup", show: "=show", youtubeStopOnClose: "=youtubeStopOnClose", // add &enablejsapi=1 to video URL, closeOnTop: "=closeOnTop" }, link: function (scope, elem) { scope.close = function () { if (scope.youtubeStopOnClose) { elem.find("iframe").each(function (i) { this.contentWindow.postMessage("{\"event\":\"command\",\"func\":\"stopVideo\",\"args\":\"\"}", "*"); }); } $window.closePopup(scope.id).then(function () { if (scope.id.startsWith("mgPopupTexting")) elem.remove(); }); }; if (scope.show) { setTimeout(function () { showPopup(scope.id); }); } } }; }) .service("mgPopup", function ($rootScope, $compile) { return function (text) { var date = +new Date(); var templateElement = angular.element( ["<div data-mg-popup=\"mgPopupTexting" + date + "\" data-show=\"true\">", "<div data-ng-bind-html=\"text\"></div>", "</div>"] .join("")); var cloned = $compile(templateElement)($rootScope.$new(true), function (clonedElement, scope) { scope.text = text; $("body").append(clonedElement); }); return function () { cloned.remove(); }; }; }); })(); <file_sep>/src/main/java/com/mgames/testproject/controllers/BaseController.java package com.mgames.testproject.controllers; import com.mgames.testproject.managers.UsersManager; import com.mgames.testproject.models.User; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; /** * * @author <NAME> */ public abstract class BaseController { private static final Logger log = LoggerFactory.getLogger(BaseController.class.getName()); @Autowired private UsersManager usersManager; @Autowired protected HttpServletRequest request; @Autowired protected HttpServletResponse response; @Autowired protected HttpSession session; protected String getUserAgent() { return request.getHeader("user-agent"); } protected String getIp() { String receiverIp = request.getHeader("X-Real-IP"); if (receiverIp == null || receiverIp.equals("") || receiverIp.equals("127.0.0.1")) { String forwardedFor = request.getHeader("x-forwarded-for"); if (forwardedFor != null) { String[] ips = forwardedFor.split(","); if (ips.length > 0) { receiverIp = ips[0].trim(); } } } if (receiverIp == null || receiverIp.equals("") || receiverIp.equals("127.0.0.1")) { receiverIp = request.getRemoteAddr(); } return receiverIp; } protected User getUser() { if (hasUser()) { return usersManager.get(request); } return null; } protected boolean hasUser() { return usersManager.has(request); } protected Map<String, String> parseRequestBody(String requestBody) { Map<String, String> map = new HashMap<>(); try { JSONObject body = new JSONObject(requestBody); Iterator<?> keys = body.keys(); while (keys.hasNext()) { String key = (String) keys.next(); map.put(key, body.get(key).toString()); } } catch (JSONException ex) { log.error("parse arguments error", ex); return map; } return map; } } <file_sep>/src/main/webapp/static/app/removeit/authorization/javascript/javascript.js (function () { "use strict"; angular.module("removeit.authorization.javascript", ["sign"]); })();<file_sep>/src/main/webapp/static/app/common/social/share.js /* global angular */ (function () { "use strict"; angular.module("share", ["app.utils"]) .factory("mgShareDialogFactory", function ($q, utils) { return function (url) { return $q(function (resolve, reject) { utils.openDialog(url, function () { resolve(); }); }); }; }) .service("mgFacebookShare", function (mgShareDialogFactory) { return function (params) { return mgShareDialogFactory(ShareUrl.facebook(params)); }; }) .directive("mgFacebookShare", function (mgFacebookShare) { return { restrict: "A", scope: { params: "=mgFacebookShare" }, link: function (scope, elem) { elem.on("click", function () { mgFacebookShare(scope.params); }); } }; }) .service("mgVkShare", function (mgShareDialogFactory) { return function (params) { return mgShareDialogFactory(ShareUrl.vk(params)); }; }) .directive("mgVkShare", function (mgVkShare) { return { restrict: "A", scope: { params: "=mgVkShare" }, link: function (scope, elem) { elem.on("click", function () { mgVkShare(scope.params); }); } }; }) .service("mgOkShare", function (mgShareDialogFactory) { return function (params) { return mgShareDialogFactory(ShareUrl.ok(params)); }; }) .directive("mgOkShare", function (mgOkShare) { return { restrict: "A", scope: { params: "=mgOkShare" }, link: function (scope, elem) { elem.on("click", function () { mgOkShare(scope.params); }); } }; }) .service("mgTwitterShare", function (mgShareDialogFactory) { return function (params) { return mgShareDialogFactory(ShareUrl.twitter(params)); }; }) .directive("mgTwitterShare", function (mgTwitterShare) { return { restrict: "A", scope: { params: "=mgTwitterShare" }, link: function (scope, elem) { elem.on("click", function () { mgTwitterShare(scope.params); }); } }; }) .service("mgMailRuShare", function (mgShareDialogFactory) { return function (params) { return mgShareDialogFactory(ShareUrl.mailRu(params)); }; }) .directive("mgMailRuShare", function (mgMailRuShare) { return { restrict: "A", scope: { params: "=mgMailRuShare" }, link: function (scope, elem) { elem.on("click", function () { mgMailRuShare(scope.params); }); } }; }) .service("mgGooglePlusShare", function (mgShareDialogFactory) { return function (params) { return mgShareDialogFactory(ShareUrl.googlePlus(params)); }; }) .directive("mgGooglePlusShare", function (mgGooglePlusShare) { return { restrict: "A", scope: { params: "=mgGooglePlusShare" }, link: function (scope, elem) { elem.on("click", function () { mgGooglePlusShare(scope.params); }); } }; }) .service("mgLinkedInShare", function (mgShareDialogFactory) { return function (params) { return mgShareDialogFactory(ShareUrl.linkedIn(params)); }; }) .directive("mgLinkedInShare", function (mgLinkedInShare) { return { restrict: "A", scope: { params: "=mgLinkedInShare" }, link: function (scope, elem) { elem.on("click", function () { mgLinkedInShare(scope.params); }); } }; }); var ShareUrl = { vk: function (params) { return ShareUrl._concat("https://vkontakte.ru/share.php", { url: params.url, title: params.title, description: params.description, image: params.image, noparse: "true" }); }, ok: function (params) { return ShareUrl._concat("https://connect.ok.ru/dk", { "st.shareUrl": params.url, "st.cmd": "WidgetSharePreview" }); }, facebook: function (params) { return ShareUrl._concat("https://www.facebook.com/sharer/sharer.php", { "u": params.url }); }, twitter: function (params) { return ShareUrl._concat("https://twitter.com/intent/tweet", { text: params.description, url: params.url, hashtags: params.hashtags, // comma separated via: params.via, related: params.related }); }, mailRu: function (params) { return ShareUrl._concat("https://connect.mail.ru/share", { url: params.url, title: params.title, description: params.description, imageurl: params.image }); }, googlePlus: function (params) { return ShareUrl._concat("https://plus.google.com/share", { url: params.url }); }, linkedIn: function (params) { return ShareUrl._concat("http://www.linkedin.com/shareArticle", { url: params.url, title: params.title, summary: params.description, mini: true }); }, _concat: function (url, params) { return url + "?" + $.param(params).replace(/&?[^&?]+=(?=(?:&|$))/g, ""); } }; })();<file_sep>/src/main/webapp/static/js/main.js function closePopup(elem) { $("#" + elem).removeClass("show"); } ; function showPopup(elem) { $("#" + elem).addClass("show"); } ; var eventOn = function (elem, event, func) { $(elem).off(event); $(elem).on(event, func); }; var count = 0; eventOn("html.index .man .helper", "click", function () { count++; if (count >= 10) { $("html").addClass("egs"); } }); eventOn(".faq .wrapper .content .list .head", "click", function () { $(this).toggleClass("show"); $(this).parent().find(".text").slideToggle(); }); <file_sep>/src/main/java/com/mgames/testproject/dao/UsersDao.java package com.mgames.testproject.dao; import com.mgames.testproject.db.handlers.UsersDBHandler; import com.mgames.testproject.models.User; import com.mgames.testproject.models.UserInfo; import com.mgames.utils.db.MgDbPool; import java.sql.Timestamp; import java.time.LocalDateTime; import java.time.ZoneId; import javax.servlet.http.Cookie; import org.apache.commons.dbutils.handlers.ScalarHandler; import org.apache.commons.lang3.RandomStringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * <p> * @author <NAME> */ @Component public class UsersDao { @Autowired private MgDbPool pool; public String createAutologinKey(int userId, LocalDateTime expired) { String autologinKey = RandomStringUtils.randomAlphanumeric(16); pool.update("DELETE FROM users_autologin WHERE user_id = ?;" + "INSERT INTO users_autologin(user_id, key, expired) VALUES(?, ?, ?)", userId, userId, autologinKey, Timestamp.from(expired.atZone(ZoneId.systemDefault()).toInstant()) ); return autologinKey; } public User createUser(UserInfo userInfo) { String salt = null; String password = userInfo.getPassword(); if (password != null) { salt = RandomStringUtils.randomAlphabetic(10); password = User.generateSha256Password(password, salt); } return pool.query("INSERT INTO users(social_id, lname, fname, sname, email, phone, repeatphone, " + "password, bdate, sex, region, city, salt, photo) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *", new UsersDBHandler(), userInfo.getSocialId(), userInfo.getLname(), userInfo.getFname(), userInfo.getSname(), userInfo.getEmail(), userInfo.getPhone(), userInfo.getRepeatPhone(), password, userInfo.getBirthday(), userInfo.getSex(), userInfo.getRegion(), userInfo.getCity(), salt, userInfo.getPhoto() ) .stream().findFirst().orElse(null); } public User getUserBySocialId(String socialId) { return pool.query("SELECT * FROM users WHERE social_id=?", new UsersDBHandler(), socialId) .stream().findFirst().orElse(null); } public String getUserSocialId(Integer userId) { return pool.query("SELECT social_id FROM users WHERE id = ?", new ScalarHandler<String>(), userId); } public String getUserSocialId(Cookie autologinCookie) { if (autologinCookie == null) { return null; } return pool.query("SELECT social_id FROM users WHERE id = (SELECT user_id FROM users_autologin WHERE key = ? AND expired > now() LIMIT 1)", new ScalarHandler<String>(), autologinCookie.getValue()); } public void updateLastVisit(int userId) { pool.update("UPDATE users SET last_visit = now() WHERE id = ?", userId); } public void updateUserInfo(int userId, UserInfo userInfo) { pool.update("UPDATE users SET fname = ?, lname = ?, photo = ?, bdate = ?, last_visit=NOW() WHERE id=?", userInfo.getFname(), userInfo.getLname(), userInfo.getPhoto(), userInfo.getBirthday(), userId); } } <file_sep>/src/main/webapp/static/app/removeit/api/ok/ok.js (function () { "use strict"; angular.module("removeit.api.ok", ["oauth", "mgPopup"]) .controller("removeit.api.ok.Ctrl", function ($scope, okoauth2) { $scope.master = { method: "users.getCurrentUser", params: JSON.stringify({fields: "uid, locale, first_name, last_name, name, gender, age, birthday, has_email, current_status, current_status_id, current_status_date, online, photo_id, pic_1, pic_2, location"}) }; $scope.oauth2 = function () { if ($scope.form.$invalid) return; okoauth2.call($scope.master.method, JSON.parse($scope.master.params), function (r) { showDialog($scope.master.method, r); }); }; function showDialog(title, body) { $scope.response = JSON.stringify(body, null, 2); showPopup("responsePopup"); $scope.form.$setPristine(); } }); })();<file_sep>/src/main/webapp/static/js/jquery.main.js $(document).ready(function(){ clearInputs(); initTimer(); initMask(); }); function initMask () { var date = $('.mask-date'); var phone = $('.mask-phone'); var datePlace = date.val(); var phonePlace = phone.val(); $.mask.definitions["j"]="[0123]"; $.mask.definitions["k"]="[01]"; $.mask.definitions["l"]="[12]"; date.mask('j9.k9.l999',{placeholder:datePlace}).val(datePlace).blur(function() { if($(this).val() == '') $(this).val(datePlace); }); phone.mask('+7 (999) 999-99-99',{placeholder:phonePlace}).val(phonePlace).blur(function() { if($(this).val() == '') $(this).val(phonePlace); }); } function initTimer () { $('[data-timer]').each(function(){ var hold = $(this); var data = hold.data('timer').split('|'); var time = { day: data[0].split('.')[0]/1, month: data[0].split('.')[1]/1, year: data[0].split('.')[2]/1, hours: data[1].split(':')[0]/1, minutes: data[1].split(':')[1]/1, seconds: data[1].split(':')[2]/1, }; var newDate = new Date(time.year, time.month-1, time.day, time.hours, time.minutes, time.seconds).getTime(); var dom = { d: hold.find('.days span'), h: hold.find('.hours span'), m: hold.find('.minutes span'), s: hold.find('.seconds span') } var timer = { d:0, h:0, m:0, s:0 } var set = function () { nowDate = new Date().getTime(); if(newDate-nowDate <= 0) if(time) clearTimeout(time); timer.d = Math.floor((newDate-nowDate)/(1000*60*60*24)); timer.h = Math.floor(((newDate-nowDate) - timer.d*(1000*60*60*24))/(1000*60*60)); timer.m = Math.floor(((newDate-nowDate) - timer.d*(1000*60*60*24) - timer.h*(1000*60*60))/(1000*60)); timer.s = Math.floor(((newDate-nowDate) - timer.d*(1000*60*60*24) - timer.h*(1000*60*60) - timer.m*(1000*60))/(1000)); $.each(dom, function(key, val){ timer[key] = timer[key].toString(); if(timer[key].length < 2) timer[key] = '0'+timer[key]; val.eq(0).text(timer[key].charAt(0)); val.eq(1).text(timer[key].charAt(1)); }); } set(); time = setInterval(set, 999); }); } function clearInputs(){ $('input.placeholder, textarea.placeholder').each(function(){ var _el = $(this); var _val = _el.val(); _el.bind('focus', function(){ if (this.value == _val) { this.value = ''; $(this).removeClass('placeholder'); } $(this).addClass('input-focus'); }).bind('blur', function(){ if(this.value == '') { this.value = _val; $(this).addClass('placeholder'); } $(this).removeClass('input-focus'); }); }); } ! function(a) { "function" == typeof define && define.amd ? define(["jquery"], a) : a("object" == typeof exports ? require("jquery") : jQuery) }(function(a) { var b, c = navigator.userAgent, d = /iphone/i.test(c), e = /chrome/i.test(c), f = /android/i.test(c); a.mask = { definitions: { 9: "[0-9]", a: "[A-Za-z]", "*": "[A-Za-z0-9]" }, autoclear: true, dataName: "rawMaskFn", placeholder: " " }, a.fn.extend({ caret: function(a, b) { var c; if (0 !== this.length && !this.is(":hidden")) return "number" == typeof a ? (b = "number" == typeof b ? b : a, this.each(function() { this.setSelectionRange ? this.setSelectionRange(a, b) : this.createTextRange && (c = this.createTextRange(), c.collapse(!0), c.moveEnd("character", b), c.moveStart("character", a), c.select()) })) : (this[0].setSelectionRange ? (a = this[0].selectionStart, b = this[0].selectionEnd) : document.selection && document.selection.createRange && (c = document.selection.createRange(), a = 0 - c.duplicate().moveStart("character", -1e5), b = a + c.text.length), { begin: a, end: b }) }, unmask: function() { return this.trigger("unmask") }, mask: function(c, g) { var h, i, j, k, l, m, n, o; if (!c && this.length > 0) { h = a(this[0]); var p = h.data(a.mask.dataName); return p ? p() : void 0 } return g = a.extend({ autoclear: a.mask.autoclear, placeholder: a.mask.placeholder, completed: null }, g), i = a.mask.definitions, j = [], k = n = c.length, l = null, a.each(c.split(""), function(a, b) { "?" == b ? (n--, k = a) : i[b] ? (j.push(new RegExp(i[b])), null === l && (l = j.length - 1), k > a && (m = j.length - 1)) : j.push(null) }), this.trigger("unmask").each(function() { function h() { if (g.completed) { for (var a = l; m >= a; a++) if (j[a] && C[a] === p(a)) return; g.completed.call(B) } } function p(a) { return g.placeholder.charAt(a < g.placeholder.length ? a : 0) } function q(a) { for (; ++a < n && !j[a];); return a } function r(a) { for (; --a >= 0 && !j[a];); return a } function s(a, b) { var c, d; if (!(0 > a)) { for (c = a, d = q(b); n > c; c++) if (j[c]) { if (!(n > d && j[c].test(C[d]))) break; C[c] = C[d], C[d] = p(d), d = q(d) } z(), B.caret(Math.max(l, a)) } } function t(a) { var b, c, d, e; for (b = a, c = p(a); n > b; b++) if (j[b]) { if (d = q(b), e = C[b], C[b] = c, !(n > d && j[d].test(e))) break; c = e } } function u() { var a = B.val(), b = B.caret(); if (a.length < o.length) { for (A(!0); b.begin > 0 && !j[b.begin - 1];) b.begin--; if (0 === b.begin) for (; b.begin < l && !j[b.begin];) b.begin++; B.caret(b.begin, b.begin) } else { for (A(!0); b.begin < n && !j[b.begin];) b.begin++; B.caret(b.begin, b.begin) } h() } function v() { A(), B.val() != E && B.change() } function w(a) { if (!B.prop("readonly")) { var b, c, e, f = a.which || a.keyCode; o = B.val(), 8 === f || 46 === f || d && 127 === f ? (b = B.caret(), c = b.begin, e = b.end, e - c === 0 && (c = 46 !== f ? r(c) : e = q(c - 1), e = 46 === f ? q(e) : e), y(c, e), s(c, e - 1), a.preventDefault()) : 13 === f ? v.call(this, a) : 27 === f && (B.val(E), B.caret(0, A()), a.preventDefault()) } } function x(b) { if (!B.prop("readonly")) { var c, d, e, g = b.which || b.keyCode, i = B.caret(); if (!(b.ctrlKey || b.altKey || b.metaKey || 32 > g) && g && 13 !== g) { if (i.end - i.begin !== 0 && (y(i.begin, i.end), s(i.begin, i.end - 1)), c = q(i.begin - 1), n > c && (d = String.fromCharCode(g), j[c].test(d))) { if (t(c), C[c] = d, z(), e = q(c), f) { var k = function() { a.proxy(a.fn.caret, B, e)() }; setTimeout(k, 0) } else B.caret(e); i.begin <= m && h() } b.preventDefault() } } } function y(a, b) { var c; for (c = a; b > c && n > c; c++) j[c] && (C[c] = p(c)) } function z() { B.val(C.join("")) } function A(a) { var b, c, d, e = B.val(), f = -1; for (b = 0, d = 0; n > b; b++) if (j[b]) { for (C[b] = p(b); d++ < e.length;) if (c = e.charAt(d - 1), j[b].test(c)) { C[b] = c, f = b; break } if (d > e.length) { y(b + 1, n); break } } else C[b] === e.charAt(d) && d++, k > b && (f = b); return a ? z() : k > f + 1 ? g.autoclear || C.join("") === D ? (B.val() && B.val(""), y(0, n)) : z() : (z(), B.val(B.val().substring(0, f + 1))), k ? b : l } var B = a(this), C = a.map(c.split(""), function(a, b) { return "?" != a ? i[a] ? p(b) : a : void 0 }), D = C.join(""), E = B.val(); B.data(a.mask.dataName, function() { return a.map(C, function(a, b) { return j[b] && a != p(b) ? a : null }).join("") }), B.one("unmask", function() { B.off(".mask").removeData(a.mask.dataName) }).on("focus.mask click.mask", function() { if (!B.prop("readonly")) { clearTimeout(b); var a; E = B.val(), a = A(), b = setTimeout(function() { z(), a == c.replace("?", "").length ? B.caret(0, a) : B.caret(a) }, 10) } }).on("blur.mask", v).on("keydown.mask", w).on("keypress.mask", x).on("input.mask paste.mask", function() { B.prop("readonly") || setTimeout(function() { var a = A(!0); B.caret(a), h() }, 0) }), e && f && B.off("input.mask").on("input.mask", u), A() }) } }) }); <file_sep>/src/main/webapp/static/app/app.router.js /* global angular */ (function () { "use strict"; angular.module("app.router", ["ui.router"]) .config(function ($stateProvider, $urlRouterProvider, $locationProvider, $urlMatcherFactoryProvider) { $stateProvider.getResolveRequst = function (page) { return ["$http", function ($http) { return $http.get("page_data/{0}".format(page)).then(function (data) { return data.data; }); }]; }; var aHost = document.createElement("a"); aHost.href = settings.HOST; // if (aHost.hostname !== window.location.hostname) { // $("base").html("<base href=\"" + window.location + "\" />"); // } else { // $("base").html("<base href=\"" + settings.HOST + "\" />"); // } $stateProvider.state("index", { url: "/", templateUrl: "static/app/index/index.html" }); $stateProvider.state("404", { url: "/404", templateUrl: "static/app/404/404.html" }); $stateProvider.state("crawlertest", { url: "/crawlertest", templateUrl: "static/app/crawlertest/crawlertest.html" }); $urlRouterProvider.when("", "/"); $urlRouterProvider.otherwise("/404"); $locationProvider.html5Mode({ enabled: true, requireBase: false }); $urlRouterProvider.rule(function ($injector, $location) { var path = $location.path(), normalized = path.toLowerCase(); if (path !== normalized) { return normalized; } }); $urlMatcherFactoryProvider.strictMode(false); }) .run(function ($rootScope) { // $rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) { // debugger; // }); $rootScope.$on("$stateChangeSuccess", function (event, toState, toParams, fromState, fromParams) { $rootScope.state = toState; }); }); })();<file_sep>/src/main/java/com/mgames/testproject/controllers/ViewController.java package com.mgames.testproject.controllers; import com.mgames.testproject.Variables; import com.mgames.testproject.controllers.response.OkResponse; import com.mgames.testproject.controllers.response.Response; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; /** * * @author <NAME> */ @Controller public class ViewController extends BaseController { private static final Logger log = LoggerFactory.getLogger(ViewController.class.getName()); private Pattern crawlerPattern = Pattern.compile("bot|googlebot|crawler|spider|robot|crawling", Pattern.CASE_INSENSITIVE); @Autowired private Variables vars; @RequestMapping("{page:^(?!robots.txt$|favicon.ico$|netbeans-tomcat-status-test$).*}") public ModelAndView anyPage(ModelAndView mav, @PathVariable(value = "page") String page) { log.info("this page {}", page); addSettings(mav); addUser(mav); addGlobalData(mav); mav.setViewName("app"); mav.addObject("PAGE", page); mav.addObject("PAGE_PATH", "static/app/" + page + "/" + page + ".html"); if (crawlerPattern.matcher(getUserAgent()).find()) { mav.addObject("CRAWLER", true); log.info("Crawler detected. User agent: {}. Page {}", getUserAgent(), page); } mav.addObject("agent", getUserAgent()); return mav; } @RequestMapping(value = "static/app/{page}/{page}.html") public ModelAndView getPageContent(ModelAndView mav, @PathVariable(value = "page") String page) { mav.setViewName("static/app/" + page + "/" + page); switch (page) { case "index": // add data to page's model break; } return mav; } @RequestMapping(value = "page_data/{page}", method = RequestMethod.GET) public Response getPageData(@PathVariable String page) { JSONObject pageData = new JSONObject(); switch (page) { case "index": // add pageData break; } return new OkResponse(pageData); } @RequestMapping({"/", ""}) public ModelAndView homePage(ModelAndView mav) { return anyPage(mav, "index"); } private void addGlobalData(ModelAndView mav) { JSONObject globalData = new JSONObject(); mav.addObject("globalData", globalData.toString()); } private void addSettings(ModelAndView mav) { try { String base = vars.HOST; URL hostUrl = new URL(request.getScheme() + ":" + base); URL requestUrl = new URL(request.getRequestURL().toString()); if (!hostUrl.getHost().equals(requestUrl.getHost())) { base = "//" + requestUrl.getHost() + "/"; } Map settings = new HashMap<String, Object>() { { put("VK_APP_IFRAME_ID", vars.VK_APP_IFRAME_ID); put("VK_APP_IFRAME_PERMISSIONS", vars.VK_APP_IFRAME_PERMISSIONS); put("VK_APP_IFRAME_URL", vars.VK_APP_IFRAME_URL); put("VK_APP_WEBSITE_ID", vars.VK_APP_WEBSITE_ID); put("VK_APP_WEBSITE_PERMISSIONS", vars.VK_APP_WEBSITE_PERMISSIONS); put("VK_APP_API_VERISON", vars.VK_APP_API_VERISON); put("FB_APP_ID", vars.FB_APP_ID); put("FB_APP_PERMISSIONS", vars.FB_APP_PERMISSIONS); put("FB_APP_URL", vars.FB_APP_URL); put("FB_API_VERSION", vars.FB_API_VERSION); put("OK_APP_ID", vars.OK_APP_ID); put("OK_APP_SCOPE", vars.OK_APP_SCOPE); put("OK_APP_URL", vars.OK_APP_URL); put("HOST", vars.HOST); put("THIRD_PARTY_COOKIE_FIX", vars.THIRD_PARTY_COOKIE_FIX); } }; settings.put("BASE", base); mav.addObject("settings", settings); } catch (MalformedURLException ex) { log.error("", ex); } } private void addUser(ModelAndView mav) { if (hasUser()) { mav.addObject("user", getUser()); } } } <file_sep>/src/main/webapp/static/app/common/social/openapi.js /* global angular, VK, FB, FAPI */ (function () { "use strict"; angular.module("openapi", []) .provider("openapiSettings", function () { var openapiSettings; this.setOpenapiSettings = function (settings) { openapiSettings = settings; }; this.$get = ["settings", function (settings) { if (!openapiSettings) openapiSettings = settings; return openapiSettings; }]; }) .factory("apiFactory", function ($rootScope, utils, $log) { return function () { var self = this; this.init = false; this.logged = false; this.setLogged = function (logged) { $rootScope.$evalAsync(function () { self.logged = logged; self.init = true; }); }; this.loginDialog = function () { $log.error("LoginDialog not implemented yet"); }; this.exec = function (callback) { self.init && !self.logged && (self.loginDialog()); $rootScope.$evalAsync(function () { utils.watchOnce($rootScope, function () { return self.init; }, function () { utils.watchOnce($rootScope, function () { return self.logged; }, function () { callback && callback(); }); }); }); }; }; }) .service("vkapi", function (apiFactory, openapiSettings, $rootScope, utils) { var api = new apiFactory(); if (isIframe) { vkIframeTransport(utils, openapiSettings, function (logged) { api.setLogged(logged); }); } else { vkTransport(openapiSettings, function (logged) { api.setLogged(logged); }); } api.call = function (method, params, callback) { api.exec(function () { if (isIframe) { VK.api(method, params, function (r) { callback && $rootScope.$evalAsync(function () { callback(r); }); }); } else { VK.Api.call(method, params, function (r) { callback && $rootScope.$evalAsync(function () { callback(r); }); }); } }); }; api.loginDialog = function () { var permissionsArray = []; var permissionsMask = 0; for (var i = 0; i < permissionsArray.length; i++) { permissionsMask = permissionsMask | VK.access[permissionsArray[i].toUpperCase()]; } VK.Auth.login(function (response) { }, permissionsMask); }; return api; }) .service("fbapi", function (apiFactory, openapiSettings, $rootScope, utils) { var api = new apiFactory(); fbTransport(openapiSettings, function (logged) { api.setLogged(logged); }); api.call = function (method, params, callback) { api.exec(function () { FB.api(method, params, function (r) { callback && $rootScope.$evalAsync(function () { callback(r); }); }); }); }; api.loginDialog = function () { if (navigator.userAgent.match("CriOS")) { utils.openDialog("https://www.facebook.com/dialog/oauth?client_id={0}&response_type=granted_scopes&scope={1}&redirect_uri={2}&state={3}".format( openapiSettings.FB_APP_ID, openapiSettings.FB_APP_PERMISSIONS, encodeURIComponent("http:" + openapiSettings.HOST + "api/auth/oauth2.html"), "fb_fix_openapi" ), function () { FB.getLoginStatus(function (response) { api.setLogged(response.status === "connected"); }, true); }); } else { FB.login(function (response) { }, {scope: openapiSettings.FB_APP_PERMISSIONS}); } }; return api; }) .service("okapi", function (apiFactory, openapiSettings, $rootScope, utils) { var api = new apiFactory(); okIframeTransport(utils, openapiSettings, function (logged) { api.setLogged(logged); }); api.call = function (method, params, callback) { api.exec(function () { var paramsCloned = angular.copy(params); paramsCloned.method = method; FAPI.Client.call(paramsCloned, function (method, result, data) { callback && $rootScope.$evalAsync(function () { callback(result); }); }); }); }; return api; }); function vkTransport(openapiSettings, callback) { window.vkAsyncInit = function () { VK.init({ apiId: openapiSettings.VK_APP_WEBSITE_ID }); VK.Auth.getLoginStatus(function (response) { callback && callback(!!response.session); }); VK.Observer.subscribe("auth.login", function () { callback && callback(true); }); VK.Observer.subscribe("auth.logout", function () { callback && callback(false); }); }; setTimeout(function () { $("body").append("<div id=\"vk_api_transport\"></div>"); var el = document.createElement("script"); el.type = "text/javascript"; el.src = "//vk.com/js/api/openapi.js"; el.async = true; document.getElementById("vk_api_transport").appendChild(el); }, 0); } function vkIframeTransport(utils, openapiSettings, callback) { utils.loadScript("//vk.com/js/api/xd_connection.js?2", function () { if (!VK.External) return; VK.init(function (r) { VK.callMethod("resizeWindow", 1000, 2000); callback && callback(true); }, function () { }, openapiSettings.VK_APP_API_VERISON); }); } function fbTransport(openapiSettings, callback) { window.fbAsyncInit = function () { FB.init({ appId: openapiSettings.FB_APP_ID, xfbml: true, status: true, version: openapiSettings.FB_API_VERSION }); FB.getLoginStatus(function (response) { callback && callback(response.status === "connected"); }); FB.Event.subscribe("auth.login", function () { callback && callback(true); }); FB.Event.subscribe("auth.logout", function () { callback && callback(false); }); FB.Canvas.setAutoGrow(); }; (function (d, s, id) { $("body").append("<div id=\"fb-root\"></div>"); var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) { return; } js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, "script", "facebook-jssdk")); } function okIframeTransport(utils, openapiSettings, callback) { utils.loadScript("//api.odnoklassniki.ru/js/fapi5.js", function () { var rParams = FAPI.Util.getRequestParameters(); rParams.api_server && rParams.apiconnection && FAPI.init(rParams.api_server, rParams.apiconnection, function (r) { callback && callback(true); } ); }); } })(); <file_sep>/src/main/java/com/mgames/testproject/models/interfaces/JsonConvertible.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mgames.testproject.models.interfaces; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * * @author <NAME> */ public interface JsonConvertible { public static JSONArray toJSONArray(List<? extends JsonConvertible> list) throws JSONException { JSONArray result = new JSONArray(); for (JsonConvertible object : list) { result.put(object.toJson()); } return result; } public JSONObject toJson() throws JSONException; }
943a62f8d92cacbffb921cf3ca51688da6aab1c4
[ "JavaScript", "Java", "Maven POM" ]
32
JavaScript
egus032/testproject_3-master
fa2a1c2753da6d2347d7a584a28f8af4ba9f8bbb
8c27a5c5c088f826efaeff3f7cf5fe0ab75d9a8e
refs/heads/master
<repo_name>anmuro7/TheObjectHome<file_sep>/app/src/main/java/com/example/toni/app_the_object_home/AdaptadorPrincipal.java package com.example.toni.app_the_object_home; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.support.v4.graphics.drawable.RoundedBitmapDrawable; import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.target.BitmapImageViewTarget; /** * Created by Toni on 30/11/2017. */ public class AdaptadorPrincipal extends CursorAdapter { public AdaptadorPrincipal(Context context, Cursor c) { super( context, c,0 ); } //<<<<<<<<<<<MÉTODO EN EL QUE INDICAMOS LA PLANTILLA QUE UTILIZAREMOS >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { final LayoutInflater inflater = LayoutInflater.from(context); final View view = inflater.inflate(R.layout.listado_productos, parent, false); return view; } //<<<<<<<<<<<<<<<<<MÉTODO EN EL QUE INSERTAREMOS LOS VALORES DE LA BD EN EL LISTADO >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> @Override public void bindView(View view, final Context context, Cursor cursor) { //Definimos los contenedores donde insertaremos la información final ImageView contImagen = (ImageView)view.findViewById( R.id.fotoProducto ); TextView contNombre= (TextView)view.findViewById( R.id.nombreProducto ); TextView contPrecio=(TextView)view.findViewById( R.id.precioProducto ); //Esxtraemos de la BD los datos a insertar en el contenedor String image=cursor.getString( cursor.getColumnIndex( DataBaseManager.CN_IMAGE )); String name=cursor.getString( cursor.getColumnIndex( DataBaseManager.CN_NAME )); String price=cursor.getString( cursor.getColumnIndex( DataBaseManager.CN_PRICE )); //Insertamos los valores extraidos dentro de los contenedores definidos //imagen de producto Glide .with(context) .load(Uri.parse("android.resource://com.example.toni.app_the_object_home/drawable/"+image )) .asBitmap() .error(R.drawable.ic_launcher_foreground) .centerCrop() .into(new BitmapImageViewTarget(contImagen) { @Override protected void setResource(Bitmap resource) { RoundedBitmapDrawable drawable = RoundedBitmapDrawableFactory.create(context.getResources(), resource); drawable.setCircular(false); contImagen.setImageDrawable(drawable); } }); //A continuación insertamos los textos dentro de los campos correspondientes contNombre.setText( name ); contPrecio.setText( price+" €"); } } <file_sep>/README.txt App The Object Home Version 1.0 05/01/2018 GENERAL USAGE NOTES ---------------------------------------------------------------------------------------- - This is an application of an online shop - The application has a product search engine, to facilitate the user access to these. -It has a functional and operative shopping cart allowing the user to modify the quantity or elimination the products - The application allows to order the products according to the choose of the user. - the application has two menus with which you can navigate through it ---------------------------------------------------------------------------------------- Minimum installation from Android API 18 ---------------------------------------------------------------------------------------- The minimum version of Android that supports this application is API 18. It works correctly for higher versions. To make it work, it is recommended to use the Genymotion emulation App testing in Google Galaxy Nexus - 4.3 - API 18 ---------------------------------------------------------------------------------------- IF YOU HAVE PROBLEMS WITH THIS SOFTWARE,YOU CAN CONTACT ME: Phone: 658981895 Web_site: www.theobjecthome.com E-mail:<EMAIL> ---------------------------------------------------------------------------------------- Copyright (c) <2018> <<NAME>> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE<file_sep>/app/src/main/java/com/example/toni/app_the_object_home/Ficha.java package com.example.toni.app_the_object_home; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.Parcelable; import android.support.v4.app.Fragment; import android.support.v4.graphics.drawable.RoundedBitmapDrawable; import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.bumptech.glide.request.target.BitmapImageViewTarget; import java.util.ArrayList; public class Ficha extends Fragment { private DataBaseManager manager; private Cursor cursor; //declaramos las variables que usaremos para almacenar los datos de consulta private String name; private String image; private String price; private String description; private View view; public Ficha() { // Required empty public constructor } public static Ficha newInstance(){ return new Ficha(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment view= inflater.inflate( R.layout.fragment_ficha, container, false ); //Creamos una instancia para la iniciación de la base de datos manager=new DataBaseManager(getContext()); //extraemos el dato enviado desde el anterior fragment String myValue = this.getArguments().getString("nombre"); //cargamos el cursor donde almacenamos la consulta a la BD cursor= manager.cargaCursorPorNombre(myValue); //extraemos los datos del cursor if(cursor.getCount() >=1){ while(cursor.moveToNext()){ image=cursor.getString( cursor.getColumnIndex( DataBaseManager.CN_IMAGE )); name=cursor.getString( cursor.getColumnIndex( DataBaseManager.CN_NAME )); price=cursor.getString( cursor.getColumnIndex( DataBaseManager.CN_PRICE )); description=cursor. getString( cursor.getColumnIndex( DataBaseManager.CN_DESCRIPTION ) ); } } //Localizamos los contenedores para añadir los datos y dar funcionalidades final ImageView fotoFicha=(ImageView)view.findViewById( R.id.fotoFicha ); final TextView nombreFicha=(TextView)view.findViewById( R.id.productoEnFicha ); TextView precioFicha=(TextView)view.findViewById( R.id.precioEnFicha ); TextView descripcionFicha=(TextView)view.findViewById( R.id.descripcionEnFicha ); TextView cantidadCarro=(TextView)view.findViewById( R.id.cantidadCarrito ); //Añadimos los valores a los contenedores Glide .with(getContext()) .load(Uri.parse("android.resource://com.example.toni.app_the_object_home/drawable/"+image )) .asBitmap() .error(R.drawable.ic_launcher_foreground) .centerCrop() .into(new BitmapImageViewTarget(fotoFicha) { @Override protected void setResource(Bitmap resource) { RoundedBitmapDrawable drawable = RoundedBitmapDrawableFactory.create(getContext().getResources(), resource); drawable.setCircular(false); fotoFicha.setImageDrawable(drawable); } }); //A continuación insertamos los textos dentro de los campos correspondientes nombreFicha.setText( name ); precioFicha.setText( price+" €"); descripcionFicha.setText( description ); //Localizamos los botones Button btnMas=(Button)view.findViewById( R.id.buttonMas ); //le aplicamos la funcionalidad btnMas.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { //Extraemos el valor del contenedor con la cantidad EditText cantidadElegida=view.findViewById( R.id.cantidadFicha ); String cantidadText=cantidadElegida.getText().toString(); cantidadElegida.setText( sumaNumero( cantidadText ) ); } } ); Button btnMenos=(Button)view.findViewById( R.id.buttonMenos ); btnMenos.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { //Extraemos el valor de la cantidad actual seleccionada EditText cantidadElegida=view.findViewById( R.id.cantidadFicha ); String cantidadText=cantidadElegida.getText().toString(); cantidadElegida.setText( restaNumero( cantidadText ) ); } } ); //A continuación asignamos las funciones al botón de compra Button btnCompra=(Button)view.findViewById( R.id.buttonCompra ); //le asignamos la funcionalidad btnCompra.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { //Extraemos el valor de la cantidad actual seleccionada EditText cantidadElegida=view.findViewById( R.id.cantidadFicha ); String cantidadText=cantidadElegida.getText().toString(); //llamamos al metodo de la activity que inserta los datos en el arrayList ((MainActivity)getActivity()).insertaCarro(name,cantidadText,price,image); //Creames el Alert Dialog y le pasamos los valores para añadir al carro createLoginDialogo(); } } ); // Inflate the layout for this fragment return view; } //mètodo que suma cantidades public String sumaNumero(String cantidadActual){ int nuevaCantidad=Integer.parseInt( cantidadActual )+1; return Integer.toString( nuevaCantidad ); } //metodo que resta cantidades public String restaNumero(String cantidadActual){ int nuevaCantidad=Integer.parseInt( cantidadActual )-1; if(nuevaCantidad<1){ Toast.makeText( getContext(),"El número mínimo de productos es 1",Toast.LENGTH_SHORT ).show(); return cantidadActual; }else{ return Integer.toString( nuevaCantidad ); } } public AlertDialog createLoginDialogo() { final AlertDialog alertDialog; //añadimos el objeto producto al arraylist, al pulsar el botón el usuario ya h decidido añadirlo //posteriormente según la decisión que tome lo pasamos o esperamos //.add( productos ); //Le indicamos que tiene que mostrar nuestro Alert Dialog personalizado AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); View v = inflater.inflate(R.layout.dialog_compra, null); builder.setView(v); //Permitimos que el ususario pueda cerrar el alertdialog al hacer clic fuera de él builder.setCancelable( true ); //localizamos los botones de nuestro alertdialog para crear su funcionalidad Button goCarro = (Button) v.findViewById(R.id.irCarro); Button continueBuy = (Button) v.findViewById(R.id.continuarCompra); //creamos y mostramos el alertdialog alertDialog= builder.create(); alertDialog.show(); //cuando el usuario quiera finalizar su compra e ir al carro... goCarro.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { Carrodecompra carro=new Carrodecompra(); getFragmentManager().beginTransaction().replace( R.id.contenedor,carro ).addToBackStack( null ).commit(); alertDialog.dismiss(); } } ); //cuando el usuario quiera continuar con su compra... continueBuy.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { alertDialog.dismiss(); } } ); //devolvemos el alertdialog return alertDialog; } } <file_sep>/app/src/main/java/com/example/toni/app_the_object_home/FragmentDecoracion.java package com.example.toni.app_the_object_home; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.GridView; import android.widget.Spinner; import android.widget.TextView; public class FragmentDecoracion extends Fragment { private DataBaseManager manager; private Cursor cursor; private GridView lista; private AdaptadorPrincipal adapter; public FragmentDecoracion() { // Required empty public constructor } public static FragmentDecoracion newInstance(){ return new FragmentDecoracion(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //Creamos una instancia para la iniciación de la base de datos manager=new DataBaseManager(getContext()); //insertamos los datos en la BD manager.CargaDatosDB(); View view = inflater.inflate(R.layout.fragment_fragment_decoracion, container, false); //Extraemos el valor pasado por el navigation drawer y asi saber que elementos mostrar final String myValue = this.getArguments().getString("categoria"); TextView Titulo= view.findViewById( R.id.titleBusqueda ); //insertamos el titulo de la categoria Titulo.setText( myValue ); TextView titleSpinnerCatalogo=(TextView)view.findViewById( R.id.titleSpnCatalogo ); Spinner spnCatalogo=(Spinner)view.findViewById( R.id.spnCatalog ); TextView numeroProductos=(TextView)view.findViewById( R.id.productosCategoria ); //Creamos el String que contiene las dos opciones String[] opciones={"Mejor coincidencia","Menor precio","Mayor precio"}; //Utilizamos un adaptador para colocar las opciones dentro del Spinner ArrayAdapter adapterSpinner = new ArrayAdapter<String>(getContext(),R.layout.item_spinner, opciones); spnCatalogo.setAdapter( adapterSpinner ); //INSERTAMOS EN EL GRIDVIEW LOS PRODUCTOS DE LA CATEGORIA CORRESPONDIENTE if (myValue=="DECORACION"){ //localizamos la lista donde usaremos el adapter lista=(GridView)view.findViewById(R.id.listaDecoración); //cargamos el cursor donde almacenamos la consulta a la BD cursor=manager.cargaCursorCatalogo( myValue ); //Creamos una instancia a nuestro Adaptador y le pasamos el cursor con los datos almacenados para que haga //el tratamiento //añadimos el número de productos disponibles en la categoria donde nos encontremos numeroProductos.setText( cursor.getCount()+" ARTÍCULOS" ); adapter= new AdaptadorPrincipal( getContext(),cursor ); //insertamos los datos en nuestra lista lista.setAdapter( adapter ); }else if(myValue=="MOBILIARIO"){ //localizamos la lista donde usaremos el adapter lista=(GridView)view.findViewById(R.id.listaDecoración); //cargamos el cursor donde almacenamos la consulta a la BD cursor=manager.cargaCursorCatalogo( myValue ); //añadimos el número de productos disponibles en la categoria donde nos encontremos numeroProductos.setText( cursor.getCount()+" ARTÍCULOS" ); //Creamos una instancia a nuestro Adaptador y le pasamos el cursor con los datos almacenados para que haga //el tratamiento adapter= new AdaptadorPrincipal( getContext(),cursor ); //insertamos los datos en nuestra lista lista.setAdapter( adapter ); }else if(myValue=="ILUMINACION"){ //localizamos la lista donde usaremos el adapter lista=(GridView)view.findViewById(R.id.listaDecoración); //cargamos el cursor donde almacenamos la consulta a la BD cursor=manager.cargaCursorCatalogo( myValue ); //añadimos el número de productos disponibles en la categoria donde nos encontremos numeroProductos.setText( cursor.getCount()+" ARTÍCULOS" ); //Creamos una instancia a nuestro Adaptador y le pasamos el cursor con los datos almacenados para que haga //el tratamiento adapter= new AdaptadorPrincipal( getContext(),cursor ); //insertamos los datos en nuestra lista lista.setAdapter( adapter ); }else if(myValue=="TEXTIL"){ //localizamos la lista donde usaremos el adapter lista=(GridView)view.findViewById(R.id.listaDecoración); //cargamos el cursor donde almacenamos la consulta a la BD cursor=manager.cargaCursorCatalogo( myValue ); //añadimos el número de productos disponibles en la categoria donde nos encontremos numeroProductos.setText( cursor.getCount()+" ARTÍCULOS" ); //Creamos una instancia a nuestro Adaptador y le pasamos el cursor con los datos almacenados para que haga //el tratamiento adapter= new AdaptadorPrincipal( getContext(),cursor ); //insertamos los datos en nuestra lista lista.setAdapter( adapter ); } //listener para los clic en el GridView lista.setOnItemClickListener (new AdapterView.OnItemClickListener () { @Override public void onItemClick (AdapterView <?> parent, View view, int position, long id) { //Se busca la referencia del TextView en la vista. TextView textView = (TextView) view.findViewById(R.id.nombreProducto); //Obtiene el texto dentro del TextView de la celda. String textItemList = textView.getText().toString(); Bundle bundle = new Bundle(); bundle.putString("nombre", textItemList); Ficha ficha =new Ficha(); ficha.setArguments( bundle ); getFragmentManager().beginTransaction().replace( R.id.contenedor,ficha ).addToBackStack( null ).commit(); //getSupportFragmentManager().beginTransaction().replace(R.id.contenedor,fragmentDeco).addToBackStack(null).commit(); } }); //listener para definir las acciones del spinner spnCatalogo.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener( ) { @Override public void onItemSelected(AdapterView <?> parent, View view, int position, long id) { if(position==0){ cursor=manager.cargaCursorCatalogo( myValue ); adapter.changeCursor( cursor ); }else if (position==1){ cursor = manager.ordenarCatalogoAscendente(myValue); adapter.changeCursor( cursor ); }else if(position==2){ cursor = manager.ordenarCatalogoDescendente(myValue); adapter.changeCursor( cursor ); } } @Override public void onNothingSelected(AdapterView <?> parent) { } } ); return view; } }
10c8c716a1bf51fb469bc47ad11a149b2e1bcfbc
[ "Java", "Text" ]
4
Java
anmuro7/TheObjectHome
ee60d52954e76a34d0567e59eedd6629be02b6b7
7525b91f1cd933917c0a44e4bee8ef904b86bec2
refs/heads/master
<repo_name>dlsimpao/PokeApp<file_sep>/global.R # packages library(shiny) library(shinythemes) library(shinycssloaders) library(shinyWidgets) library(tidyverse) library(knitr) library(ggfortify) library(plotly) library(FNN) library(jsonlite) library(lubridate) library(httr) library(rvest) library(shinyjs) library(gtrendsR) # To install packages <- c( "shiny", "shinythemes", "shinycssloaders", "shinyWidgets", "tidyverse", "knitr", "ggfortify", "plotly", "FNN", "jsonlite", "lubridate", "httr", "rvest", "shinyjs", "gtrendsR" ) # Inspired by https://github.com/ThiagoValentimMarques/The-ten-most-similar-players-Pro-Evolution-Soccer-2019 # package.check <- lapply(packages, FUN = function(x) { # if (!require(x, character.only = TRUE)) { # install.packages(x, dependencies = TRUE) # } # }) links <- data.frame( api_mon = "https://pokeapi.co/api/v2/pokemon", api_nat = "https://pokeapi.co/api/v2/nature", db_stats = "https://pokemondb.net/pokedex/all", db_spr = "https://pokemondb.net/pokedex/national", db_item = "https://pokemondb.net/item/all", db_ab = "https://pokemondb.net/ability", db_move = "https://pokemondb.net/move/all", stringsAsFactors = FALSE ) # API Requests # rname <- GET(links$api_mon, query = list(limit = 897)) rnat <- GET(links$api_nat, query = list(limit = 60)) stop_for_status(rname) stop_for_status(rnat) jname <- content(rname, as = "text") %>% fromJSON() jnat <- content(rnat, as = "text") %>% fromJSON() # df of names and url api_mons <- as.data.frame(jname$results) # all mons with hypenated names hype_names <- api_mons[grepl("-", api_mons$name), ] # list of natures natures <- jnat$results$name # Web Scraping # # `html`: sprites html <- read_html(links$db_spr) # list of sprite pngs sprites <- html %>% html_nodes("span.infocard-lg-img") %>% html_nodes(".img-fixed.img-sprite") %>% html_attr("data-src") # names available in the PokeDB dbnames <- html %>% html_nodes("a.ent-name") %>% html_text() %>% as.data.frame() # rename columns to 'name' colnames(dbnames) <- "name" dbmon_sprites <- tibble(dbnames) %>% mutate(name = str_to_lower(name), sprite = sprites) # add new sprites png (Nidoran, Mr. Mime, other Megas not matched) dbsprites <- left_join(api_mons, dbmon_sprites, by = "name") %>% select(name, sprite) %>% filter(!is.na(sprite)) # More Web Scraping # html2 <- read_html(links$db_item) # items html3 <- read_html(links$db_ab) # abilities html4 <- read_html(links$db_move) # moves html5 <- read_html(links$db_stats) # stats # `html2`: items items <- html2 %>% html_nodes("table.data-table.block-wide") %>% html_table() %>% as.data.frame() %>% tibble() # Table of item information - filtered on usable held items usable_items <- items %>% filter(Category %in% c("Hold items", "Berries")) %>% arrange(Category) # `html3`: abilities ab_info <- html3 %>% html_nodes("table#abilities") %>% html_table() %>% as.data.frame() %>% tibble() # Table of ability information ab_info <- ab_info %>% select(Name, Description) %>% mutate(Name = sub("\\s", "-", .$Name)) # `html4`: attacks atk_info <- html4 %>% html_nodes("table#moves") %>% html_table() %>% as.data.frame() %>% tibble() # Table of attack information atk_info <- atk_info %>% select(Name, Type, Power, `Acc.`, Effect) # %>% mutate(Name = sub(' +','-',.$Name)) # `html5`: stats dbstats <- html5 %>% html_nodes("table#pokedex") %>% html_table() %>% as.data.frame() %>% tibble() dbstats <- dbstats %>% select(`X.`, Name, Total, HP, Attack, Defense, `Sp..Atk`, `Sp..Def`, Speed) %>% mutate(Name = str_to_lower(Name)) # Modify dbstats names to match api_mons names temp <- dbstats %>% mutate(Name = case_when( grepl("<U+2640>", Name) ~ gsub("<U+2640>", "-f", Name), grepl("<U+2642>", Name) ~ gsub("<U+2642>", "-m", Name), grepl("é", Name) ~ gsub("é", "e", Name), grepl("(meganium|yanmega)", Name) ~ Name, # <- important potential bug grepl("mimikyu", Name) ~ "mimikyu-disguised", grepl("(mega charizard )", Name) ~ gsub("(mega charizard )", "-mega-", Name), grepl("(mega mewtwo )", Name) ~ gsub("(mega mewtwo )", "-mega-", Name), grepl("(mega)", Name) ~ gsub("(mega).*", "-mega", Name), grepl("(\\. )", Name) ~ gsub("(. )", "-", Name), grepl("(\\: )", Name) ~ gsub("(. )", "-", Name), grepl("\\.$", Name) ~ gsub("\\.$", "", Name), grepl("( form).*", Name) ~ gsub("( form).*", "", Name), grepl(".(mode|cloak|kyogre|groudon|rotom|style|kyurem|size)$", Name) ~ gsub(".(mode|cloak|kyogre|groudon|rotom|style|kyurem|size)$", "", Name), grepl("^hoopa", Name) ~ gsub("^hoopa", "", Name), TRUE ~ Name )) regexMons <- "(castform|kyogre|groudon|deoxys|wormadam|rotom|giratina|basculin|darmanitan|tornadus|landorus|thundurus| kyurem|meloetta|aegislash|oricorio|shaymin|keldeo|lycanroc|wishiwashi|gourgeist|pumpkaboo|meowstic|indeedee)" temp <- temp %>% mutate(Name = case_when( grepl(paste0(regexMons, "[^-]"), Name) ~ gsub(regexMons, "\\1-", Name), grepl("(minior)[^-]", Name) ~ gsub("(minior)", "\\1-red-", Name), grepl(".(confined)", Name) ~ gsub(".(confined)", "", Name), grepl("(complete|ultra-necrozma)", Name) ~ gsub("(complete|ultra-necrozma)", "", Name), grepl("\\s", Name) ~ gsub("\\s", "-", Name), grepl(".{2}%", Name) ~ gsub(".{2}%", "", Name), grepl("'", Name) ~ gsub("'", "", Name), TRUE ~ Name )) # LEFT JOIN with api_mons; Table of stats info stat_info <- left_join(api_mons, temp, by = c("name" = "Name")) %>% select(name, Total, HP, Attack, Defense, `Sp..Atk`, `Sp..Def`, Speed) %>% drop_na() # Pokemon Roles based on stats # Physical Sweeper ps <- stat_info[[4]] + stat_info[[8]] # Special Sweeper ss <- stat_info[[6]] + stat_info[[8]] # Wall w <- stat_info[[3]] + stat_info[[5]] + stat_info[[7]] # Physical Tank pt <- stat_info[[4]] + stat_info[[5]] # Special Tank st <- stat_info[[6]] + stat_info[[7]] stat_role <- tibble( name = stat_info[1], `Physical Sweeper` = ps, `Special Sweeper` = ss, # Wall = w, `Physical Tank` = pt, `Special Tank` = st ) role <- colnames(stat_role)[max.col(stat_role[2:5], ties.method = "first") + 1] set.seed(151) stat_role <- stat_role %>% mutate(role = role) ############### Role Desc ################### roleDesc <- tibble( ps = "This Pokémon has good Attack and Speed stats. To do well, it needs to outspeed the opponent's team and deal heavy damage. Here is an example of Physical Sweeper:<br><br> Lucario @ Life Orb <br>Ability: Inner Focus <br>EVs: 4 HP / 252 Atk / 252 Spe <br>Adamant nature <br>- Swords Dance <br>- Close Combat <br>- ExtremeSpeed <br>- Crunch", ss = "This Pokémon has good Special Attack and Speed stats. To do well, it needs to outspeed the opponent's team and deal heavy damage. Here is an example of Special Sweeper:<br><br> Starmie @ Leftovers <br>Ability: Natural Cure <br>EVs: 42 HP / 216 Spe / 252 SpA <br>Timid Nature <br>- Surf <br>- Ice Beam <br>- Thunderbolt <br>- Recover", pt = "This Pokémon has good Attack and Defense stats. To do well, it must take the brunt of the opposing team's damage and wear them down. Here is an example of Physical Tank:<br><br> Steelix @ Leftovers <br>Ability: Sturdy <br>EVs: 252 HP / 80 Atk / 176 Def <br>Impish Nature <br>- Earthquake <br>- Rock Slide <br>- Explosion <br>- Toxic", st = "This Pokémon has good Special Attack and Special Defense stats. To do well, it must take the brunt of the opposing team's damage and wear them down. Here is an example of Special Tank:<br><br> Blissey @ Leftovers <br>Ability: Natural Cure <br>EVs: 252 HP / 252 Def / 4 SpD <br>Bold Nature <br>- Seismic Toss <br>- Toxic <br>- Soft-Boiled <br>- Heal Bell" ) <file_sep>/ui.R ui <- fluidPage( theme = shinytheme("united"), # test tags$head( tags$link(rel = "stylesheet", type = "text/css", href = "card.css"), tags$link(rel = "stylesheet", type = "text/css", href = "polaroid.css") ), headerPanel("Poké Battle Matchup"), sidebarPanel( navbarPage("Trainers:", id = "tabs", tabPanel( " You ", helpText("Generation VIII not included."), textOutput("mytypes"), fluidRow( column( 9, selectInput( "mon", "Pokemon", str_to_title(api_mons$name) %>% gsub("-", " ", .), "Pikachu Phd" ) ), column(3, style = "margin-top: 24px; width: auto", actionButton("mongo", "I choose you!") ) ), br(), br(), selectInput("ability", "Ability", ""), textOutput("ability-info"), br(), selectInput("nature", "Nature", c("-", str_to_title(natures)), "-"), selectInput("item", "Held Item", c("-", str_to_title(usable_items$Name)), "-"), textOutput("item-info"), br(), helpText("Pokémon can learn at most 4 moves for battle."), selectizeInput("moves", "See Learnable Moves", "-", multiple = TRUE, options = list(maxItems = 4) ), actionButton("script", "Generate Pokémon File"), helpText(HTML("Formats the Pokémon's information. <br> Attributes included: Item, Ability, EVs, Nature, Moves <br> (Websites like <a>Pokemon Showdown</a> can import this file.)")), br(), br(), br(), br(), h2("Effort Values (EVs)", align = "center"), helpText("Effort Values help raise your total base stats.", textOutput("ev")), sliderInput("hp", "HP", 0, 252, 0, step = 4), sliderInput("atk", "Attack", 0, 252, 0, step = 4), sliderInput("spatk", "Sp. Attack", 0, 252, 0, step = 4), sliderInput("def", "Defense", 0, 252, 0, step = 4), sliderInput("spdef", "Sp. Defense", 0, 252, 0, step = 4), sliderInput("spd", "Speed", 0, 252, 0, step = 4) ), tabPanel( "Rival", helpText("Generation VIII not included."), textOutput("opptypes"), fluidRow( column( 9, selectInput( "mon2", "Pokemon", str_to_title(api_mons$name) %>% gsub("-", " ", .), "Blissey" ) ), column(3, style = "margin-top: 24px; width: auto", actionButton("mongo2", "I choose you!") ) ), br(), br(), selectInput("ability2", "Ability", ""), textOutput("ability-info2"), br(), selectInput("nature2", "Nature", c("-", str_to_title(natures)), selected = "-"), selectInput("item2", "Held Item", c("-", str_to_title(usable_items$Name)), selected = "-"), textOutput("item-info2"), br(), helpText("Pokémon can learn at most 4 moves for battle."), selectizeInput("moves2", "See Learnable Moves", "-", multiple = TRUE, options = list(maxItems = 4) ), actionButton("script2", "Generate Pokémon File"), helpText(HTML("Generates a text file that stores Pokémon info in a specified format. <br> Attributes included: Item, Ability, EVs, Nature, Moves <br> (Websites like <a>Pokemon Showdown</a> can import this file.)")), br(), br(), br(), br(), h2("Effort Values (EVs)", align = "center"), helpText("Effort Values help raise your total base stats.", textOutput("ev2")), sliderInput("hp2", "HP", 0, 252, 0, step = 4), sliderInput("atk2", "Attack", 0, 252, 0, step = 4), sliderInput("spatk2", "Sp. Attack", 0, 252, 0, step = 4), sliderInput("def2", "Defense", 0, 252, 0, step = 4), sliderInput("spdef2", "Sp. Defense", 0, 252, 0, step = 4), sliderInput("spd2", "Speed", 0, 252, 0, step = 4) ) ) ), mainPanel( navbarPage( "", tabPanel( "Home", fluidRow( column( 6, div( class = "card", tags$img(uiOutput("sprite1"), width = "auto") ) ), column( 6, div( class = "card", tags$img(uiOutput("sprite2"), width = "auto") ) ) ), br(), div( h2(textOutput("table-title"), align = "center"), tableOutput("like"), align = "center" ), br(), br(), br(), div(plotlyOutput("fullstats", width = 600, height = 600), align = "center", tags$i(textOutput("caption"), style = "font-size:25px", align = "center") ) # full stats at Lv. 100 ), tabPanel( "Trends", h1("Popularity Plot"), helpText("Gauged by search hits. (Proof of Concept)"), actionButton("popplot", "Generate Plot"), br(), br(), div( class = "polaroid", withSpinner(plotOutput("popularity"), type = 6, color = "red") ), br(), br(), h1("Popular Roles"), h3(strong(textOutput("role1"))), p(htmlOutput("desc1")), tags$head(tags$style("#desc1{ font-size: 20px; }")), h3(strong(textOutput("role2"))), p(htmlOutput("desc2")), tags$head(tags$style("#desc2{ font-size: 20px; }")) ), tabPanel( "About", h1("What are Pokémon?"), helpText("Taken from the Official Pokémon Website."), p("Pokémon are creatures of all shapes and sizes who live in the wild or alongside humans. For the most part, Pokémon do not speak except to utter their names. Pokémon are raised and commanded by their owners (called “Trainers”). During their adventures, Pokémon grow and become more experienced and even, on occasion, evolve into stronger Pokémon. There are currently more than 700 creatures that inhabit the Pokémon universe.", style = "font-size:20px"), br(), h2("Concepts"), p(strong("Pokémon Battle"), ": Pokémon use moves to cause the opposing Pokémon to faint (when their HP reaches zero). In a single battle turn, the Pokémon make moves sequentially, according to their speed and move priorities.", style = "font-size: 20px"), br(), p(strong("HP"), ": Hit points; the amount of damage the Pokemon can take", style = "font-size:20px"), p(strong("ATK"), ": base attack; accounts for physical damage it can give", style = "font-size:20px"), p(strong("DEF"), ": base defense; accounts for physical damage it can take", style = "font-size:20px"), p(strong("SPATK"), ": base special attack; accounts for special damage it can give", style = "font-size:20px"), p(strong("SPDEF"), ": base special defense; accounts for special damage it can take", style = "font-size:20px"), p(strong("SPD"), ": base speed; determines the move order in a battle", style = "font-size:20px"), br(), p(strong("EVs"), ": Effort Values; determines the allocation of stat increases as a Pokémon levels up.", style = "font-size: 20px"), p(strong("Max EVs per stat"), ": 252", style = "font-size:20px"), p(strong("Max Total EVs"), ": 510", style = "font-size: 20px"), p(strong("EV training"), ": In game, upon defeat of an opponent, certain EV stats are raised.", style = "font-size: 20px"), p(strong("IVs"), ": Individual Values; increases base stats by one. Max: 31", style = "font-size: 20px"), p("Different Natures influence base stats differently. (e.g. Adamant Nature boosts the ATK stat by 10% and lowers SPATK stat by 10%.)", style = "font-size: 20px"), helpText("For practicality, EVs are capped at 508 and IVs are automatically included. The influence of Natures are assumed."), br(), h2("About the App"), p("The app serves as a statistical tool for players in the Pokémon Video Game Competition (VGC). The app has two main components: 'Home' and 'Trends'. The first page of the app displays the sprites and statistics of the two chosen Pokémon. To change the selected Pokémon, simply scroll through the select box to choose your Pokémon and your rival's Pokémon. The table titled 'Top 10 Pokémon with Similar Stats' is generated through KNN algorithm, which finds the 10 closest Pokémon in terms of stats. Utility-wise, this provides useful alternatives for the players. Furthermore, the radar plot is gerenated through 'plotly' and gives reference to strengths and weakness of the two Pokémon. The last feature of the first page is the 'Generate Pokémon File' button on the side panel, which gathers the user inputs, formats them, and provides a pop-out for copying. The next page, 'Trends', portrays the Pokémon's popularity based on search hits over time. This provides some insight into the Pokémon's prevalence in Pokémon VGC community. Moreover, the most natural battle roles are assigned to the chosen Pokémon with some descriptions.", style = "font-size:20px") ) ) ) ) <file_sep>/server.R server <- function(input, output, session) { # reactive variables # Sets default values myMon <- reactive({ if (input$mongo == 0) "pikachu-phd" else x() }) oppMon <- reactive({ if (input$mongo2 == 0) "blissey" else x2() }) # for gtrends selected <- reactive({ p1 <- myMon() %>% gsub("-", " ", .) p2 <- oppMon() %>% gsub("-", " ", .) c(p1, p2) }) # updates default values x <- eventReactive(input$mongo, { str_to_lower(input$mon) %>% gsub("\\s", "-", .) }) x2 <- eventReactive(input$mongo2, { str_to_lower(input$mon2) %>% gsub("\\s", "-", .) }) ################################################################################### # REQUESTS # apimon <- reactive({ str_glue("https://pokeapi.co/api/v2/pokemon/{specie}/", specie = myMon()) %>% fromJSON(flatten = TRUE) }) apimon2 <- reactive({ str_glue("https://pokeapi.co/api/v2/pokemon/{specie}/", specie = oppMon()) %>% fromJSON(flatten = TRUE) }) ### Learnset ### learnset <- reactive({ j <- str_glue("https://pokeapi.co/api/v2/pokemon/{specie}/", specie = myMon()) %>% fromJSON(flatten = TRUE) j$moves$move.name %>% str_to_title() %>% gsub("-", " ", .) }) learnset2 <- reactive({ j <- str_glue("https://pokeapi.co/api/v2/pokemon/{specie}/", specie = oppMon()) %>% fromJSON(flatten = TRUE) j$moves$move.name %>% str_to_title() %>% gsub("-", " ", .) }) ### Types ### types1 <- reactive({ j <- str_glue("https://pokeapi.co/api/v2/pokemon/{specie}/", specie = myMon()) %>% fromJSON(flatten = TRUE) paste0("[", j$types$type.name %>% str_to_upper(), "]") }) types2 <- reactive({ j <- str_glue("https://pokeapi.co/api/v2/pokemon/{specie}/", specie = oppMon()) %>% fromJSON(flatten = TRUE) paste0("[", j$types$type.name %>% str_to_upper(), "]") }) ### Abilities ### ability1 <- reactive({ j <- str_glue("https://pokeapi.co/api/v2/pokemon/{specie}/", specie = myMon()) %>% fromJSON(flatten = TRUE) j$abilities$ability.name %>% str_to_title() }) ability2 <- reactive({ j <- str_glue("https://pokeapi.co/api/v2/pokemon/{specie}/", specie = oppMon()) %>% fromJSON(flatten = TRUE) j$abilities$ability.name %>% str_to_title() }) ### Sprites ### mysprite <- reactive({ if (myMon() %in% dbsprites$name) { dbsprites %>% filter(name == myMon()) %>% select(sprite) %>% pull() } else { j2 <- str_glue("https://pokeapi.co/api/v2/pokemon/{specie}/", specie = myMon()) %>% fromJSON(flatten = TRUE) j2$sprites$front_default } }) oppsprite <- reactive({ if (oppMon() %in% dbsprites$name) { dbsprites %>% filter(name == oppMon()) %>% select(sprite) %>% pull() } else { j2 <- str_glue("https://pokeapi.co/api/v2/pokemon/{specie}/", specie = oppMon()) %>% fromJSON(flatten = TRUE) j2$sprites$front_default } }) ############################ gtrends ############################ trend <- reactive({ t <- lapply(selected(), function(x) { gtrends(x)$interest_over_time %>% select(keyword, date, hits) %>% filter(as.Date(date) > Sys.Date() - 31 * 3) %>% mutate(hits = as.numeric(hits)) }) rbind(t[[1]], t[[2]]) }) new_trend <- eventReactive(input$popplot, { trend() }) ############################################### stats for KNN ############################################# kdata <- reactive({ stat_info %>% filter(name != myMon()) }) kstat <- reactive({ a <- data.frame( name = myMon(), HP = apimon()$stats$base_stat[[1]], Attack = apimon()$stats$base_stat[[2]], Defense = apimon()$stats$base_stat[[3]], `Sp..Atk` = apimon()$stats$base_stat[[4]], `Sp..Def` = apimon()$stats$base_stat[[5]], Speed = apimon()$stats$base_stat[[6]] ) a <- a %>% mutate(Total = as.integer(rowSums(.[2:7]))) a <- a %>% select(1, 8, 2:7) }) kdata3 <- reactive({ rbind(kstat(), kdata()) # puts the chosen mon in the first row }) kdata4 <- reactive({ kdata3() %>% select(2:8) }) # KNN # kdata5 <- reactive({ as.numeric(knnx.index(kdata4(), kdata4()[1, , drop = FALSE], k = 11)) }) kdata6 <- reactive({ df <- (kdata3()[kdata5(), 1]) %>% str_to_title() df[2:11] %>% gsub("-", " ", .) }) # Rival # k2data <- reactive({ stat_info %>% filter(name != oppMon()) }) k2stat <- reactive({ a <- data.frame( name = oppMon(), HP = apimon2()$stats$base_stat[[1]], Attack = apimon2()$stats$base_stat[[2]], Defense = apimon2()$stats$base_stat[[3]], `Sp..Atk` = apimon2()$stats$base_stat[[4]], `Sp..Def` = apimon2()$stats$base_stat[[5]], Speed = apimon2()$stats$base_stat[[6]] ) a <- a %>% mutate(Total = as.integer(rowSums(.[2:7]))) a <- a %>% select(1, 8, 2:7) }) k2data3 <- reactive({ rbind(k2stat(), k2data()) # puts the chosen mon in the first row }) k2data4 <- reactive({ k2data3() %>% select(2:8) }) # KNN # k2data5 <- reactive({ as.numeric(knnx.index(k2data4(), k2data4()[1, , drop = FALSE], k = 11)) }) k2data6 <- reactive({ df <- (k2data3()[k2data5(), 1]) %>% str_to_title() df[2:11] %>% gsub("-", " ", .) }) # Combine Tables ktable <- reactive({ t <- cbind(kdata6(), k2data6()) tnames <- c(myMon(), oppMon()) %>% str_to_title() %>% gsub("-", " ", .) colnames(t) <- tnames t }) ########################################################################################################## # Base Stats at 100 # Include Nature influence bstat <- reactive({ temp <- data.frame( HP = apimon()$stats$base_stat[[1]] * 2, ATK = apimon()$stats$base_stat[[2]] * 2, DEF = apimon()$stats$base_stat[[3]] * 2, SPATK = apimon()$stats$base_stat[[4]] * 2, SPDEF = apimon()$stats$base_stat[[5]] * 2, SPD = apimon()$stats$base_stat[[6]] * 2 ) }) bstat2 <- reactive({ temp <- data.frame( HP = apimon2()$stats$base_stat[[1]] * 2, ATK = apimon2()$stats$base_stat[[2]] * 2, DEF = apimon2()$stats$base_stat[[3]] * 2, SPATK = apimon2()$stats$base_stat[[4]] * 2, SPDEF = apimon2()$stats$base_stat[[5]] * 2, SPD = apimon2()$stats$base_stat[[6]] * 2 ) }) #################################### EVS ############################################# totev <- reactive({ sum(input$hp + input$atk + input$def + input$spatk + input$spdef + input$spd) }) totev2 <- reactive({ sum(input$hp2 + input$atk2 + input$def2 + input$spatk2 + input$spdef2 + input$spd2) }) # Works with observe # Resets EVs if they go over 508 evlist <- reactive({ a <- data.frame( HP = 0, Atk = 0, Def = 0, SpA = 0, SpD = 0, Spe = 0 ) if (totev() <= 508) { a <- data.frame( HP = input$hp, Atk = input$atk, Def = input$def, SpA = input$spatk, SpD = input$spdef, Spe = input$spd ) } a }) evlist2 <- reactive({ a <- data.frame( HP = 0, Atk = 0, Def = 0, SpA = 0, SpD = 0, Spe = 0 ) if (totev2() <= 508) { a <- data.frame( HP = input$hp2, Atk = input$atk2, Def = input$def2, SpA = input$spatk2, SpD = input$spdef2, Spe = input$spd2 ) } a }) # Impact of EVs on base stats evhp <- reactive(input$hp / 4) evstk <- reactive(input$atk / 4) evdf <- reactive(input$def / 4) evsatk <- reactive(input$spatk / 4) evsdf <- reactive(input$spdef / 4) evspd <- reactive(input$spd / 4) evhp2 <- reactive(input$hp2 / 4) evstk2 <- reactive(input$atk2 / 4) evdf2 <- reactive(input$def2 / 4) evsatk2 <- reactive(input$spatk2 / 4) evsdf2 <- reactive(input$spdef2 / 4) evspd2 <- reactive(input$spd2 / 4) # stats chart stats_chart <- reactive({ # add in IVs values later - just add 31 a <- tibble( HP = c(bstat()$HP + 204, 0, bstat()$HP + 110 + evhp()), Attack = c(bstat()$ATK + 99, 0, bstat()$ATK + 5 + evstk()), Defense = c(bstat()$DEF + 99, 0, bstat()$DEF + 5 + evdf()), `Sp. Attack` = c(bstat()$SPATK + 99, 0, bstat()$SPATK + 5 + evsatk()), `Sp. Defense` = c(bstat()$SPDEF + 99, 0, bstat()$SPDEF + 5 + evsdf()), Speed = c(bstat()$SPD + 99, 0, bstat()$SPD + 5 + evspd()) ) names(a) <- c( paste("HP", bstat()$HP + 110 + evhp()), paste("Attack", bstat()$ATK + 5 + evstk()), paste("Defense", bstat()$DEF + 5 + evdf()), paste("Sp. Attack", bstat()$SPATK + 5 + evsatk()), paste("Sp. Defense", bstat()$SPDEF + 5 + evsdf()), paste("Speed", bstat()$SPD + 5 + evspd()) ) a }) stats_chart2 <- reactive({ # add in IVs values later - just add 31 a <- tibble( HP = c(bstat2()$HP + 204, 0, bstat2()$HP + 110 + evhp2()), Attack = c(bstat2()$ATK + 99, 0, bstat2()$ATK + 5 + evstk2()), Defense = c(bstat2()$DEF + 99, 0, bstat2()$DEF + 5 + evdf2()), `Sp. Attack` = c(bstat2()$SPATK + 99, 0, bstat2()$SPATK + 5 + evsatk2()), `Sp. Defense` = c(bstat2()$SPDEF + 99, 0, bstat2()$SPDEF + 5 + evsdf2()), Speed = c(bstat2()$SPD + 99, 0, bstat2()$SPD + 5 + evspd2()) ) names(a) <- c( paste("HP", "(", bstat2()$HP + 110 + evhp2(), ")"), paste("Attack", "(", bstat2()$ATK + 5 + evstk2(), ")"), paste("Defense", "(", bstat2()$DEF + 5 + evdf2(), ")"), paste("Sp. Attack", "(", bstat2()$SPATK + 5 + evsatk2(), ")"), paste("Sp. Defense", "(", bstat2()$SPDEF + 5 + evsdf2(), ")"), paste("Speed", "(", bstat2()$SPD + 5 + evspd2(), ")") ) a }) ########## ITEMS ############## item1 <- reactive({ usable_items %>% filter(Name == input$item) %>% select(Effect) %>% pull() }) item2 <- reactive({ usable_items %>% filter(Name == input$item2) %>% select(Effect) %>% pull() }) ########### ABILITY ############# ab1 <- reactive({ ab_info %>% filter(Name == input$ability %>% gsub(" ", "-", .)) %>% select(Description) %>% pull() }) ab2 <- reactive({ ab_info %>% filter(Name == input$ability2 %>% gsub(" ", "-", .)) %>% select(Description) %>% pull() }) ################ EV ############### ev1 <- reactive({ if (totev() <= 508) { paste0("Remaining: ", 508 - totev()) } else { paste0("Exceeded!") } }) ev2 <- reactive({ if (totev2() <= 508) { paste0("Remaining: ", 508 - totev2()) } else { paste0("Exceeded!") } }) myMove <- reactive({ req(input$moves != "") atk_info %>% filter(Name %in% input$moves) %>% select(Name, Type, Effect) }) oppMove <- reactive({ req(input$moves2 != "") atk_info %>% filter(Name %in% input$moves2) %>% select(Name, Type, Effect) }) ######################## OUTPUTS ######################## output$sprite1 <- renderUI({ tags$img( src = mysprite(), width = "250", height = "250", style = "display: block; margin-left: auto; margin-right: auto" ) }) output$sprite2 <- renderUI({ tags$img( src = oppsprite(), width = "250", height = "250", style = "display: block; margin-left: auto; margin-right: auto" ) }) output$`table-title` <- renderText("Top 10 Pokémon with Similar Stats to:") output$knn_info <- renderText("Table generated from KNN") output$like <- renderTable(ktable(), width = "75%", align = "c", border = TRUE, hover = TRUE, colnames = TRUE, caption = "The table above is generated from a KNN algorithm." ) ############################ RADAR PLOT ######################### output$fullstats <- renderPlotly({ validate( need(myMon() %in% api_mons & oppMon() %in% api_mons, "Please enter a valid Pokemon.") ) plot_ly( type = "scatterpolar", mode = "closest", fill = "toself" ) %>% add_trace( r = as.matrix(stats_chart()[3, ]), theta = c("HP", "ATK", "DEF", "SP.ATK", "SP.DEF", "SPD"), showlegend = TRUE, mode = "markers", name = str_to_title(myMon()) ) %>% add_trace( r = as.matrix(stats_chart2()[3, ]), theta = c("HP", "ATK", "DEF", "SP.ATK", "SP.DEF", "SPD"), showlegend = TRUE, mode = "markers", name = str_to_title(oppMon()) ) %>% layout( title = list( text = "Base Stats at Lv. 100", x = 0.46, font = list( size = 30 ) ), margin = list(t = 100), polar = list( radialaxis = list( visible = T, range = c(0, 700) ) ), showlegend = TRUE ) }) # roles myRole <- reactive({ if (grepl("pikachu", myMon())) { stat_role %>% filter(name == "pikachu") %>% pull(role) } else { stat_role %>% filter(name == myMon()) %>% pull(role) } }) oppRole <- reactive({ if (grepl("pikachu", oppMon())) { stat_role %>% filter(name == "pikachu") %>% pull(role) } else { stat_role %>% filter(name == oppMon()) %>% pull(role) } }) myRoleDesc <- reactive({ if (myRole() == "Physical Sweeper") { s <- roleDesc$ps } else if (myRole() == "Special Sweeper") { s <- roleDesc$ss } else if (myRole() == "Physical Tank") { s <- roleDesc$pt } else { s <- roleDesc$st } }) oppRoleDesc <- reactive({ if (oppRole() == "Physical Sweeper") { s <- roleDesc$ps } else if (oppRole() == "Special Sweeper") { s <- roleDesc$ss } else if (oppRole() == "Physical Tank") { s <- roleDesc$pt } else { s <- roleDesc$st } }) ################################################################# output$mytypes <- renderText(types1()) output$opptypes <- renderText(types2()) output$`ability-info` <- renderText(ab1()) output$`ability-info2` <- renderText(ab2()) output$`item-info` <- renderText(item1()) output$`item-info2` <- renderText(item2()) output$`move-info` <- renderTable(myMove(), width = "auto" ) output$`move-info2` <- renderTable(oppMove(), width = "auto" ) output$ev <- renderText(ev1()) output$ev2 <- renderText(ev2()) output$caption <- renderText("*Toggle the EVs to see how it affects base stats.") # gtrend output$popularity <- renderPlot({ ggplot() + geom_line(aes(x = date, y = hits, color = keyword), data = new_trend(), size = 2) + xlab("Date") + ylab("Hits") + ggtitle("Popularity in the Past Three Months") + theme_bw() }) # roles output$role1 <- renderText({ aname <- myMon() %>% gsub("-", " ", .) %>% str_to_title() paste0(aname, " - ", myRole()) }) output$role2 <- renderText({ aname <- oppMon() %>% gsub("-", " ", .) %>% str_to_title() paste0(aname, " - ", oppRole()) }) output$desc1 <- renderUI(HTML(myRoleDesc())) output$desc2 <- renderUI(HTML(oppRoleDesc())) ###################### OBSERVE ######################### ####################### MOVES ############################ observe({ updateSelectInput(session, "moves", choices = c(learnset()), selected = "" ) }) observe({ updateSelectInput(session, "moves2", choices = c(learnset2()), selected = "" ) }) ######################## ABILITIY ####################### observe({ updateSelectInput(session, "ability", choices = c(ability1() %>% gsub("-", " ", .)) ) }) observe({ updateSelectInput(session, "ability2", choices = c(ability2() %>% gsub("-", " ", .)) ) }) ############################ EVS ########################## observe({ updateSliderInput(session, "hp", value = evlist()$HP) }) observe({ updateSliderInput(session, "atk", value = evlist()$Atk) }) observe({ updateSliderInput(session, "def", value = evlist()$Def) }) observe({ updateSliderInput(session, "spatk", value = evlist()$SpA) }) observe({ updateSliderInput(session, "spdef", value = evlist()$SpD) }) observe({ updateSliderInput(session, "spd", value = evlist()$Spe) }) observe({ updateSliderInput(session, "hp2", value = evlist2()$HP) }) observe({ updateSliderInput(session, "atk2", value = evlist2()$Atk) }) observe({ updateSliderInput(session, "def2", value = evlist2()$Def) }) observe({ updateSliderInput(session, "spatk2", value = evlist2()$SpA) }) observe({ updateSliderInput(session, "spdef2", value = evlist2()$SpD) }) observe({ updateSliderInput(session, "spd2", value = evlist2()$Spe) }) ###################################################################### # Pokemon Script observeEvent(input$script, { # items i <- ifelse(input$item == "-", "", paste0(" @ ", input$item)) # nature n <- ifelse(input$nature == "-", "", paste0(input$nature, " Nature<br>")) # evs e <- if (sum(evlist()) != 0) { e1 <- names(evlist()) e2 <- lapply(seq(evlist()), function(x) paste(evlist()[x], e1[x], "/")) e3 <- paste0("EVs: ", paste(unlist(e2), collapse = " "), "<br>") } else { "" } # moves m <- if (length(input$moves) > 0) { m1 <- lapply(seq(input$moves), function(x) paste0("- ", input$moves[x], "<br>")) m2 <- paste0(unlist(m1), collapse = " ") } else { "" } showModal(modalDialog( title = "Copy/Paste: Pokémon Text File", easyClose = TRUE, p(HTML( input$mon, i, "<br>", "Ability:", input$ability, "<br>", e, n, m )) )) }) observeEvent(input$script2, { # items i <- ifelse(input$item2 == "-", "", paste0(" @ ", input$item2)) # nature n <- ifelse(input$nature2 == "-", "", paste0(input$nature2, " Nature<br>")) # evs e <- if (sum(evlist2()) != 0) { e1 <- names(evlist2()) e2 <- lapply(seq(evlist2()), function(x) paste(evlist2()[x], e1[x], "/")) e3 <- paste0("EVs: ", paste(unlist(e2), collapse = " "), "<br>") } else { "" } # moves m <- if (length(input$moves2) > 0) { m1 <- lapply(seq(input$moves2), function(x) paste0("- ", input$moves2[x], "<br>")) m2 <- paste0(unlist(m1), collapse = " ") } else { "" } showModal(modalDialog( title = "Copy/Paste: Pokémon Text File", easyClose = TRUE, p(HTML( input$mon2, i, "<br>", "Ability:", input$ability2, "<br>", e, n, m )) )) }) } <file_sep>/renaming.R # Table of stats information stat_info <- stat_info %>% select(`X.`,Name,Total,HP,Attack,Defense,`Sp..Atk`,`Sp..Def`,Speed) %>% mutate(Name = str_to_lower(Name)) # Filter problem names pnames <- stat_info[grepl('\\s',stat_info$Name),2] %>% pull() pnames <- pnames[!grepl('(alolan|galarian|partner|size|face|tempo)',pnames)] # First name change temp <- case_when( grepl('(mega charizard )',pnames) ~ gsub('(mega charizard )','-mega-',pnames), grepl('(mega mewtwo )',pnames) ~ gsub('(mega mewtwo )','-mega-',pnames), grepl('(mega)',pnames) ~ gsub('(mega).*','-mega',pnames), grepl('(\\. )', pnames) ~ gsub('(. )','-',pnames), grepl('(\\: )', pnames) ~ gsub('(. )','-',pnames), grepl('\\.$',pnames) ~ gsub('\\.$','',pnames), grepl('( form).*',pnames) ~ gsub('( form).*','',pnames), grepl('.(mode|cloak|kyogre|groudon|rotom|style|kyurem)$',pnames) ~ gsub('.(mode|cloak|kyogre|groudon|rotom|style|kyurem)$','',pnames), grepl('^hoopa',pnames) ~ gsub('^hoopa','',pnames), TRUE ~ pnames ) # Second name change temp <- case_when( grepl('(castform)[^-]',temp) ~ gsub('(castform)','castform-',temp), grepl('(kyogre)[^-]',temp) ~ gsub('(kyogre)','kyogre-',temp), grepl('(groudon)[^-]',temp) ~ gsub('(groudon)','groudon-',temp), grepl('(deoxys)[^-]',temp) ~ gsub('(deoxys)','deoxys-',temp), grepl('(wormadam)[^-]',temp) ~ gsub('(wormadam)','wormadam-',temp), grepl('(rotom)[^-]',temp) ~ gsub('(rotom)','rotom-',temp), grepl('(giratina)[^-]',temp) ~ gsub('(giratina)','giratina-',temp), grepl('(basculin)[^-]',temp) ~ gsub('(basculin)','basculin-',temp), grepl('(darmanitan)[^-]',temp) ~ gsub('(darmanitan)','darmanitan-',temp), grepl('(tornadus)[^-]',temp) ~ gsub('(tornadus)','tornadus-',temp), grepl('(landorus)[^-]',temp) ~ gsub('(landorus)','landorus-',temp), grepl('(thundurus)[^-]',temp) ~ gsub('(thundurus)','thundurus-',temp), grepl('(kyurem)[^-]',temp) ~ gsub('(kyurem)','kyurem-',temp), grepl('(meloetta)[^-]',temp) ~ gsub('(meloetta)','meloetta-',temp), grepl('(aegislash)[^-]',temp) ~ gsub('(aegislash)','aegislash-',temp), grepl('(oricorio)[^-]',temp) ~ gsub('(oricorio)','oricorio-',temp), grepl('(shaymin)[^-]',temp) ~ gsub('(shaymin)','shaymin-',temp), grepl('(keldeo)[^-]',temp) ~ gsub('(keldeo)','keldeo-',temp), grepl('(lycanroc)[^-]',temp) ~ gsub('(lycanroc)','lycanroc-',temp), grepl('(wishiwashi)[^-]',temp) ~ gsub('(wishiwashi)','wishiwashi-',temp), grepl('[^d](-meteor)',temp) ~ gsub('(-meteor)','-red-meteor',temp), grepl('(complete|-confined|ultra-necrozma)',temp) ~ gsub('(complete|-confined|ultra-necrozma)','',temp), grepl('\\s',temp) ~ gsub('\\s','-',temp), grepl('.{2}%',temp) ~ gsub('.{2}%','',temp), TRUE ~ temp ) ################################################################################# # Modify stat info with better names temp <- dbstats %>% mutate(Name = case_when( grepl('♀',Name) ~ gsub('♀','-f',Name), grepl('♂',Name) ~ gsub('♂','-m',Name), grepl('é',Name) ~ gsub('é','e',Name), grepl('(meganium|yanmega)',Name) ~ Name, # <- important potential bug grepl('mimikyu',Name) ~ 'mimikyu-disguised', grepl('(mega charizard )',Name) ~ gsub('(mega charizard )','-mega-',Name), grepl('(mega mewtwo )',Name) ~ gsub('(mega mewtwo )','-mega-',Name), grepl('(mega)',Name) ~ gsub('(mega).*','-mega',Name), grepl('(\\. )', Name) ~ gsub('(. )','-',Name), grepl('(\\: )', Name) ~ gsub('(. )','-',Name), grepl('\\.$',Name) ~ gsub('\\.$','',Name), grepl('( form).*',Name) ~ gsub('( form).*','',Name), grepl('.(mode|cloak|kyogre|groudon|rotom|style|kyurem|size)$',Name) ~ gsub('.(mode|cloak|kyogre|groudon|rotom|style|kyurem|size)$','',Name), grepl('^hoopa',Name) ~ gsub('^hoopa','',Name), TRUE ~ Name) ) temp <- temp %>% mutate(Name = case_when( grepl('(castform)[^-]',Name) ~ gsub('(castform)','castform-',Name), grepl('(kyogre)[^-]',Name) ~ gsub('(kyogre)','kyogre-',Name), grepl('(groudon)[^-]',Name) ~ gsub('(groudon)','groudon-',Name), grepl('(deoxys)[^-]',Name) ~ gsub('(deoxys)','deoxys-',Name), grepl('(wormadam)[^-]',Name) ~ gsub('(wormadam)','wormadam-',Name), grepl('(rotom)[^-]',Name) ~ gsub('(rotom)','rotom-',Name), grepl('(giratina)[^-]',Name) ~ gsub('(giratina)','giratina-',Name), grepl('(basculin)[^-]',Name) ~ gsub('(basculin)','basculin-',Name), grepl('(darmanitan)[^-]',Name) ~ gsub('(darmanitan)','darmanitan-',Name), grepl('(tornadus)[^-]',Name) ~ gsub('(tornadus)','tornadus-',Name), grepl('(landorus)[^-]',Name) ~ gsub('(landorus)','landorus-',Name), grepl('(thundurus)[^-]',Name) ~ gsub('(thundurus)','thundurus-',Name), grepl('(kyurem)[^-]',Name) ~ gsub('(kyurem)','kyurem-',Name), grepl('(meloetta)[^-]',Name) ~ gsub('(meloetta)','meloetta-',Name), grepl('(aegislash)[^-]',Name) ~ gsub('(aegislash)','aegislash-',Name), grepl('(oricorio)[^-]',Name) ~ gsub('(oricorio)','oricorio-',Name), grepl('(shaymin)[^-]',Name) ~ gsub('(shaymin)','shaymin-',Name), grepl('(keldeo)[^-]',Name) ~ gsub('(keldeo)','keldeo-',Name), grepl('(lycanroc)[^-]',Name) ~ gsub('(lycanroc)','lycanroc-',Name), grepl('(wishiwashi)[^-]',Name) ~ gsub('(wishiwashi)','wishiwashi-',Name), grepl('(gourgeist)[^-]',Name) ~ gsub('(gourgeist)','gourgeist-',Name), grepl('(pumpkaboo)[^-]',Name) ~ gsub('(pumpkaboo)','pumpkaboo-',Name), grepl('(meowstic)[^-]',Name) ~ gsub('(meowstic)','meowstic-',Name), grepl('(indeedee)[^-]',Name) ~ gsub('(indeedee)','indeedee-',Name), grepl('(minior)[^-]',Name) ~ gsub('(minior)','minior-red-',Name), grepl('.(confined)',Name) ~ gsub('.(confined)','',Name), grepl('(complete|ultra-necrozma)',Name) ~ gsub('(complete|ultra-necrozma)','',Name), grepl('\\s',Name) ~ gsub('\\s','-',Name), grepl('.{2}%',Name) ~ gsub('.{2}%','',Name), grepl("'",Name) ~ gsub("'",'',Name), TRUE ~ Name) ) #stat_info[is.na(stat_info$Total),] temp$Name[grepl('minior',temp$Name)] dbstats$Name[grepl('tapu',dbstats$Name)] api_mons$name[grepl('farfetch',api_mons$name)]<file_sep>/README.md # PokeApp App for Pokemon-related data Main Components: global.R, server.R, ui.R, www folder Run global.R to start the app
3f31ca3ea4ead0c1c4672448eb1440775535254a
[ "Markdown", "R" ]
5
R
dlsimpao/PokeApp
161254bd0a2a11f48e5df83f32c0dccd08ddce59
f2d2af0a26d509edb7e8680daa177409e84781aa
refs/heads/master
<file_sep>/* * Copyright (c) 2019 - Adjacent Link LLC, Bridgewater, New Jersey * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Adjacent Link LLC nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * See toplevel COPYING for more information. */ #ifndef EMANELTE_MHAL_H #define EMANELTE_MHAL_H #include <vector> #include <string> #include <sys/time.h> #include "libemanelte/otacommon.pb.h" #include "libemanelte/sinrtester.h" namespace EMANELTE { namespace MHAL { typedef std::string Data; struct RxData { uint16_t nemId_; // src nem uint64_t rx_seqnum_; // seqnum timeval rx_time_; // actual rx time timeval tx_time_; // actual tx time timeval sf_time_; // slot time float peak_sum_; // sum of power over whole message uint32_t num_samples_; // number of segments in peak_sum RxData() {} RxData(uint16_t nemId, uint64_t rx_seqnum, const timeval & rx_time, const timeval & tx_time, const timeval & sf_time, const float & peak_sum, const uint32_t & num_samples) : nemId_(nemId), rx_seqnum_(rx_seqnum), rx_time_(rx_time), tx_time_(tx_time), sf_time_(sf_time), peak_sum_(peak_sum), num_samples_(num_samples) {} }; struct RxControl { RxData rxData_; SINRTester SINRTester_; RxControl() {} RxControl(uint16_t nemId, uint64_t rx_seqnum, const timeval & rx_time, const timeval & tx_time, const timeval & sf_time, const float & peak_sum, const uint32_t & num_samples) : rxData_(nemId, rx_seqnum, rx_time, tx_time, sf_time, peak_sum, num_samples), SINRTester_() { } }; typedef std::pair<Data, RxControl> RxMessage; typedef std::vector<RxMessage> RxMessages; } } #endif <file_sep>#!/bin/bash - top_dir=$1 node_name=$2 start_time=$3 echo "top_dir: $top_dir" echo "node_name: $node_name" echo "start_time: $start_time" cd "$top_dir/$node_name" cp -f $top_dir/../templates/ue/pcr.xml $top_dir/$node_name/pcr.xml # delay enb startup so that epc is ready for S1 connection sleep 5 srsenb-emane enb.conf # start otestpointd if [ -f otestpointd.xml ]; then otestpointd -d otestpointd.xml fi <file_sep>/* * Copyright (c) 2019 - Adjacent Link LLC, Bridgewater, New Jersey * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Adjacent Link LLC nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * See toplevel COPYING for more information. */ #include "mhalenb_impl.h" #include "configmanager.h" void EMANELTE::MHAL::MHALENBImpl::initialize(const mhal_config_t & mhal_config, const ENB::mhal_enb_config_t & mhal_enb_config) { MHALCommon::initialize(mhal_enb_config.subframe_interval_msec_, mhal_config); physicalCellId_ = mhal_enb_config.physical_cell_id_; pRadioModel_->setSymbolsPerSlot(mhal_enb_config.symbols_per_slot_); pRadioModel_->setFrequencies(llroundf(mhal_enb_config.uplink_frequency_hz_), llroundf(mhal_enb_config.downlink_frequency_hz_)); pRadioModel_->setNumResourceBlocks(mhal_enb_config.num_resource_blocks_); } void EMANELTE::MHAL::MHALENBImpl::init_emane() { auto & configManager = ConfigManager::getInstance(); auto & platformConfig = configManager.getPlatformConfig(); auto & radioModelConfig = configManager.getRadioModelConfig(); auto & phyConfig = configManager.getPhyConfig(); // create an NEM builder EMANE::Application::NEMBuilder nemBuilder{}; // create the appropriate radio model, skip config auto items = nemBuilder.buildMACLayer_T<EMANE::Models::LTE::ENBRadioModel>( platformConfig.id_, "lteenbradiomodel", { {"maxpropagationdelay", {radioModelConfig.sMaxPropagationDelay_}}, {"pcrcurveuri", {radioModelConfig.sPcrCurveURI_}}, {"resourceblocktxpower", {radioModelConfig.sResourceBlockTxPower_}}, {"subid", {phyConfig.sSubId_}} }, false); pRadioModel_ = std::get<0>(items); pRadioModel_->setMHAL(this); // create an NEMLayers instance to hold the layers of your NEM EMANE::Application::NEMLayers layers{}; // add your radio model (as an NEMLayer) to your NEM layers layers.push_back(std::move(std::get<1>(items))); // create and add to layers an emulator physical layer instance layers.push_back(nemBuilder.buildPHYLayer(platformConfig.id_, "", { {"fixedantennagain", {phyConfig.sAntennaGain_}}, {"fixedantennagainenable", {phyConfig.sFixedAntennaGainEnable_}}, {"noisemode", {phyConfig.sNoiseMode_}}, {"propagationmodel", {phyConfig.sPropagationModel_}}, {"systemnoisefigure", {phyConfig.sSystemNoiseFigure_}}, {"subid", {phyConfig.sSubId_}} }, false)); // skip config nems_.push_back(nemBuilder.buildNEM(platformConfig.id_, layers, {}, false)); // create application instance UUID uuid_t uuid; uuid_generate(uuid); pNEMManager_ = nemBuilder.buildNEMManager(uuid, nems_, { {"otamanagerchannelenable", {platformConfig.sOtamManagerChannelEnable_}}, {"otamanagergroup", {platformConfig.sOtaManagerGroup_}}, {"otamanagerloopback", {platformConfig.sOtaManagerLoopback_}}, {"otamanagerdevice", {platformConfig.sOtaManagerDevice_}}, {"eventservicegroup", {platformConfig.sEventServiceGroup_}}, {"eventservicedevice", {platformConfig.sEventServiceDevice_}}, {"controlportendpoint", {platformConfig.sControlPortEndpoint_}}, {"antennaprofilemanifesturi", {platformConfig.sAntennaProfileManifest_}} }); pNEMManager_->start(); pNEMManager_->postStart(); } void EMANELTE::MHAL::MHALENBImpl::start() { logger_.log(EMANE::INFO_LEVEL, "MHAL::PHY %s, physicalCellId_=0x%x", __func__, physicalCellId_); MHALCommon::start(5); } void EMANELTE::MHAL::MHALENBImpl::send_downstream(const Data & data, TxControlMessage & txControl, const EMANE::TimePoint & timestamp) { if(pRadioModel_) { pRadioModel_->sendDownstreamMessage(data, txControl, timestamp); } else { logger_.log(EMANE::INFO_LEVEL, " MHALENBImpl %s radiomodel not ready", __func__); } } void EMANELTE::MHAL::MHALENBImpl::handle_upstream_msg(const Data & data, const RxData & rxData, const PHY::OTAInfo & otaInfo, const TxControlMessage & txControl) { MHALCommon::handle_upstream_msg(data, rxData, otaInfo, txControl); } EMANE::SpectrumWindow EMANELTE::MHAL::MHALENBImpl::get_noise(FrequencyHz frequencyHz, const EMANE::Microseconds & span, const EMANE::TimePoint & sor) { return pRadioModel_->getNoise(frequencyHz, span, sor); } long long unsigned int EMANELTE::MHAL::MHALENBImpl::get_tx_prb_frequency(int prb_index) { return pRadioModel_->getTxResourceBlockFrequency(prb_index); } void EMANELTE::MHAL::MHALENBImpl::noise_processor(const uint32_t bin, const EMANE::Models::LTE::SpectrumWindowCache & spectrumWindowCache) { // Track the combined transmit power of all UEs on shared channels EMANE::Models::LTE::SegmentSOTMap inBandSegmentPowerMap_mW; // Track the individual transmit power for segments from each source std::map<EMANE::NEMId, EMANE::Models::LTE::SegmentMap> nemRxPowers_dBm; // For the first pass, store the combined receive power for all transmitters sending on the same segment offset and duration for(auto & msg : pendingMessageBins_[bin].get()) { auto rxControl = std::get<1>(msg); const auto & otaInfo = std::get<2>(msg); const auto & txControl = std::get<3>(msg); if(txControl.phy_cell_id() != physicalCellId_) { // transmitters on other cells are considered noise continue; } nemRxPowers_dBm.emplace(rxControl.nemId_, EMANE::Models::LTE::SegmentMap()); EMANE::Models::LTE::SegmentMap & nemRxPowerMap_dBm(nemRxPowers_dBm.find(rxControl.nemId_)->second); for(auto & segment : otaInfo.segments_) { const auto rxPower_dBm = segment.getRxPowerdBm(); const auto rxPower_mW = EMANELTE::DB_TO_MW(segment.getRxPowerdBm()); EMANE::Models::LTE::SegmentKey key{segment.getFrequencyHz(), segment.getOffset(), segment.getDuration()}; nemRxPowerMap_dBm.emplace(key, rxPower_dBm); auto inBandIter = inBandSegmentPowerMap_mW.find(key); if(inBandIter == inBandSegmentPowerMap_mW.end()) { inBandSegmentPowerMap_mW.emplace(key, EMANE::Models::LTE::SegmentSOTValue(otaInfo.sot_, otaInfo.sot_, rxPower_mW)); } else { EMANE::TimePoint & minSot(std::get<0>(inBandIter->second)); EMANE::TimePoint & maxSot(std::get<1>(inBandIter->second)); float & partialRxPower_mW{std::get<2>(inBandIter->second)}; minSot = std::min(minSot, otaInfo.sot_); maxSot = std::max(maxSot, otaInfo.sot_); partialRxPower_mW += rxPower_mW; } } } // For the second pass, determine the noise floor once all in band segment power is removed. // For dedicated channels there should only be 1 in-band transmitter assuming the enb scheduler does not // allocate uplink PDSCH resources to more than one UE (an assumption we are making currently). // For PUSCH and PRACH, we make an a simplifying assumption for now that inband receptions are time aligned and // orthogonal so do not interfere with each other; uplink sinr is calculated for each segment // as the segment receive power less the noisefloor of out of band contributions. EMANE::Models::LTE::SegmentMap outOfBandNoiseFloor_dBm; for(auto & segment : inBandSegmentPowerMap_mW) { const auto frequencyHz = std::get<0>(segment.first); const auto spectrumWindow = spectrumWindowCache.find(frequencyHz); if(spectrumWindow == spectrumWindowCache.end()) { logger_.log(EMANE::ERROR_LEVEL, "MHAL::PHY %s, bin %u, no spectrumWindow cache info for freq %lu", __func__, bin, frequencyHz); pRadioModel_->getStatisticManager().updateRxFrequencySpectrumError(frequencyHz); continue; } const auto & noiseData = std::get<0>(spectrumWindow->second); if(noiseData.empty()) { logger_.log(EMANE::ERROR_LEVEL, "MHAL::PHY %s, bin %u, freq %lu, no noise data", __func__, bin, frequencyHz); pRadioModel_->getStatisticManager().updateRxFrequencySpectrumError(frequencyHz); continue; } const auto offset = std::get<1>(segment.first); const auto duration = std::get<2>(segment.first); EMANE::TimePoint minSot, maxSot; double rxPower_mW; std::tie(minSot, maxSot, rxPower_mW) = segment.second; const auto rxPower_dBm = EMANELTE::MW_TO_DB(rxPower_mW); const auto minSor = minSot + offset; const auto maxEor = maxSot + offset + duration; // find the max out-of-band noise across the segment bins const auto rangeInfo = EMANE::Utils::maxBinNoiseFloorRange(spectrumWindow->second, rxPower_dBm, minSor, maxEor); const auto noiseFloor_dBm = rangeInfo.first; outOfBandNoiseFloor_dBm.emplace(EMANE::Models::LTE::SegmentKey(frequencyHz, offset, duration), noiseFloor_dBm); } // now process each message based on rx power from the source nem and // the out of band noise floor for(auto & msg : pendingMessageBins_[bin].get()) { RxControl rxControl{}; rxControl.rxData_ = std::move(std::get<1>(msg)); const auto & otaInfo = std::get<2>(msg); const auto & txControl = std::get<3>(msg); // grab num segments here, some stl list size() calls are not O(1) const size_t numSegments = otaInfo.segments_.size(); if(txControl.phy_cell_id() != physicalCellId_) { // ignore transmitters from other cells continue; } #ifdef ENABLE_INFO_2_LOGS logger_.log(EMANE::INFO_LEVEL, "MHAL::PHY %s, src %hu, seqnum %lu, segments %zu", __func__, rxControl.rxData_.nemId_, rxControl.rxData_.rx_seqnum_, numSegments); #endif double signalSum_mW = 0, noiseFloorSum_mW = 0; int segnum = -1; float peak_sum = 0.0; uint32_t num_samples = 0; EMANE::Models::LTE::SegmentMap segmentCache; // build segmentCache for(auto & segment : otaInfo.segments_) { const auto frequencyHz = segment.getFrequencyHz(); const auto spectrumWindow = spectrumWindowCache.find(frequencyHz); logger_.log(EMANE::DEBUG_LEVEL, "MHAL::PHY %s, src %hu, bin %u, freq %lu, offset %lu, duration %lu", __func__, rxControl.rxData_.nemId_, bin, frequencyHz, segment.getOffset().count(), segment.getDuration().count()); ++segnum; if(spectrumWindow == spectrumWindowCache.end()) { logger_.log(EMANE::ERROR_LEVEL, "MHAL::PHY %s, src %hu, bin %u, no spectrumWindow cache info for freq %lu", __func__, rxControl.rxData_.nemId_, bin, frequencyHz); pRadioModel_->getStatisticManager().updateRxFrequencySpectrumError(frequencyHz); continue; } float rxPower_dBm = segment.getRxPowerdBm(); float rxPower_mW = EMANELTE::DB_TO_MW(segment.getRxPowerdBm()); double noiseFloor_dBm = outOfBandNoiseFloor_dBm.find(EMANE::Models::LTE::SegmentKey(segment.getFrequencyHz(), segment.getOffset(), segment.getDuration()))->second; double noiseFloor_mW = EMANELTE::DB_TO_MW(noiseFloor_dBm); signalSum_mW += rxPower_mW; noiseFloorSum_mW += noiseFloor_mW; const auto sinr_dB = rxPower_dBm - noiseFloor_dBm; logger_.log(EMANE::DEBUG_LEVEL, "MHAL::PHY %s, src %hu, freq %lu, offset %lu, duration %lu, rxPower_dBm %0.1f, noisefloor_dbm %0.1f, sinr_dB %0.1f", __func__, rxControl.rxData_.nemId_, segment.getFrequencyHz(), segment.getOffset().count(), segment.getDuration().count(), rxPower_dBm, noiseFloor_dBm, sinr_dB); segmentCache.emplace(EMANE::Models::LTE::SegmentKey(frequencyHz, segment.getOffset(), segment.getDuration()), sinr_dB); pRadioModel_->getStatisticManager().updateRxFrequencyAvgNoiseFloor(frequencyHz, noiseFloor_mW); #ifdef ENABLE_INFO_1_LOGS bool inBand = rangeInfo.second; const bool & bSignalInNoise{std::get<4>(spectrumWindow->second)}; logger_.log(EMANE::INFO_LEVEL, "MHAL::PHY %s, " "src %hu, " "sfIdx=%d, " "seqnum %lu, " "inband %d, " "siginnoise %d, " "freq %lu, " "offs %lu, " "dur %lu, " "rxPwr %5.3f dBm, " "nf %5.3lf dBm, " "sinr %5.3lf dB", __func__, rxControl.rxData_.nemId_, txControl.tti_tx(), rxControl.rxData_.rx_seqnum_, inBand, bSignalInNoise, frequencyHz, segment.getOffset().count(), segment.getDuration().count(), rxPower_dBm, noiseFloor_dBm, sinr_dB); #endif peak_sum += sinr_dB; num_samples++; } // end each segment // now check for number of pass/fail segments if(numSegments > 0) { const auto signalAvg_dBm = EMANELTE::MW_TO_DB(signalSum_mW / numSegments); const auto noiseFloorAvg_dBm = EMANELTE::MW_TO_DB(noiseFloorSum_mW / numSegments); UplinkSINRTesterImpl * pSINRTester = new UplinkSINRTesterImpl(signalAvg_dBm - noiseFloorAvg_dBm, noiseFloorAvg_dBm); rxControl.SINRTester_.setImpl(pSINRTester); rxControl.rxData_.peak_sum_ = peak_sum; rxControl.rxData_.num_samples_ = num_samples; if(txControl.uplink().has_prach()) { putSINRResult(txControl.uplink().prach(), rxControl, pSINRTester, pRadioModel_->noiseTestChannelMessage(txControl, txControl.uplink().prach(), segmentCache)); } for(int i = 0; i < txControl.uplink().pucch_size(); ++i) { putSINRResult(txControl.uplink().pucch(i), rxControl, pSINRTester, pRadioModel_->noiseTestChannelMessage(txControl, txControl.uplink().pucch(i), segmentCache)); } for(int i = 0; i < txControl.uplink().pusch_size(); ++i) { putSINRResult(txControl.uplink().pusch(i), rxControl, pSINRTester, pRadioModel_->noiseTestChannelMessage(txControl, txControl.uplink().pusch(i), segmentCache)); } StatisticManager::ReceptionInfoMap receptionInfoMap; // add entry per src receptionInfoMap[rxControl.rxData_.nemId_] = StatisticManager::ReceptionInfoData{signalAvg_dBm, noiseFloorAvg_dBm, numSegments}; statisticManager_.updateReceptionTable(receptionInfoMap); // lastly, make ready, take ownership of data and control readyMessageBins_[bin].get().push_back(RxMessage{std::move(std::get<0>(msg)), std::move(rxControl)}); } } // end for each msg } void EMANELTE::MHAL::MHALENBImpl::putSINRResult(const ChannelMessage & channel_message, RxControl & rxControl, UplinkSINRTesterImpl * pSINRTester, bool received) { CHANNEL_TYPE ctype = channel_message.channel_type(); if(channel_message.has_rnti()) { logger_.log(EMANE::DEBUG_LEVEL, "MHAL::PHY %s insert sinr result, src %hu, seqnum %lu, chantype %d, rnti %hu", __func__, rxControl.rxData_.nemId_, rxControl.rxData_.rx_seqnum_, ctype, channel_message.rnti()); pSINRTester->rntiChannelSINRResults_.emplace(ChannelRNTI(ctype, channel_message.rnti()), received); } else { logger_.log(EMANE::DEBUG_LEVEL, "MHAL::PHY %s insert sinr result, src %hu, seqnum %lu, chantype %d", __func__, rxControl.rxData_.nemId_, rxControl.rxData_.rx_seqnum_, ctype); pSINRTester->channelSINRResults_.emplace(ctype, received); } } bool EMANELTE::MHAL::MHALENBImpl::get_messages(RxMessages & messages, timeval & tv_sor) { bool in_step = false; timing_.lockTime(); timeval tv_now, tv_diff, tv_process_diff, tv_sf_time = timing_.getCurrSfTime(); gettimeofday(&tv_now, NULL); // get the process time for the calling thread for the time remaining in this subframe timersub(&tv_now, &tv_sf_time, &tv_process_diff); // get the time till the next subframe timersub(&timing_.getNextSfTime(), &tv_now, &tv_diff); // this is where we set the pace for the system pulse if(timercmp(&tv_diff, &tv_zero_, >)) { // next sf is still in the future // wait until next subframe time select(0, NULL, NULL, NULL, &tv_diff); in_step = true; } else { const time_t dT = timing_.ts_sf_interval_usec() + tvToUseconds(tv_diff); if(dT < 0) { // we passed the next sf mark, continue and try to catch up on subsequent call(s) in_step = false; } else { // we passed the next sf mark, but are still within the sf window in_step = true; } } // use sf_time for the bin const uint32_t bin = getMessageBin(tv_sf_time, timing_.ts_sf_interval_usec()); pendingMessageBins_[bin].lockBin(); // now advance the subframe times, curr -> next, next -> next+1 uint32_t nextbin{timing_.stepTime()}; pendingMessageBins_[nextbin].lockBin(); // check for orphans if(size_t orphaned = pendingMessageBins_[nextbin].clearAndCheck()) { logger_.log(EMANE::ERROR_LEVEL, "MHAL::RADIO %s curr_sf %ld:%06ld, bin %u, purge %zu pending orphans", __func__, timing_.getCurrSfTime().tv_sec, timing_.getCurrSfTime().tv_usec, nextbin, orphaned); statisticManager_.updateOrphanedMessages(nextbin, orphaned); } clearReadyMessages(nextbin); pendingMessageBins_[nextbin].unlockBin(); // get msgs from the previous subframe noise_worker(bin, tv_sf_time); // set the sor to the sf time (time aligned via lte time advance) tv_sor = tv_sf_time; timing_.unlockTime(); #ifdef ENABLE_INFO_1_LOGS const timeval tv_curr_sf = timing_.getCurrSfTime(); logger_.log(EMANE::INFO_LEVEL, "MHAL::PHY %s bin %u, sor %ld:%06ld, prev_sf %ld:%06ld, curr_sf %ld:%06ld, %zu msgs ready", __func__, bin, tv_sor.tv_sec, tv_sor.tv_usec, tv_sf_time.tv_sec, tv_sf_time.tv_usec, tv_curr_sf.tv_sec, tv_curr_sf.tv_usec, pendingMessageBins_[bin].getReady().size()); #endif // transfer to caller messages = std::move(readyMessageBins_[bin].get()); // clear bin pendingMessageBins_[bin].clear(); readyMessageBins_[bin].clear(); pendingMessageBins_[bin].unlockBin(); statisticManager_.updateHandoffMessages(bin, messages.size()); statisticManager_.tallySubframeProcessTime(bin, tv_process_diff, !in_step); return in_step; } <file_sep>/* * Copyright (c) 2019 - Adjacent Link LLC, Bridgewater, New Jersey * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Adjacent Link LLC nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * See toplevel COPYING for more information. */ #include "libemanelte/uestatisticmanager.h" #include "iptrafficstats.h" #include "channelcounter.h" #include <ostatistic/service.h> #include <ostatistic/statisticnumeric.h> #include <ostatistic/table.h> #include <array> #include <string> #include <sys/time.h> namespace { OpenStatistic::Table<std::uint64_t> * pNodeInfoTable_ = NULL; OpenStatistic::Table<std::uint64_t> * pGWThruputTable_ = NULL; OpenStatistic::Table<std::uint64_t> * pRLCThruputTable_ = NULL; OpenStatistic::Table<std::uint64_t> * pRLCMRBThruputTable_ = NULL; OpenStatistic::Table<std::uint64_t> * pPhySearchStateTable_ = NULL; OpenStatistic::Table<std::uint64_t> * pPhyTable_ = NULL; OpenStatistic::Table<std::uint64_t> * pCellTable_ = NULL; OpenStatistic::Table<std::uint64_t> * pMacTable_ = NULL; OpenStatistic::Table<std::uint64_t> * pULGrantRntiTable_ = NULL; OpenStatistic::Table<std::uint64_t> * pPDCCHRntiTable_ = NULL; OpenStatistic::Table<std::uint64_t> * pPDSCHRntiTable_ = NULL; float report_interval_secs_ = 0; const std::array<std::string, 8> phySearchStateNames = { "CellSearchPass", // 0 "CellSearchFail", // 1 "MIBSearchPass", // 2 "MIBSearchFail", // 3 "SFNSearchPass", // 4 "SFNSearchFail", // 5 "SyncSearchPass", // 6 "SyncSearchFail" }; // 7 std::array<std::uint64_t, 8> phySearchStateCounts_; void setPhySearchStateCell_i(size_t state, bool bStatus) { if(pPhySearchStateTable_) { // state plus pass/fail offset const size_t idx = state + (bStatus ? 0 : 1); // row, column, value pPhySearchStateTable_->setCell(idx, 1, OpenStatistic::Any{++phySearchStateCounts_[idx]}); pPhySearchStateTable_->setCell(idx, 2, OpenStatistic::Any{time(NULL)}); } } EMANELTE::IPTrafficTable * pDlIPTrafficTable_ = NULL; EMANELTE::IPTrafficTable * pUlIPTrafficTable_ = NULL; EMANELTE::IPTrafficDB dlTrafficDB_; EMANELTE::IPTrafficDB ulTrafficDB_; GrantRNTICounter ulGrantDB_; ChannelRNTICounter pdcchDB_; ChannelRNTICounter pdschDB_; } void UESTATS::initialize(float report_interval_secs) { OpenStatistic::Service * service = OpenStatistic::Service::instance(); OpenStatistic::Registrar & registrar = service->registrar(); report_interval_secs_ = report_interval_secs; // phy state search table pPhySearchStateTable_ = registrar.registerTable<std::uint64_t>( "PhySearchStateTable", {"State", "Count", "Time"}, OpenStatistic::StatisticProperties::NONE, "Phy Search State Table"); // fixed size table, setup all rows for(size_t n = 0; n < phySearchStateNames.size(); ++n) { pPhySearchStateTable_->addRow( n, {OpenStatistic::Any{phySearchStateNames[n]}, // 0 State OpenStatistic::Any{std::uint64_t{}}, // 1 Count OpenStatistic::Any{std::uint64_t{}}}); // 2 Time } // node info table pNodeInfoTable_ = registrar.registerTable<std::uint64_t>( "NodeInfoTable", {"RNTI", "IpAddress", "Netmask", "RRCState", "EMMState", "Time"}, OpenStatistic::StatisticProperties::NONE, "Node Info Table"); // fixed size table, setup 1 row pNodeInfoTable_->addRow( 0, {OpenStatistic::Any{std::uint64_t{}}, // 0 RNTI OpenStatistic::Any{"N/A"}, // 1 IpAddress OpenStatistic::Any{"N/A"}, // 2 Netmask OpenStatistic::Any{"N/A"}, // 3 RRCState OpenStatistic::Any{"N/A"}, // 4 EMMState OpenStatistic::Any{std::uint64_t{}}}); // 5 Time // thruput table pGWThruputTable_ = registrar.registerTable<std::uint64_t>( "GWThruputTable", {"DLKbps", "ULKbps", "Time"}, OpenStatistic::StatisticProperties::NONE, "Gateway Thruput Table in kbps"); // fixed size table, setup 1 row pGWThruputTable_->addRow( 0, {OpenStatistic::Any{std::uint64_t{}}, // 0 DL OpenStatistic::Any{std::uint64_t{}}, // 1 UL OpenStatistic::Any{std::uint64_t{}}}); // 2 Time // variable length rlc thruput table pRLCThruputTable_ = registrar.registerTable<std::uint64_t>( "RLCThruputTable", {"LCID", "DLKbps", "ULKbps", "Type", "Cap", "Size", "HighWater", "NumPush", "NumPushFail", "NumPop", "NumPopFail", "Cleared", "Time"}, OpenStatistic::StatisticProperties::NONE, "RLC Thruput Table in kbps"); // variable length rlc mrb thruput table pRLCMRBThruputTable_ = registrar.registerTable<std::uint64_t>( "RLCMRBThruputTable", {"LCID", "DLKbps", "Type", "Cap", "Size", "HighWater", "NumPush", "NumPushFail", "NumPop", "NumPopFail", "Cleared", "Time"}, OpenStatistic::StatisticProperties::NONE, "RLC MRB Thruput Table in kbps"); // variable length cell table pCellTable_ = registrar.registerTable<std::uint64_t>( "CellTable", {"Id", "EARFCN", "Peak SNR", "Time"}, OpenStatistic::StatisticProperties::NONE, "Cell Table"); // mac table pMacTable_ = registrar.registerTable<std::uint64_t>( "MACTable", {"ULPkts", "ULErr", "ULKbps", "ULPkts", "ULErr", "DLKbps", "ULBuffer", "DLRetxAvg", "ULRetxAvg", "Time"}, OpenStatistic::StatisticProperties::NONE, "Mac Table"); // fixed size table, setup 1 row pMacTable_->addRow( 0, {OpenStatistic::Any{std::uint64_t{}}, // 0 ULPkts OpenStatistic::Any{std::uint64_t{}}, // 1 ULErr OpenStatistic::Any{std::uint64_t{}}, // 2 ULRate OpenStatistic::Any{std::uint64_t{}}, // 3 DLPkts OpenStatistic::Any{std::uint64_t{}}, // 4 DLErr OpenStatistic::Any{0.0}, // 5 DLRate OpenStatistic::Any{std::uint64_t{}}, // 6 ULBuffer OpenStatistic::Any{0.0}, // 7 DLRetxAvg OpenStatistic::Any{0.0}, // 8 ULRetxAvg OpenStatistic::Any{std::uint64_t{}}}); // 9 Time // phy table pPhyTable_ = registrar.registerTable<std::uint64_t>( "PHYTable", {"CFO", "SFO", "DLSINR", "DLNoise", "DLRSRP", "DLRSRQ", "DLRSSI", "DLMCS", "DLPathLoss", "DLMbps", "ULMCS", "ULPower", "ULMbps", "Time"}, OpenStatistic::StatisticProperties::NONE, "Phy Table"); // fixed size table, setup 1 row pPhyTable_->addRow( 0, {OpenStatistic::Any{0.0}, // 0 CFO OpenStatistic::Any{0.0}, // 1 SFO OpenStatistic::Any{0.0}, // 2 DLSINR OpenStatistic::Any{0.0}, // 3 DLNoise OpenStatistic::Any{0.0}, // 4 DLRSRP OpenStatistic::Any{0.0}, // 5 DLRSRQ OpenStatistic::Any{0.0}, // 6 DLRSSI OpenStatistic::Any{0.0}, // 7 DLMCS OpenStatistic::Any{0.0}, // 8 DLPathLoss OpenStatistic::Any{0.0}, // 9 DLMbps OpenStatistic::Any{0.0}, // 10 ULMCS OpenStatistic::Any{0.0}, // 11 ULPower OpenStatistic::Any{0.0}, // 12 ULMbps OpenStatistic::Any{uint64_t{}}}); // 13 Time // variable length tables pDlIPTrafficTable_ = registrar.registerTable<std::string>( "DownlinkTrafficTable", {"Src", "Dst", "Count", "Bytes", "Time"}, OpenStatistic::StatisticProperties::NONE, "Downlink Traffic Table"); // variable length tables pUlIPTrafficTable_ = registrar.registerTable<std::string>( "UplinkTrafficTable", {"Src", "Dst", "Count", "Bytes", "Time"}, OpenStatistic::StatisticProperties::NONE, "Uplink Traffic Table"); pULGrantRntiTable_ = registrar.registerTable<std::uint64_t>( "ULGrantTable", {"RNTI", "Count", "Time"}, OpenStatistic::StatisticProperties::NONE, "Uplink Grants tx per RNTI"); pPDCCHRntiTable_ = registrar.registerTable<std::uint64_t>( "PDCCHGrantTable", {"RNTI", "Pass", "Fail", "Time"}, OpenStatistic::StatisticProperties::NONE, "Dowmlink PDCCH Grants rx per RNTI"); pPDSCHRntiTable_ = registrar.registerTable<std::uint64_t>( "PDSCHGrantTable", {"RNTI", "Pass", "Fail", "Time"}, OpenStatistic::StatisticProperties::NONE, "Dowmlink PDSCH Grants rx per RNTI"); } void UESTATS::enterCellSearch(const UESTATS::Cells & cells, std::uint32_t earfcn) { const time_t ts = time(NULL); setPhySearchStateCell_i(0, !cells.empty()); // update cell table if(pCellTable_) { pCellTable_->clear(); size_t n = 0; for(auto & cell : cells) { pCellTable_->addRow( n++, {OpenStatistic::Any{cell.first}, OpenStatistic::Any{uint64_t{earfcn}}, OpenStatistic::Any{cell.second}, OpenStatistic::Any{ts}}); } } } void UESTATS::enterMibSearch(bool bStatus) { setPhySearchStateCell_i(2, bStatus); } void UESTATS::enterSysFrameSearch(bool bStatus) { setPhySearchStateCell_i(4, bStatus); } void UESTATS::enterSyncSearch(bool bStatus) { setPhySearchStateCell_i(6, bStatus); } void UESTATS::setCrnti(std::uint16_t crnti) { if(pNodeInfoTable_) { pNodeInfoTable_->setCell(0, 0, OpenStatistic::Any{static_cast<uint64_t>(crnti)}); pNodeInfoTable_->setCell(0, 5, OpenStatistic::Any{time(NULL)}); } } void UESTATS::setIpAddress(uint32_t ip_addr, uint32_t netmask) { if(pNodeInfoTable_) { pNodeInfoTable_->setCell(0, 1, OpenStatistic::Any{inet_ntoa(*((in_addr*)&ip_addr))}); // addr pNodeInfoTable_->setCell(0, 2, OpenStatistic::Any{inet_ntoa(*((in_addr*)&netmask))}); // netmask pNodeInfoTable_->setCell(0, 5, OpenStatistic::Any{time(NULL)}); // timestamp } } void UESTATS::setRRCState(const char * state) { if(pNodeInfoTable_) { pNodeInfoTable_->setCell(0, 3, OpenStatistic::Any{state}); // state pNodeInfoTable_->setCell(0, 5, OpenStatistic::Any{time(NULL)}); // timestamp } } void UESTATS::setEMMState(const char * state) { if(pNodeInfoTable_) { pNodeInfoTable_->setCell(0, 4, OpenStatistic::Any{state}); // state pNodeInfoTable_->setCell(0, 5, OpenStatistic::Any{time(NULL)}); // timestamp } } void UESTATS::setRLCMetrics(const UESTATS::RLCMetrics & metrics) { if(pRLCThruputTable_) { pRLCThruputTable_->clear(); for(size_t n = 0; n < metrics.qmetrics_.size(); ++n) { pRLCThruputTable_->addRow(n, {OpenStatistic::Any{n}, // LCID OpenStatistic::Any{1e3 * metrics.dl_mbps_[n]}, // DL kbps OpenStatistic::Any{1e3 * metrics.ul_mbps_[n]}, // UL kbps OpenStatistic::Any{metrics.qmetrics_[n].typeToString()}, // type OpenStatistic::Any{metrics.qmetrics_[n].capacity_}, // capacity OpenStatistic::Any{metrics.qmetrics_[n].currSize_}, // currsize OpenStatistic::Any{metrics.qmetrics_[n].highWater_}, // highwater OpenStatistic::Any{metrics.qmetrics_[n].numPush_}, // numPush OpenStatistic::Any{metrics.qmetrics_[n].numPushFail_}, // numPushFail OpenStatistic::Any{metrics.qmetrics_[n].numPop_}, // numPop OpenStatistic::Any{metrics.qmetrics_[n].numPopFail_}, // numPopFail OpenStatistic::Any{metrics.qmetrics_[n].numCleared_}, // numCleared OpenStatistic::Any{time(NULL)}}); // timestamp } } if(pRLCMRBThruputTable_) { pRLCMRBThruputTable_->clear(); for(size_t n = 0; n < metrics.mrb_qmetrics_.size(); ++n) { pRLCMRBThruputTable_->addRow(n, {OpenStatistic::Any{n}, // LCID OpenStatistic::Any{1e3 * metrics.dl_mrb_mbps_[n]}, // DL kbps OpenStatistic::Any{metrics.mrb_qmetrics_[n].typeToString()}, // type OpenStatistic::Any{metrics.mrb_qmetrics_[n].capacity_}, // capacity OpenStatistic::Any{metrics.mrb_qmetrics_[n].currSize_}, // currsize OpenStatistic::Any{metrics.mrb_qmetrics_[n].highWater_}, // highwater OpenStatistic::Any{metrics.mrb_qmetrics_[n].numPush_}, // numPush OpenStatistic::Any{metrics.mrb_qmetrics_[n].numPushFail_}, // numPushFail OpenStatistic::Any{metrics.mrb_qmetrics_[n].numPop_}, // numPop OpenStatistic::Any{metrics.mrb_qmetrics_[n].numPopFail_}, // numPopFail OpenStatistic::Any{metrics.mrb_qmetrics_[n].numCleared_}, // numCleared OpenStatistic::Any{time(NULL)}}); // timestamp } } } void UESTATS::setGWMetrics(const UESTATS::GWMetrics & metrics) { if(pGWThruputTable_) { pGWThruputTable_->setCell(0, 0, OpenStatistic::Any{1e3 * metrics.dl_mbps_}); // kbps pGWThruputTable_->setCell(0, 1, OpenStatistic::Any{1e3 * metrics.ul_mbps_}); // kbps pGWThruputTable_->setCell(0, 2, OpenStatistic::Any{time(NULL)}); // timestamp } } void UESTATS::setMACMetrics(const UESTATS::MACMetrics & metrics) { if(pMacTable_) { pMacTable_->setRow( 0, {OpenStatistic::Any{metrics.tx_pkts_}, OpenStatistic::Any{metrics.tx_errors_}, OpenStatistic::Any{metrics.tx_brate_kbps_/report_interval_secs_}, OpenStatistic::Any{metrics.rx_pkts_}, OpenStatistic::Any{metrics.rx_errors_}, OpenStatistic::Any{metrics.rx_brate_kbps_/report_interval_secs_}, OpenStatistic::Any{metrics.ul_buffer_}, OpenStatistic::Any{metrics.dl_retx_avg_}, OpenStatistic::Any{metrics.ul_retx_avg_}, OpenStatistic::Any{time(NULL)}}); } } void UESTATS::setPHYMetrics(const UESTATS::PHYMetrics & metrics) { if(pPhyTable_) { pPhyTable_->setRow( 0, {OpenStatistic::Any{metrics.sync_cfo_}, OpenStatistic::Any{metrics.sync_sfo_}, OpenStatistic::Any{metrics.dl_sinr_}, OpenStatistic::Any{metrics.dl_noise_}, OpenStatistic::Any{metrics.dl_rsrp_}, OpenStatistic::Any{metrics.dl_rsrq_}, OpenStatistic::Any{metrics.dl_rssi_}, OpenStatistic::Any{metrics.dl_mcs_}, OpenStatistic::Any{metrics.dl_pathloss_}, OpenStatistic::Any{metrics.dl_mabr_mbps_}, OpenStatistic::Any{metrics.ul_mcs_}, OpenStatistic::Any{metrics.ul_power_}, OpenStatistic::Any{metrics.ul_mabr_mbps_}, OpenStatistic::Any{time(NULL)}}); } } void UESTATS::updateUplinkTraffic(uint32_t src, uint32_t dst, size_t numBytes) { updateIPTrafficTable_(pUlIPTrafficTable_, ulTrafficDB_, src, dst, numBytes); } void UESTATS::updateDownlinkTraffic(uint32_t src, uint32_t dst, size_t numBytes) { updateIPTrafficTable_(pDlIPTrafficTable_, dlTrafficDB_, src, dst, numBytes); } void UESTATS::putULGrant(uint16_t rnti) { auto iter = ulGrantDB_.find(rnti); if(iter == ulGrantDB_.end()) { pULGrantRntiTable_->addRow(rnti, {OpenStatistic::Any{uint64_t{rnti}}, OpenStatistic::Any{uint64_t{1}}, OpenStatistic::Any{time(NULL)}}); ulGrantDB_.insert(std::make_pair(rnti, 1)); } else { pULGrantRntiTable_->setRow(rnti, {OpenStatistic::Any{uint64_t{rnti}}, OpenStatistic::Any{uint64_t{++iter->second}}, OpenStatistic::Any{time(NULL)}}); } } void UESTATS::getPDCCH(uint16_t rnti, bool bPass) { updateChannelCounter_i(rnti, bPass, pPDCCHRntiTable_, pdcchDB_); } void UESTATS::getPDSCH(uint16_t rnti, bool bPass) { updateChannelCounter_i(rnti, bPass, pPDSCHRntiTable_, pdschDB_); } <file_sep>/* * Copyright (c) 2019 - Adjacent Link LLC, Bridgewater, New Jersey * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Adjacent Link LLC nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * See toplevel COPYING for more information. */ #ifndef EMANELTE_UESTATISTICMANAGER_H #define EMANELTE_UESTATISTICMANAGER_H #include <stdint.h> #include <arpa/inet.h> #include <map> #include <vector> namespace UESTATS { void initialize(float report_interval_secs); typedef std::map<uint64_t, float> Cells; void enterCellSearch(const Cells & cells, uint32_t earfcn); void enterMibSearch(bool bStatus); void enterSysFrameSearch(bool bStatus); void enterSyncSearch(bool bStatus); void setCrnti(uint16_t crtni); void setIpAddress(uint32_t ip_addr, uint32_t netmask); void setRRCState(const char * state); void setEMMState(const char * state); struct GWMetrics { const float dl_mbps_; const float ul_mbps_; GWMetrics(float dl, float ul): dl_mbps_(dl), ul_mbps_(ul) {} }; void setGWMetrics(const GWMetrics & metrics); struct RLCQueueMetrics { int type_; int64_t capacity_; uint64_t currSize_; uint64_t highWater_; uint64_t numCleared_; uint64_t numPush_; uint64_t numPushFail_; uint64_t numPop_; uint64_t numPopFail_; RLCQueueMetrics() : type_(-1), capacity_(0), currSize_(0), highWater_(0), numCleared_(0), numPush_(0), numPushFail_(0), numPop_(0), numPopFail_(0) { } RLCQueueMetrics(int type, int64_t capacity, uint64_t currSize, uint64_t highWater, uint64_t numCleared, uint64_t numPush, uint64_t numPushFail, uint64_t numPop, uint64_t numPopFail) : type_(type), capacity_(capacity), currSize_(currSize), highWater_(highWater), numCleared_(numCleared), numPush_(numPush), numPushFail_(numPushFail), numPop_(numPop), numPopFail_(numPopFail) { } std::string typeToString() const { return type_ == 0 ? "TM" : type_ == 1 ? "UM" : type_ == 2 ? "AM" : "N/A"; } }; typedef std::vector<RLCQueueMetrics> RLCQueueMetricsList; // see lib/src/upper/rlc.cc dl == rx, ul == tx struct RLCMetrics { const float * dl_mbps_; const float * ul_mbps_; const RLCQueueMetricsList & qmetrics_; const float * dl_mrb_mbps_; const RLCQueueMetricsList & mrb_qmetrics_; RLCMetrics(const float * dl, const float * ul, const RLCQueueMetricsList & qmetrics, const float * dl_mrb, const RLCQueueMetricsList & mrb_qmetrics) : dl_mbps_(dl), ul_mbps_(ul), qmetrics_(qmetrics), dl_mrb_mbps_(dl_mrb), mrb_qmetrics_(mrb_qmetrics) { } }; void setRLCMetrics(const RLCMetrics & metrics); struct MACMetrics { const uint64_t tx_pkts_; const uint64_t tx_errors_; const float tx_brate_kbps_; const uint64_t rx_pkts_; const uint64_t rx_errors_; const float rx_brate_kbps_; const uint64_t ul_buffer_; const float dl_retx_avg_; const float ul_retx_avg_; MACMetrics(int tx_pkts, int tx_errors, int tx_brate, int rx_pkts, int rx_errors, int rx_brate, int ul_buffer, float dl_retx_avg, float ul_retx_avg): tx_pkts_(tx_pkts), tx_errors_(tx_errors), tx_brate_kbps_(tx_brate/1e3), rx_pkts_(rx_pkts), rx_errors_(rx_errors), rx_brate_kbps_(rx_brate/1e3), ul_buffer_(ul_buffer), dl_retx_avg_(dl_retx_avg), ul_retx_avg_(ul_retx_avg) {} }; void setMACMetrics(const MACMetrics & metrics); struct PHYMetrics { const float sync_ta_us_; const float sync_cfo_; const float sync_sfo_; const float dl_noise_; const float dl_sinr_; const float dl_rsrp_; const float dl_rsrq_; const float dl_rssi_; const float dl_turbo_iters_; const float dl_mcs_; const float dl_pathloss_; const float dl_mabr_mbps_; const float ul_mcs_; const float ul_power_; const float ul_mabr_mbps_; PHYMetrics(float sync_ta_us, float sync_cfo, float sync_sfo, float dl_noise, float dl_sinr, float dl_rsrp, float dl_rsrq, float dl_rssi, float dl_turbo_iters, float dl_mcs, float dl_pathloss, float dl_mabr_mbps, float ul_mcs, float ul_power, float ul_mabr_mbps): sync_ta_us_(sync_ta_us), sync_cfo_(sync_cfo), sync_sfo_(sync_sfo), dl_noise_(dl_noise), dl_sinr_(dl_sinr), dl_rsrp_(dl_rsrp), dl_rsrq_(dl_rsrq), dl_rssi_(dl_rssi), dl_turbo_iters_(dl_turbo_iters), dl_mcs_(dl_mcs), dl_pathloss_(dl_pathloss), dl_mabr_mbps_(dl_mabr_mbps), ul_mcs_(ul_mcs), ul_power_(ul_power), ul_mabr_mbps_(ul_mabr_mbps) {} }; void setPHYMetrics(const PHYMetrics & metrics); void updateUplinkTraffic(uint32_t src, uint32_t dst, size_t numBytes); void updateDownlinkTraffic(uint32_t src, uint32_t dst, size_t numBytes); void putULGrant(uint16_t rnti); void getPDCCH(uint16_t rnti, bool bPass); void getPDSCH(uint16_t rnti, bool bPass); } #endif // EMANELTE_UESTATISTICMANAGER_H <file_sep>#!/bin/bash - top_dir=$1 node_name=$2 start_time=$3 echo "top_dir: $top_dir" echo "node_name: $node_name" echo "start_time: $start_time" cd $top_dir/$node_name cp -f $top_dir/../templates/ue/dot_fftw_wisdom $top_dir/$node_name/dot_fftw_wisdom cp -f $top_dir/../templates/ue/pcr.xml $top_dir/$node_name/pcr.xml rm -f .ctxt srsue-emane ue.conf # start otestpointd if [ -f otestpointd.xml ]; then otestpointd -d otestpointd.xml fi <file_sep>/* * Copyright (c) 2019 - Adjacent Link LLC, Bridgewater, New Jersey * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Adjacent Link LLC nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * See toplevel COPYING for more information. */ #include "radiomodel.h" #include "mhalphy.h" #include "basicstatistichelper.h" #include "emane/frequencysegment.h" #include "emane/controls/serializedcontrolmessage.h" #include "emane/controls/frequencycontrolmessage.h" #include "emane/controls/frequencyofinterestcontrolmessage.h" #include "emane/controls/receivepropertiescontrolmessage.h" #include "emane/controls/receivepropertiescontrolmessageformatter.h" #include "emane/controls/frequencycontrolmessageformatter.h" #include "emane/controls/timestampcontrolmessage.h" #include "emane/configureexception.h" #include "emane/utils/parameterconvert.h" namespace { const char * pzModuleName_ = "RadioModel"; inline EMANE::Microseconds tvToMicroseconds(const timeval & tv) { return EMANE::Microseconds{tv.tv_sec * 1000000 + tv.tv_usec}; } inline timeval tpToTimeval(const EMANE::TimePoint & tp) { const EMANE::Microseconds usecs{std::chrono::duration_cast<EMANE::Microseconds>(tp.time_since_epoch())}; return timeval{usecs.count()/1000000, usecs.count()%1000000}; } } template <class RadioStatManager, class MessageProcessor> EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::RadioModel(EMANE::NEMId id, EMANE::PlatformServiceProvider * pPlatformService, EMANE::RadioServiceProvider * pRadioService) : MACLayerImplementor{id, pPlatformService, pRadioService}, bRunning_{}, subframeIntervalMicroseconds_{}, u16SubId_{}, pcrCurveURI_{}, maxPropagationDelay_{}, u64TxSeqNum_{}, u64RxFrequencyHz_{}, u64TxFrequencyHz_{}, u32NumResourceBlocks_{}, u32SymbolsPerSlot_{}, statisticManager_{id, pPlatformService}, messageProcessor_(id, pPlatformService, statisticManager_) {} template <class RadioStatManager, class MessageProcessor> EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::~RadioModel() {} template <class RadioStatManager, class MessageProcessor> void EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::initialize(EMANE::Registrar & registrar) { LOGGER_STANDARD_LOGGING(pPlatformService_->logService(), EMANE::INFO_LEVEL, "%s %03hu %s", pzModuleName_, id_, __func__); auto & configRegistrar = registrar.configurationRegistrar(); configRegistrar.registerNonNumeric<std::string>("subid", EMANE::ConfigurationProperties::DEFAULT, {"65533"}, "EMANE Lte Radio Model SubId"); configRegistrar.registerNonNumeric<std::string>("maxpropagationdelay", EMANE::ConfigurationProperties::DEFAULT, {"0"}, "EMANE Lte Radio Model Max Propagation Delay"); configRegistrar.registerNonNumeric<std::string>("pcrcurveuri", EMANE::ConfigurationProperties::REQUIRED, {}, "Defines the URI of the Packet Completion Rate (PCR) curve " "file. The PCR curve file contains probability of reception curves " "as a function of Signal to Interference plus Noise Ratio (SINR)."); configRegistrar.registerNonNumeric<std::string>("resourceblocktxpower", EMANE::ConfigurationProperties::DEFAULT, {"0.0"}, "The transmit power per LTE Resource Block in dBm."); statisticManager_.registerStatistics(registrar); auto & statisticRegistrar = registrar.statisticRegistrar(); pSubframeReceiveCounts_ = statisticRegistrar.registerTable<std::uint64_t>( "SubframeReceiveCounts", {"NEMId", "NumPass", "DropPropDelay", "DropFreqMismatch", "DropDirection", "Time"}, EMANE::StatisticProperties::NONE, "Tally of results from checks on subframe receive messages organized by sender: " "NumPass - subframe passes all checks. " "DropPropDelay - subframe dropped because it exceeds the value fo maxpropagationdelay parameter. " "DropFreqMismatch - subframe dropped because the transmitter and receiver are not on the same carrier frequency. " "DropDirection - subframe dropped if an uplink message is expected and a downlink message is received, and vice versa. " "Time - the last time a check occurred."); } template <class RadioStatManager, class MessageProcessor> void EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::configure(const EMANE::ConfigurationUpdate & update) { for(const auto & item : update) { if(item.first == "subid") { u16SubId_ = EMANE::Utils::ParameterConvert(item.second[0].asString()).toUINT16(); LOGGER_STANDARD_LOGGING(pPlatformService_->logService(), EMANE::INFO_LEVEL, "%s %03hu %s: %s = %hu", pzModuleName_, id_, __func__, item.first.c_str(), u16SubId_); } else if(item.first == "maxpropagationdelay") { maxPropagationDelay_ = EMANE::Microseconds(EMANE::Utils::ParameterConvert(item.second[0].asString()).toUINT64()); LOGGER_STANDARD_LOGGING(pPlatformService_->logService(), EMANE::INFO_LEVEL, "%s %03hu %s: %s = %lu", pzModuleName_, id_, __func__, item.first.c_str(), maxPropagationDelay_.count()); } else if(item.first == "pcrcurveuri") { pcrCurveURI_ = item.second[0].asString(); LOGGER_STANDARD_LOGGING(pPlatformService_->logService(), EMANE::INFO_LEVEL, "%s %03hu %s: %s = %s", pzModuleName_, id_, __func__, item.first.c_str(), pcrCurveURI_.c_str()); messageProcessor_.loadPCRFile(pcrCurveURI_); } else if(item.first == "resourceblocktxpower") { float resourceBlockTxPowerdBm{EMANE::Utils::ParameterConvert(item.second[0].asString()).toFloat()}; messageProcessor_.setTxPower(resourceBlockTxPowerdBm); LOGGER_STANDARD_LOGGING(pPlatformService_->logService(), EMANE::INFO_LEVEL, "%s %03hu %s: %s = %0.1f", pzModuleName_, id_, __func__, item.first.c_str(), resourceBlockTxPowerdBm); } else { throw EMANE::makeException<EMANE::ConfigureException>("EMANE::Models::LTE::RadioModel: " "Unexpected configuration item %s", item.first.c_str()); } } } template <class RadioStatManager, class MessageProcessor> void EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::start() { LOGGER_STANDARD_LOGGING(pPlatformService_->logService(), EMANE::INFO_LEVEL, "%s %03hu %s", pzModuleName_, id_, __func__); bRunning_ = true; } template <class RadioStatManager, class MessageProcessor> void EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::postStart() { LOGGER_STANDARD_LOGGING(pPlatformService_->logService(), EMANE::INFO_LEVEL, "%s %03hu %s", pzModuleName_, id_, __func__); } template <class RadioStatManager, class MessageProcessor> void EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::stop() { LOGGER_STANDARD_LOGGING(pPlatformService_->logService(), EMANE::INFO_LEVEL, "%s %03hu %s", pzModuleName_, id_, __func__); bRunning_ = false; } template <class RadioStatManager, class MessageProcessor> void EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::destroy() throw() { LOGGER_STANDARD_LOGGING(pPlatformService_->logService(), EMANE::INFO_LEVEL, "%s %03hu %s", pzModuleName_, id_, __func__); } template <class RadioStatManager, class MessageProcessor> void EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::processDownstreamControl(const EMANE::ControlMessages &) { // no-op } template <class RadioStatManager, class MessageProcessor> void EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::processDownstreamPacket(EMANE::DownstreamPacket &, const EMANE::ControlMessages &) { // no-op } template <class RadioStatManager, class MessageProcessor> void EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::processUpstreamControl(const EMANE::ControlMessages & /* msgs */) { LOGGER_STANDARD_LOGGING(pPlatformService_->logService(), EMANE::INFO_LEVEL, "%s %03hu %s:XXX TODO", pzModuleName_, id_, __func__); } template <class RadioStatManager, class MessageProcessor> void EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::processTimedEvent(EMANE::TimerEventId eventId, const EMANE::TimePoint & /* expireTime */, const EMANE::TimePoint & /* scheduleTime */, const EMANE::TimePoint & /* fireTime */, const void * /* arg */) { LOGGER_STANDARD_LOGGING(pPlatformService_->logService(), EMANE::INFO_LEVEL, "%s %03hu %s: unexpected event id %ld", pzModuleName_, id_, __func__, eventId); } template <class RadioStatManager, class MessageProcessor> void EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::setMHAL(EMANELTE::MHAL::PHY::MHALPHY * pMHAL) { pMHAL_ = pMHAL; } template <class RadioStatManager, class MessageProcessor> void EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::setSubframeInterval(std::uint32_t sfIntervalMsec) { LOGGER_STANDARD_LOGGING(pPlatformService_->logService(), EMANE::INFO_LEVEL, "%s %03hu %s: sf_interval_msec %u", pzModuleName_, id_, __func__, sfIntervalMsec); subframeIntervalMicroseconds_ = EMANE::Microseconds(sfIntervalMsec * 1000); } template <class RadioStatManager, class MessageProcessor> void EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::setSymbolsPerSlot(std::uint32_t symbolsPerSlot) { LOGGER_STANDARD_LOGGING(pPlatformService_->logService(), EMANE::INFO_LEVEL, "%s %03hu %s: symbols_per_slot %u", pzModuleName_, id_, __func__, symbolsPerSlot); u32SymbolsPerSlot_ = symbolsPerSlot; } template <class RadioStatManager, class MessageProcessor> void EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::setNumResourceBlocks(std::uint32_t numResourceBlocks, bool search) { EMANELTE::FrequencyHz halfChannelBandwidthHz{ numResourceBlocks * EMANELTE::ResourceBlockBandwidthHz + EMANELTE::HalfResourceBlockBandwidthHz}; // Don't allow configured channel to have negative frequencies if(halfChannelBandwidthHz > u64RxFrequencyHz_ || halfChannelBandwidthHz > u64TxFrequencyHz_) { throw EMANE::makeException<EMANE::ConfigureException>("Invalid configuration, first resource block crosses 0 Hz."); } LOGGER_STANDARD_LOGGING(pPlatformService_->logService(), EMANE::INFO_LEVEL, "%s %03hu %s: numResourceBlocks %d, search %d", pzModuleName_, id_, __func__, numResourceBlocks, search); u32NumResourceBlocks_ = numResourceBlocks; setFrequenciesOfInterest(search); } template <class RadioStatManager, class MessageProcessor> void EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::setFrequencies(EMANELTE::FrequencyHz rxFrequency, EMANELTE::FrequencyHz txFrequency) { LOGGER_STANDARD_LOGGING(pPlatformService_->logService(), EMANE::INFO_LEVEL, "%s %03hu %s: rx_freq %lu, tx_freq %lu", pzModuleName_, id_, __func__, rxFrequency, txFrequency); u64RxFrequencyHz_ = rxFrequency; u64TxFrequencyHz_ = txFrequency; } template <class RadioStatManager, class MessageProcessor> EMANELTE::FrequencyHz EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::getRxResourceBlockFrequency(std::uint32_t resourceBlockIndex) const { return getResourceBlockFrequency(resourceBlockIndex, u64RxFrequencyHz_, u32NumResourceBlocks_); } template <class RadioStatManager, class MessageProcessor> EMANELTE::FrequencyHz EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::getTxResourceBlockFrequency(std::uint32_t resourceBlockIndex) const { return getResourceBlockFrequency(resourceBlockIndex, u64TxFrequencyHz_, u32NumResourceBlocks_); } template <class RadioStatManager, class MessageProcessor> EMANELTE::FrequencyHz EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::getResourceBlockFrequency(std::uint64_t resourceBlockIndex, EMANELTE::FrequencyHz centerFreq, std::uint64_t numResourceBlocks) const { return centerFreq + ((resourceBlockIndex - numResourceBlocks/2) * 180000) + (((numResourceBlocks + 1) % 2) * 90000); } template <class RadioStatManager, class MessageProcessor> EMANE::SpectrumWindow EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::getNoise(EMANELTE::FrequencyHz frequency, const EMANE::Microseconds & span, const EMANE::TimePoint & sor) { EMANE::SpectrumWindow spectrumWindow; try { spectrumWindow = pRadioService_->spectrumService().request(frequency, span, sor); } catch(EMANE::SpectrumServiceException & exp) { LOGGER_STANDARD_LOGGING(pPlatformService_->logService(), EMANE::ERROR_LEVEL, "%s %03hu %s: %s", pzModuleName_, id_, __func__, exp.what()); } return spectrumWindow; } template <class RadioStatManager, class MessageProcessor> double EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::getReceiverSensitivitydBm() { return pRadioService_->spectrumService().getReceiverSensitivitydBm(); } template <class RadioStatManager, class MessageProcessor> EMANE::FrequencySet EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::getFrequencies() { return pRadioService_->spectrumService().getFrequencies(); } template <class RadioStatManager, class MessageProcessor> void EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::setFrequenciesOfInterest(bool search) { LOGGER_STANDARD_LOGGING(pPlatformService_->logService(), EMANE::INFO_LEVEL, "MACI %03hu %s::%s: search=%d.", id_, pzModuleName_, __func__, search); EMANE::FrequencySet rxFrequencies{}; EMANELTE::FrequencyResourceBlockMap rxFreqToRBMap{}; EMANE::FrequencySet txFrequencies{}; EMANELTE::FrequencyResourceBlockMap txFreqToRBMap{}; EMANELTE::FrequencyHz freq; for(uint32_t rbidx=0; rbidx<u32NumResourceBlocks_; ++rbidx) { freq = getTxResourceBlockFrequency(rbidx); LOGGER_STANDARD_LOGGING(pPlatformService_->logService(), EMANE::DEBUG_LEVEL, "%s %03hu %s: rbidx=%d txfreq=%lu", pzModuleName_, id_, __func__, rbidx, freq); txFreqToRBMap.insert(std::pair<EMANELTE::FrequencyHz, uint32_t>(freq, rbidx)); txFrequencies.insert(getTxResourceBlockFrequency(rbidx)); } for(uint32_t rbidx=0; rbidx<u32NumResourceBlocks_; ++rbidx) { freq = getRxResourceBlockFrequency(rbidx); LOGGER_STANDARD_LOGGING(pPlatformService_->logService(), EMANE::DEBUG_LEVEL, "%s %03hu %s: rbidx=%d rxfreq=%lu", pzModuleName_, id_, __func__, rbidx, freq); rxFreqToRBMap.insert(std::pair<EMANELTE::FrequencyHz, uint32_t>(freq, rbidx)); rxFrequencies.insert(freq); } // During cell search the ue doesn't know the enb bandwidth or the frequencies // which the enb is transmitting on. The enb may be configured for a bandwidth // that contains an even or an odd number of resource blocks. When told to // search, register FOI for the largest even (100) and odd (75) resource block // bandwidths to ensure receipt of enb packets from the phy for any enb. if(search) { if(u32NumResourceBlocks_ != 100) { LOGGER_STANDARD_LOGGING(pPlatformService_->logService(), EMANE::ERROR_LEVEL, "%s %03hu %s: Attempt to do cell search with numResourceBlocks set to %d. Ignoring.", pzModuleName_, id_, __func__, u32NumResourceBlocks_); return; } EMANELTE::FrequencyResourceBlockMap rx75FreqToRBMap{}; for(uint32_t rbidx=0; rbidx<75; ++rbidx) { freq = getResourceBlockFrequency(rbidx, u64RxFrequencyHz_, 75); LOGGER_STANDARD_LOGGING(pPlatformService_->logService(), EMANE::DEBUG_LEVEL, "%s %03hu %s: rbidx=%d rxfreq=%lu", pzModuleName_, id_, __func__, rbidx, freq); rx75FreqToRBMap.insert(std::pair<EMANELTE::FrequencyHz, uint32_t>(freq, rbidx)); rxFrequencies.insert(freq); } messageProcessor_.swapSearchFrequencyMaps(rxFreqToRBMap, rx75FreqToRBMap, txFreqToRBMap); } else { messageProcessor_.swapFrequencyMaps(rxFreqToRBMap, txFreqToRBMap); } statisticManager_.updateFrequencies(rxFrequencies, txFrequencies); sendDownstreamControl({EMANE::Controls::FrequencyOfInterestControlMessage::create(EMANELTE::ResourceBlockBandwidthHz, rxFrequencies)}); } template <class RadioStatManager, class MessageProcessor> void EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::sendDownstreamMessage(const EMANELTE::MHAL::Data & data, EMANELTE::MHAL::TxControlMessage & txControl, const EMANE::TimePoint & timestamp) { LOGGER_STANDARD_LOGGING(pPlatformService_->logService(), EMANE::DEBUG_LEVEL, "%s %03hu %s data_len %3zu, tti_tx %05u, sf_time %d:%06d, timestamp %f", pzModuleName_, id_, __func__, data.length(), txControl.tti_tx(), txControl.sf_time().ts_sec(), txControl.sf_time().ts_usec(), timestamp.time_since_epoch().count()/1e9); EMANE::FrequencySegments frequencySegments{ messageProcessor_.buildFrequencySegments(txControl, u32SymbolsPerSlot_)}; const EMANE::Microseconds sfDuration{txControl.subframe_duration_microsecs()}; txControl.set_tx_frequency_hz(u64TxFrequencyHz_); const EMANE::ControlMessages msgs = {EMANE::Controls::FrequencyControlMessage::create(EMANELTE::ResourceBlockBandwidthHz, frequencySegments), EMANE::Controls::TimeStampControlMessage::create(timestamp)}; // sot std::string sSerialization{}; txControl.SerializeToString(&sSerialization); EMANE::DownstreamPacket pkt{EMANE::PacketInfo{id_, EMANE::NEM_BROADCAST_MAC_ADDRESS, 0, EMANE::Clock::now()}, // clock tx time (creation time) data.data(), data.length()}; pkt.prepend(sSerialization.c_str(), sSerialization.length()); pkt.prependLengthPrefixFraming(sSerialization.length()); sendDownstreamPacket(EMANE::CommonMACHeader{u16SubId_, ++u64TxSeqNum_}, pkt, msgs); } template <class RadioStatManager, class MessageProcessor> void EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::processUpstreamPacket(const EMANE::CommonMACHeader & commonMACHeader, EMANE::UpstreamPacket & pkt, const EMANE::ControlMessages & controlMessages) { const EMANE::TimePoint tpRxTime = EMANE::Clock::now(); if(commonMACHeader.getRegistrationId() != u16SubId_) { LOGGER_STANDARD_LOGGING(pPlatformService_->logService(), EMANE::ERROR_LEVEL, "MACI %03hu %s::%s: MAC Registration Id %hu does not match our Id %hu, drop.", id_, pzModuleName_, __func__, commonMACHeader.getRegistrationId(), u16SubId_); return; } const EMANE::PacketInfo & pktInfo{pkt.getPacketInfo()}; const EMANE::Controls::ReceivePropertiesControlMessage * pReceivePropertiesControlMessage = NULL; const EMANE::Controls::FrequencyControlMessage * pFrequencyControlMessage = NULL; for(EMANE::ControlMessages::const_iterator iter = controlMessages.begin(); iter != controlMessages.end(); ++iter) { switch((*iter)->getId()) { case EMANE::Controls::ReceivePropertiesControlMessage::IDENTIFIER: { pReceivePropertiesControlMessage = static_cast<const EMANE::Controls::ReceivePropertiesControlMessage *>(*iter); } break; case EMANE::Controls::FrequencyControlMessage::IDENTIFIER: { pFrequencyControlMessage = static_cast<const EMANE::Controls::FrequencyControlMessage *>(*iter); } break; } } if(!pReceivePropertiesControlMessage || !pFrequencyControlMessage) { LOGGER_STANDARD_LOGGING(pPlatformService_->logService(), EMANE::ERROR_LEVEL, "MACI %03hu %s::%s: phy control " "message not provided from src %hu, drop", id_, pzModuleName_, __func__, pktInfo.getSource()); return; } const uint16_t prefixLength{pkt.stripLengthPrefixFraming()}; if(prefixLength && (pkt.length() >= prefixLength)) { // start of reception w/o segment offset info const std::string sSerialization{reinterpret_cast<const char*>(pkt.get()), prefixLength}; pkt.strip(prefixLength); EMANELTE::MHAL::TxControlMessage txControl; if(txControl.ParseFromString(sSerialization)) { LOGGER_VERBOSE_LOGGING(pPlatformService_->logService(), EMANE::DEBUG_LEVEL, "MACI %03hu %s::%s: src %hu, cell 0x%x, seqnum %lu, span %lu, prop_delay %lu, max_delay %lu", id_, pzModuleName_, __func__, pktInfo.getSource(), txControl.phy_cell_id(), txControl.tx_seqnum(), pReceivePropertiesControlMessage->getSpan().count(), pReceivePropertiesControlMessage->getPropagationDelay().count(), maxPropagationDelay_.count()); // if enabled (!=0) check propagation delay limit const bool bPassPropagationDelay = maxPropagationDelay_.count() > 0 ? pReceivePropertiesControlMessage->getPropagationDelay() <= maxPropagationDelay_ : true; if(!bPassPropagationDelay) { updateSubframeDropPropagationDelay_i(pktInfo.getSource()); return; } if(txControl.tx_frequency_hz() != u64RxFrequencyHz_) { updateSubframeDropFrequencyMismatch_i(pktInfo.getSource()); return; } if(txControl.message_type() != messageProcessor_.receiveMessageType_) { updateSubframeDropDirection_i(pktInfo.getSource()); return; } statisticManager_.updateRxTableCounts(txControl); pMHAL_->handle_upstream_msg( EMANELTE::MHAL::Data{reinterpret_cast<const char *>(pkt.get()), pkt.length()}, // opaque data EMANELTE::MHAL::RxData{pktInfo.getSource(), // src nem txControl.tx_seqnum(), // tx seqnum tpToTimeval(tpRxTime), // clock rx time tpToTimeval(pktInfo.getCreationTime()), // clock tx time timeval{txControl.sf_time().ts_sec(), // sf time txControl.sf_time().ts_usec()}, 0.0, // peak sum 0}, // num samples EMANELTE::MHAL::PHY::OTAInfo{pReceivePropertiesControlMessage->getTxTime(), // emulation sot pReceivePropertiesControlMessage->getPropagationDelay(), // propagation delay pReceivePropertiesControlMessage->getSpan(), // span pFrequencyControlMessage->getFrequencySegments()}, // freq segments txControl); // txControl updateSubframePass_i(pktInfo.getSource()); } else { LOGGER_STANDARD_LOGGING(pPlatformService_->logService(), EMANE::ERROR_LEVEL, "%s %03hu %s: serialization error prefix_len %hu, pkt_len %zu", pzModuleName_, id_, __func__, prefixLength, pkt.length()); } } else { LOGGER_STANDARD_LOGGING(pPlatformService_->logService(), EMANE::ERROR_LEVEL, "%s %03hu %s: pkt length error prefix_len %hu, pkt_len %zu", pzModuleName_, id_, __func__, prefixLength, pkt.length()); } } template <class RadioStatManager, class MessageProcessor> void EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::updateSubframePass_i(EMANE::NEMId id) { auto iter = subframeReceiveCountDB_.find(id); if(iter == subframeReceiveCountDB_.end()) { subframeReceiveCountDB_.insert(std::make_pair(id, SubframeReceiveCountEntry{1,0,0,0})).first; EMANELTE::addRowWithCheck_(pSubframeReceiveCounts_, id, {EMANE::Any{std::uint64_t{id}}, EMANE::Any{std::uint64_t{1}}, EMANE::Any{std::uint64_t{0}}, EMANE::Any{std::uint64_t{0}}, EMANE::Any{std::uint64_t{0}}, EMANE::Any{time(NULL)}}); } else { EMANELTE::setRowWithCheck_(pSubframeReceiveCounts_, id, {EMANE::Any{std::uint64_t{id}}, EMANE::Any{std::uint64_t{++std::get<0>(iter->second)}}, EMANE::Any{std::uint64_t{std::get<1>(iter->second)}}, EMANE::Any{std::uint64_t{std::get<2>(iter->second)}}, EMANE::Any{std::uint64_t{std::get<3>(iter->second)}}, EMANE::Any{time(NULL)}}); } } template <class RadioStatManager, class MessageProcessor> void EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::updateSubframeDropPropagationDelay_i(EMANE::NEMId id) { auto iter = subframeReceiveCountDB_.find(id); if(iter == subframeReceiveCountDB_.end()) { subframeReceiveCountDB_.insert(std::make_pair(id, SubframeReceiveCountEntry{0,1,0,0})).first; EMANELTE::addRowWithCheck_(pSubframeReceiveCounts_, id, {EMANE::Any{std::uint64_t{id}}, EMANE::Any{std::uint64_t{0}}, EMANE::Any{std::uint64_t{1}}, EMANE::Any{std::uint64_t{0}}, EMANE::Any{std::uint64_t{0}}, EMANE::Any{time(NULL)}}); } else { EMANELTE::setRowWithCheck_(pSubframeReceiveCounts_, id, {EMANE::Any{std::uint64_t{id}}, EMANE::Any{std::uint64_t{std::get<0>(iter->second)}}, EMANE::Any{std::uint64_t{++std::get<1>(iter->second)}}, EMANE::Any{std::uint64_t{std::get<2>(iter->second)}}, EMANE::Any{std::uint64_t{std::get<3>(iter->second)}}, EMANE::Any{time(NULL)}}); } } template <class RadioStatManager, class MessageProcessor> void EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::updateSubframeDropFrequencyMismatch_i(EMANE::NEMId id) { auto iter = subframeReceiveCountDB_.find(id); if(iter == subframeReceiveCountDB_.end()) { subframeReceiveCountDB_.insert(std::make_pair(id, SubframeReceiveCountEntry{0,0,1,0})).first; EMANELTE::addRowWithCheck_(pSubframeReceiveCounts_, id, {EMANE::Any{std::uint64_t{id}}, EMANE::Any{std::uint64_t{0}}, EMANE::Any{std::uint64_t{0}}, EMANE::Any{std::uint64_t{1}}, EMANE::Any{std::uint64_t{0}}, EMANE::Any{time(NULL)}}); } else { EMANELTE::setRowWithCheck_(pSubframeReceiveCounts_, id, {EMANE::Any{std::uint64_t{id}}, EMANE::Any{std::uint64_t{std::get<0>(iter->second)}}, EMANE::Any{std::uint64_t{std::get<1>(iter->second)}}, EMANE::Any{std::uint64_t{++std::get<2>(iter->second)}}, EMANE::Any{std::uint64_t{std::get<3>(iter->second)}}, EMANE::Any{time(NULL)}}); } } template <class RadioStatManager, class MessageProcessor> void EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::updateSubframeDropDirection_i(EMANE::NEMId id) { auto iter = subframeReceiveCountDB_.find(id); if(iter == subframeReceiveCountDB_.end()) { subframeReceiveCountDB_.insert(std::make_pair(id, SubframeReceiveCountEntry{0,0,0,1})).first; EMANELTE::addRowWithCheck_(pSubframeReceiveCounts_, id, {EMANE::Any{std::uint64_t{id}}, EMANE::Any{std::uint64_t{0}}, EMANE::Any{std::uint64_t{0}}, EMANE::Any{std::uint64_t{0}}, EMANE::Any{std::uint64_t{1}}, EMANE::Any{time(NULL)}}); } else { EMANELTE::setRowWithCheck_(pSubframeReceiveCounts_, id, {EMANE::Any{std::uint64_t{id}}, EMANE::Any{std::uint64_t{std::get<0>(iter->second)}}, EMANE::Any{std::uint64_t{std::get<1>(iter->second)}}, EMANE::Any{std::uint64_t{std::get<2>(iter->second)}}, EMANE::Any{std::uint64_t{++std::get<3>(iter->second)}}, EMANE::Any{time(NULL)}}); } } template <class RadioStatManager, class MessageProcessor> bool EMANE::Models::LTE::RadioModel<RadioStatManager, MessageProcessor>::noiseTestChannelMessage( const EMANELTE::MHAL::TxControlMessage & txControl, const EMANELTE::MHAL::ChannelMessage & channel_msg, SegmentMap & segmentCache) { return messageProcessor_.noiseTestChannelMessage(txControl, channel_msg, segmentCache); } namespace EMANE { namespace Models { namespace LTE { template class RadioModel<UERadioStatisticManager, UEMessageProcessor>; typedef RadioModel<UERadioStatisticManager, UEMessageProcessor> UERadioModel; template class RadioModel<ENBRadioStatisticManager, ENBMessageProcessor>; typedef RadioModel<ENBRadioStatisticManager, ENBMessageProcessor> ENBRadioModel; } } } <file_sep>/* * Copyright (c) 2019 - Adjacent Link LLC, Bridgewater, New Jersey * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Adjacent Link LLC nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * See toplevel COPYING for more information. */ #include "libemanelte/epcstatisticmanager.h" #include "gtpcinterfacetypes.h" #include "basicstatistichelper.h" #include "iptrafficstats.h" #include <ostatistic/service.h> #include <ostatistic/statisticnumeric.h> #include <ostatistic/table.h> #include <map> #include <string> #include <sstream> #include <utility> #include <sys/time.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> namespace { EMANELTE::IPTrafficTable * pDlIPTrafficTable_ = NULL; EMANELTE::IPTrafficTable * pUlIPTrafficTable_ = NULL; EMANELTE::IPTrafficTable * pDropIPTrafficTable_ = NULL; EMANELTE::IPTrafficDB dlTrafficDB_; EMANELTE::IPTrafficDB ulTrafficDB_; EMANELTE::IPTrafficDB dropTrafficDB_; using BearerTable = OpenStatistic::Table<std::string>; BearerTable * pBearerTable_ = NULL; struct BearerEntry { std::uint64_t teid_; std::uint32_t addr_; std::uint64_t imsi_; std::uint8_t ebi_; BearerEntry(std::uint64_t teid, std::uint32_t addr, std::uint64_t imsi, std::uint8_t ebi) : teid_{teid}, addr_{addr}, imsi_{imsi}, ebi_{ebi} { } }; using BearerKey = std::uint32_t; using BearerDB = std::map<BearerKey, BearerEntry>; std::string keyToString(const BearerKey & key) { const std::string s1 = inet_ntoa(*(in_addr*)&(key)); return s1; } BearerDB BearerDB_; void updateBearerTable_(BearerTable * table, BearerDB & db, std::uint32_t dst, std::uint64_t teid, std::uint32_t addr, std::uint64_t imsi, std::uint8_t ebi) { const BearerKey key{dst}; const auto keyAsString = keyToString(key); const std::string sAddr = inet_ntoa(*(in_addr*)(&addr)); auto iter = db.find(key); const BearerEntry entry{teid, addr, imsi, ebi}; if(iter == db.end()) { // new entry db.insert(std::make_pair(key, entry)); EMANELTE::addRowWithCheck_(table, keyAsString, {OpenStatistic::Any{keyAsString}, // 0 dst OpenStatistic::Any{EMANELTE::toHex(teid)}, // 1 teid OpenStatistic::Any{sAddr}, // 2 addr OpenStatistic::Any{imsi}, // 3 imsi OpenStatistic::Any{std::uint64_t{ebi}}, // 4 ebi OpenStatistic::Any{time(NULL)}}); // 5 Time } else { // update entry iter->second = entry; EMANELTE::setRowWithCheck_(table, keyAsString, {OpenStatistic::Any{keyAsString}, // 0 dst OpenStatistic::Any{EMANELTE::toHex(iter->second.teid_)}, // 1 teid OpenStatistic::Any{sAddr}, // 2 addr OpenStatistic::Any{imsi}, // 3 imsi OpenStatistic::Any{std::uint64_t{ebi}}, // 4 ebi OpenStatistic::Any{time(NULL)}}); // 5 Time } } void deleteBearerTable_(BearerTable * table, BearerDB & db, std::uint32_t dst) { const BearerKey key{dst}; const auto keyAsString = keyToString(key); auto iter = db.find(key); if(iter != db.end()) { db.erase(iter); EMANELTE::delRowWithCheck_(table, keyAsString); } } } void EPCSTATS::initialize(const std::string & endpoint) { OpenStatistic::Service * service = OpenStatistic::Service::instance(); OpenStatistic::Registrar & registrar = service->registrar(); // variable length tables pDlIPTrafficTable_ = registrar.registerTable<std::string>( "DownlinkTrafficTable", {"Src", "Dst", "Count", "Bytes", "Time"}, OpenStatistic::StatisticProperties::NONE, "Downlink Traffic Table"); pUlIPTrafficTable_ = registrar.registerTable<std::string>( "UplinkTrafficTable", {"Src", "Dst", "Count", "Bytes", "Time"}, OpenStatistic::StatisticProperties::NONE, "Downlink Traffic Table"); pDropIPTrafficTable_ = registrar.registerTable<std::string>( "DownlinkDropTrafficTable", {"Src", "Dst", "Count", "Bytes", "Time"}, OpenStatistic::StatisticProperties::NONE, "Downlink Traffic Table"); pBearerTable_ = registrar.registerTable<std::string>( "BearerTable", {"Dst", "eNBTEID", "eNBAddr", "IMSI", "EBI", "Time"}, OpenStatistic::StatisticProperties::NONE, "Bearer Table"); OpenStatistic::Service::instance()->start(endpoint); } void EPCSTATS::updateDstNotFound(uint32_t src, uint32_t dst, size_t numBytes) { EMANELTE::updateIPTrafficTable_(pDropIPTrafficTable_, dropTrafficDB_, src, dst, numBytes); } void EPCSTATS::updateUplinkTraffic(uint32_t src, uint32_t dst, size_t numBytes) { EMANELTE::updateIPTrafficTable_(pUlIPTrafficTable_, ulTrafficDB_, src, dst, numBytes); } void EPCSTATS::updateDownlinkTraffic(uint32_t src, uint32_t dst, size_t numBytes) { EMANELTE::updateIPTrafficTable_(pDlIPTrafficTable_, dlTrafficDB_, src, dst, numBytes); } void EPCSTATS::addBearer(uint32_t dst, uint64_t teid, uint32_t addr, uint64_t imsi, uint8_t ebi) { updateBearerTable_(pBearerTable_, BearerDB_, dst, teid, addr, imsi, ebi); } void EPCSTATS::delBearer(uint32_t dst) { deleteBearerTable_(pBearerTable_, BearerDB_, dst); } <file_sep>/* * Copyright (c) 2019 - Adjacent Link LLC, Bridgewater, New Jersey * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Adjacent Link LLC nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * See toplevel COPYING for more information. */ #include "mhalcommon.h" #include "configmanager.h" #undef ENABLE_INFO_1_LOGS #undef ENABLE_INFO_2_LOGS // uncomment to enable info 1/2 logs //#define ENABLE_INFO_1_LOGS //#define ENABLE_INFO_2_LOGS void EMANELTE::MHAL::MHALCommon::initialize(uint32_t sf_interval_msec, const mhal_config_t & mhal_config) { set_logger(mhal_config); // subframe step is 1 msec/subframe timing_.set_tv_sf_interval(0, sf_interval_msec * 1000); timing_.set_tv_slot_interval(0, sf_interval_msec * 1000/2); timing_.set_ts_sf_interval_usec(sf_interval_msec * 1000); int parent_policy = 0; struct sched_param parent_priority = {0}; // get caller priority pthread_getschedparam(pthread_self(), &parent_policy, &parent_priority); // elevate so emane can inherit if(parent_policy == SCHED_OTHER) { set_thread_priority(pthread_self(), SCHED_RR, 50); } else { set_thread_priority(pthread_self(), parent_policy, parent_priority.sched_priority + 1); } statisticManager_.start(mhal_config.statistic_service_endpoint, sf_interval_msec); init_emane(); // reset caller priority set_thread_priority(pthread_self(), parent_policy, parent_priority.sched_priority); } void EMANELTE::MHAL::MHALCommon::start(uint32_t nof_advance_sf) { if(! state_.isStarted()) { for(size_t bin = 0; bin < EMANELTE::NUM_SF_PER_FRAME; ++bin) { pendingMessageBins_[bin].lockBin(); pendingMessageBins_[bin].clear(); clearReadyMessages(bin); pendingMessageBins_[bin].unlockBin(); } timing_.lockTime(); timing_.alignTime(nof_advance_sf); const auto & tv_curr_sf = timing_.getCurrSfTime(); logger_.log(EMANE::INFO_LEVEL, "MHAL::RADIO %s curr_sf_time %ld:%06ld", __func__, tv_curr_sf.tv_sec, tv_curr_sf.tv_usec); timing_.unlockTime(); state_.start(); } else { logger_.log(EMANE::INFO_LEVEL, "MHAL::RADIO %s already running", __func__); } } void EMANELTE::MHAL::MHALCommon::set_tti(uint16_t curr_tti) { logger_.log(EMANE::DEBUG_LEVEL, " MHAL::RADIO %s%u", __func__, curr_tti); } void EMANELTE::MHAL::MHALCommon::set_logger(const mhal_config_t & mhal_config) { auto & configManager = ConfigManager::getInstance(); auto & platformConfig = configManager.getPlatformConfig(); logger_.setLogLevel(EMANE::LogLevel::DEBUG_LEVEL); configManager.setLogger(logger_); configManager.configure(mhal_config.emane_configfile); if(platformConfig.sLogLevel_ >= "4") { logger_.setLogLevel(EMANE::LogLevel::DEBUG_LEVEL); } else if(platformConfig.sLogLevel_ == "3") { logger_.setLogLevel(EMANE::LogLevel::INFO_LEVEL); } else if(platformConfig.sLogLevel_ == "2") { logger_.setLogLevel(EMANE::LogLevel::ERROR_LEVEL); } else if(platformConfig.sLogLevel_ == "1") { logger_.setLogLevel(EMANE::LogLevel::ABORT_LEVEL); } else { logger_.setLogLevel(EMANE::LogLevel::NOLOG_LEVEL); } if(!platformConfig.sLogFileName_.empty()) { logger_.redirectLogsToFile(platformConfig.sLogFileName_.c_str()); } } void EMANELTE::MHAL::MHALCommon::send_msg(const Data & data, TxControlMessage & txControl) { txControl.set_subframe_duration_microsecs(timing_.ts_sf_interval_usec()); timeval tv_sf_time{txControl.sf_time().ts_sec(), txControl.sf_time().ts_usec()}; if(TX_TIME_ADJUST > 0) { // pull back tx timestamp to allow for greater processing time on at the receiver timeval tv_adjust = tsToTv(timing_.ts_sf_interval_usec() * TX_TIME_ADJUST); timersub(&tv_sf_time, &tv_adjust, &tv_sf_time); } #ifdef ENABLE_INFO_1_LOGS const timeval & tv_curr_sf = timing_.getCurrSfTime(); logger_.log(EMANE::INFO_LEVEL, "MHAL::RADIO %s seqnum %lu, tti_tx %u, curr_sf %ld:%06ld, adjust %d, sf_time %ld:%06ld", __func__, txControl.tx_seqnum(), txControl.tti_tx(), tv_curr_sf.tv_sec, tv_curr_sf.tv_usec, TX_TIME_ADJUST, tv_sf_time.tv_sec, tv_sf_time.tv_usec); #endif send_downstream(data, txControl, EMANE::TimePoint(EMANE::Microseconds(tvToUseconds(tv_sf_time)))); } void EMANELTE::MHAL::MHALCommon::stop() { logger_.log(EMANE::INFO_LEVEL, " MHAL::RADIO %s", __func__); state_.stop(); statisticManager_.stop(); } void EMANELTE::MHAL::MHALCommon::set_thread_priority(pthread_t tid, int policy, int priority) { struct sched_param param = {priority}; if(pthread_setschedparam(tid, policy, &param) < 0) { logger_.log(EMANE::ERROR_LEVEL, "could not set thread %ld, priority/policy %d:%d, %s\n", tid, priority, policy, strerror(errno)); } else { logger_.log(EMANE::INFO_LEVEL, "set thread %ld, priority/policy %d:%d\n", tid, priority, policy); } } void EMANELTE::MHAL::MHALCommon::noise_worker(const uint32_t bin, const timeval & tv_sf_start __attribute__((unused))) { struct timeval tv_in, tv_out, tv_diff; // track work time gettimeofday(&tv_in, NULL); #ifdef ENABLE_INFO_2_LOGS logger_.log(EMANE::INFO_LEVEL, "MHAL::RADIO %s, sf_start %ld:%06ld, bin %u, %zu pending", __func__, tv_sf_start.tv_sec, tv_sf_start.tv_usec, bin, pendingMessageBins_[bin].getPending().size()); #endif clearReadyMessages(bin); // container for all freqs and energy for this subframe // allows for consulting the spectrum sevice once and only once for each freq/timerange EMANE::Models::LTE::SpectrumWindowCache spectrumWindowCache; // load the spectrumWindow cache for each frequency for(auto & span : pendingMessageBins_[bin].getSegmentSpans()) { const auto & minSor = std::get<0>(span.second); const auto & maxEor = std::get<1>(span.second); const auto & frequencyHz = span.first; const auto duration = std::chrono::duration_cast<EMANE::Microseconds>(maxEor.time_since_epoch() - minSor.time_since_epoch()); #ifdef ENABLE_INFO_1_LOGS auto & numEntries = std::get<2>(span.second); logger_.log(EMANE::INFO_LEVEL, "MHAL::PHY %s, freq %lu, minSor %f, maxEor %f, duration %ld, numEntries %zu", __func__, frequencyHz, minSor.time_since_epoch().count()/1e9, maxEor.time_since_epoch().count()/1e9, duration.count(), numEntries); #endif spectrumWindowCache[frequencyHz] = get_noise(frequencyHz, duration, minSor); } statisticManager_.updateDequeuedMessages(bin, pendingMessageBins_[bin].get().size()); noise_processor(bin, spectrumWindowCache); // done with pending msgs pendingMessageBins_[bin].clear(); gettimeofday(&tv_out, NULL); timersub(&tv_out, &tv_in, &tv_diff); // update process time statisticManager_.updateNoiseProcessDelay(bin, tvToSeconds(tv_diff)); } void EMANELTE::MHAL::MHALCommon::handle_upstream_msg(const Data & data, const RxData & rxData, const PHY::OTAInfo & otaInfo, const TxControlMessage & txControl) { if(state_.isRunning()) { const auto sor = otaInfo.sot_; // LTE timing advance negates propagation delay (sor == sot) const auto eor = sor + otaInfo.span_; const auto now = EMANE::Clock::now(); const auto dT = std::chrono::duration_cast<EMANE::Microseconds>(eor.time_since_epoch() - now.time_since_epoch()); // get bin for msg sf_time (tti) this is the sf that the msg is expected to arrive tx/rx const uint32_t bin = getMessageBin(rxData.sf_time_, timing_.ts_sf_interval_usec()); timeval tv_diff; // get ota diff timersub(&rxData.rx_time_, &rxData.tx_time_, &tv_diff); statisticManager_.updateRxPacketOtaDelay(bin, tvToSeconds(tv_diff)); // eor should be in the future if(dT > EMANE::Microseconds{0}) { statisticManager_.updateEnqueuedMessages(bin); // lock this bin pendingMessageBins_[bin].lockBin(); // add to the pending queue for this bin pendingMessageBins_[bin].add(rxData.sf_time_, bin, PendingMessage{data, rxData, otaInfo, txControl}, statisticManager_); // unlock bin pendingMessageBins_[bin].unlockBin(); } else { // rx late too late, discard statisticManager_.updateLateMessages(bin); } #ifdef ENABLE_INFO_1_LOGS const auto & tv_curr_sf = timing_.getCurrSfTime(); logger_.log(EMANE::INFO_LEVEL, "MHAL::PHY %s seqnum %lu, bin %u, curr_sf %ld:%06ld, sf_time %ld:%06ld, sot %f, span %ld, sor %f, eor %f, dT %ld usec, pending %zu", __func__, rxData.rx_seqnum_, bin, tv_curr_sf.tv_sec, tv_curr_sf.tv_usec, rxData.sf_time_.tv_sec, rxData.sf_time_.tv_usec, otaInfo.sot_.time_since_epoch().count()/1e9, otaInfo.span_.count(), sor.time_since_epoch().count()/1e9, eor.time_since_epoch().count()/1e9, dT.count(), pendingMessageBins_[bin].getPending().size()); #endif } else { logger_.log(EMANE::ERROR_LEVEL, " MHAL::PHY %s not started, discard", __func__); } } void EMANELTE::MHAL::MHALCommon::clearReadyMessages(const uint32_t bin) { if(size_t orphaned = readyMessageBins_[bin].clearAndCheck()) { logger_.log(EMANE::ERROR_LEVEL, "MHAL::RADIO %s, bin %u, purge %zu ready orphans", __func__, bin, orphaned); statisticManager_.updateOrphanedMessages(bin, orphaned); } } <file_sep>/* * Copyright (c) 2019 - Adjacent Link LLC, Bridgewater, New Jersey * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Adjacent Link LLC nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * See toplevel COPYING for more information. */ #ifndef EMANELTE_MHAL_TIMINGINFO_H #define EMANELTE_MHAL_TIMINGINFO_H #include <emane/application/logger.h> #include <sys/time.h> #include <unistd.h> namespace EMANELTE { namespace MHAL { const time_t USEC_PER_SECOND = 1000000; inline time_t tvToUseconds(const timeval & tv) { return (tv.tv_sec * USEC_PER_SECOND) + tv.tv_usec; } inline float tvToSeconds(const timeval & tv) { return (tv.tv_sec + tv.tv_usec/1e6); } inline EMANE::Microseconds tvToMicroseconds(const timeval & tv) { return EMANE::Microseconds{tv.tv_sec * USEC_PER_SECOND + tv.tv_usec}; } inline timeval tsToTv(const time_t ts) { return timeval{ts/USEC_PER_SECOND, ts%USEC_PER_SECOND}; } inline EMANE::TimePoint tvToTp(const timeval & tv) { return EMANE::TimePoint{EMANE::Microseconds{tv.tv_sec * USEC_PER_SECOND + tv.tv_usec}}; } inline uint32_t getMessageBin(const timeval & tv, std::uint64_t ts_sf_interval) { return (tvToUseconds(tv) / ts_sf_interval) % EMANELTE::NUM_SF_PER_FRAME; } class TimingInfo { public: TimingInfo(timeval tv_sf_interval, timeval tv_slot_interval, time_t ts_sf_interval_usec) : tv_curr_sf_(), tv_next_sf_(), tv_sf_interval_(tv_sf_interval), tv_slot_interval_(tv_slot_interval), ts_sf_interval_usec_(ts_sf_interval_usec) { init_mutex(&mutex_); } void set_tv_sf_interval(uint32_t tv_sec, uint32_t tv_usec) { tv_sf_interval_.tv_sec = tv_sec; tv_sf_interval_.tv_usec = tv_usec; } void set_tv_slot_interval(uint32_t tv_sec, uint32_t tv_usec) { tv_slot_interval_.tv_sec = tv_sec; tv_slot_interval_.tv_usec = tv_usec; } uint32_t ts_sf_interval_usec() { return ts_sf_interval_usec_; } void set_ts_sf_interval_usec(uint32_t tv_usec) { ts_sf_interval_usec_ = tv_usec; } // called after lock is set uint32_t stepTime() { tv_curr_sf_ = tv_next_sf_; timeradd(&tv_next_sf_, &tv_sf_interval_, &tv_next_sf_); // new upstream depost bin = curr_bin + 4 return (getMessageBin(tv_curr_sf_, ts_sf_interval_usec_) + 4) % EMANELTE::NUM_SF_PER_FRAME; } // called after lock is set void alignTime(uint32_t nof_advance_sf) { timeval tv_sos; gettimeofday(&tv_sos, NULL); // get next second boundry if(tv_sos.tv_usec > 0) { usleep(USEC_PER_SECOND - tv_sos.tv_usec); tv_sos.tv_sec += 1; tv_sos.tv_usec = 0; } tv_curr_sf_ = tv_sos; timeradd(&tv_sos, &tv_sf_interval_, &tv_next_sf_); for(uint32_t n = 0; n < nof_advance_sf; ++n) { tv_curr_sf_ = tv_next_sf_; timeradd(&tv_next_sf_, &tv_sf_interval_, &tv_next_sf_); usleep(ts_sf_interval_usec_); } } const timeval & getCurrSfTime() const { return tv_curr_sf_; } const timeval & getNextSfTime() const { return tv_next_sf_; } inline std::pair<timeval, timeval> get_slot_times(const timeval &tv_sf_start, int slot) { timeval tv1, tv2; // first slot if(slot == 0) { tv1 = tv_sf_start; timeradd(&tv_sf_start, &tv_slot_interval_, &tv2); } // second slot else if(slot == 1) { timeradd(&tv_sf_start, &tv_slot_interval_, &tv1); timeradd(&tv_sf_start, &tv_sf_interval_, &tv2); } // both else { tv1 = tv_sf_start; timeradd(&tv_sf_start, &tv_sf_interval_, &tv2); } return std::pair<timeval, timeval>(tv1, tv2); } // get the slot index 0 for the first slot, 1 for the second slot, 2 for both int get_slot_number(const EMANE::Microseconds & duration, const EMANE::Microseconds & offset) { if(tvToMicroseconds(tv_sf_interval_) == duration) { return 2; } else { return offset == EMANE::Microseconds{} ? 0 : 1; } } inline void lockTime() { LOCK_WITH_CHECK(&mutex_); } inline void unlockTime() { UNLOCK_WITH_CHECK(&mutex_); } private: struct timeval tv_curr_sf_, tv_next_sf_; timeval tv_sf_interval_; timeval tv_slot_interval_; time_t ts_sf_interval_usec_; pthread_mutex_t mutex_; }; } } #endif
0861b05fd9c742655054cb6adf3fb8638e7f8a13
[ "C++", "Shell" ]
10
C++
learning-lte/emane-model-lte
b98f28db8b0dc30f94eace042f48915e309f8420
d338925a125fce7ba13e749dfbd7d5893f6101b4
refs/heads/master
<repo_name>CrazyLemonLin/ctjs2016-ng2demo<file_sep>/src/app/shared/data.service.ts import { Injectable } from '@angular/core'; import { Http, Request } from '@angular/http'; import 'rxjs/add/operator/map'; @Injectable() export class DataService { url = '/api/articles.json'; constructor(private http: Http) {} searchArticles(keyword: string) { return this.http.get(this.url) .map(res => { return res.json().filter(value => { if(keyword) { return value.title.toLowerCase().indexOf(keyword.toLowerCase()) >= 0; } else { return true; } }); }); } } <file_sep>/src/app/article/article.component.ts import { Component, OnInit, OnChanges, Input, Output } from '@angular/core'; import { DataService } from '../shared/'; @Component({ moduleId: module.id, selector: 'app-article', templateUrl: 'article.component.html', styleUrls: ['article.component.css'] }) export class ArticleComponent implements OnInit, OnChanges { posts: any[]; @Input() keyword: string; constructor(private ds: DataService) {} ngOnInit() { this.ds.searchArticles(this.keyword) .subscribe(data => this.posts = data); } ngOnChanges() { this.ds.searchArticles(this.keyword) .subscribe(data => this.posts = data); } }
9c6a77793c83b32eaf576437361066f28ddeed99
[ "TypeScript" ]
2
TypeScript
CrazyLemonLin/ctjs2016-ng2demo
7059eb6368a8447252235fc617b7e30e49b7ae6e
7e786004980cd6728683321368dafd46fa382699
refs/heads/master
<repo_name>nikkelberg/telegrambotgetchatid<file_sep>/chatidtoken.php <?php include 'funzioniutili.php'; $response = file_get_contents("https://api.telegram.org/bot<bottoken>/getUpdates"); $dati = explode('"id":', $response);//divide for id unset($dati[0]); //delete first array field $users = Array(); foreach($dati as $value){ $userapp = Array(); //take chat id $value = explode(',', $value); array_push($userapp, $value[0]); //take name $name = explode('"first_name":', $value[1]); $name = explode('"', $name[1]); //clean "" array_push($userapp, $name[1]); //take username $nickname = explode('"username":',$value[2]); $nickname = explode('"', $nickname[1]); //clean "" array_push($userapp, $nickname[1]); array_push($users, $userapp); } //dd($users); echo "<table border=\"1\" style=\"width:50%\">"; echo "<tr><th>CHATID</th><th>NAME</th><th>USERNAME</th></tr>"; $lastuser = " "; foreach($users as $user){ if($user[1] == NULL){ //delete NULL value, needless unset($users[$user]); }else{ if($user[0] != $lastuser){ //control for not repeat value echo "<tr>"; echo "<td>".$user[0]."</td><td>".$user[1]."</td><td>".$user[2]."</td>"; echo "</tr>"; $lastuser = $user[0]; } } } echo "</table>"; ?> <file_sep>/README.md # telegrambotgetchatid With this code you can take a user chat id with URL request "getUpdates". The code clean and extract the chat id. Edit the third row and run visit the page on your server! ENJOY!
03628cc62394c41212ccb4e6d045e2171d7e3651
[ "Markdown", "PHP" ]
2
PHP
nikkelberg/telegrambotgetchatid
4b4caf0e4bbc6a2b5cd6dff29d9623906a31d061
655247d7e1517d0c7c077a361e3b9a52ada35cd9
refs/heads/main
<file_sep>from os import add_dll_directory import re from flask import * import sqlite3 import itertools from datetime import date,datetime,time app = Flask(__name__) app.secret_key = 'MRP' @app.route('/pedidos/<float:total>') def pedidos(total): now = datetime.now() data = str(date(day = now.day, month = now.month, year = now.year)) hora = str(time(hour=now.hour, minute=now.minute)) formadepagamento = ("credito") usuario_logado = session['usuario_logado'] print(data,hora,formadepagamento,usuario_logado,total) con = sqlite3.connect('banco.db') con.execute("INSERT INTO Orders (Valor, Data, Horario, Pagamento, Email) VALUES (?,?,?,?,?) ", (total , data , hora , formadepagamento , usuario_logado)) con.commit() con.close() return redirect('/') @app.route('/minhaconta') def minhaconta(): con = sqlite3.connect('banco.db') cur = con.cursor() usuario_logado = session['usuario_logado'] nome_usuario = cur.execute("SELECT nome FROM Cliente where email = '" + usuario_logado +"'").fetchone()[0] flash('Olá, ' + nome_usuario + '') return render_template ('Minhaconta.html') @app.route('/meuspedidos') def meuspedidos(): if 'usuario_logado' not in session or session['usuario_logado'] == None: return redirect('/login') con = sqlite3.connect('banco.db') cur = con.cursor() usuario_logado = session['usuario_logado'] pedidos = cur.execute("SELECT ID_Pedidos,Valor,Data,Horario,Pagamento,Email FROM Orders where Email = '" + usuario_logado +"'").fetchall() con.close() return render_template ('MeusPedidos.html', pedidos = pedidos) @app.route('/deletar/<int:id>') def deletar(id): con = sqlite3.connect('banco.db') con.execute("delete from Shopping_Cart where ID_Cart = ?",(id,)) con.commit() con.close() return redirect('/carrinho') @app.route('/pagando') def pagando(): usuario_logado = session['usuario_logado'] con = sqlite3.connect('banco.db') cur = con.cursor() produtos_carrinho = cur.execute("SELECT Valor FROM Shopping_Cart where email = '" + usuario_logado +"'").fetchall() total = 0 for tota in produtos_carrinho: subtotal = tota[0] total = total + subtotal pagamentosregistrados = cur.execute("SELECT Nomec, Numero FROM payment where email = '" + usuario_logado +"'").fetchall() con.close() return render_template ('cartao.html', total = total, registrados = pagamentosregistrados) @app.route('/carrinho') def carrinho(): if 'usuario_logado' not in session or session['usuario_logado'] == None: return redirect('/login') usuario_logado = session['usuario_logado'] con = sqlite3.connect('banco.db') cur = con.cursor() produtos_carrinho = cur.execute("SELECT Nome,Valor,Imagem,ID_Cart FROM Shopping_Cart where email = '" + usuario_logado +"'").fetchall() total = 0 for tota in produtos_carrinho: subtotal = tota[1] total = total + subtotal con.close() return render_template ('Carrinho.html',titulo='Produtos', produtos = produtos_carrinho, total = total) @app.route('/adicionar/<int:id>') def adicionar(id): usuario_logado = session['usuario_logado'] if 'usuario_logado' not in session or session['usuario_logado'] == None: return redirect('/login') con = sqlite3.connect('banco.db') cur = con.cursor() Nome = cur.execute("SELECT Nome FROM livros where ID_Livros = ?",(id,)).fetchone()[0] Valor = cur.execute("SELECT Valor FROM livros where ID_Livros = ?",(id,)).fetchone()[0] Imagem = cur.execute("SELECT Fotos FROM livros where ID_Livros = ?",(id,)).fetchone()[0] cur.execute("INSERT INTO Shopping_Cart (Nome,Valor,Imagem,Email) VALUES (?,?,?,?) " ,(Nome,Valor,Imagem,usuario_logado)) con.commit() con.close() return redirect('/') #telas @app.route('/descricao/<int:id>') def descricao(id): con = sqlite3.connect('banco.db') cur = con.cursor() produtos = cur.execute("SELECT Nome,Valor,Fotos,Descricao FROM livros where ID_Livros = ?",(id,)).fetchone() con.close() return render_template('produtodescricao.html', produtos = produtos) @app.route('/') def principal(): if 'usuario_logado' not in session or session['usuario_logado'] != None: return redirect('logado') con = sqlite3.connect('banco.db') cur = con.cursor() produtos = cur.execute("SELECT Nome,Valor,Fotos,ID_Livros FROM Livros ").fetchall()[0:6] con.close() return render_template('Telamenupro.html', produtos = produtos) @app.route('/logado') def logado(): if 'usuario_logado' not in session or session['usuario_logado'] == None: return redirect('/') con = sqlite3.connect('banco.db') cur = con.cursor() usuario_logado = session['usuario_logado'] produtos = cur.execute("SELECT Nome,Valor,Fotos,ID_Livros FROM Livros ").fetchall()[0:6] nome_usuario = cur.execute("SELECT nome FROM Cliente where email = '" + usuario_logado +"'").fetchone()[0] flash('Olá, ' + nome_usuario + '') con.close() return render_template('TelamenuproLogada.html',produtos = produtos) @app.route('/login') def login(): return render_template('TelaLogin.html') @app.route('/autenticar', methods=['POST',]) def autenticar(): senha = request.form['senha'] email = request.form['email'] con = sqlite3.connect('banco.db') cur = con.cursor() verificar = cur.execute("SELECT email FROM Cliente where email = '" + email +"'").fetchall() if verificar == [] : flash('Você ainda não é cliente, realize seu cadastro!') return redirect ('/login') else: cliente_senha = cur.execute("SELECT senha FROM Cliente where email = '" + email +"'").fetchone()[0] if cliente_senha != senha: return redirect ('/login') else: if cliente_senha == senha: session ['usuario_logado'] = request.form['email'] return redirect('/') else : flash('Dados errados, tente novamente!') return redirect ('/login') @app.route('/logout') def logout(): session['usuario_logado'] = None flash('Usuário deslogado!') return redirect('/') @app.route('/addnovoproduto',methods=['POST',]) def addnovoproduto(): nome = request.form['nome'] genero = request.form['genero'] fotos = request.form['fotos'] valor = request.form['valor'] descricao = request.form['descricao'] con = sqlite3.connect('banco.db') cur = con.cursor() cur.execute("INSERT INTO livros (Nome, Genero, Fotos, Valor, Descricao) VALUES (?,?,?,?) ", (nome , genero , fotos , valor, descricao)) con.commit() con.close() return redirect('/') @app.route('/cadastro') def cadastro(): return render_template('TelaCadastro.html') @app.route('/cadastrando',methods=['POST',]) def cadastrando(): nome = request.form['nome'] email = request.form['email'] senha = request.form['senha'] cpf = request.form['cpf'] cep = request.form['cep'] endereco = request.form['endereco'] bairro = request.form['bairro'] numero = request.form['numero'] complemento = request.form['complemento'] cidade = request.form['cidade'] con = sqlite3.connect('banco.db') cur = con.cursor() cur.execute("INSERT INTO Cliente (Nome, Email, Senha, CPF) VALUES (?,?,?,?) ", (nome , email , senha , cpf)) cur.execute("INSERT INTO Endereco (CEP, Endereco, Numero, Complemento, Bairro, Cidade) VALUES (?,?,?,?,?,?) ", (cep , endereco , numero , complemento, bairro, cidade)) con.commit() con.close() return redirect('/') @app.route('/produtos') def produto(): con = sqlite3.connect('banco.db') cur = con.cursor() produtos = cur.execute("SELECT Nome,Valor,Fotos FROM Livros ").fetchall() con.close() return render_template('produtos.html',produtos = produtos) @app.route('/terror') def terror(): con = sqlite3.connect('banco.db') cur = con.cursor() produtos = cur.execute("SELECT Nome,Valor,Fotos FROM Livros where Genero = 'terror' ").fetchall() con.close() return render_template('terror.html',produtos = produtos) @app.route('/aventura') def aventura(): con = sqlite3.connect('banco.db') cur = con.cursor() produtos = cur.execute("SELECT Nome,Valor,Fotos FROM Livros where Genero = 'aventura' ").fetchall() con.close() return render_template('aventura.html',produtos = produtos) @app.route('/programacao') def programacao(): con = sqlite3.connect('banco.db') cur = con.cursor() produtos = cur.execute("SELECT Nome,Valor,Fotos FROM Livros where Genero = 'programacao' ").fetchall() con.close() return render_template('programacao.html',produtos = produtos) @app.route('/medicina') def medicina(): con = sqlite3.connect('banco.db') cur = con.cursor() produtos = cur.execute("SELECT Nome,Valor,Fotos FROM Livros where Genero = 'medicina' ").fetchall() con.close() return render_template('medicina.html',produtos = produtos) @app.route('/advocacia') def advogacia(): con = sqlite3.connect('banco.db') cur = con.cursor() produtos = cur.execute("SELECT Nome,Valor,Fotos FROM Livros where Genero = 'advocacia' ").fetchall() con.close() return render_template('advocacia.html',produtos = produtos) app.run(debug=True)
477af100bcc99dc323e01081f588a1536e1749cc
[ "Python" ]
1
Python
Marianaap/E-commerce-
c094ad1c7b90b744ac4168eb79f16f3a7565a0d9
fb7469dda513129ca80201649c50cd548b28ec2e
refs/heads/master
<repo_name>swaff68/JS18-I-Quotes<file_sep>/main.js var quoteArray = []; var quoteMemory = []; var QuoteInput = function (quote, album, song){ this.quote = quote this.album = album this.song = song }; QuoteInput.prototype.create = function(){ this.el = $('<div class="quoteBox"><div class="quoteArea"><i>Quote: </i><div class="quote"> '+ this.quote + '</div></br><i>Album: </i><div class="album">'+ this.album + ' </div><i>Song: </i><div class="song"> '+ this.song + '</div></br><input class="remove" type="submit" value="Remove Quote"></div></div>'); return this.el } $('#create').click(function(){ $('#quoteForm').show() $('#create').hide() }); $('#finished').click(function(e){ e.preventDefault() $('#quoteForm').hide() $('#create').show() $('.quoteArea').show() }); $(document).on('click', '#submit', function(e){ var quote = $('#quoteInput').val() $('#quoteInput').val('') var album = $('#albumInput').val() $('#albumInput').val('') var song = $('#songInput').val() $('#songInput').val('') quoteArray.push(new QuoteInput(quote, album, song)); e.preventDefault() $('#display').empty() for(var i=0; i<quoteArray.length; i++){ $('#display').append(quoteArray[i].create()) } var memLength= $('.quoteArea') quoteMemory = []; for (var i = 0; i < memLength.length; i++) { quoteMemory.push(memLength[i]); }; }); $(document).on('click', '.remove', function(){ $(this).closest('.quoteArea').remove(); var memLength= $('.quoteArea') quoteArray = [] quoteMemory = [] for (var i = 0; i < memLength.length; i++) { quoteMemory.push(memLength[i]); }; }); // $(document).on('click', '.album', function(){ // var albumSort = $(this).text() // var albumMatch = []; // // console.log(instanceof quoteArray[0]) // for (var i = 0; i < quoteArray.length; i++) { // if (quoteArray[i].album === albumSort){ // albumMatch.push(quoteArray[i]) // } // } // // $('#display').empty() // // console.log(instanceof albumMatch[0]) // for(var i=0; i<albumMatch.length; i++){ // $('#display').append(albumMatch[i].create()) // } // }) $(document).on('ready', function() { });
aa6b161a68f5e7f8503a3419c734bceb2abf4064
[ "JavaScript" ]
1
JavaScript
swaff68/JS18-I-Quotes
5f668619b396c4c600d0d14a2e2fd7204f6d0dde
68b356440cf74144b68f95b974799f007375585a
refs/heads/master
<file_sep>#!/bin/bash echo "compilando" gfortran -o prueba2 -fcheck=all -Wall constants.f90 linalg.f90 aus.f90 mesh.f90 prueba2.f90 echo "Listo. Ejecute prueba2" <file_sep># mi-primer-fortran Code for the started program Some codes in fortran ## Para compilar Para compilar el programa prueba1 necesitas tambien compilar los modulos `mesh` y `constants` ``` gfortran -o prueba1 mesh.f90 constants.f90 prueba1.f90 ```
bddb3a90d551d287ff70a071d48f45a561db1754
[ "Markdown", "Shell" ]
2
Shell
vicmans/mi-primer-fortran
2cceb4735e8543f84e5e4fbf6eafb1fcde073864
576db75b342f08f276695376e012949aec6910f6
refs/heads/master
<file_sep>namespace Supermarket.EneityFramework { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("AdminInfo")] public partial class AdminInfo { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public AdminInfo() { Orders = new HashSet<Orders>(); Purchases = new HashSet<Purchases>(); SysLog = new HashSet<SysLog>(); } [Key] public int AdminID { get; set; } public int RoleID { get; set; } [Required] [StringLength(50)] public string UserName { get; set; } [Required] [StringLength(20)] public string Account { get; set; } [Required] [StringLength(50)] public string PassWord { get; set; } public virtual Role Role { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Orders> Orders { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Purchases> Purchases { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<SysLog> SysLog { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Supermarket.EneityFramework; using Supermarket.Code; namespace Supermarket.Web.Controllers { public class UserController : Controller { SupermarketDB db = new SupermarketDB(); public ActionResult Index() { return View(); } /// <summary> /// 获取需要的会员信息 /// </summary> /// <param name="limit">页面大小</param> /// <param name="offset">页码</param> /// <returns></returns> public ActionResult GetInfo(int limit, int offset) { try { string UserName = Request["UserName"]; int UserCard = 0; if (!string.IsNullOrEmpty(Request["UserCard"])) { UserCard = Convert.ToInt32(Request["UserCard"]); } //延迟查询 var result = from cus in db.User join card in db.Card on cus.CardID equals card.CardID where ((UserName.Length == 0) || (cus.UserName.Contains(UserName))) where ((UserCard == 0) || (cus.CardID == UserCard)) select new { cus.UserID, cus.UserName, cus.Sex, cus.Age, cus.UserPassWord, cus.AlterInTime, cus.IDNumber, cus.IsDelete, card.CardID, card.TotalCost, card.Score }; //得到结果总数 var total = result.Count(); //即时查询,当前页数据 var rows = result.OrderBy(m => m.UserID).Skip((offset-1)*limit).Take(limit).ToList(); //返回数据 return Json(new { total = total, rows = rows }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { //出现异常,前台可接收该字符串进行提示 return Content(ex.Message); } } /// <summary> /// 删除会员 /// </summary> /// <param name="UserIDs">会员ID</param> /// <returns></returns> public ActionResult Delete(string[] UserIDs) { SysLog log = new SysLog { Behavior = (Session["Admin"] as AdminInfo).UserName + "删除了" + UserIDs.Length + "个会员", FK_TypeID = 7, FK_AdminID = (Session["Admin"] as AdminInfo).AdminID, Parameters = "UserID", IP = Request.UserHostAddress, CheckInTime = DateTime.Now }; try { for (int i = 0; i < UserIDs.Length; i++) { //找到要删除的对象 User info = db.User.Find(Convert.ToInt32(UserIDs[i])); info.IsDelete = 1; } //更新到数据库 db.SaveChanges(); log.IsException = 0; log.Exception = string.Empty; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.success.ToString(), message = "执行删除操作成功!" }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { log.IsException = 1; log.Exception = ex.Message; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }, JsonRequestBehavior.AllowGet); } } /// <summary> /// 激活会员 /// </summary> /// <returns></returns> [HttpPost] public ActionResult Activate() { SysLog log = null; try { User info = db.User.Find(Convert.ToInt32(Request["UserID"])); log = new SysLog { Behavior = (Session["Admin"] as AdminInfo).UserName + "激活了会员" + info.UserName, FK_TypeID = 8, FK_AdminID = (Session["Admin"] as AdminInfo).AdminID, Parameters = "UserID", IP = Request.UserHostAddress, CheckInTime = DateTime.Now }; info.IsDelete = 0; db.SaveChanges(); log.IsException = 0; log.Exception = string.Empty; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.success.ToString(), message = "会员已成功激活!" }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { log.IsException = 1; log.Exception = ex.Message; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }, JsonRequestBehavior.AllowGet); } } /// <summary> /// 添加会员信息 /// </summary> /// <param name="info">需要添加的新会员信息</param> /// <returns></returns> [HttpPost] public ActionResult AddUser(User info) { SysLog log = new SysLog { Behavior = (Session["Admin"] as AdminInfo).UserName + "添加了新的会员" + info.UserName, FK_TypeID = 6, FK_AdminID = (Session["Admin"] as AdminInfo).AdminID, Parameters = "EF.User", IP = Request.UserHostAddress, CheckInTime = DateTime.Now }; try { db.Card.Add(new Card { TotalCost = 0, Score = 0 }); info.CardID = db.Card.Max(c => c.CardID) + 1; info.AlterInTime = DateTime.Now; db.User.Add(info); db.SaveChanges(); log.IsException = 0; log.Exception = string.Empty; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.success.ToString(), message = "添加会员操作成功!" }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { log.IsException = 1; log.Exception = ex.Message; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }, JsonRequestBehavior.AllowGet); } } /// <summary> /// 编辑会员信息 /// </summary> /// <param name="info"></param> /// <returns></returns> [HttpPost] public ActionResult EditUser(User info) { SysLog log = new SysLog { Behavior = (Session["Admin"] as AdminInfo).UserName + "修改了会员" + info.UserName, FK_TypeID = 8, FK_AdminID = (Session["Admin"] as AdminInfo).AdminID, Parameters = "EF.User", IP = Request.UserHostAddress, CheckInTime = DateTime.Now }; try { info.AlterInTime = DateTime.Now; db.Entry(info).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); log.IsException = 0; log.Exception = string.Empty; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.success.ToString(), message = "编辑会员信息成功!" }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { log.IsException = 1; log.Exception = ex.Message; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }, JsonRequestBehavior.AllowGet); } } } }<file_sep>namespace Supermarket.EneityFramework { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("Stock")] public partial class Stock { public int StockID { get; set; } public int ProductID { get; set; } public DateTime StorageTime { get; set; } public decimal CommodityStockAmount { get; set; } public decimal StockUp { get; set; } public decimal StockDown { get; set; } public DateTime AlterTime { get; set; } public virtual Product Product { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Supermarket.Code; using Supermarket.EneityFramework; using System.Web.Security; namespace Supermarket.Web.Controllers { public class LoginController : Controller { SupermarketDB db = new SupermarketDB(); /// <summary> /// 显示登录视图 /// </summary> /// <returns></returns> [HttpGet] public virtual ActionResult Index() { var test = string.Format("{0:E2}", 1); return View(); } /// <summary> /// 获取验证码 /// </summary> /// <returns></returns> [HttpGet] public ActionResult GetAuthCode() { return File(new VerifyCode().GetVerifyCode(), @"image/Gif"); } /// <summary> /// 登录验证 /// </summary> /// <param name="username">登录账号</param> /// <param name="password">密码</param> /// <param name="code">验证码</param> /// <returns>返回json</returns> [HttpPost] public ActionResult CheckLogin(string username, string password, string code) { var Admin = db.AdminInfo.FirstOrDefault(p => p.Account == username); SysLog log = null; if (Admin == null) { log = new SysLog { Behavior = username + "登录系统", FK_TypeID = 1, FK_AdminID = null, Parameters = "UserName,<PASSWORD>", IP = Request.UserHostAddress, CheckInTime = DateTime.Now }; } else { log = new SysLog { Behavior = username + "登录系统", FK_TypeID = 1, FK_AdminID = Admin.AdminID, Parameters = "UserName,Password", IP = Request.UserHostAddress, CheckInTime = DateTime.Now }; } try { if (string.IsNullOrWhiteSpace(Session["nfine_session_verifycode"].ToString()) || code.ToLower() != Session["nfine_session_verifycode"].ToString()) { throw new Exception("验证码错误"); } var data = db.AdminInfo.FirstOrDefault(model => model.Account == username && model.PassWord == <PASSWORD>); if (data == null) { throw new Exception("账号或密码错误"); } Session["Admin"] = data; FormsAuthentication.SetAuthCookie("Admin", false); log.IsException = 0; log.Exception = string.Empty; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.success.ToString(), message = "登录成功。" }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { log.IsException = 1; log.Exception = ex.Message; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }, JsonRequestBehavior.AllowGet); } } /// <summary> /// 退出登录 /// </summary> /// <returns></returns> [HttpPost] public ActionResult Exit() { try { SysLog log = new SysLog { Behavior = (Session["Admin"] as AdminInfo).UserName + "退出系统", FK_TypeID = 2, FK_AdminID = (Session["Admin"] as AdminInfo).AdminID, Parameters = "UserName,<PASSWORD>", IP = Request.UserHostAddress, CheckInTime = DateTime.Now,IsException=0,Exception=string.Empty }; Session.Clear(); db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.success.ToString(), message = "成功退出系统!" }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { SysLog log = new SysLog { Behavior = (Session["Admin"] as AdminInfo).UserName + "退出系统", FK_TypeID = 2, FK_AdminID = (Session["Admin"] as AdminInfo).AdminID, Parameters = "UserName,Password", IP = Request.UserHostAddress, CheckInTime = DateTime.Now, IsException = 1, Exception = ex.Message}; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }, JsonRequestBehavior.AllowGet); } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Supermarket.Code; using Supermarket.EneityFramework; namespace Supermarket.Web.Controllers { public class SysLogController : Controller { SupermarketDB db = new SupermarketDB(); public ActionResult Index() { return View(); } /// <summary> /// 获取需要的日志信息 /// </summary> /// <param name="limit">页面大小</param> /// <param name="offset">页码</param> /// <returns></returns> public ActionResult GetInfo(int limit, int offset) { try { int AdminID = Convert.ToInt32(Request["AdminID"]); var result = from log in db.SysLog where ((AdminID == 0) || (log.FK_AdminID == AdminID)) select new { log.LogID, log.AdminInfo.UserName, log.LogDic.TypeName, log.IP, log.Parameters, log.CheckInTime, log.IsException, log.Exception, log.Behavior }; var rows = result.OrderBy(p => p.LogID).Skip(offset).Take(limit).ToList(); return Json(new { total = result.Count(), rows = rows }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { return Json(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }, JsonRequestBehavior.AllowGet); } } /// <summary> /// 获取管理员信息 /// </summary> /// <returns></returns> public ActionResult GetAllAdmin() { try { var result = from admin in db.AdminInfo select new { admin.AdminID, admin.UserName }; return Json(result, JsonRequestBehavior.AllowGet); } catch (Exception ex) { return Json(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }, JsonRequestBehavior.AllowGet); } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Supermarket.EneityFramework; using Supermarket.Code; namespace Supermarket.Web.Controllers { public class AdminInfoController : Controller { //实例化数据模型 SupermarketDB db = new SupermarketDB(); /// <summary> /// AdminInfo /// </summary> /// <returns>Index视图</returns> public ActionResult Index() { return View(); } /// <summary> /// 获取角色信息 /// </summary> /// <returns>返回json</returns> public ActionResult GetRoles() { var data = from role in db.Role select new {role.RoleID,role.RoleName}; return Json(data,JsonRequestBehavior.AllowGet); } /// <summary> /// 获取AdminInfo表中数据方法,填充表格 /// </summary> /// <param name="limit">页面大小</param> /// <param name="offset">页码</param> /// <param name="rolename">角色名称</param> /// <param name="username">用户名</param> /// <returns>table当前页面数据</returns> public ActionResult GetInfo(int limit, int offset, string rolename, string username) { try { int RoleID = Convert.ToInt32(rolename); //延迟查询 var result = from a in db.AdminInfo //判断传入查询条件是否为空,true?skip:go where ((RoleID == 0) || (a.Role.RoleID == RoleID)) where ((username.Length == 0) || (a.UserName.Contains(username))) select new { a.AdminID, a.UserName, a.Account, a.RoleID, a.Role.RoleName, a.PassWord }; //得到结果总数 var total = result.Count(); //即时查询,当前页数据 var rows = result.OrderBy(m => m.AdminID).Skip(offset).Take(limit).ToList(); //返回数据 return Json(new { total = total, rows = rows }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { //出现异常,前台可接收该字符串进行提示 return Content(ex.Message); } } /// <summary> /// 修改Action方法 /// </summary> /// <param name="ai">存储当前要修改的数据</param> /// <returns>返回字符串用来判断执行结果</returns> public ActionResult Edit(AdminInfo admin) { SysLog log = new SysLog { Behavior = (Session["Admin"] as AdminInfo).UserName + "修改了"+admin.UserName+"的信息", FK_TypeID = 5, FK_AdminID = (Session["Admin"] as AdminInfo).AdminID, Parameters = "UserName", IP = Request.UserHostAddress, CheckInTime = DateTime.Now}; try { //更新实体 var data = db.AdminInfo.Find(admin.AdminID); data.UserName = admin.UserName; db.SaveChanges(); log.IsException = 0; log.Exception = string.Empty; db.SysLog.Add(log);db.SaveChanges(); return Json(new AjaxResult {state=ResultType.success.ToString(),message="修改成功" },JsonRequestBehavior.AllowGet); } catch (Exception ex) { log.IsException = 1; log.Exception = ex.Message; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.error.ToString(), message =ex.Message }, JsonRequestBehavior.AllowGet); } } /// <summary> /// 添加Action方法 /// </summary> /// <param name="ai">存储要添加的数据</param> /// <returns>返回字符串用来判断执行结果</returns> public ActionResult Add(AdminInfo admin) { SysLog log = new SysLog { Behavior = (Session["Admin"] as AdminInfo).UserName + "添加了新的管理员" + admin.UserName, FK_TypeID = 3, FK_AdminID = (Session["Admin"] as AdminInfo).AdminID, Parameters = "UserName", IP = Request.UserHostAddress, CheckInTime = DateTime.Now }; try { db.AdminInfo.Add(admin); db.SaveChanges(); log.IsException = 0; log.Exception = string.Empty; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.success.ToString(), message = "修改成功" }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { log.IsException = 1; log.Exception = ex.Message; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }, JsonRequestBehavior.AllowGet); } } /// <summary> /// 删除Action方法 /// </summary> /// <param name="AdminIDs">当前要删除的对象(主键)集合</param> /// <returns>返回字符串用来判断执行结果</returns> public ActionResult Delete(string[] AdminIDs) { SysLog log = new SysLog { Behavior = (Session["Admin"] as AdminInfo).UserName + "删除了"+AdminIDs.Length+"个管理员" , FK_TypeID = 4, FK_AdminID = (Session["Admin"] as AdminInfo).AdminID, Parameters = "UserName", IP = Request.UserHostAddress, CheckInTime = DateTime.Now }; try { for (int i = 0; i < AdminIDs.Length; i++) { //1、创建要删除的对象 AdminInfo admin = new AdminInfo() { AdminID = Convert.ToInt32(AdminIDs[i]) }; //2、将对象添加到EF管理容器中 db.AdminInfo.Attach(admin); //3、将对象包装类的状态标识为删除状态 db.AdminInfo.Remove(admin); } //4、更新到数据库 db.SaveChanges(); log.IsException = 0; log.Exception = string.Empty; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.success.ToString(), message = "删除成功" }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { log.IsException = 1; log.Exception = ex.Message; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }, JsonRequestBehavior.AllowGet); } } } }<file_sep> $(function () { //1.初始化Table var oTable = new TableInit(); oTable.Init(); //2.初始化Button的点击事件 var oButtonInit = new ButtonInit(); oButtonInit.Init(); //隐藏RoleID列 $('#tb_departments').bootstrapTable('hideColumn', 'RoleID'); //初始化select/selectpicker $('#order_status2').selectpicker({ }); //change触发事件(可删) $('#order_status2').change(function () { var i = $(this).val(); //alert(i); } ); GetRoels(); }); //填充角色信息 function GetRoels() { $("#RoleName").html("<option value='0'>全部</option>"); $.ajax({ url: "/AdminInfo/GetRoles", dataType: "json", success: function (data) { $.each(data, function (index, role) { $("#RoleName").append("<option value=" + role.RoleID + ">" + role.RoleName + "</option>"); }); }, error: function (XMLHttpRequest, textStatus, errorThrown) { window.alert("获取角色信息失败!"); } }); } var TableInit = function () { var oTableInit = new Object(); //初始化Table oTableInit.Init = function () { $('#tb_departments').bootstrapTable({ url: '/AdminInfo/GetInfo', //请求后台的URL(*) method: 'get', //请求方式(*) toolbar: '#toolbar', //工具按钮用哪个容器 striped: true, //是否显示行间隔色 cache: false, //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*) pagination: true, //是否显示分页(*) sortable: true, //是否启用排序 sortOrder: "asc", //排序方式 queryParams: oTableInit.queryParams,//传递参数(*) sidePagination: "server", //分页方式:client客户端分页,server服务端分页(*) pageNumber: 1, //初始化加载第一页,默认第一页 pageSize: 10, //每页的记录行数(*) pageList: [10, 15, 20, 50], //可供选择的每页的行数(*) search: true, //是否显示表格搜索,此搜索是客户端搜索,不会进服务端,所以,个人感觉意义不大 strictSearch: true, //严格搜索 showColumns: true, //是否显示所有的列 showRefresh: true, //是否显示刷新按钮 minimumCountColumns: 2, //最少允许的列数 clickToSelect: true, //是否启用点击选中行 uniqueId: "AdminID", //每一行的唯一标识,一般为主键列 showToggle: true, //是否显示详细视图和列表视图的切换按钮 cardView: false, //是否显示详细视图 detailView: false, //是否显示父子表 editable: true, columns: [{ checkbox: true //显示勾选框 }, { field: 'AdminID', //实际元素 title: '管理编号' //显示文本 }, { field: 'RoleID', title: '角色ID' }, { field: 'RoleName', title: '角色名称' }, { field: 'UserName', title: '用户名', //启用编辑(暂不可用) //editable: { // type: 'text', // title: '用户名', // validate: function (v) { // if (!v) return '用户名不能为空'; // } //} }, { field: 'Account', title: '账号' }, { field: '<PASSWORD> <PASSWORD>', title: '密码' }, ] //确认保存编辑(暂不可用) //onEditableSave: function (field, row, oldValue, $el) { // $.ajax({ // type: "post", // url: "/AdminInfo/Edit", // data: row, // dataType: 'JSON', // success: function (data, status) { // if (status == "success") { // alert('提交数据成功'); // } // }, // error: function () { // alert('编辑失败'); // }, // complete: function () { // } // }); //} }); }; //得到查询的参数 oTableInit.queryParams = function (params) { var temp = { //这里的键的名字和控制器的变量名必须一直,这边改动,控制器也需要改成一样的 limit: params.limit, //页面大小 offset: params.offset, //页码 rolename: $("#RoleName").val(),//角色名称 username: $("#text_UserName").val() //用户名 }; return temp; }; return oTableInit; }; var ButtonInit = function () { var oInit = new Object(); var postdata = {}; oInit.Init = function () { GetRoels1(); //点击新增触发事件 $("#btn_add").click(function () { $("#order_status2").val(0); //回到初始状态 $("#order_status2").selectpicker('refresh');//对searchPayState这个下拉框进行重置刷新 //模态框属性设置并显示 $("#myModalLabel").text("新增"); $("#myModal").find(".form-control").val(""); $('#myModal').modal(); }); //点击编辑触发事件 $("#btn_edit").click(function () { //获取当前选中行数据 var arrselections = $("#tb_departments").bootstrapTable('getSelections'); if (arrselections.length > 1) { alert('只能选择一行进行编辑'); return; } if (arrselections.length <= 0) { alert('请选择有效数据'); return; } //模态框属性设置并显示 $("#myModalLabel").text("编辑"); $("#txt_UserName").val(arrselections[0].UserName); $("#txt_Account").val(arrselections[0].Account); $("#txt_PassWord").val(arrselections[0].PassWord); $("#txt_AdminID").val(arrselections[0].AdminID); $("#order_status2").val(arrselections[0].RoleID); $("#order_status2").selectpicker('refresh');//对searchPayState这个下拉框进行重置刷新 $('#myModal').modal(); }); //点击删除触发事件 $("#btn_delete").click(function () { //获取当前选中行数据 var arrselections = $("#tb_departments").bootstrapTable('getSelections'); var info = JSON.stringify(arrselections); var AdminIDs = new Array(); if (arrselections.length <= 0) { alert("请至少选择一列!"); return; } else { // alert('getSelections: ' + JSON.stringify(arrselections)); //alert(info); //数组遍历选中项数据 $.each(eval(info), function (index, item) { AdminIDs[index] = item.AdminID; }); //alert(AdminIDs); } //友情提示,是否删除? confirm_ = confirm('Are you sure?'); if (confirm_) { $.ajax({ type: "post", url: "/AdminInfo/Delete", data: { "AdminIDs": AdminIDs }, success: function (data) { if (data.state == "success") { $("#tb_departments").bootstrapTable('refresh'); window.alert(data.message); } }, error: function () { window.alert("操作失败,请稍后再试"); }, complete: function () { $("#tb_departments").bootstrapTable('refresh'); } }); //alert("Refresh!"); //$("#tb_departments").bootstrapTable('refresh'); } }); //对话框提交触发事件 $("#btn_submit").click(function () { if ($("#myModalLabel").text() == "新增") { var data = $('#form').serialize(); //序列化获得表单数据, var submitData = decodeURIComponent(data, true); //submitData是解码后的表单数据,结果同上 //执行添加 $.ajax({ url: "/AdminInfo/Add", data: submitData, beforeSend: function () { //请求前 }, success: function (data) { //请求成功时 if (data.state == "success") { $("#tb_departments").bootstrapTable('refresh'); window.alert(data.message); } else { window.alert("网络延迟,请稍后再试!"); } }, error: function () { window.alert("操作失败,请稍后再试!"); } }) } else { // alert("Edit is loading"); var data = $('#form').serialize(); //序列化获得表单数据, var submitData = decodeURIComponent(data, true); $.ajax({ url: "/AdminInfo/Edit", data: submitData, beforeSend: function () { //请求前 }, success: function (data) { //请求成功时 if (data.state == "success") { $("#tb_departments").bootstrapTable('refresh'); window.alert(data.message); } else { window.alert("网络延迟,请稍后再试!"); } }, error: function () { window.alert("操作失败,请稍后再试!"); } }) } }); //查询触发事件 $("#btn_query").click(function () { $("#tb_departments").bootstrapTable('refresh'); }); //填充角色信息 function GetRoels1() { $("#order_status2").html("<option value='0'>请选择</option>"); $.ajax({ url: "/AdminInfo/GetRoles", dataType: "json", success: function (data) { $.each(data, function (index, role) { $("#order_status2").append("<option value=" + role.RoleID + ">" + role.RoleName + "</option>"); }); }, error: function (XMLHttpRequest, textStatus, errorThrown) { window.alert("获取角色信息失败!"); } }); } }; return oInit; };<file_sep>namespace Supermarket.EneityFramework { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class Purchases { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Purchases() { DetailePurchases = new HashSet<DetailePurchases>(); } public int PurchasesID { get; set; } [Column(TypeName = "money")] public decimal PurchasesTotal { get; set; } public int AdminID { get; set; } [StringLength(50)] public string Reamrk { get; set; } public DateTime PurchasesTime { get; set; } public virtual AdminInfo AdminInfo { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<DetailePurchases> DetailePurchases { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Supermarket.EneityFramework; using Supermarket.Code; namespace Supermarket.Web.Controllers { public class StockController : Controller { SupermarketDB db = new SupermarketDB(); public ActionResult Index() { return View(); } /// <summary> /// 获取需要的库存信息 /// </summary> /// <param name="limit"></param> /// <param name="offset"></param> /// <returns></returns> public ActionResult GetInfo(int limit, int offset) { try { var ProductName = Request["ProductName"]; var TypeID = Convert.ToInt32(Request["TypeID"]); var StorageStarTime = Request["StorageStarTime"]; var StorageEndTime = Request["StorageEndTime"]; DateTime start=DateTime.Now, end=DateTime.Now; if (StorageStarTime != "") { start= Convert.ToDateTime(StorageStarTime); } if (StorageEndTime != "") { end= Convert.ToDateTime(StorageEndTime); } var result = from stock in db.Stock where ((ProductName.Length == 0) || (stock.Product.ProductName.Contains(ProductName))) where ((TypeID == 0) || (stock.Product.TypeID == TypeID)) where ((StorageStarTime.Length == 0) || (stock.StorageTime >= start)) where ((StorageEndTime.Length == 0) || (stock.StorageTime <= end)) select new { stock.StockID, stock.StorageTime, stock.CommodityStockAmount, stock.StockUp, stock.StockDown, stock.AlterTime, stock.Product.ProductName, stock.Product.Type.TypeName, stock.Product.Unit.UnitName }; var rows = result.OrderBy(p => p.StockID).Skip(offset).Take(limit).ToList(); return Json(new { total = result.Count(), rows = rows }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { return Json(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }, JsonRequestBehavior.AllowGet); } } /// <summary> /// 修改库存量 /// </summary> /// <param name="stock"></param> /// <returns></returns> public ActionResult Edit(EneityFramework.Stock stock) { SysLog log = new SysLog { Behavior = (Session["Admin"] as AdminInfo).UserName + "修改了编号为" + stock.StockID + "的库存", FK_TypeID = 23, FK_AdminID = (Session["Admin"] as AdminInfo).AdminID, Parameters = "StockID,CommodityStockAmount", IP = Request.UserHostAddress, CheckInTime = DateTime.Now }; try { EneityFramework.Stock newStock = db.Stock.Find(stock.StockID); newStock.CommodityStockAmount = stock.CommodityStockAmount; db.SaveChanges(); log.IsException = 0; log.Exception = string.Empty; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.success.ToString(), message = "成功修改库存" }, JsonRequestBehavior.AllowGet); } catch(Exception ex) { log.IsException = 1; log.Exception = ex.Message; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult {state=ResultType.error.ToString(),message=ex.Message },JsonRequestBehavior.AllowGet); } } } }<file_sep>namespace Supermarket.EneityFramework { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class Orders { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Orders() { DetailOrder = new HashSet<DetailOrder>(); } [Key] public int OrderFormID { get; set; } public int CustomsID { get; set; } [Column(TypeName = "money")] public decimal SunPrice { get; set; } public DateTime? CheckInTime { get; set; } [Required] [StringLength(20)] public string Way { get; set; } public int? AdminID { get; set; } public virtual AdminInfo AdminInfo { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<DetailOrder> DetailOrder { get; set; } public virtual User User { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Supermarket.EneityFramework; using Supermarket.Code; namespace Supermarket.Web.Controllers { public class ReturnGoodsController : Controller { SupermarketDB db = new SupermarketDB(); public ActionResult Index() { return View(); } /// <summary> /// 获取需要的出库信息 /// </summary> /// <param name="limit">页面大小</param> /// <param name="offset">页码</param> /// <returns></returns> public ActionResult GetInfo(int limit, int offset) { try { var ProductName = Request["ProductName"]; var TypeID = Convert.ToInt32(Request["TypeID"]); var StorageStarTime = Request["StarTime"]; var StorageEndTime = Request["EndTime"]; DateTime start = DateTime.Now, end = DateTime.Now; if (StorageStarTime != "") { start = Convert.ToDateTime(StorageStarTime); } if (StorageEndTime != "") { end = Convert.ToDateTime(StorageEndTime); } var result = from good in db.ReturnGoods where ((ProductName.Length == 0) || (good.Product.ProductName.Contains(ProductName))) where ((TypeID == 0) || (good.Product.TypeID == TypeID)) where ((StorageStarTime.Length == 0) || (good.CheckInTime >= start)) where ((StorageEndTime.Length == 0) || (good.CheckInTime <= end)) select new { good.ReturnGoodsID, good.ReturnAmount, good.Remark, good.CheckInTime, good.Product.ProductName, good.Product.Type.TypeName, good.Product.Unit.UnitName }; //即时查询,当前页数据 var rows = result.OrderBy(m => m.ReturnGoodsID).Skip(offset).Take(limit).ToList(); //返回数据 return Json(new { total = result.Count(), rows = rows }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { //出现异常,前台可接收该字符串进行提示 return Content(ex.Message); } } /// <summary> /// 编辑出库信息 /// </summary> /// <param name="good"></param> /// <returns></returns> public ActionResult Edit(EneityFramework.ReturnGoods good) { SysLog log = new SysLog { Behavior = (Session["Admin"] as AdminInfo).UserName + "修改了编号为" + good.ReturnGoodsID + "的出库信息", FK_TypeID = 20, FK_AdminID = (Session["Admin"] as AdminInfo).AdminID, Parameters = "ReturnGoodsID,Remark,ReturnAmount", IP = Request.UserHostAddress, CheckInTime = DateTime.Now }; try { EneityFramework.ReturnGoods newGood = db.ReturnGoods.Find(good.ReturnGoodsID); newGood.Remark = good.Remark; newGood.ReturnAmount = good.ReturnAmount; db.SaveChanges(); log.IsException = 0; log.Exception = string.Empty; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.success.ToString(), message = "编辑成功" }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { log.IsException = 1; log.Exception = ex.Message; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }, JsonRequestBehavior.AllowGet); } } /// <summary> /// 删除出库信息 /// </summary> /// <param name="Goods"></param> /// <returns></returns> [HttpPost] public ActionResult Delete(string[] GoodIDs) { SysLog log = new SysLog { Behavior = (Session["Admin"] as AdminInfo).UserName + "删除了" + GoodIDs.Length + "个出库信息", FK_TypeID = 20, FK_AdminID = (Session["Admin"] as AdminInfo).AdminID, Parameters = "GoodIDs", IP = Request.UserHostAddress, CheckInTime = DateTime.Now }; try { for (int i = 0; i < GoodIDs.Length; i++) { Supermarket.EneityFramework.ReturnGoods newGood = db.ReturnGoods.Find(Convert.ToInt32(GoodIDs[i])); db.ReturnGoods.Remove(newGood); } db.SaveChanges(); log.IsException = 0; log.Exception = string.Empty; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.success.ToString(), message = "成功删除" }, JsonRequestBehavior.AllowGet); } catch(Exception ex) { log.IsException = 1; log.Exception = ex.Message; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state= ResultType.error.ToString() ,message=ex.Message},JsonRequestBehavior.AllowGet); } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Supermarket.EneityFramework; using Supermarket.Code; namespace Supermarket.Web.Controllers { public class PurchasesController : Controller { SupermarketDB db = new SupermarketDB(); public ActionResult Index() { return View(); } /// <summary> /// 获取需要的进货信息 /// </summary> /// <param name="limit">页面大小</param> /// <param name="offest">页码</param> /// <returns></returns> public ActionResult GetInfo(int limit, int offset) { try { var ID = Convert.ToInt32(Request["AdminID"]); var StarTime = Request["StarTime"]; var EndTime = Request["EndTime"]; DateTime start = DateTime.Now, end = DateTime.Now; if (StarTime != "") { start = Convert.ToDateTime(StarTime); } if (EndTime != "") { end = Convert.ToDateTime(EndTime); } var result = from pur in db.Purchases where ((ID == 0) || (pur.AdminID == ID)) where ((StarTime.Length == 0) || (pur .PurchasesTime >= start)) where ((EndTime.Length == 0) || (pur.PurchasesTime <= end)) select new { pur.PurchasesID, pur.PurchasesTime, pur.Reamrk, pur.AdminInfo.UserName, pur.PurchasesTotal }; var rows = result.OrderBy(p => p.PurchasesID).Skip(offset).Take(limit).ToList(); return Json(new { total = result.Count(), rows = rows }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { return Json(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }, JsonRequestBehavior.AllowGet); } } /// <summary> /// 进货详情 /// </summary> /// <param name="limit"></param> /// <param name="offset"></param> /// <returns></returns> public ActionResult GetDetail(int limit, int offset) { try { var PurID = Convert.ToInt32(Request["PurID"]); var retsult = from detail in db.DetailePurchases where ((PurID == 0) || (detail.PurchasesID == PurID)) select new { detail.DetailePurchasesID, detail.Product.ProductName, detail.Product.Unit.UnitName, detail.Product.Type.TypeName, detail.ProductAmount, detail.Reamrk }; var rows = retsult.OrderBy(p => p.DetailePurchasesID).Skip(offset).Take(limit).ToList(); return Json(new { total = retsult.Count(), rows = rows }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { return Json(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }, JsonRequestBehavior.AllowGet); } } /// <summary> /// 编辑入库信息 /// </summary> /// <param name="pur"></param> /// <returns></returns> [HttpPost] public ActionResult EditPurchases(EneityFramework.Purchases pur) { SysLog log = new SysLog { Behavior = (Session["Admin"] as AdminInfo).UserName + "修改了编号为" + pur.PurchasesID + "的入库信息", FK_TypeID = 17, FK_AdminID = (Session["Admin"] as AdminInfo).AdminID, Parameters = "PurchasesID,PurchasesTotal,Reamrk", IP = Request.UserHostAddress, CheckInTime = DateTime.Now }; try { EneityFramework.Purchases newPur = db.Purchases.Find(pur.PurchasesID); newPur.PurchasesTotal = pur.PurchasesTotal; newPur.Reamrk = pur.Reamrk; db.SaveChanges(); log.IsException = 0; log.Exception = string.Empty; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.success.ToString(), message = "编辑成功" }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { log.IsException = 1; log.Exception = ex.Message; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }, JsonRequestBehavior.AllowGet); } } /// <summary> /// 删除入库信息 /// </summary> /// <param name="PurIDs"></param> /// <returns></returns> [HttpPost] public ActionResult Delete(string[] PurIDs) { SysLog log = new SysLog { Behavior = (Session["Admin"] as AdminInfo).UserName + "删除了" + PurIDs.Length + "个入库信息", FK_TypeID = 18, FK_AdminID = (Session["Admin"] as AdminInfo).AdminID, Parameters = "PurchasesID", IP = Request.UserHostAddress, CheckInTime = DateTime.Now }; try { for(int i = 0; i < PurIDs.Length; i++) { EneityFramework.Purchases newPur = db.Purchases.Find(Convert.ToInt32(PurIDs[i])); db.Database.ExecuteSqlCommand("delete DetailePurchases where PurchasesID=" + Convert.ToInt32(PurIDs[i])); db.SaveChanges(); log.IsException = 0; log.Exception = string.Empty; db.SysLog.Add(log); db.SaveChanges(); db.Purchases.Remove(newPur); } db.SaveChanges(); return Json(new AjaxResult { state = ResultType.success.ToString(), message = "成功删除入库信息" }, JsonRequestBehavior.AllowGet); } catch(Exception ex) { log.IsException = 1; log.Exception = ex.Message; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state=ResultType.error.ToString(),message=ex.Message},JsonRequestBehavior.AllowGet); } } /// <summary> /// 获取仓库管理员 /// </summary> /// <returns></returns> [HttpPost] public ActionResult GetPurchasesName() { try { var result = from admin in db.AdminInfo where admin.RoleID == 4 select new { admin.AdminID, admin.UserName }; return Json(result,JsonRequestBehavior.AllowGet); } catch(Exception ex) { return Json(new AjaxResult {state=ResultType.error,message=ex.Message },JsonRequestBehavior.AllowGet); } } } }<file_sep>namespace Supermarket.EneityFramework { using System; using System.Data.Entity; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; public partial class SupermarketDB : DbContext { public SupermarketDB() : base("name=SupermarketDBConnString") { } public virtual DbSet<AdminInfo> AdminInfo { get; set; } public virtual DbSet<Card> Card { get; set; } public virtual DbSet<DetailePurchases> DetailePurchases { get; set; } public virtual DbSet<DetailOrder> DetailOrder { get; set; } public virtual DbSet<LogDic> LogDic { get; set; } public virtual DbSet<Orders> Orders { get; set; } public virtual DbSet<Product> Product { get; set; } public virtual DbSet<Purchases> Purchases { get; set; } public virtual DbSet<ReturnGoods> ReturnGoods { get; set; } public virtual DbSet<Role> Role { get; set; } public virtual DbSet<Stock> Stock { get; set; } public virtual DbSet<SysLog> SysLog { get; set; } public virtual DbSet<Type> Type { get; set; } public virtual DbSet<Unit> Unit { get; set; } public virtual DbSet<User> User { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<AdminInfo>() .Property(e => e.UserName) .IsUnicode(false); modelBuilder.Entity<AdminInfo>() .Property(e => e.Account) .IsUnicode(false); modelBuilder.Entity<AdminInfo>() .Property(e => e.PassWord) .IsUnicode(false); modelBuilder.Entity<AdminInfo>() .HasMany(e => e.Purchases) .WithRequired(e => e.AdminInfo) .WillCascadeOnDelete(false); modelBuilder.Entity<AdminInfo>() .HasMany(e => e.SysLog) .WithOptional(e => e.AdminInfo) .HasForeignKey(e => e.FK_AdminID); modelBuilder.Entity<Card>() .Property(e => e.TotalCost) .HasPrecision(19, 4); modelBuilder.Entity<Card>() .HasMany(e => e.User) .WithRequired(e => e.Card) .WillCascadeOnDelete(false); modelBuilder.Entity<DetailePurchases>() .Property(e => e.ProductAmount) .HasPrecision(18, 0); modelBuilder.Entity<DetailePurchases>() .Property(e => e.Reamrk) .IsUnicode(false); modelBuilder.Entity<DetailOrder>() .Property(e => e.Amount) .HasPrecision(18, 0); modelBuilder.Entity<DetailOrder>() .Property(e => e.subtotal) .HasPrecision(19, 4); modelBuilder.Entity<LogDic>() .Property(e => e.TypeName) .IsUnicode(false); modelBuilder.Entity<LogDic>() .HasMany(e => e.SysLog) .WithOptional(e => e.LogDic) .HasForeignKey(e => e.FK_TypeID); modelBuilder.Entity<Orders>() .Property(e => e.SunPrice) .HasPrecision(19, 4); modelBuilder.Entity<Orders>() .Property(e => e.Way) .IsUnicode(false); modelBuilder.Entity<Orders>() .HasMany(e => e.DetailOrder) .WithRequired(e => e.Orders) .WillCascadeOnDelete(false); modelBuilder.Entity<Product>() .Property(e => e.ProductName) .IsUnicode(false); modelBuilder.Entity<Product>() .Property(e => e.BarCode) .IsUnicode(false); modelBuilder.Entity<Product>() .Property(e => e.Manufacturer) .IsUnicode(false); modelBuilder.Entity<Product>() .Property(e => e.CommodityDepict) .IsUnicode(false); modelBuilder.Entity<Product>() .Property(e => e.CommodityPriceOut) .HasPrecision(19, 4); modelBuilder.Entity<Product>() .Property(e => e.CommodityPriceIn) .HasPrecision(19, 4); modelBuilder.Entity<Product>() .HasMany(e => e.DetailePurchases) .WithRequired(e => e.Product) .WillCascadeOnDelete(false); modelBuilder.Entity<Product>() .HasMany(e => e.DetailOrder) .WithRequired(e => e.Product) .WillCascadeOnDelete(false); modelBuilder.Entity<Product>() .HasMany(e => e.ReturnGoods) .WithRequired(e => e.Product) .WillCascadeOnDelete(false); modelBuilder.Entity<Product>() .HasMany(e => e.Stock) .WithRequired(e => e.Product) .WillCascadeOnDelete(false); modelBuilder.Entity<Purchases>() .Property(e => e.PurchasesTotal) .HasPrecision(19, 4); modelBuilder.Entity<Purchases>() .Property(e => e.Reamrk) .IsUnicode(false); modelBuilder.Entity<Purchases>() .HasMany(e => e.DetailePurchases) .WithRequired(e => e.Purchases) .WillCascadeOnDelete(false); modelBuilder.Entity<ReturnGoods>() .Property(e => e.ReturnAmount) .HasPrecision(18, 0); modelBuilder.Entity<ReturnGoods>() .Property(e => e.Remark) .IsUnicode(false); modelBuilder.Entity<Role>() .HasMany(e => e.AdminInfo) .WithRequired(e => e.Role) .WillCascadeOnDelete(false); modelBuilder.Entity<Stock>() .Property(e => e.CommodityStockAmount) .HasPrecision(18, 0); modelBuilder.Entity<Stock>() .Property(e => e.StockUp) .HasPrecision(18, 0); modelBuilder.Entity<Stock>() .Property(e => e.StockDown) .HasPrecision(18, 0); modelBuilder.Entity<SysLog>() .Property(e => e.Behavior) .IsUnicode(false); modelBuilder.Entity<SysLog>() .Property(e => e.Parameters) .IsUnicode(false); modelBuilder.Entity<SysLog>() .Property(e => e.IP) .IsUnicode(false); modelBuilder.Entity<SysLog>() .Property(e => e.Exception) .IsUnicode(false); modelBuilder.Entity<Type>() .Property(e => e.TypeName) .IsUnicode(false); modelBuilder.Entity<Type>() .HasMany(e => e.Product) .WithRequired(e => e.Type) .WillCascadeOnDelete(false); modelBuilder.Entity<Unit>() .Property(e => e.UnitName) .IsUnicode(false); modelBuilder.Entity<User>() .Property(e => e.UserName) .IsUnicode(false); modelBuilder.Entity<User>() .Property(e => e.IDNumber) .IsUnicode(false); modelBuilder.Entity<User>() .Property(e => e.UserPassWord) .IsUnicode(false); modelBuilder.Entity<User>() .HasMany(e => e.Orders) .WithRequired(e => e.User) .HasForeignKey(e => e.CustomsID) .WillCascadeOnDelete(false); } } } <file_sep>$(function () { //1.初始化Table var oTable = new TableInit(); oTable.Init(); GetProductType(); //2.初始化Button的点击事件 var oButtonInit = new ButtonInit(); oButtonInit.Init(); }); //获取商品类别信息 function GetProductType() { $("#ProductType").html("<option value='0'>请选择</option>"); $.ajax({ type: 'post', url: "/Product/GetProductType", dataType: "json", success: function (data) { $.each(data, function (index, type) { $("#ProductType").append("<option value=" + type.TypeID + ">" + type.TypeName + "</option>"); }); }, error: function (XMLHttpRequest, textStatus, errorThrown) { window.alert("获取商品类型失败!"); } }); } var TableInit = function () { var oTableInit = new Object(); //初始化Table oTableInit.Init = function () { $('#ReturnGoods').bootstrapTable({ url: '/ReturnGoods/GetInfo', //请求后台的URL(*) method: 'get', //请求方式(*) toolbar: '#toolbar', //工具按钮用哪个容器 cache: false, //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*) pagination: true, //是否显示分页(*) sortable: true, //是否启用排序 sortOrder: "asc", //排序方式 queryParams: oTableInit.queryParams,//传递参数(*) sidePagination: "server", //分页方式:client客户端分页,server服务端分页(*) pageNumber: 1, //初始化加载第一页,默认第一页 pageSize: 10, //每页的记录行数(*) pageList: [10, 15, 20, 50], //可供选择的每页的行数(*) search: true, //是否显示表格搜索,此搜索是客户端搜索,不会进服务端,所以,个人感觉意义不大 strictSearch: true, //严格搜索 showColumns: true, //是否显示所有的列 showRefresh: true, //是否显示刷新按钮 minimumCountColumns: 2, //最少允许的列数 clickToSelect: true, //是否启用点击选中行 //行高,如果没有设置height属性,表格自动根据记录条数觉得表格高度 uniqueId: "ReturnGoodsID", //每一行的唯一标识,一般为主键列 showToggle: true, //是否显示详细视图和列表视图的切换按钮 cardView: false, //是否显示详细视图 detailView: false, //是否显示父子表 editable: true, columns: [{ checkbox: true //显示勾选框 }, { field: 'ReturnGoodsID', //实际元素 title: '编号' //显示文本 }, { field: 'ProductName', title: '商品名称' }, { field: 'UnitName', title: '单位' }, { field: 'TypeName', title: '类别' }, { field: 'ReturnAmount', title: '出库数量', }, { field: 'Remark', title: '出库原因' }, { field: 'CheckInTime', title: '出库时间', formatter: formatDatebox }] }); }; //得到查询的参数 oTableInit.queryParams = function (params) { var temp = { //这里的键的名字和控制器的变量名必须一直,这边改动,控制器也需要改成一样的 limit: params.limit, //页面大小 offset: params.offset, //页码 ProductName: $("#ProductNmae").val(), TypeID: $("#ProductType").val(), StarTime: $("#StarTime").val(), EndTime: $("#EndTime").val() }; return temp; }; return oTableInit; }; var ButtonInit = function () { var oInit = new Object(); var postdata = {}; oInit.Init = function () { //点击删除触发事件 $("#btn_delete").click(function () { //获取当前选中行数据 var arrselections = $("#ReturnGoods").bootstrapTable('getSelections'); var info = JSON.stringify(arrselections); var GoodIDs = new Array(); if (arrselections.length <= 0) { alert("请至少选择一列!"); return; } else { //数组遍历选中项数据 $.each(eval(info), function (index, item) { GoodIDs[index] = item.ReturnGoodsID; }); } //友情提示,是否删除? confirm_ = confirm('你确定要进行删除吗?'); if (confirm_) { $.ajax({ type: "post", url: "/ReturnGoods/Delete", data: { "GoodIDs": GoodIDs }, success: function (data) { if (data.state == "success") { window.alert(data.message); } else { window.alert("网络延迟,请稍后再试"); } }, error: function () { alert("操作失败,请稍后再试!"); }, complete: function () { $("#ReturnGoods").bootstrapTable('refresh'); } }); } }); //对话框提交触发事件 $("#btn_submit").click(function () { $.lbl_error = { formMessage: function (msg) { $("#lbl_error").append(msg + "<br/>"); } } var data = $('#form').serialize(); //序列化获得表单数据, var submitData = decodeURIComponent(data, true); $.ajax({ type: 'post', url: "/ReturnGoods/Edit", data: submitData, beforeSend: function () { var state = true; $("#lbl_error").html(""); if (!IsNumber($("#txt_ReturnAmount").val())) { $.lbl_error.formMessage("请填写正确的数量"); state = false; } return state; }, success: function (data) { if (data.state == "success") { window.alert(data.message); $('#myModal').modal('hide'); $("#ReturnGoods").bootstrapTable('refresh'); } else { window.alert("网络延迟,请稍后再试"); } }, error: function () { window.alert("操作失败,请稍后再试!"); } }) }); //查询触发事件 $("#btn_query").click(function () { $("#ReturnGoods").bootstrapTable('refresh'); }); }; return oInit; };<file_sep>namespace Supermarket.EneityFramework { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class DetailePurchases { public int DetailePurchasesID { get; set; } public int PurchasesID { get; set; } public int ProductID { get; set; } public decimal ProductAmount { get; set; } [StringLength(50)] public string Reamrk { get; set; } public virtual Product Product { get; set; } public virtual Purchases Purchases { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Supermarket.EneityFramework; using Supermarket.Code; namespace Supermarket.Web.Controllers { public class CategoryController : Controller { SupermarketDB db = new SupermarketDB(); // GET: Category public ActionResult Index() { return View(); } /// <summary> /// 获取商品类别信息 /// </summary> /// <param name="limit">页面大小</param> /// <param name="offset">页码</param> /// <returns></returns> public ActionResult GetInfo(int limit, int offset) { try { var result = from type in db.Type select new { type.TypeID, type.TypeName }; //得到结果总数 var total = result.Count(); //即时查询,当前页数据 var rows = result.OrderBy(m => m.TypeID).Skip(offset).Take(limit).ToList(); //返回数据 return Json(new { total = total, rows = rows }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { return Json(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }, JsonRequestBehavior.AllowGet); } } /// <summary> /// 添加新的类别信息 /// </summary> /// <param name="type"></param> /// <returns></returns> public ActionResult AddType(Supermarket.EneityFramework.Type type) { SysLog log = new SysLog { Behavior = (Session["Admin"] as AdminInfo).UserName + "添加了新的商品类别" + type.TypeName, FK_TypeID = 9, FK_AdminID = (Session["Admin"] as AdminInfo).AdminID, Parameters = "TypeName", IP = Request.UserHostAddress, CheckInTime = DateTime.Now }; try { db.Type.Add(type); db.SaveChanges(); log.IsException = 0; log.Exception = string.Empty; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.success.ToString(), message = "添加成功" }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { log.IsException = 1; log.Exception = ex.Message; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }, JsonRequestBehavior.AllowGet); } } /// <summary> /// 商品类别的删除 /// </summary> /// <returns></returns> [HttpPost] public ActionResult Delete(string[] TypeIDs) { SysLog log = new SysLog { Behavior = (Session["Admin"] as AdminInfo).UserName + "删除了"+TypeIDs.Length+"个商品类别", FK_TypeID = 11, FK_AdminID = (Session["Admin"] as AdminInfo).AdminID, Parameters = "TypeID", IP = Request.UserHostAddress, CheckInTime = DateTime.Now }; try { for (var i = 0; i < TypeIDs.Length; i++) { EneityFramework.Type type = new EneityFramework.Type { TypeID = Convert.ToInt32(TypeIDs[i]) }; db.Type.Attach(type); db.Type.Remove(type); } db.SaveChanges(); log.IsException = 0; log.Exception = string.Empty; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.success.ToString(), message = "删除成功" }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { log.IsException = 1; log.Exception = ex.Message; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }, JsonRequestBehavior.AllowGet); } } /// <summary> /// 编辑商品类别 /// </summary> /// <returns></returns> [HttpPost] public ActionResult Edit(Supermarket.EneityFramework.Type type) { SysLog log = new SysLog { Behavior = (Session["Admin"] as AdminInfo).UserName + "修改了商品类别" + type.TypeName, FK_TypeID = 10, FK_AdminID = (Session["Admin"] as AdminInfo).AdminID, Parameters = "TypeID,TypeName", IP = Request.UserHostAddress, CheckInTime = DateTime.Now }; try { db.Entry(type).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); log.IsException = 0; log.Exception = string.Empty; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.success.ToString(), message = "编辑商品成功" }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { log.IsException = 1; log.Exception = ex.Message; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }, JsonRequestBehavior.AllowGet); } } } }<file_sep>$(function () { $("#all").click(function () { var docElm = document.documentElement; //W3C if (docElm.requestFullscreen) { docElm.requestFullscreen(); } //FireFox else if (docElm.mozRequestFullScreen) { docElm.mozRequestFullScreen(); } //Chrome else if (docElm.webkitRequestFullScreen) { docElm.webkitRequestFullScreen(); } //IE11 else if (elem.msRequestFullscreen) { elem.msRequestFullscreen(); } }) })<file_sep>namespace Supermarket.EneityFramework { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class ReturnGoods { public int ReturnGoodsID { get; set; } public int ProductID { get; set; } public decimal ReturnAmount { get; set; } [StringLength(200)] public string Remark { get; set; } public DateTime CheckInTime { get; set; } public virtual Product Product { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Supermarket.EneityFramework; using Supermarket.Code; namespace Supermarket.Web.Controllers { public class ProductController : Controller { SupermarketDB db = new SupermarketDB(); /// <summary> /// 显示视图 /// </summary> /// <returns></returns> public ActionResult Index() { return View(); } /// <summary> /// 获取想要的商品信息 /// </summary> /// <param name="limit">页面大小</param> /// <param name="offset">页码</param> /// <returns></returns> public ActionResult GetInfo(int limit, int offset) { try { var ProName = Request["ProductName"]; var ptype = Convert.ToInt32(Request["type"]); var IsDel = Convert.ToInt32(Request["IsDel"]); //延迟查询 var result = from pro in db.Product join type in db.Type on pro.TypeID equals type.TypeID join unit in db.Unit on pro.UnitID equals unit.UnitID where ((ProName.Length == 0) || (pro.ProductName.Contains(ProName))) where ((ptype == 0) || (type.TypeID == ptype)) where ((IsDel == 2) || (pro.IsDelete == IsDel)) select new { pro.ProductID, pro.ProductName, pro.Manufacturer, pro.CommodityPriceOut, pro.CommodityPriceIn, pro.CommodityDepict, pro.IsDelete, pro.BarCode, type.TypeName, unit.UnitName, }; //得到结果总数 var total = result.Count(); //即时查询,当前页数据 var rows = result.OrderBy(m => m.ProductID).Skip(offset).Take(limit).ToList(); //返回数据 return Json(new { total = total, rows = rows }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { //出现异常,前台可接收该字符串进行提示 return Content(ex.Message); } } /// <summary> /// 获取商品类别 /// </summary> /// <returns></returns> [HttpPost] public ActionResult GetProductType() { try { var type = from t in db.Type select new { t.TypeID, t.TypeName }; return Json(type, JsonRequestBehavior.AllowGet); } catch (Exception ex) { return Json(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }, JsonRequestBehavior.AllowGet); } } /// <summary> /// 商品的上下架 /// </summary> /// <returns></returns> [HttpPost] public ActionResult IsActivate() { SysLog log = null; try { var state = Convert.ToInt32(Request["state"]); int TypeID = state == 0 ? 14 : 15; log = new SysLog { Behavior = (Session["Admin"] as AdminInfo).UserName + (state == 0 ? "上架" : "下架") + "了商品", FK_TypeID = TypeID, FK_AdminID = (Session["Admin"] as AdminInfo).AdminID, Parameters = "ProductID,IsDelete", IP = Request.UserHostAddress, CheckInTime = DateTime.Now }; Product pro = db.Product.Find(Convert.ToInt32(Request["ProductID"])); pro.IsDelete = state; db.Entry(pro).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); log.IsException = 0; log.Exception = string.Empty; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.success.ToString(), message = "操作成功!" }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { log.IsException = 1; log.Exception = ex.Message; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }, JsonRequestBehavior.AllowGet); } } /// <summary> /// 批量对商品进行操作 /// </summary> /// <param name="ProductIDs">需要操作的商品ID的数组</param> /// <returns></returns> public ActionResult InActivate(string[] ProductIDs, int state) { int TypeID = state == 0 ? 14 : 15; SysLog log = new SysLog { Behavior = (Session["Admin"] as AdminInfo).UserName + (state == 0 ? "上架" : "下架")+"了"+ProductIDs.Length+"个商品", FK_TypeID = TypeID, FK_AdminID = (Session["Admin"] as AdminInfo).AdminID, Parameters = "ProductID,IsDelete", IP = Request.UserHostAddress, CheckInTime = DateTime.Now }; try { for (var i = 0; i < ProductIDs.Length; i++) { Product info = db.Product.Find(Convert.ToInt32(ProductIDs[i])); info.IsDelete = state; db.Entry(info).State = System.Data.Entity.EntityState.Modified; } db.SaveChanges(); log.IsException = 0; log.Exception = string.Empty; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.success.ToString(), message = (state == 0 ? "上架" : "下架") + "商品操作成功!" }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { log.IsException = 1; log.Exception = ex.Message; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }, JsonRequestBehavior.AllowGet); } } /// <summary> /// 编辑商品信息 /// </summary> /// <param name="pro"></param> /// <returns></returns> public ActionResult Edit(Product pro) { SysLog log = new SysLog { Behavior = (Session["Admin"] as AdminInfo).UserName + "修改了编号为"+pro.ProductID+"的商品信息", FK_TypeID = 13, FK_AdminID = (Session["Admin"] as AdminInfo).AdminID, Parameters = "ProductID,ProductName,CommodityPriceOut,CommodityDepict,Isdelete", IP = Request.UserHostAddress, CheckInTime = DateTime.Now }; try { Product product = db.Product.Find(pro.ProductID); product.ProductName = pro.ProductName; product.CommodityPriceOut = pro.CommodityPriceOut; product.CommodityDepict = pro.CommodityDepict; product.IsDelete = pro.IsDelete; db.SaveChanges(); log.IsException = 0; log.Exception = string.Empty; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.success.ToString(), message = "商品编辑成功!" }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { log.IsException = 1; log.Exception = ex.Message; db.SysLog.Add(log); db.SaveChanges(); return Json(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }, JsonRequestBehavior.AllowGet); } } } }<file_sep>namespace Supermarket.EneityFramework { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("User")] public partial class User { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public User() { Orders = new HashSet<Orders>(); } public int UserID { get; set; } public int CardID { get; set; } [Required] [StringLength(50)] public string UserName { get; set; } [Required] [StringLength(18)] public string IDNumber { get; set; } public int? Sex { get; set; } public int? Age { get; set; } [StringLength(50)] public string UserPassWord { get; set; } public DateTime? AlterInTime { get; set; } public int IsDelete { get; set; } public virtual Card Card { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Orders> Orders { get; set; } } } <file_sep>$(function () { $("#Exit").click(function () { if (confirm("你确定要退出吗?")) { $.ajax({ type:'post', url: '/Login/Exit', success:function(data){ if (data.state == "success") { window.location.replace("/Login/Index"); } } }) } }) });<file_sep>$(function () { //1.初始化Table var oTable = new TableInit(); oTable.Init(); GetPurchasesName(); var oTable = new NewTableInit(); oTable.Init(); //2.初始化Button的点击事件 var oButtonInit = new ButtonInit(); oButtonInit.Init(); }); function GetPurchasesName() { $("#AdminName").html("<option value='0'>全部</option>"); $.ajax({ type: 'post', url: "/Purchases/GetPurchasesName", dataType: "json", success: function (data) { $.each(data, function (index, admin) { $("#AdminName").append("<option value=" + admin.AdminID + ">" + admin.UserName + "</option>"); }); }, error: function (XMLHttpRequest, textStatus, errorThrown) { window.alert("获取创库管理员失败!"); } }); } var PurID = 0; function Detail(value) { $("#DetailModal").modal(); PurID = $(value).parent().parent().find("td:eq(1)").text(); $("#Detail").bootstrapTable('refresh'); } var NewTableInit = function () { var oTableInit = new Object(); //初始化Table oTableInit.Init = function () { $('#Detail').bootstrapTable({ url: '/Purchases/GetDetail', //请求后台的URL(*) method: 'get', //请求方式(*) cache: false, //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*) pagination: true, //是否显示分页(*) sortable: true, //是否启用排序 sortOrder: "asc", //排序方式 queryParams: oTableInit.queryParams,//传递参数(*) sidePagination: "server", //分页方式:client客户端分页,server服务端分页(*) pageNumber: 1, //初始化加载第一页,默认第一页 pageSize: 10, //每页的记录行数(*) pageList: [10, 15, 20, 50], //可供选择的每页的行数(*) showColumns: false, //是否显示所有的列 minimumCountColumns: 2, //最少允许的列数 clickToSelect: true, //是否启用点击选中行 //行高,如果没有设置height属性,表格自动根据记录条数觉得表格高度 uniqueId: "DetailePurchasesID", //每一行的唯一标识,一般为主键列 columns: [{ field: 'avc', title: '', formatter: function (value,row,index) { return index + 1; } }, { field: 'ProductName', title: '商品名称' }, { field: 'UnitName', title: '单位' }, { field: 'TypeName', title: '类型' }, { field: 'ProductAmount', title: '进货数量' }, { field: 'Reamrk', title: '简介' } ] }); }; //得到查询的参数 oTableInit.queryParams = function (params) { var temp = { //这里的键的名字和控制器的变量名必须一直,这边改动,控制器也需要改成一样的 limit: params.limit, //页面大小 offset: params.offset, //页码 PurID: PurID }; return temp; }; return oTableInit; }; var TableInit = function () { var oTableInit = new Object(); //初始化Table oTableInit.Init = function () { $('#Purchases').bootstrapTable({ url: '/Purchases/GetInfo', //请求后台的URL(*) method: 'get', //请求方式(*) toolbar: '#toolbar', //工具按钮用哪个容器 cache: false, //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*) pagination: true, //是否显示分页(*) sortable: true, //是否启用排序 sortOrder: "asc", //排序方式 queryParams: oTableInit.queryParams,//传递参数(*) sidePagination: "server", //分页方式:client客户端分页,server服务端分页(*) pageNumber: 1, //初始化加载第一页,默认第一页 pageSize: 10, //每页的记录行数(*) pageList: [10, 15, 20, 50], //可供选择的每页的行数(*) search: true, //是否显示表格搜索,此搜索是客户端搜索,不会进服务端,所以,个人感觉意义不大 strictSearch: true, //严格搜索 showColumns: true, //是否显示所有的列 showRefresh: true, //是否显示刷新按钮 minimumCountColumns: 2, //最少允许的列数 clickToSelect: true, //是否启用点击选中行 //行高,如果没有设置height属性,表格自动根据记录条数觉得表格高度 uniqueId: "PurchasesID", //每一行的唯一标识,一般为主键列 showToggle: true, //是否显示详细视图和列表视图的切换按钮 cardView: false, //是否显示详细视图 detailView: false, //是否显示父子表 editable: true, columns: [{ checkbox: true //显示勾选框 }, { field: 'PurchasesID', //实际元素 title: '进货编号' //显示文本 }, { field: 'UserName', title: '进货经手人' }, { field: 'PurchasesTotal', title: '总价' }, { field: 'Reamrk', title: '备注' }, { field: 'PurchasesTime', title: '进货时间', formatter: formatDatebox }, { field: 'avs', title: '操作', formatter: formatDetail } ] }); }; //得到查询的参数 oTableInit.queryParams = function (params) { var temp = { //这里的键的名字和控制器的变量名必须一直,这边改动,控制器也需要改成一样的 limit: params.limit, //页面大小 offset: params.offset, //页码 AdminID: $("#AdminName").val(), StarTime:$("#StarTime").val(), EndTime:$("#EndTime").val() }; return temp; }; return oTableInit; }; var ButtonInit = function () { var oInit = new Object(); var postdata = {}; oInit.Init = function () { //点击编辑触发事件 $("#btn_edit").click(function () { $("#lbl_error").html(""); //获取当前选中行数据 var arrselections = $("#Purchases").bootstrapTable('getSelections'); if (arrselections.length > 1) { alert('只能选择一行进行编辑'); return; } if (arrselections.length <= 0) { alert('请选择有效数据'); return; } //模态框属性设置并显示 $("#myModalLabel").text("修改入库信息"); $("#txt_PurchasesTotal").val(arrselections[0].PurchasesTotal); $("#txt_Reamrk").val(arrselections[0].Reamrk); $("#txt_PurchasesID").val(arrselections[0].PurchasesID); $('#myModal').modal(); }); //点击删除触发事件 $("#btn_delete").click(function () { //获取当前选中行数据 var arrselections = $("#Purchases").bootstrapTable('getSelections'); var info = JSON.stringify(arrselections); var PurIDs = new Array(); if (arrselections.length <= 0) { alert("请至少选择一列!"); return; } else { //数组遍历选中项数据 $.each(eval(info), function (index, item) { PurIDs[index] = item.PurchasesID; }); } //友情提示,是否删除? confirm_ = confirm('你确定要进行删除吗?'); if (confirm_) { $.ajax({ type: "post", url: "/Purchases/Delete", data: { "PurIDs": PurIDs }, success: function (data) { if (data.state == "success") { window.alert(data.message); } else { window.alert("网络延迟,请稍后再试"); } }, error: function () { alert("操作失败,请稍后再试!"); }, complete: function () { $("#Purchases").bootstrapTable('refresh'); } }); } }); //对话框提交触发事件 $("#btn_submit").click(function () { $.lbl_error = { formMessage: function (msg) { $("#lbl_error").append(msg + "<br/>"); } } var data = $('#form').serialize(); //序列化获得表单数据, var submitData = decodeURIComponent(data, true); //submitData是解码后的表单数据,结果同上 if ($("#myModalLabel").text() == "添加会员信息") { } else { $.ajax({ type: 'post', url: "/Purchases/EditPurchases", data: submitData, beforeSend: function () { var state = true; $("#lbl_error").html(""); if (!IsMoney($("#txt_PurchasesTotal").val())) { $.lbl_error.formMessage("请填写正确的总价"); state = false; } return state; }, success: function (data) { if (data.state == "success") { window.alert(data.message); $('#myModal').modal('hide'); $("#Purchases").bootstrapTable('refresh'); } else { window.alert("网络延迟,请稍后再试"); } }, error: function () { window.alert("操作失败,请稍后再试!"); } }) } }); //查询触发事件 $("#btn_query").click(function () { $("#Purchases").bootstrapTable('refresh'); }); }; return oInit; };<file_sep>namespace Supermarket.EneityFramework { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("Product")] public partial class Product { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Product() { DetailePurchases = new HashSet<DetailePurchases>(); DetailOrder = new HashSet<DetailOrder>(); ReturnGoods = new HashSet<ReturnGoods>(); Stock = new HashSet<Stock>(); } public int ProductID { get; set; } [Required] [StringLength(50)] public string ProductName { get; set; } [Required] [StringLength(50)] public string BarCode { get; set; } [Required] [StringLength(100)] public string Manufacturer { get; set; } [StringLength(250)] public string CommodityDepict { get; set; } [Column(TypeName = "money")] public decimal CommodityPriceOut { get; set; } [Column(TypeName = "money")] public decimal CommodityPriceIn { get; set; } public int TypeID { get; set; } public int? UnitID { get; set; } public int? IsDelete { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<DetailePurchases> DetailePurchases { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<DetailOrder> DetailOrder { get; set; } public virtual Type Type { get; set; } public virtual Unit Unit { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<ReturnGoods> ReturnGoods { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Stock> Stock { get; set; } } } <file_sep>namespace Supermarket.EneityFramework { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("Card")] public partial class Card { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Card() { User = new HashSet<User>(); } public int CardID { get; set; } [Column(TypeName = "money")] public decimal TotalCost { get; set; } public int Score { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<User> User { get; set; } } } <file_sep>$(function () { //1.初始化Table var oTable = new TableInit(); oTable.Init(); var oTable = new NewTableInit(); oTable.Init(); GetSalesName(); $("#SalesName").change(function () { $("#Sales").bootstrapTable('refresh'); }) }); //获取销售员 function GetSalesName() { $("#SalesName").html("<option value='0'>全部</option>"); $.ajax({ type: 'post', url: "/Sales/GetSalesName", dataType: "json", success: function (data) { $.each(data, function (index, admin) { $("#SalesName").append("<option value=" + admin.AdminID + ">" + admin.UserName + "</option>"); }); }, error: function (XMLHttpRequest, textStatus, errorThrown) { window.alert("获取销售员失败!"); } }); } var DetailID = 0; function Detail(value) { $("#DetailModal").modal(); DetailID = $(value).parent().parent().find("td:eq(0)").text(); $("#Detail").bootstrapTable('refresh'); } var NewTableInit = function () { var oTableInit = new Object(); //初始化Table oTableInit.Init = function () { $('#Detail').bootstrapTable({ url: '/Sales/GetDetail', //请求后台的URL(*) method: 'get', //请求方式(*) cache: false, //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*) pagination: true, //是否显示分页(*) sortable: true, //是否启用排序 sortOrder: "asc", //排序方式 queryParams: oTableInit.queryParams,//传递参数(*) sidePagination: "server", //分页方式:client客户端分页,server服务端分页(*) pageNumber: 1, //初始化加载第一页,默认第一页 pageSize: 5, //每页的记录行数(*) pageList: [5,10, 15, 20, 50], //可供选择的每页的行数(*) showColumns: false, //是否显示所有的列 minimumCountColumns: 2, //最少允许的列数 clickToSelect: true, //是否启用点击选中行 //行高,如果没有设置height属性,表格自动根据记录条数觉得表格高度 uniqueId: "DetailOrderID", //每一行的唯一标识,一般为主键列 columns: [{ field: 'avc', title: '', formatter: function (value, row, index) { return index + 1; } }, { field: 'ProductName', title: '商品名称' }, { field: 'Amount', title: '数量' }, { field: 'subtotal', title: '小计' } ] }); }; //得到查询的参数 oTableInit.queryParams = function (params) { var temp = { //这里的键的名字和控制器的变量名必须一直,这边改动,控制器也需要改成一样的 limit: params.limit, //页面大小 offset: params.offset, //页码 DetailID: DetailID }; return temp; }; return oTableInit; }; var TableInit = function () { var oTableInit = new Object(); //初始化Table oTableInit.Init = function () { $('#Sales').bootstrapTable({ url: '/Sales/GetInfo', //请求后台的URL(*) method: 'get', //请求方式(*) toolbar: '#toolbar', //工具按钮用哪个容器 cache: false, //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*) pagination: true, //是否显示分页(*) sortable: true, //是否启用排序 sortOrder: "asc", //排序方式 queryParams: oTableInit.queryParams,//传递参数(*) sidePagination: "server", //分页方式:client客户端分页,server服务端分页(*) pageNumber: 1, //初始化加载第一页,默认第一页 pageSize: 10, //每页的记录行数(*) pageList: [10, 15, 20, 50], //可供选择的每页的行数(*) search: true, //是否显示表格搜索,此搜索是客户端搜索,不会进服务端,所以,个人感觉意义不大 strictSearch: true, //严格搜索 showColumns: true, //是否显示所有的列 showRefresh: true, //是否显示刷新按钮 minimumCountColumns: 2, //最少允许的列数 clickToSelect: true, //是否启用点击选中行 //行高,如果没有设置height属性,表格自动根据记录条数觉得表格高度 uniqueId: "OrderFormID", //每一行的唯一标识,一般为主键列 showToggle: true, //是否显示详细视图和列表视图的切换按钮 cardView: false, //是否显示详细视图 detailView: false, //是否显示父子表 editable: true, columns: [{ field: 'OrderFormID', //实际元素 title: '销售编号' //显示文本 }, { field: 'UserName', title: '顾客姓名' }, { field: 'SunPrice', title: '总价', }, { field: 'Way', title: '支付方式' }, { field: 'AdminName', title: '收银员' }, { field: 'CheckInTime', title: '销售时间', formatter: formatDatebox }, { field: 'abc', title: '操作', formatter: formatDetail }] }); }; //得到查询的参数 oTableInit.queryParams = function (params) { var temp = { //这里的键的名字和控制器的变量名必须一直,这边改动,控制器也需要改成一样的 limit: params.limit, //页面大小 offset: params.offset, //页码 SalesID: $("#SalesName").val() }; return temp; }; return oTableInit; };<file_sep>$(function () { //1.初始化Table var oTable = new TableInit(); oTable.Init(); GetProductType(); //2.初始化Button的点击事件 var oButtonInit = new ButtonInit(); oButtonInit.Init(); }); //获取商品类别信息 function GetProductType() { $("#ProductType").html("<option value='0'>请选择</option>"); $.ajax({ type: 'post', url: "/Product/GetProductType", dataType: "json", success: function (data) { $.each(data, function (index, type) { $("#ProductType").append("<option value=" + type.TypeID + ">" + type.TypeName + "</option>"); }); }, error: function (XMLHttpRequest, textStatus, errorThrown) { window.alert("获取商品类型失败!"); } }); } //商品上下架的方法 function IsActivate(value) { var state = 0; var text = $(value).text(); if ( text== " 下架") { state = 1; } var ProductID = $(value).parent().parent().find("td:eq(1)").text(); if (confirm("确定要" + text + "商品吗?")) { $.ajax({ type: 'post', url: '/Product/IsActivate', data: { "ProductID": ProductID, "state": state }, dataType: 'json', success: function (data) { if (data.state = "success") { window.alert(text + data.message); $("#Product").bootstrapTable('refresh'); } }, error: function () { window.alert("操作失败,请稍后再试!"); $("#Product").bootstrapTable('refresh'); } }); } } var TableInit = function () { var oTableInit = new Object(); //初始化Table oTableInit.Init = function () { $('#Product').bootstrapTable({ url: '/Product/GetInfo', //请求后台的URL(*) method: 'get', //请求方式(*) toolbar: '#toolbar', //工具按钮用哪个容器 cache: false, //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*) pagination: true, //是否显示分页(*) sortable: true, //是否启用排序 sortOrder: "asc", //排序方式 queryParams: oTableInit.queryParams,//传递参数(*) sidePagination: "server", //分页方式:client客户端分页,server服务端分页(*) pageNumber: 1, //初始化加载第一页,默认第一页 pageSize: 10, //每页的记录行数(*) pageList: [10, 15, 20, 50], //可供选择的每页的行数(*) search: true, //是否显示表格搜索,此搜索是客户端搜索,不会进服务端,所以,个人感觉意义不大 strictSearch: true, //严格搜索 showColumns: true, //是否显示所有的列 showRefresh: true, //是否显示刷新按钮 minimumCountColumns: 2, //最少允许的列数 clickToSelect: true, //是否启用点击选中行 //行高,如果没有设置height属性,表格自动根据记录条数觉得表格高度 uniqueId: "ProductID", //每一行的唯一标识,一般为主键列 showToggle: true, //是否显示详细视图和列表视图的切换按钮 cardView: false, //是否显示详细视图 detailView: false, //是否显示父子表 editable: true, columns: [{ checkbox: true //显示勾选框 }, { field: 'ProductID', //实际元素 title: '商品编号' //显示文本 }, { field: 'ProductName', title: '商品名称' }, { field: 'CommodityPriceIn', title: '进货价' }, { field: 'CommodityPriceOut', title: '出售价' }, { field: 'TypeName', title: '商品类别', }, { field: 'UnitName', title: '单位' }, { field: 'Manufacturer', title: '生产厂家' }, { field: 'CommodityDepict', title: '商品描述', formatter: function (value, row, index) { return value.length > 25 ? value.substring(0, 25) + "..." : value; } }, { field: 'IsDelete', title: '操作', formatter: formatProductIsDelete } ], onCheck: function (item, element) { if (item.IsDelete==1) { $(".ProductIn").css("display", "block"); $(".ProductOut").css("display", "none"); } else { $(".ProductIn").css("display", "none"); $(".ProductOut").css("display", "block"); } } }); }; //得到查询的参数 oTableInit.queryParams = function (params) { var temp = { //这里的键的名字和控制器的变量名必须一直,这边改动,控制器也需要改成一样的 limit: params.limit, //页面大小 offset: params.offset, //页码 ProductName: $("#searchProductNmae").val(), type: $("#ProductType").val(), IsDel: $("input[name='IsDelete']:checked").val() }; return temp; }; return oTableInit; }; var ButtonInit = function () { var oInit = new Object(); var postdata = {}; oInit.Init = function () { //点击编辑触发事件 $("#btn_edit").click(function () { $("#lbl_error").html(""); //获取当前选中行数据 var arrselections = $("#Product").bootstrapTable('getSelections'); if (arrselections.length > 1) { alert('只能选择一行进行编辑'); return; } if (arrselections.length <= 0) { alert('请选择有效数据'); return; } //模态框属性设置并显示 $("#myModalLabel").text("编辑商品信息"); if (arrselections[0].IsDelete == 0) { $("#rb_IsDel0").attr("checked", "checked"); } else { $("#rb_IsDel1").attr("checked", "checked"); } $("#txt_ProductName").val(arrselections[0].ProductName); $("#txt_CommodityPriceOut").val(arrselections[0].CommodityPriceOut); $("#txt_CommodityDepict").val(arrselections[0].CommodityDepict); $("#txt_ProductID").val(arrselections[0].ProductID); $('#myModal').modal(); }); $(".ProductOut").bind('click',InActivate); $(".ProductIn").bind('click',InActivate); //商品批量上下架 function InActivate() { //获取当前选中行数据 var arrselections = $("#Product").bootstrapTable('getSelections'); var info = JSON.stringify(arrselections); var ProductIDs = new Array(); var state = eval(info)[0].IsDelete; for (var i = 0; i < eval(info).length; i++) { if (eval(info)[i].IsDelete != state) { window.alert("请选择同一状态的商品!"); return; } } if (arrselections.length <= 0) { alert("请至少选择一列!"); return; } else { //数组遍历选中项数据 $.each(eval(info), function (index, item) { ProductIDs[index] = item.ProductID; }); } //友情提示,是否操作? confirm_ = confirm('确定要进行' + (state == 0 ? "下架" : "上架") + '操作吗?'); if (confirm_) { $.ajax({ type: "post", url: "/Product/InActivate", data: { "ProductIDs": ProductIDs,"state":state==1?0:1 }, success: function (data) { if (data.state == "success") { window.alert(data.message); } }, error: function () { window.alert("操作失败,请稍后再试!"); }, complete: function () { $("#Product").bootstrapTable('refresh'); } }); } }; //对话框提交触发事件 $("#btn_submit").click(function () { $.lbl_error = { formMessage: function (msg) { $("#lbl_error").append(msg + "<br/>"); } } var data = $('#form').serialize(); //序列化获得表单数据, var submitData = decodeURIComponent(data, true); $.ajax({ type: 'post', url: "/Product/Edit", data: submitData, beforeSend: function () { var state = true; $("#lbl_error").html(""); if (!IsMoney($("#txt_CommodityPriceOut").val())) { $.lbl_error.formMessage("请填写正确的出售价"); state = false; } return state; }, success: function (data) { if (data.state == "success") { window.alert(data.message); $('#myModal').modal('hide'); $("#Product").bootstrapTable('refresh'); } }, error: function () { window.alert("操作失败,请稍后再试!"); } }) }); //查询触发事件 $("#btn_query").click(function () { $("#Product").bootstrapTable('refresh'); }); }; return oInit; };<file_sep>namespace Supermarket.EneityFramework { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("DetailOrder")] public partial class DetailOrder { public int DetailOrderID { get; set; } public int ProductID { get; set; } public int OrderFormID { get; set; } public decimal Amount { get; set; } [Column(TypeName = "money")] public decimal subtotal { get; set; } public virtual Orders Orders { get; set; } public virtual Product Product { get; set; } } } <file_sep>namespace Supermarket.EneityFramework { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("SysLog")] public partial class SysLog { [Key] public int LogID { get; set; } [StringLength(500)] public string Behavior { get; set; } public int? FK_TypeID { get; set; } public int? FK_AdminID { get; set; } public string Parameters { get; set; } [StringLength(20)] public string IP { get; set; } public DateTime? CheckInTime { get; set; } public string Exception { get; set; } public byte? IsException { get; set; } public virtual AdminInfo AdminInfo { get; set; } public virtual LogDic LogDic { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Supermarket.Code; using Supermarket.EneityFramework; namespace Supermarket.Web.Controllers { public class SalesController : Controller { SupermarketDB db = new SupermarketDB(); public ActionResult Index() { return View(); } /// <summary> /// 获取需要的销售信息 /// </summary> /// <param name="limit">页面大小</param> /// <param name="offset">页码</param> /// <returns></returns> public ActionResult GetInfo(int limit, int offset) { try { int SalesID = Convert.ToInt32(Request["SalesID"]); var result = from sales in db.Orders where ((SalesID == 0) || (sales.AdminID == SalesID)) select new { sales.OrderFormID, sales.User.UserName, sales.SunPrice, sales.Way, sales.CheckInTime, AdminName = sales.AdminInfo.UserName }; var rows = result.OrderBy(p => p.OrderFormID).Skip(offset).Take(limit).ToList(); return Json(new { total = result.Count(), rows = rows }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { return Json(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }, JsonRequestBehavior.AllowGet); } } /// <summary> /// 销售详情 /// </summary> /// <returns></returns> public ActionResult GetDetail(int limit, int offset) { try { int DetailtID = Convert.ToInt32(Request["DetailID"]); var result = from detail in db.DetailOrder where ((DetailtID == 0) || (detail.OrderFormID == DetailtID)) select new { detail.DetailOrderID, detail.Product.ProductName, detail.Amount, detail.subtotal }; var rows = result.OrderBy(p => p.DetailOrderID).Skip(offset).Take(limit).ToList(); return Json(new { total = result.Count(), rows = rows }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { return Json(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }, JsonRequestBehavior.AllowGet); } } /// <summary> /// 获取销售员 /// </summary> /// <returns></returns> [HttpPost] public ActionResult GetSalesName() { try { var result = from admin in db.AdminInfo where admin.RoleID == 2 select new { admin.AdminID, admin.UserName }; return Json(result, JsonRequestBehavior.AllowGet); } catch (Exception ex) { return Json(new AjaxResult { state = ResultType.error, message = ex.Message }, JsonRequestBehavior.AllowGet); } } } }
6f8f91ef52e9d669dbb5a6983afbdfbb9c0c5ce9
[ "JavaScript", "C#" ]
29
C#
Meng1231/supmarket
b32585424a3a4d2a7cb245ec0c2ee4d0b760efbe
e994067685a87b14fcd20ead9439c234e7fe0777
refs/heads/master
<repo_name>digideskio/js-data<file_sep>/test/integration/datastore.test.js import { assert, JSData } from '../_setup' describe('DataStore integration tests', function () { it('relation links should stay up-to-date', function () { const store = new JSData.DataStore() store.defineMapper('foo', { schema: { properties: { id: { type: 'number' } } }, relations: { hasMany: { bar: { localField: 'bars', foreignKey: 'foo_id' } } } }) store.defineMapper('bar', { schema: { properties: { id: { type: 'number' }, foo_id: { type: 'number' } } }, relations: { belongsTo: { foo: { localField: 'foo', foreignKey: 'foo_id' } } } }) const foo66 = store.add('foo', { id: 66 }) const foo77 = store.add('foo', { id: 77 }) const bar88 = store.add('bar', { id: 88, foo_id: 66 }) assert.strictEqual(bar88.foo, foo66) assert.strictEqual(foo66.bars[0], bar88) assert.deepEqual(foo77.bars, []) assert.equal(bar88.foo_id, 66) bar88.foo_id = 77 assert.strictEqual(bar88.foo, foo77) assert.equal(bar88.foo_id, 77) assert.strictEqual(foo77.bars[0], bar88) assert.deepEqual(foo66.bars, []) bar88.foo = foo66 assert.strictEqual(bar88.foo, foo66) assert.equal(bar88.foo_id, 66) assert.strictEqual(foo66.bars[0], bar88) assert.deepEqual(foo77.bars, []) foo77.bars = [bar88] assert.strictEqual(foo77.bars[0], bar88) assert.equal(bar88.foo_id, 77) assert.deepEqual(foo66.bars, []) foo66.bars = [bar88] assert.strictEqual(foo66.bars[0], bar88) assert.equal(bar88.foo_id, 66) assert.deepEqual(foo77.bars, []) }) it('should allow enhanced relation getters', function () { let wasItActivated = false const store = new JSData.DataStore({ linkRelations: true }) store.defineMapper('foo', { relations: { belongsTo: { bar: { localField: 'bar', foreignKey: 'barId', get (def, foo, orig) { // "relation.name" has relationship "relation.type" to "relation.relation" wasItActivated = true return orig() } } } } }) store.defineMapper('bar', { relations: { hasMany: { foo: { localField: 'foos', foreignKey: 'barId' } } } }) const foo = store.add('foo', { id: 1, barId: 1, bar: { id: 1 } }) assert.equal(foo.bar.id, 1) assert(wasItActivated) }) it('should configure enumerability and linking of relations', function () { const store = new JSData.DataStore() store.defineMapper('parent', { relations: { hasMany: { child: { localField: 'children', foreignKey: 'parentId' }, otherChild: { localField: 'otherChildren', foreignKey: 'parentId' } } } }) store.defineMapper('child', { relations: { belongsTo: { parent: { localField: 'parent', foreignKey: 'parentId' } } } }) store.defineMapper('otherChild', { relations: { belongsTo: { parent: { enumerable: true, localField: 'parent', foreignKey: 'parentId' } } } }) const child = store.add('child', { id: 1, parent: { id: 2 } }) const otherChild = store.add('otherChild', { id: 3, parent: { id: 4 } }) assert(store.get('child', child.id)) assert.equal(child.parentId, 2) assert(child.parent === store.get('parent', child.parentId)) assert(store.get('otherChild', otherChild.id)) assert.equal(otherChild.parentId, 4) assert(otherChild.parent === store.get('parent', otherChild.parentId), 'parent was injected and linked') assert(store.get('parent', otherChild.parentId), 'parent was injected and linked') let foundParent = false let k for (k in child) { if (k === 'parent' && child[k] === child.parent && child[k] === store.get('parent', child.parentId)) { foundParent = true } } assert(!foundParent, 'parent is NOT enumerable') foundParent = false for (k in otherChild) { if (k === 'parent' && otherChild[k] === otherChild.parent && otherChild[k] === store.get('parent', otherChild.parentId)) { foundParent = true } } assert(foundParent, 'parent is enumerable') }) it.skip('should unlink upon ejection', function () { this.UserCollection.add(this.data.user10) this.OrganizationCollection.add(this.data.organization15) this.CommentCollection.add(this.data.comment19) this.ProfileCollection.add(this.data.profile21) // user10 relations assert(Array.isArray(this.UserCollection.get(10).comments)) this.CommentCollection.remove(11) assert(!this.CommentCollection.get(11)) assert.equal(this.UserCollection.get(10).comments.length, 2) this.CommentCollection.remove(12) assert(!this.CommentCollection.get(12)) assert.equal(this.UserCollection.get(10).comments.length, 1) this.CommentCollection.remove(13) assert(!this.CommentCollection.get(13)) assert.equal(this.UserCollection.get(10).comments.length, 0) this.OrganizationCollection.remove(14) assert(!this.OrganizationCollection.get(14)) assert(!this.UserCollection.get(10).organization) // organization15 relations assert(Array.isArray(this.OrganizationCollection.get(15).users)) this.UserCollection.remove(16) assert(!this.UserCollection.get(16)) assert.equal(this.OrganizationCollection.get(15).users.length, 2) this.UserCollection.remove(17) assert(!this.UserCollection.get(17)) assert.equal(this.OrganizationCollection.get(15).users.length, 1) this.UserCollection.remove(18) assert(!this.UserCollection.get(18)) assert.equal(this.OrganizationCollection.get(15).users.length, 0) // comment19 relations assert.deepEqual(this.UserCollection.get(20), this.CommentCollection.get(19).user) assert.deepEqual(this.UserCollection.get(19), this.CommentCollection.get(19).approvedByUser) this.UserCollection.remove(20) assert(!this.CommentCollection.get(19).user) this.UserCollection.remove(19) assert(!this.CommentCollection.get(19).approvedByUser) // profile21 relations assert.deepEqual(this.UserCollection.get(22), this.ProfileCollection.get(21).user) this.UserCollection.remove(22) assert(!this.ProfileCollection.get(21).user) }) it('should emit change events', function (done) { const store = new JSData.DataStore() let handlersCalled = 0 store.defineMapper('foo', { type: 'object', schema: { properties: { bar: { type: 'string', track: true } } } }) const foo = store.add('foo', { id: 1 }) assert.equal(foo.bar, undefined) setTimeout(() => { if (handlersCalled !== 6) { done('not all handlers were called') } else { done() } }, 1000) store.on('change', function (mapperName, record, changes) { assert.equal(mapperName, 'foo') assert.strictEqual(record, foo) assert.deepEqual(changes, { added: { bar: 'baz' }, changed: {}, removed: {} }) handlersCalled++ }) store.getCollection('foo').on('change', function (record, changes) { assert.strictEqual(record, foo) assert.deepEqual(changes, { added: { bar: 'baz' }, changed: {}, removed: {} }) handlersCalled++ }) foo.on('change', (record, changes) => { assert.strictEqual(record, foo) assert.deepEqual(changes, { added: { bar: 'baz' }, changed: {}, removed: {} }) handlersCalled++ }) store.on('change:bar', function (mapperName, record, value) { assert.equal(mapperName, 'foo') assert.strictEqual(record, foo) assert.equal(value, 'baz') handlersCalled++ }) store.getCollection('foo').on('change:bar', function (record, value) { assert.strictEqual(record, foo) assert.equal(value, 'baz') handlersCalled++ }) foo.on('change:bar', (record, value) => { assert.strictEqual(record, foo) assert.equal(value, 'baz') handlersCalled++ }) foo.bar = 'baz' }) }) <file_sep>/test/unit/collection/remove.test.js import { assert, JSData } from '../../_setup' describe('Collection#remove', function () { it('should remove an item from the collection', function () { this.UserCollection.createIndex('age') const user = this.UserCollection.add({ id: 1, age: 30 }) const user2 = this.UserCollection.add({ id: 2, age: 31 }) const user3 = this.UserCollection.add({ id: 3, age: 32 }) const users = [user, user2, user3] assert(this.UserCollection.get(1) === user, 'user 1 is in the store') assert(this.UserCollection.get(2) === user2, 'user 2 is in the store') assert(this.UserCollection.get(3) === user3, 'user 3 is in the store') assert.deepEqual(this.UserCollection.between([30], [32], { rightInclusive: true, index: 'age' }), users, 'users can be selected by age index') this.UserCollection.remove(1) assert(!this.UserCollection.get(1), 'user 1 is no longer in the store') users.shift() assert.deepEqual(this.UserCollection.between([30], [32], { rightInclusive: true, index: 'age' }), users, 'user 1 cannot be retrieved by index') }) it('should remove plain records', function () { const data = [ { id: 1, getId () { return this.id } }, { id: 2, getId () { return this.id } } ] const collection = new JSData.Collection(data) const item = collection.get(1) const removed = collection.remove(1) assert.equal(item === removed, true) }) }) <file_sep>/test/unit/schema/typeGroupValidators/index.test.js import { assert, JSData } from '../../../_setup' describe('Schema.typeGroupValidators', function () { it('has the right default validators', function () { const typeGroupValidators = JSData.Schema.typeGroupValidators const EXPECTED_KEYS = [ 'array', 'integer', 'number', 'numeric', 'object', 'string' ] assert.deepEqual( Object.keys(typeGroupValidators), EXPECTED_KEYS, 'has the expected keys' ) }) })
a15b962ea4553a3b55be16a71589e3c617557220
[ "JavaScript" ]
3
JavaScript
digideskio/js-data
135651e4a8edc62793050fce300cb64a4058a8da
3c32b4b730a47fe98be122189f0748975f78e5f7
refs/heads/master
<file_sep>//MUSIC var audio = new Audio('music/The_End_Is_Near.mp3'); audio.play(); //GAMEPLAY var circleFill = $('.circle-fill'); var circleHole = $('.circle-hole'); var t = 0; var isRotate = false; var life = 10; var score = 0; var newLeft; var newTop; var speed = 31; function calcRotate(){ t += 0.05; var r = 125; var xcenter = 95; var ycenter = 95; newLeft = Math.floor(xcenter + (r * Math.cos(t))); newTop = Math.floor(ycenter + (r * Math.sin(t))); } function setInitialPosition(){ calcRotate(); circleFill.offset({top: newTop, left: newLeft}); } function moveCircle() { calcRotate(); circleFill.animate({ top: newTop, left: newLeft, }, speed, function() { moveCircle(); }); } function isCenter(){ var positionFill = getPosition(circleFill); var positionHole = getPosition(circleHole); var isTopFill = positionFill.top; var isLeftFill = positionFill.left; var isTopHole = positionHole.top + 5; var isLeftHole = positionHole.left + 5; if ( ((isTopFill >= isTopHole - 5 && isTopFill <= isTopHole + 5)) && ((isLeftFill >= isLeftHole - 5) && (isLeftFill <= isLeftHole + 5)) ) { return true; } return false; } function getPosition(circle){ return circle.offset(); } //MAIN $(document).ready(function() { setInitialPosition(); //posizione iniziale circleFill $('#life').append(life); //vita inziale $('#score').append(score); //score iniziale //CLICK PLAY $('.app').on('tap', '.play-button', function(){ event.preventDefault(); $(this).css('visibility', 'hidden'); //nascondo bottone play $(circleFill).css('display', 'block'); //appare circleFill isRotate = true; moveCircle(); }); //CLICK CENTRO $('.circle-container').on('tap', function(){ event.preventDefault(); if(speed > 1){ if (isRotate){ //se ho gia cliccato play if (life > 0){ //se ho vite if (isCenter()){ //se ho fatto centro $('.result-container h1').empty(); $('.result-container h1').html('SUCCESS'); $('.result-container').animate({ opacity: 1 }, 500, function(){ $(this).animate({ opacity: 0 }, 500); } ); //aggiungo una vita life += 1; $('#life').empty(); $('#life').append(life); //aumento il punteggio score += 1; $('#score').empty(); $('#score').append(score); //aumento velocita speed -= 10; } else{ //se non ho fatto centro $('.result-container h1').empty(); $('.result-container h1').html('RETRY'); $('.result-container').animate({ opacity: 1 }, 500, function(){ $(this).animate({ opacity: 0 }, 500); } ); //tolgo una vita life -= 1; $('#life').empty(); $('#life').append(life); } } else{ //se non ho piu vite //TODO } } } else{ //se speed è 1 } }); $('.life-button').on('tap', function(){ life = 10; $('#life').empty(); $('#life').append(life); }); });
fb7c5a9c571875aa754b4bd9ae729540f3358a78
[ "JavaScript" ]
1
JavaScript
devmanuelragusa/Center
b1832ac0f851b82f286030204cb52910a72b976e
4f77843792999484f2538973ac77be4a7b238db3
refs/heads/master
<repo_name>danben2904/findmamik<file_sep>/main/views.py from django.shortcuts import get_object_or_404, render, redirect from django.http import HttpResponse from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.contrib.auth.models import User, Group from django.contrib.auth.decorators import login_required from .forms import CreateUserForm, SeekerForm, MamikForm, ChildForm from .decorators import unauthenticated_user from .models import Seeker from random import uniform @login_required(login_url="main:login") def home(request): context = {} return render(request, "main/home.html", context) @unauthenticated_user def registerPage(request): form = CreateUserForm() if request.method == "POST": form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() Seeker.objects.create(user=user, email=user.email) return redirect("main:login") context = {"form":form} return render(request, "main/register.html", context) @unauthenticated_user def loginPage(request): if request.method == "POST": username = request.POST.get("username") password = request.POST.get("<PASSWORD>") user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect("main:home") else: messages.info(request, "username or passoword in incorrect") context = {} return render(request, "main/login.html", context) def logoutUser(request): logout(request) return redirect("main:login") def userPage(request, username): user = get_object_or_404(User, username=username) context = {"user" : user} return render(request, "main/user.html", context) @login_required(login_url="main:login") def accountSettings(request): seeker = request.user.seeker form = SeekerForm(instance=seeker) if request.method == "POST": form = SeekerForm(request.POST, request.FILES, instance=seeker) if form.is_valid(): form.save() context = {"form" : form} return render(request, "main/account_settings.html", context) def get_mamiks(min_age, max_age, min_salary): return User.objects.filter( seeker__is_mamik=True ).filter( seeker__is_free=True ).exclude( seeker__age__lt=min_age ).exclude( seeker__age__gt=max_age ).exclude( seeker__salary__lt=min_salary ) def get_children(min_age, max_age): return User.objects.filter( seeker__is_mamik=False ).filter( seeker__is_free=True ).exclude( seeker__age__lt=min_age ).exclude( seeker__age__gt=max_age ) @login_required(login_url="main:login") def find(request): results = [] data = [] if request.user.seeker.is_mamik: form = ChildForm() if request.method == 'POST': form = ChildForm(request.POST) if form.is_valid(): min_age = form.cleaned_data['min_age'] max_age = form.cleaned_data['max_age'] data = get_children(min_age, max_age) else: form = MamikForm() if request.method == 'POST': form = MamikForm(request.POST) if form.is_valid(): min_age = form.cleaned_data['min_age'] max_age = form.cleaned_data['max_age'] min_salary = form.cleaned_data['min_salary'] data = get_mamiks(min_age, max_age, min_salary) array = [] for user in data: array.append(user) user_number = len(array) for i in range(user_number): for j in range(user_number - i - 1): if array[j].seeker.loyalty_points > array[j + 1].seeker.loyalty_points: if uniform(0, 1) < 9e-1: array[j], array[j + 1] = array[j + 1], array[j] array.reverse() array = array[:20] context = {"form" : form, "data" : array} return render(request, "main/find.html", context) <file_sep>/main/migrations/0008_remove_seeker_img_num.py # Generated by Django 3.1.6 on 2021-06-02 22:38 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main', '0007_auto_20210602_1457'), ] operations = [ migrations.RemoveField( model_name='seeker', name='img_num', ), ] <file_sep>/main/migrations/0010_auto_20210602_1546.py # Generated by Django 3.1.6 on 2021-06-02 22:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0009_seeker_email'), ] operations = [ migrations.AlterField( model_name='seeker', name='country', field=models.CharField(default='None', max_length=4), ), ] <file_sep>/main/admin.py from django.contrib import admin from .models import Seeker admin.site.register(Seeker) <file_sep>/main/migrations/0009_seeker_email.py # Generated by Django 3.1.6 on 2021-06-02 22:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0008_remove_seeker_img_num'), ] operations = [ migrations.AddField( model_name='seeker', name='email', field=models.CharField(default='None', max_length=100), ), ] <file_sep>/main/migrations/0012_auto_20210602_1557.py # Generated by Django 3.1.6 on 2021-06-02 22:57 from django.db import migrations, models import main.models class Migration(migrations.Migration): dependencies = [ ('main', '0011_remove_seeker_email'), ] operations = [ migrations.AddField( model_name='seeker', name='email', field=models.CharField(default='', max_length=100), ), migrations.AlterField( model_name='seeker', name='profile_pic', field=models.ImageField(default='olikpipi.png', upload_to=main.models.image_directory_path), ), ] <file_sep>/main/migrations/0001_initial.py # Generated by Django 3.1.6 on 2021-05-17 07:49 from django.db import migrations, models import django.db.models.deletion import main.models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('is_mamik', models.BooleanField(default=False)), ('is_free', models.BooleanField(default=True)), ('age', models.IntegerField(default=-1)), ('salary', models.IntegerField(default=0)), ('country', models.CharField(max_length=3)), ('loyalty_points', models.IntegerField(default=0)), ('img_num', models.IntegerField(default=0)), ], ), migrations.CreateModel( name='Photo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('image', models.ImageField(upload_to=main.models.image_directory_path)), ('is_pfp', models.BooleanField(default=False)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='main.user')), ], ), ] <file_sep>/main/migrations/0007_auto_20210602_1457.py # Generated by Django 3.1.6 on 2021-06-02 21:57 from django.db import migrations, models import main.models class Migration(migrations.Migration): dependencies = [ ('main', '0006_auto_20210602_1348'), ] operations = [ migrations.AddField( model_name='seeker', name='profile_pic', field=models.ImageField(null=True, upload_to=main.models.image_directory_path), ), migrations.DeleteModel( name='Photo', ), ] <file_sep>/main/migrations/0003_auto_20210602_0220.py # Generated by Django 3.1.6 on 2021-06-02 09:20 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('main', '0002_user_name'), ] operations = [ migrations.CreateModel( name='Seeker', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(default='None', max_length=100)), ('email', models.CharField(default='None', max_length=100)), ('phone', models.CharField(default='None', max_length=100)), ('is_mamik', models.BooleanField(default=False)), ('is_free', models.BooleanField(default=True)), ('age', models.IntegerField(default=-1)), ('salary', models.IntegerField(default=0)), ('country', models.CharField(max_length=3)), ('loyalty_points', models.IntegerField(default=0)), ('img_num', models.IntegerField(default=0)), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.AlterField( model_name='photo', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='main.seeker'), ), migrations.DeleteModel( name='User', ), ] <file_sep>/main/models.py from django.db import models from django.contrib.auth.models import User def image_directory_path(instance, filename): return '{0}/{1}'.format(instance.user.id, filename) class Seeker(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=100, default='None') second_name = models.CharField(max_length=100, default='None') email = models.CharField(max_length=100) is_mamik = models.BooleanField(default=False) is_free = models.BooleanField(default=True) age = models.IntegerField(default=-1) salary = models.IntegerField(default=0) country = models.CharField(max_length=4, default='None') loyalty_points = models.IntegerField(default=0) profile_pic = models.ImageField(upload_to=image_directory_path, default="olikpipi.png") def __str__(self): return self.user.username <file_sep>/main/urls.py from django.urls import path, reverse_lazy from django.conf.urls import url from django.contrib.auth import views as auth_views from . import views app_name = 'main' urlpatterns = [ path('', views.home, name='home'), path('register', views.registerPage, name='register'), path('login', views.loginPage, name='login'), path('logout', views.logoutUser, name='logout'), path('user/<str:username>', views.userPage, name='user'), path('account', views.accountSettings, name='account'), path('find', views.find, name='find'), ] <file_sep>/main/forms.py from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from .models import Seeker class CreateUserForm(UserCreationForm): class Meta: model = User fields = ["username", "email", "<PASSWORD>", "<PASSWORD>"] class SeekerForm(ModelForm): class Meta: model = Seeker fields = "__all__" exclude = ["user", "loyalty_points"] class MamikForm(forms.Form): min_age = forms.IntegerField(label='Min age') max_age = forms.IntegerField(label='Max age') min_salary = forms.IntegerField(label='Min salary') class ChildForm(forms.Form): min_age = forms.IntegerField(label='Min age') max_age = forms.IntegerField(label='Max age')
28ed5b814f49e431dc2d10b485b79d7424b94667
[ "Python" ]
12
Python
danben2904/findmamik
be7d99c0335780b321975a4a5b96971fc038f1d4
3ed89c0d06cfbfc31999de0ca6f612055b16e600
refs/heads/master
<file_sep>'use strict'; const config = require('./configuration'); const Response = require('./response'); module.exports = function signout (req, res) { req[config.session.name].reset(); Response.ok(res); }; <file_sep>'use strict'; const config = require('./configuration'); const Gstore = require('gstore-node'); const datastore = require('@google-cloud/datastore')({ namespace: config.datastore.namespace }); Gstore.connect(datastore); const Schema = Gstore.Schema; const schema = new Schema(config.schema); // Queries schema.queries('list', { limit: 20, select: [config.fields.primary] }); const User = Gstore.model(config.datastore.kind, schema); module.exports = User; <file_sep>'use strict'; const app = require('../support/test-app'); const expect = require('chai').expect; describe('middleware', function () { it('returns 404 on PUT without ID', function (done) { app.put('/users').end(function (err, res) { expect(res.body.code).to.equal('NOT_FOUND'); done(); }); }); it('returns 404 on PUT without ID and trailing slashes', function (done) { app.put('/users/').end(function (err, res) { expect(res.body.code).to.equal('NOT_FOUND'); app.put('/users///').end(function (err, res) { expect(res.body.code).to.equal('NOT_FOUND'); done(); }); }); }); it('returns 404 on DELETE without ID', function (done) { app.del('/users').end(function (err, res) { expect(res.body.code).to.equal('NOT_FOUND'); done(); }); }); it('returns 404 on DELETE without ID and trailing slashes', function (done) { app.del('/users/').end(function (err, res) { expect(res.body.code).to.equal('NOT_FOUND'); app.del('/users///').end(function (err, res) { expect(res.body.code).to.equal('NOT_FOUND'); done(); }); }); }); }); <file_sep>'use strict'; const Response = require('./response'); const User = require('./user'); module.exports = function list (req, res) { let options = {}; let start = req.query.start; if (start) { options.start = start; } let limit = +(req.query.limit || 20); if (limit > 20 || limit < 1) { limit = 20; } options.limit = limit; User.list(options, (err, response) => { /* istanbul ignore if */ if (err) { console.error('List Error:', err); Response.internalError(res); return; } Response.ok(res, { items: response.entities, next: response.nextPageCursor, limit: limit }); }); }; <file_sep>'use strict'; const app = require('../support/test-app'); const User = require('../lib/user'); const password = require('../lib/password'); // Using underscore naming conventions here // just so they're more readable in tests. module.exports = { create_entity, create_many_users, create_user_and_sign_in, delete_all_users, delete_all_users_and_sign_out, sign_in, sign_in_as_admin, sign_out, sign_out_and_delete_user }; function create_entity (body, done) { password(body, (err, data) => { let entity = new User(data); entity.save((err, entity) => { if (err) return done(err); done(null, entity.plain()); }); }); } function create_many_users (quantity, done) { var i, data, remaining = quantity; for (i = 0; i < quantity; ++i) { data = {username: `user${i}`, email: `<EMAIL>`, password: '<PASSWORD>'}; create_entity(data, (err, entity) => { remaining--; if (remaining === 0) { done(); } }); } } function create_user_and_sign_in (data, done) { create_entity(data, (err, entity) => { if (err) return done(err); sign_in(data.email, data.password, done); }); } function delete_all_users (done) { User.deleteAll(done); } function delete_all_users_and_sign_out (done) { delete_all_users((err) => { if (err) return done(err); sign_out(done); }); } function sign_in (email, password, done) { app.post('/users/signin').send({email, password}).end((err, res) => { done(err, res.body.user); }); } function sign_in_as_admin (done) { let body = {email: '<EMAIL>', password: '<PASSWORD>', role: 'admin'}; create_user_and_sign_in(body, done); } function sign_out (done) { app.post('/users/signout').end(done); } function sign_out_and_delete_user (userId, done) { sign_out((err) => { if (err) return done(err); User.delete(userId, done); }) } <file_sep>'use strict'; const config = require('./configuration'); const sessions = require('client-sessions'); const session = sessions({ cookieName: config.session.name, secret: config.session.secret, duration: config.session.duration, activeDuration: config.session.activeDuration }); module.exports = function _session (req, res, next) { session(req, res, () => { next(req, res); }); }; <file_sep>'use strict'; const password = require('./password'); const Response = require('./response'); const User = require('./user'); module.exports = function create (req, res) { delete req.body.id; password(req.body, (err, data) => { // TODO: move this to model? see Gstore Schema docs if (err) { return Response.badRequest(res, err); } _create(req, res, data); }); }; function _create (req, res, data) { let user = new User(User.sanitize(data)); user.save((err, entity) => { if (err) { return Response.badRequest(res, err); } Response.ok(res, {user: entity.plain()}); }); } <file_sep>'use strict'; const app = require('../support/test-app'); const expect = require('chai').expect; const helpers = require('../support/test-helpers'); const User = require('../lib/user'); describe('signin', function () { let user; before(function (done) { let data = {email: '<EMAIL>', password: '<PASSWORD>'}; helpers.create_entity(data, (err, entity) => { user = entity; done(err); }); }); after(function (done) { helpers.delete_all_users_and_sign_out(done); }); it('fails with blank email', function (done) { let data = {password: '<PASSWORD>', email: ''}; app.post('/users/signin').send(data).end(function (err, res) { expect(res.body.reason).to.equal('PRIMARY_FIELD_REQUIRED'); expect(res.body.code).to.equal('BAD_REQUEST'); done(); }); }); it('fails with blank password', function (done) { let data = {email: '<EMAIL>', password: ''}; app.post('/users/signin').send(data).end(function (err, res) { expect(res.body.reason).to.equal('PASSWORD_REQUIRED'); expect(res.body.code).to.equal('BAD_REQUEST'); done(); }); }); it('fails with wrong password', function (done) { let data = {email: '<EMAIL>', password: '<PASSWORD>'}; app.post('/users/signin').send(data).end(function (err, res) { expect(res.body.reason).to.equal('WRONG_PASSWORD'); expect(res.body.code).to.equal('BAD_REQUEST'); done(); }); }); it('signs user in with correct credentials', function (done) { let data = {password: '<PASSWORD>', email: '<EMAIL>'}; app.post('/users/signin').send(data).end(function (err, res) { expect(res.body.code).to.equal('OK'); expect(res).to.have.cookie('userSession'); expect(res.body.user.email).to.equal('<EMAIL>'); expect(res.statusCode).to.equal(200); expect(res.body.user.id).to.exist; expect(res.body.user.password).to.not.exist; expect(res.body.user.confirmationToken).to.not.exist; // Session test app.get(`/users/${res.body.user.id}`).end((err, res) => { expect(res.body.code).to.equal('OK'); done(); }); }); }); }); <file_sep># google-function-authorizer [![Build Status](https://semaphoreci.com/api/v1/pauloddr/google-function-authorizer/branches/master/shields_badge.svg)](https://semaphoreci.com/pauloddr/google-function-authorizer) [![Test Coverage](https://lima.codeclimate.com/github/pauloddr/google-function-authorizer/badges/coverage.svg)](https://lima.codeclimate.com/github/pauloddr/google-function-authorizer/coverage) [![Code Climate](https://lima.codeclimate.com/github/pauloddr/google-function-authorizer/badges/gpa.svg)](https://lima.codeclimate.com/github/pauloddr/google-function-authorizer) [![npm version](https://badge.fury.io/js/google-function-authorizer.svg)](https://badge.fury.io/js/google-function-authorizer) A simple user authentication and management system for [Google Cloud HTTP Functions](https://cloud.google.com/functions/docs/writing/http). It stores user data in [Google Datastore](https://cloud.google.com/datastore/) using [gstore-node](https://github.com/sebelga/gstore-node); hashes passwords with [bcrypt](https://github.com/kelektiv/node.bcrypt.js); and manages browser sessions with [client-session](https://github.com/mozilla/node-client-sessions). ## Usage Create a new Google HTTP Function with the following code: ```javascript const users = require('google-function-authorizer')({ session: {secret: 'MYSECRETKEY'} // required! }); exports.handleRequest = function (req, res) { users.handle(req, res); }; ``` Add the library to __package.json__: ```json { "name": "your-function", "version": "0.0.1", "dependencies": { "google-function-authorizer": "0.1.0" } } ``` Finally, make sure the __entry point__ is correct. In the example above, it should be `handleRequest`. Then, assuming you named your function "users", the following endpoints will be served by your function: * `POST /users` * `POST /users/signin` * `POST /users/signout` * `GET /users` * `GET /users/:id` * `PUT|PATCH /users/:id` * `DELETE /users/:id` * `DELETE /users/signin` * `OPTIONS /users(/*)` Read more about how each endpoint works in the next section. ## Actions All actions respond with a JSON object with a `code` attribute with the following possible string values: * `OK` - action has completed successfully * `BAD_REQUEST` - action has failed due to request not being in expected format * `NOT_FOUND` - endpoint not found, or user not found * `UNAUTHORIZED` - action requires that a user signs in first * `FORBIDDEN` - action requires that signed-in user has permission to perform it * `INTERNAL_ERROR` - an unexpected error has occurred while performing the action ### Create User * `POST /users` This endpoint creates a new user. <table> <tr><th>Request Body</th><th>Response</th></tr> <tr><td> ```javascript { "username": "MyUsername", "email": "<EMAIL>", "password": "<PASSWORD>" } ``` </td><td> ```javascript { "code": "OK", "user": { "id": "12345", "username": "MyUsername", "email": "<EMAIL>" } } ``` </td></tr> </table> ### Sign User In * `POST /users/signin` Signs a user in, starting a new session. This endpoint sets a session cookie upon successful response, which will be sent in the next requests. <table> <tr><th>Request Body</th><th>Response</th></tr> <tr><td> ```javascript { "email": "<EMAIL>", "password": "<PASSWORD>" } ``` </td><td> ```javascript { "code": "OK", "user": { "id": "12345", "username": "MyUsername", "email": "<EMAIL>" } } ``` </td></tr> </table> ### Sign User Out * `POST /users/signout` * `DELETE /users/signin` (alternatively) Signs a user out, removing the session cookie. <table> <tr><th>Request Body</th><th>Response</th></tr> <tr><td>(empty)</td><td> ```javascript { "code": "OK" } ``` </td></tr> </table> ### List Users * `GET /users` Returns a list of users with pagination. Default page size is 20. By default, this endpoint requires the signed-in user role to be `admin`. <table> <tr><th>Request Query Parameters</th><th>Response</th></tr> <tr><td> * `/users` * first 20 users * `/users?limit=10` * first 10 users * `/users?start=NextPageKey000123` * first 20 users * starting from key "NextPageKey000123" </td><td> ```javascript { "code": "OK", "items": [ {"id": "1", "username": "user1", "email": "<EMAIL>", ...}, {"id": "2", "username": "user2", "email": "<EMAIL>", ...}, ... ], "limit": 20, "next": "NextPageKey000123" } ``` </td></tr> </table> The `next` attribute will be absent from the response if there are no more entries to fetch. (Filters and sorting are not yet supported.) ### Show User * `GET /users/:id` Returns data of a single user. By default, this endpoint has the following requirements: * user ID being requested matches with signed-in user ID; or * the signed-in user role is `admin`. <table> <tr><th>Request URI</th><th>Response</th></tr> <tr><td> * `/users/12345` * shows info of user ID=12345 </td><td> ```javascript { "code": "OK", "user": { "id": "12345", "username": "MyUsername", "email": "<EMAIL>" } } ``` </td></tr> </table> ### Update User * `PUT /users/:id` * `PATCH /users/:id` Updates data of a single user, including password. Both `PUT` and `PATCH` methods behave the same way, and partial data can be provided. By default, this endpoint has the following requirements: * user ID being updated matches with signed-in user ID; or * the signed-in user role is `admin`. (Not yet implemented) The user `role` attribute can only be updated by other admins. <table> <tr><th>Request Body</th><th>Response</th></tr> <tr><td> ```javascript { "username": "EditedUsername" } ``` </td><td> ```javascript { "code": "OK", "user": { "id": "12345", "username": "EditedUsername", "email": "<EMAIL>" } } ``` </td></tr> </table> ### Destroy User * `DELETE /users/:id` Removes a user. By default, this endpoint has the following requirements: * user ID being deleted matches with signed-in user ID; or * the signed-in user role is `admin`. If user being deleted matches the user currently signed in, the user will be automatically signed out. <table> <tr><th>Request Body</th><th>Response</th></tr> <tr><td>(empty)</td><td> ```javascript { "code": "OK" } ``` </td></tr> </table> ### Preflight Requests / Current Signed-in User * `OPTIONS /users` Some clients will fire a "preflight request" prior to making the real request to verify CORS options, which are supported by this library. You can also use this method to retrieve the current signed-in user, which will be present in the response body, as well as the current endpoint rules (see Configuration for details), which the client can then use to prevent certain actions on their side. <table> <tr><th>Request Body</th><th>Response</th></tr> <tr><td>(empty)</td><td> ```javascript { "code": "OK", "userId": "12345", "rules": { "signin": "all", "create": "all", "update": "self", "find": "self", "list": "admin", "destroy": "self" } } ``` </td></tr> </table> ## Authorization Call `authorize` in your _other_ Google Functions to have the session cookie read from the request before calling your code: ```javascript const users = require('google-function-authorizer')({ session: {secret: 'MYSECRETKEY'} // required! must be the same as your users endpoint! }); exports.handleRequest = function (req, res) { users.authorize(req, res, mainFunction); }; function mainFunction (req, res, user) { // session is valid -- execute the rest of your function } ``` If the session is valid, a `user` object will be passed along to your main function, containing a subset of stored attributes. If the session is invalid, a `401 - Unauthorized` error will be returned automatically. If you want to take control of error processing, pass a fourth argument to `authorize` with an error function that takes `req` and `res` arguments. ## Roles This library comes with a very simple role management system built-in. The default rules are: * Anyone can create a user or sign in. * Users with `admin` role are able to edit and delete other users. * Users with any other role are only allowed to edit or delete themselves. * Only admins can list users. * Users cannot be created with a role, since that specific endpoint is public. * Another admin must edit newly created users if they need defined roles. These rules are customizable. Refer to the next section to learn how to change them. ## Configuration Settings can be customized upon requiring the library, and have the following defaults: ```javascript const users = require('google-function-authorizer')({ // Configure session cookie behavior here. session: { name: 'userSession', // cookie name secret: null, // must be set! will raise error (and crash) if not defined duration: 24 * 60 * 60 * 1000, // session expiration in ms activeDuration: 1000 * 60 * 5 // session active duration in ms }, // Datastore settings. datastore: { kind: 'User', namespace: undefined }, // You can overwrite the full schema, but it needs at least: // - the primary field, and // - the password field. // Both field names can be defined in the "fields" section. // If your schema is missing "confirmation" fields, // confirmation workflows will not run. schema: { username: { type: 'string', optional: true, excludeFromIndexes: true }, email: { type: 'string', required: true, validate: 'isEmail' }, password: { type: 'string', required: true, read: false, excludeFromIndexes: true }, role: { type: 'string', write: false }, confirmationToken: { type: 'string', read: false }, confirmedOn: { type: 'datetime', excludeFromIndexes: true }, createdOn: { type: 'datetime', write: false, default: Gstore.defaultValues.NOW, excludeFromIndexes: true }, modifiedOn: { type: 'datetime', write: false, excludeFromIndexes: true } }, // If you use a custom schema, you can have custom field names as well. fields: { primary: 'email', // will be used in signin with password username: 'username', email: 'email', password: '<PASSWORD>', role: 'role' }, // Customize CORS headers here to anything you'd like. // Multiple headers are accepted. cors: { "Access-Control-Allow-Origin": "*" }, // Apply rules for certain user-related actions. // The following values are accepted: // - "all": public and unrestricted access // - "user": access for logged-in users only // - "self": access for record owner only, or admins // - "admin": admin access only // - false: endpoint is disabled // (useful if you want to disable user creation, for example) // Absence of field or value will default to "admin". rules: { signin: 'all', create: 'all', update: 'self', find: 'self', list: 'admin', destroy: 'self' } }); exports.handleRequest = function (req, res) { users.handle(req, res); }; ``` Please note that __settings must be the same across all functions__. So if you change any of the default values, make sure to replicate them accordingly. _When Google Cloud Functions support environment variables, we will change this approach so configuration can be unified and the copy/pasting avoided._ If you want to customize Schema validators with your own functions, take a look at the [Gstore Schema documentation](https://sebelga.gitbooks.io/gstore-node/content/schema/). ## TODO/Wishlist * Google reCAPTCHA support on user creation and update. * Email service support (Mailgun, SendGrid, etc) for sending various confirmation messages. * Customizable cache TTL support for `authorization`. * Currently, it stores values in session until user signs out or session expires. * Support other data stores (like MySQL). * Support JSON Web Tokens instead of client-sessions. ## License MIT <file_sep>'use strict'; const password = require('../lib/password'); const expect = require('chai').expect; const Bcrypt = require('bcrypt'); describe('password', function () { let body = {}; it('returns error on blank password', function (done) { body.password = ''; password(body, (err, data) => { expect(err).to.equal('EMPTY_PASSWORD'); done(); }); }); it('sets hashed password in returned object', function (done) { body.password = '<PASSWORD>'; password(body, (err, data) => { expect(data.password).to.not.equal(body.password); expect(err).to.not.exist; Bcrypt.compare(body.password, data.password, (err, valid) => { expect(valid).to.equal(true); expect(err).to.not.exist; done(); }); }); }); }); <file_sep>'use strict'; const app = require('../support/test-app'); const expect = require('chai').expect; const helpers = require('../support/test-helpers'); const User = require('../lib/user'); const EMAIL = '<EMAIL>'; const PASSWORD = '<PASSWORD>'; describe('find', function () { after(function (done) { helpers.delete_all_users_and_sign_out(done); }); describe('without session', function () { it('returns unauthorized', function (done) { app.get('/users/1').end(function (err, res) { expect(res.body.code).to.equal('UNAUTHORIZED'); expect(res.statusCode).to.equal(401); done(); }); }); }); describe('with session', function () { let user; describe('as non-admin', function () { before(function (done) { let data = {email: EMAIL, password: <PASSWORD>, username: 'user1'} helpers.create_user_and_sign_in(data, (err, entity) => { user = entity; done(err); }); }); it('is forbidden if ID requested is different from signed-in user', function (done) { app.get('/users/anotherid').end(function (err, res) { expect(res.body.code).to.equal('FORBIDDEN'); done(); }); }); it('returns user data if ID matches signed-in user', function (done) { app.get(`/users/${user.id}`).end(function (err, res) { expect(res.body.code).to.equal('OK'); done(); }); }); }); describe('as admin', function () { let admin; before(function (done) { helpers.sign_in_as_admin((err, entity) => { admin = entity; done(err); }); }); it('returns 404 if user does not exist', function (done) { app.get('/users/idonotexist').end(function (err, res) { expect(res.body.code).to.equal('NOT_FOUND'); done(); }); }); it('returns user data from any ID', function (done) { app.get(`/users/${user.id}`).end(function (err, res) { expect(res.body.code).to.equal('OK'); done(); }); }); }); }); }); <file_sep>'use strict'; const config = require('./lib/configuration'); module.exports = function (customConfig) { config.override(customConfig); /* istanbul ignore if */ if (!config.session.secret) { throw new Error('config.session.secret not set'); } const authorize = require('./lib/authorize'); const handle = require('./lib/handle'); return {authorize, handle}; }; <file_sep>'use strict'; const config = require('./configuration'); const middleware = require('./middleware'); const Response = require('./response'); module.exports = function authorize (req, res, next, err) { middleware(req, res, () => { let session = req[config.session.name]; let userId = session.userId; if (!userId) { if (err) { return err(req, res); } return Response.unauthorized(res); } if (!next) { console.error('Authorize: No next() function specified'); return Response.internalError(res); } next(req, res, { id: session.userId, username: session.username, email: session.email, role: session.role }); }); }; <file_sep>'use strict'; const cors = require('./cors'); const Response = require('./response'); const session = require('./session'); module.exports = function middleware (req, res, next) { _params(req); const validMethod = _method(req, res); /* istanbul ignore if */ if (!validMethod) { return Response.notFound(res); } cors(req, res, () => { session(req, res, () => { next(req, res); }); }); }; function _params (req) { /* istanbul ignore if */ if (!req.params) { return; } let path = req.params['0']; if (!path) { return; } req.params.parts = path.split('/'); while (req.params.parts[0] === '') { req.params.parts.shift(); } if (req.params.parts.length === 0) { delete req.params.parts; } } function _method (req) { switch (req.method) { case 'POST': return _post(req); case 'PUT': case 'PATCH': return _put(req); case 'GET': return _get(req); case 'DELETE': return _delete(req); case 'OPTIONS': return true; // handled by middleware /* istanbul ignore next */ default: return false; } } function _post (req) { if (!req.params.parts) { req.params.action = 'create'; return true; } let part = req.params.parts[0]; switch (part) { case 'signin': case 'signout': req.params.action = part; return true; /* istanbul ignore next */ default: return false; } } function _put (req) { if (!req.params.parts) { return false; } req.params.action = 'update'; req.params.userId = req.params.parts[0]; return true; } function _get (req) { if (!req.params.parts) { req.params.action = 'list'; return true; } let part = req.params.parts[0]; /* istanbul ignore else */ if (part) { req.params.action = 'find'; req.params.userId = part; return true; } else { return false; } } function _delete (req) { if (!req.params.parts) { return false; } let part = req.params.parts[0]; if (part === 'signin') { req.params.action = 'signout'; return true; } req.params.action = 'destroy'; req.params.userId = part; return true; } <file_sep>'use strict'; const OK = {code: 'OK'}; const NOT_FOUND = {code: 'NOT_FOUND'}; const BAD_REQUEST = {code: 'BAD_REQUEST'}; const FORBIDDEN = {code: 'FORBIDDEN'}; const UNAUTHORIZED = {code: 'UNAUTHORIZED'}; const INTERNAL_ERROR = {code: 'INTERNAL_ERROR'}; module.exports = { ok: function _ok (res, data) { res.status(200); if (data) { Object.assign(data, OK); res.json(data); } else { res.json(OK); } }, notFound: function _notFound (res) { res.status(404).json(NOT_FOUND); }, badRequest: function _badRequest (res, err) { let data = {}; /* istanbul ignore else */ if (err.name === 'ValidatorError') { data.reason = err.message.message; } else { data.reason = err; } Object.assign(data, BAD_REQUEST); res.status(400).json(data); }, internalError: function _internalError (res) { /* istanbul ignore next */ res.status(500).json(INTERNAL_ERROR); }, forbidden: function _forbidden (res) { res.status(403).json(FORBIDDEN); }, unauthorized: function _unauthorized (res) { res.status(401).json(UNAUTHORIZED); } }; <file_sep>'use strict'; require('dotenv').config(); // If you have a credentials file, create .env and // define GOOGLE_APPLICATION_CREDENTIALS in it. // It will allow your tests to connect to a real // Datastore server, which can be needed for CI. // Otherwise, the Datastore emulator will be used. if (process.env.GOOGLE_APPLICATION_CREDENTIALS) { delete process.env.DATASTORE_EMULATOR_HOST; delete process.env.GCLOUD_PROJECT; } <file_sep>'use strict'; const Gstore = require('gstore-node'); // After changing this object, // make sure to copy/paste it into README. let configuration = { // Configure session cookie behavior here. session: { name: 'userSession', // cookie name secret: null, // must be set! will raise error (and crash) if not defined duration: 24 * 60 * 60 * 1000, // session expiration in ms activeDuration: 1000 * 60 * 5 // session active duration in ms }, // Datastore settings. datastore: { kind: 'User', namespace: undefined }, // You can overwrite the full schema, but it needs at least: // - the primary field, and // - the password field. // Both field names can be defined in the "fields" section. // If your schema is missing "confirmation" fields, // confirmation workflows will not run. schema: { username: { type: 'string', optional: true, excludeFromIndexes: true }, email: { type: 'string', required: true, validate: 'isEmail' }, password: { type: 'string', required: true, read: false, excludeFromIndexes: true }, role: { type: 'string', write: false }, confirmationToken: { type: 'string', read: false }, confirmedOn: { type: 'datetime', excludeFromIndexes: true }, createdOn: { type: 'datetime', write: false, default: Gstore.defaultValues.NOW, excludeFromIndexes: true }, modifiedOn: { type: 'datetime', write: false, excludeFromIndexes: true } }, // If you use a custom schema, you can have custom field names as well. fields: { primary: 'email', // will be used in signin with password username: 'username', email: 'email', password: '<PASSWORD>', role: 'role' }, // Customize CORS headers here to anything you'd like. // Multiple headers are accepted. cors: { "Access-Control-Allow-Origin": "*" }, // Apply rules for certain user-related actions. // The following values are accepted: // - "all": public and unrestricted access // - "user": access for logged-in users only // - "self": access for record owner only, or admins // - "admin": admin access only // - false: endpoint is disabled // (useful if you want to disable user creation, for example) // Absence of field or value will default to "admin". rules: { signin: 'all', create: 'all', update: 'self', find: 'self', list: 'admin', destroy: 'self' } }; configuration.override = function _override (config) { /* istanbul ignore if */ if (!config) { return; } _set('session', config); _set('datastore', config); _set('schema', config); _set('fields', config); _set('cors', config); _set('rules', config); }; function _set (section, object) { if (!object || !object[section]) { return; } Object.assign(configuration[section], object[section]); } module.exports = configuration; <file_sep>'use strict'; const config = require('./configuration'); const password = require('./password'); const Response = require('./response'); const User = require('./user'); module.exports = function update (req, res) { // hash password if it's present if (req.body[config.fields.password]) { password(req.body, (err, data) => { /* istanbul ignore if */ if (err) { return Response.badRequest(res, err); } _update(req, res, data); }); } else { delete req.body[config.fields.password]; _update(req, res, req.body); } }; function _update (req, res, data) { delete data.id; let userId = req.params.userId; let role = data.role; let sanitizedData = User.sanitize(data); if (req[config.session.name].role === 'admin') { sanitizedData.role = role; } User.update(userId, sanitizedData, (err, entity) => { if (err) { return Response.badRequest(res, err); } Response.ok(res, {user: entity.plain()}); }); } <file_sep>'use strict'; const config = require('./configuration'); const User = require('./user'); const Response = require('./response'); module.exports = function destroy (req, res) { const userId = req.params.userId; /* istanbul ignore if */ if (!userId) { console.error('Routing Error: Destroy without UserId'); return Response.internalError(res); } User.delete(userId, (err, response) => { /* istanbul ignore if */ if (err) { console.error('User Deletion Error:', err); return Response.internalError(res); } let session = req[config.session.name]; if (session.userId === userId) { session.reset(); } if (!response.success) { return Response.notFound(res); } Response.ok(res); }); }; <file_sep>'use strict'; const Response = require('./response'); const User = require('./user'); module.exports = function find (req, res) { const userId = req.params.userId; /* istanbul ignore if */ if (!userId) { console.error('Routing Error: Find without UserId'); return Response.internalError(res); } User.get(userId, (err, entity) => { /* istanbul ignore if */ if (err) { if (err.code === 404) { return Response.notFound(res); } console.error('Find User error:', err); return Response.internalError(res); } Response.ok(res, {user: entity.plain()}); }); }; <file_sep>'use strict'; const app = require('../support/test-app'); const expect = require('chai').expect; describe('cors', function () { it('returns proper header', function (done) { app.options('/users').end(function (err, res) { expect(res.statusCode).to.equal(200); expect(res.headers['access-control-allow-origin']).to.equal('*'); done(); }); }); }); <file_sep>'use strict'; const app = require('../support/test-app'); const expect = require('chai').expect; const helpers = require('../support/test-helpers'); describe('signout', function () { let user; beforeEach(function (done) { let data = {email: '<EMAIL>', password: '<PASSWORD>'}; helpers.create_user_and_sign_in(data, (err, entity) => { user = entity; done(err); }); }); after(function (done) { helpers.delete_all_users_and_sign_out(done); }); it('signs user out', function (done) { app.get(`/users/${user.id}`).end(function (err, res) { expect(res.body.user.id).to.equal(user.id); app.post('/users/signout').end(function (err, res) { expect(res.body.code).to.equal('OK'); app.get(`/users/${user.id}`).end(function (err, res) { expect(res.body.code).to.equal('UNAUTHORIZED'); done(); }); }); }); }); it('also works with DELETE /users/signin', function (done) { app.get(`/users/${user.id}`).end(function (err, res) { expect(res.body.user.id).to.equal(user.id); app.del('/users/signin').end(function (err, res) { expect(res.body.code).to.equal('OK'); app.get(`/users/${user.id}`).end(function (err, res) { expect(res.body.code).to.equal('UNAUTHORIZED'); done(); }); }); }); }); });
b9861913f34b88832a04cff07d0b21e7606ef4a8
[ "JavaScript", "Markdown" ]
22
JavaScript
Eric013/google-function-authorizer
e4adf9e5620694c1c71c7e546c84dcbf3189e197
9e4728ebe551b99bcc2a7a4de5d2b2333d8007e1
refs/heads/master
<file_sep>spring.datasource.url=jdbc:postgresql://localhost/spring spring.datasource.username=postgres spring.datasource.password=123 spring.jpa.generate-ddl=false spring.jpa.show-sql=false spring.jpa.hibernate.ddl-auto=validate spring.freemarker.expose-request-attributes=true upload.path=/home/artur/IdeaProjects/spring/filesUpload spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true spring.mail.host=smtp.yandex.ru spring.mail.username=<EMAIL> spring.mail.password=<PASSWORD> spring.mail.port=465 spring.mail.protocol=smtps mail.debug=true recaptcha.secret=<KEY> spring.session.jdbc.initialize-schema=always spring.session.jdbc.table-name=SPRING_SESSION hostname=localhost:8080<file_sep>#!/usr/bin/env bash mvn clean package echo 'Copy files...' scp -i ~/.ssh/spring-art.pem \ target/spring-1.0-SNAPSHOT.jar \ [email protected]:/home/ubuntu/ echo 'Restart server...' ssh -i ~/.ssh/spring-art.pem [email protected] << EOF pgrep java | xargs kill -9 nohup java -jar spring-1.0-SNAPSHOT.jar > log.txt & EOF echo 'Bye'
58d0c2bd3407dd54db2cf2c1a67ae878bb28102a
[ "Shell", "INI" ]
2
INI
ArturAzizean/Spring-project
b3dd5a889635872f6370052cfac0dff3c86bf38d
d8a57fb147463c97a850bc61d19359257542f84f
refs/heads/master
<file_sep>class NycParks::CLI def call make_parks greetings list_boroughs until boro_valid? == true list_boroughs end list_borough_parks until park_valid? == true list_borough_parks end list_a_park again end def make_parks parks_array = NycParks::Scraper.park_scrape NycParks::Park.create_from_collection(parks_array) end def greetings puts "Welcome to NYC Parks:" end def list_boroughs @borough = NycParks::Scraper.scrape_boroughs @borough.each do |borough| puts "#{borough}" end puts "Enter a borough for a list of parks or type exit to exit:" @input = gets.strip.downcase if @input == "exit" goodbye end end def boro_valid? if ["bronx", "manhattan", "queens", "brooklyn", "staten island"].include?(@input) return true else puts "Please enter a valid borough or type exit to exit." return false end end def list_borough_parks hash = NycParks::Scraper.scrape_borough_parks hash[@input.split[0].to_sym].each do |parks| puts parks end puts "Enter the park name exactly as listed for more info or type exit to exit." @input_park = gets.strip if @input_park == "exit" goodbye end end def park_valid? hash = NycParks::Scraper.scrape_borough_parks if hash[@input.split[0].to_sym].include?(@input_park) return true else return false end end def list_a_park park = NycParks::Park.all.detect {|park_obj| park_obj.name == @input_park} puts park.name puts park.address puts park.borough puts park.park_info end def goodbye puts "Thanks for stopping by!" exit end def again puts "Would you like to look at another park (yes or no)?" @again_input = gets.strip if @again_input == "yes" self.call elsif @again_input == "no" self.goodbye else self.again end end end <file_sep>#!/usr/bin/env ruby require "./lib/NycParks" require "bundler/setup" require "NycParks" NycParks::CLI.new.call <file_sep>class NycParks::Park attr_accessor :name, :address, :borough, :park_info @@all = [] def initialize(park_hash) park_hash.each do |attribute, value| self.send("#{attribute}=", value) end @@all << self end def self.create_from_collection(parks_array) parks_array.each do |park_hash| self.new(park_hash) end end def self.all @@all end end <file_sep>class NycParks::Scraper def self.scrape_boroughs doc = Nokogiri::HTML(open("https://www.nycgovparks.org/park-features/parks-list")) borough_name = doc.css("#li_id>.nav-tabs a").collect do |boro| boro.text end borough_name end def self.scrape_borough_url hash = {} doc = Nokogiri::HTML(open("https://www.nycgovparks.org/park-features/parks-list")) doc.css("#li_id>.nav-tabs a").each do |boro| hash["#{boro.text}".split.join.to_sym] = "https://www.nycgovparks.org/park-features/parks-list" + boro.attribute("href").text end hash end def self.scrape_borough_parks boroparks_hash = {} self.scrape_borough_url.values.each do |url| doc = Nokogiri::HTML(open(url)) name = doc.css("#navlist_header").text boroparks_hash["#{name}".split[0].downcase.to_sym] = doc.css("#boro-park-highlights a").collect {|park| park.text} end boroparks_hash end def self.all_boro_parks park_url = {} boro_url = self.scrape_borough_url boro_url.values.each do |url| doc = Nokogiri::HTML(open(url)) doc.css("#boro-park-highlights a").collect {|x| park_url[x.text.to_sym] = "https://www.nycgovparks.org" + x.attribute("href").text} end park_url end def self.park_scrape arr_park_url = self.all_boro_parks.values arr_park_url.collect do |url| doc = Nokogiri::HTML(open(url)) { :name => doc.css(".park_name_title").text, :address => doc.css(".park_location").text, :borough => doc.css("#park_info span").text, :park_info => doc.css('div#park_description p').text } end end end
0f23c4efd3b30f40c40863e6e18275849038efc5
[ "Ruby" ]
4
Ruby
verokim85/NycParks-cli-app
c82917f92f1edb109ed306ee7a595cc2cac07718
a2741279a0fee531ff123ab38815eeaeb1b8e1f4
refs/heads/main
<repo_name>happygeekme/Opdracht26_function_3ways<file_sep>/script.js // function squared(number1, number2) { // const squared1 = Math.pow(number1, 2); // const squared2 = Math.pow(number2, 2); // const sumSquared = squared1 + squared2; // return(Math.pow(sumSquared , 2)); // } // const outcome = squared(1, 1); // console.log(outcome) // const squared = function(number1, number2) { // const squared1 = Math.pow(number1, 2); // const squared2 = Math.pow(number2, 2); // const sumSquared = squared1 + squared2; // return(Math.pow(sumSquared , 2)); // }; // const outcome = squared(2,3); // console.log(outcome); const squared = (number1, number2) => { const squared1 = Math.pow(number1, 2); const squared2 = Math.pow(number2, 2); const sumSquared = squared1 + squared2; return(Math.pow(sumSquared , 2)); }; const outcome = squared(2, 2); console.log(outcome);
f20833ecf4363233902d04f887d8920bc423b7ed
[ "JavaScript" ]
1
JavaScript
happygeekme/Opdracht26_function_3ways
8610127769582ff2b1a0bd6fe4e964c1a49be297
97d567c1d69072c81a945680edd37a128ff7d915
refs/heads/master
<repo_name>andrewboisen/SarahSoundBoard<file_sep>/SarahSoundBoard/SarahSoundBoard.iOS/Service/AudioService.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using Foundation; using UIKit; using SoundBoard.Service; using SoundBoard.iOS.Service; [assembly: Xamarin.Forms.Dependency(typeof(AudioService))] namespace SoundBoard.iOS.Service { class AudioService : IAudioService { public void PlayAudio(string filename) { } } }<file_sep>/SarahSoundBoard/SarahSoundBoard/Service/IAudioService.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoundBoard.Service { public interface IAudioService { void PlayAudio(string filename); } } <file_sep>/SarahSoundBoard/SarahSoundBoard/MainPage.xaml.cs using SoundBoard.Service; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace SoundBoard { public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); } private void ButtonBeepBeep_Clicked(object sender, EventArgs e) { var audioService = DependencyService.Get<IAudioService>(); audioService.PlayAudio("beepbeep.mp3"); } private void ButtonBigBurn_Clicked(object sender, EventArgs e) { var audioService = DependencyService.Get<IAudioService>(); audioService.PlayAudio("bigburn.mp3"); } private void ButtonDuhDah_Clicked(object sender, EventArgs e) { var audioService = DependencyService.Get<IAudioService>(); audioService.PlayAudio("duhdah.mp3"); } private void ButtonMeMe_Clicked(object sender, EventArgs e) { var audioService = DependencyService.Get<IAudioService>(); audioService.PlayAudio("meme.mp3"); } private void ButtonOhlalaa_Clicked(object sender, EventArgs e) { var audioService = DependencyService.Get<IAudioService>(); audioService.PlayAudio("ohlalaa.mp3"); } private void ButtonQuack_Clicked(object sender, EventArgs e) { var audioService = DependencyService.Get<IAudioService>(); audioService.PlayAudio("quack.mp3"); } } } <file_sep>/SarahSoundBoard/SarahSoundBoard.Android/Service/AudioService.cs using Android.Media; using SoundBoard.Droid.Service; using SoundBoard.Service; [assembly: Xamarin.Forms.Dependency(typeof(AudioService))] namespace SoundBoard.Droid.Service { internal class AudioService : IAudioService { public void PlayAudio(string filename) { var player = new MediaPlayer(); var fileDescriptor = Xamarin.Forms.Forms.Context.Assets.OpenFd(filename); player.Prepared += (s, e) => { player.Start(); }; player.Completion += (s, e) => { player.Release(); }; player.SetDataSource(fileDescriptor.FileDescriptor, fileDescriptor.StartOffset, fileDescriptor.Length); player.Prepare(); } } }
31466665c75e5fcbf2c135e85607962db5e8a8a3
[ "C#" ]
4
C#
andrewboisen/SarahSoundBoard
b509d1d73cac4f62307c5d2c7fd01d959b5d1d82
72b5ba7ee7a687e5214e08df2e4b82f4e58b9dcf
refs/heads/master
<file_sep>package com.lifeistech.andoroid.tapnumber; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class SubActivity extends AppCompatActivity { TextView textView8;//今回の得点 TextView textView9;//highschore int highscore; int tennsuu; PreferenceManager preferenceManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sub); Intent intent = getIntent(); tennsuu = intent.getIntExtra("tennsuu", 0); preferenceManager = new PreferenceManager(getApplication()); textView8 = (TextView) findViewById(R.id.textView8); int savedHighScore = preferenceManager.getInt("TENNSUU", 0); //highscore = tennsuu; textView8.setText(String.valueOf(savedHighScore)); // ここにfindViewByIdを書こう textView9 = (TextView) findViewById(R.id.textView9); textView9.setText(String.valueOf(preferenceManager.getInt("TENNSUU", 0))); // 点数を保存 if(tennsuu > savedHighScore) { preferenceManager.setInt("TENNSUU", tennsuu); textView9.setText(String.valueOf(tennsuu)); } else { // highscore = 0; // preferenceManager.setInt("TENNSUU", 2); //textView8.setText(String.valueOf(tennsuu)); } textView8.setText(String.valueOf(tennsuu)); //Intent intent = getIntent(); //point = intent.getIntExtra("tokutenn", 0);*/ } public void challenge(View view) { Intent intent = new Intent(SubActivity.this, StartActivity.class); startActivity(intent); } public void finish(View view) { android.os.Process.killProcess(android.os.Process.myPid()); } } <file_sep>package com.lifeistech.andoroid.tapnumber; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; import android.widget.Toast; import java.util.Random; public class Level2Activity extends AppCompatActivity { int[] hairetu = {2, 4, 6}; String mondai; int seikai; int error; int point; TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_level2); textView = (TextView) findViewById(R.id.textView); error = 0; point = 0; start(); } public void start() { hairetu = new int[6]; Random rand = new Random(); // 0,1,2,3でランダムを作る -> +1する -> 1,2,3,4 hairetu[0] = rand.nextInt(4) + 1; hairetu[1] = rand.nextInt(4) + 1; hairetu[2] = rand.nextInt(4) + 1; hairetu[3] = rand.nextInt(4) + 1; hairetu[4] = rand.nextInt(4) + 1; hairetu[5] = rand.nextInt(4) + 1; // hairetuを文字にする mondai = String.valueOf(hairetu[0]) + String.valueOf(hairetu[1]) + String.valueOf(hairetu[2]) + String.valueOf(hairetu[3]) + String.valueOf(hairetu[4] +String.valueOf(hairetu[5])); textView.setText(mondai); seikai = 0; } public void number1(View v) { if (hairetu[seikai] == 1) { mondai = mondai.substring(1); textView.setText(mondai); seikai = seikai + 1; if (seikai == 6) { point = point + 1; Toast.makeText(this, point+"点ゲット", Toast.LENGTH_SHORT).show(); start(); } } else { error = error + 1; Toast.makeText(this, "間違えた回数"+error, Toast.LENGTH_SHORT).show(); if (error == 5){ Toast.makeText(this, "ゲームオーバー", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(Level2Activity.this, SubActivity.class); intent.putExtra("tennsuu",point); startActivity(intent); finish(); } } } public void number2(View v) { if (hairetu[seikai] == 2) { mondai = mondai.substring(1); textView.setText(mondai); seikai = seikai + 1; if (seikai == 6) { point = point + 1; Toast.makeText(this, point+"点ゲット", Toast.LENGTH_SHORT).show(); start(); } }else { error = error + 1; Toast.makeText(this, "間違えた回数"+error, Toast.LENGTH_SHORT).show(); Log.d("エラー", "error"+error+"個"); if (error == 5){ Toast.makeText(this, "ゲームオーバー", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(Level2Activity.this, SubActivity.class); //intent.putExtra("tokutenn", point); intent.putExtra("tennsuu",point); startActivity(intent); finish(); } } } public void number3(View v) { if (hairetu[seikai] == 3) { mondai = mondai.substring(1); textView.setText(mondai); seikai = seikai + 1; if (seikai == 6) { point = point + 1; Toast.makeText(this, point+"点ゲット", Toast.LENGTH_SHORT).show(); start(); } }else { error = error + 1; Toast.makeText(this, "間違えた回数"+error, Toast.LENGTH_SHORT).show(); if (error == 5){ Toast.makeText(this, "ゲームオーバー", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(Level2Activity.this, SubActivity.class); intent.putExtra("tennsuu",point); startActivity(intent); finish(); } } } public void number4(View v) { if (hairetu[seikai] == 4) { mondai = mondai.substring(1); textView.setText(mondai); seikai = seikai + 1; if (seikai == 6) { point = point + 1; Toast.makeText(this, point+"点ゲット", Toast.LENGTH_SHORT).show(); start(); } }else { error = error + 1; Toast.makeText(this, "間違えた回数"+error, Toast.LENGTH_SHORT).show(); if (error == 5){ Toast.makeText(this, "ゲームオーバー", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(Level2Activity.this, SubActivity.class); intent.putExtra("tennsuu",point); startActivity(intent); finish(); } } } } <file_sep>package com.lifeistech.andoroid.tapnumber; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; public class StartActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_start); } public void level1(View v) { Intent intent = new Intent(StartActivity.this, Level1Activity.class); // どの画面からどの画面に遷移するか startActivity(intent); // 次の画面を起動する finish(); // 今の画面を終了する } public void level2(View v) { Intent intent = new Intent(StartActivity.this, Level2Activity.class); // どの画面からどの画面に遷移するか startActivity(intent); // 次の画面を起動する finish(); // 今の画面を終了する } public void level3(View v) { Intent intent = new Intent(StartActivity.this, Level3Activity.class); // どの画面からどの画面に遷移するか startActivity(intent); // 次の画面を起動する finish(); // 今の画面を終了する } public void level4(View v) { Intent intent = new Intent(StartActivity.this, Level4Activity.class); // どの画面からどの画面に遷移するか startActivity(intent); // 次の画面を起動する finish(); // 今の画面を終了する } public void level5(View v) { Intent intent = new Intent(StartActivity.this, Level5Activity.class); // どの画面からどの画面に遷移するか startActivity(intent); // 次の画面を起動する finish(); // 今の画面を終了する } }
356debf0e160614cfaf0d0d5abb259833ccd8ef0
[ "Java" ]
3
Java
LiT-Android10th/p_tapnumber_level
ae67330d0ecd3e822f155a5435b07c5c51e166e7
1f0fb916eb67339ba7d31f2c62441d97a70af1c1
refs/heads/master
<file_sep># ''' # generate gt file based on siammask tracking result # ''' import glob import argparse import torch import cv2 import numpy as np from os.path import join, isdir, isfile from utils.config_helper import load_config from utils.load_helper import load_pretrain from utils.tracker_config import TrackerConfig from tracker import Tracker, tracker_init, tracker_track parser = argparse.ArgumentParser(description='PyTorch Tracking Demo') parser.add_argument('--base_path', default='data/tennis', help='imgs path') args = parser.parse_args() def main(): # args.base_path = base_path args.resume = "../SiamMask/experiments/siammask_sharp/SiamMask_DAVIS.pth" args.config = "../SiamMask/experiments/siammask_sharp/config_davis.json" print(join(args.base_path, 'groundtruth_rect.txt')) # Setup device device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') torch.backends.cudnn.benchmark = True # Setup Model cfg = load_config(args) p = TrackerConfig() p.renew() siammask = Tracker(p=p, anchors=cfg['anchors']) if args.resume: assert isfile(args.resume), 'Please download {} first.'.format(args.resume) siammask = load_pretrain(siammask, args.resume) siammask.eval().to(device) # Parse Image file img_files = sorted(glob.glob(join(join(args.base_path, 'imgs'), '*.jp*'))) ims = [cv2.imread(imf) for imf in img_files] # Select ROI cv2.namedWindow("SiamMask", cv2.WND_PROP_FULLSCREEN) try: init_rect = cv2.selectROI('SiamMask', ims[0], False, False) gts = None x, y, w, h = init_rect except: exit() file1 = open(join(args.base_path, 'groundtruth_rect.txt'), 'w') file1.write('{0:d},{1:d},{2:d},{3:d}\n'.format(x, y, w, h)) toc = 0 for f, im in enumerate(ims): tic = cv2.getTickCount() if f == 0: # init target_pos = np.array([x + w / 2, y + h / 2]) target_sz = np.array([w, h]) state = tracker_init(im, target_pos, target_sz, siammask, device=device) # init tracker state['gts'] = gts state['device'] = device elif f > 0: # tracking state = tracker_track(state, im, siammask, device=device) # track target_pos, target_sz =state['target_pos'], state['target_sz'] x, y = (target_pos - target_sz/2).astype(int) x2, y2 = (target_pos + target_sz/2).astype(int) cv2.rectangle(im, (x, y), (x2, y2), (0, 255, 0), 4) cv2.imshow('SiamMask', im) key = cv2.waitKey(1) if key == ord('q'): break file1.write('{0:d},{1:d},{2:d},{3:d}\n'.format(x, y, x2-x, y2-y)) toc += cv2.getTickCount() - tic file1.close() toc /= cv2.getTickFrequency() fps = f / toc print('SiamMask Time: {:02.1f}s Speed: {:3.1f}fps (with visulization!)'.format(toc, fps)) if __name__ == "__main__": main() <file_sep>import glob import argparse import torch import cv2 import kornia import numpy as np from os.path import join, isdir, isfile import torch.nn.functional as F from torch.utils.data import DataLoader from utils.config_helper import load_config from utils.load_helper import load_pretrain from utils.tracker_config import TrackerConfig from utils.bbox_helper import IoU, corner2center, center2corner from tracker import Tracker, bbox2center_sz from masks import get_bbox_mask_tv, scale_bbox, warp_patch from attack_dataset import AttackDataset from tmp import rand_shift from matplotlib import pyplot as plt parser = argparse.ArgumentParser(description='PyTorch Tracking Demo') args = parser.parse_args() class PatchTrainer(object): def __init__(self, args): super(PatchTrainer, self).__init__() # Setup device self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') torch.backends.cudnn.benchmark = True # Setup tracker cfg cfg = load_config(args) p = TrackerConfig() p.renew() self.p = p # Setup tracker siammask = Tracker(p=p, anchors=cfg['anchors']) if args.resume: assert isfile(args.resume), 'Please download {} first.'.format(args.resume) siammask = load_pretrain(siammask, args.resume) siammask.eval().to(self.device) self.model = siammask def get_tracking_result(self, template_img, template_bbox, search_img, track_bbox, out_layer='score'): device = self.device model = self.model p = self.p pos_z, size_z = bbox2center_sz(template_bbox) pos_x, size_x = bbox2center_sz(track_bbox) model.template(template_img.to(device), pos_z.to(device), size_z.to(device)) pscore, delta, pscore_size = model.track(search_img.to(device), pos_x.to(device), size_x.to(device)) if out_layer == 'score': return pscore, delta, pscore_size elif out_layer == 'bbox': scale_x = self.model.penalty.get_scale_x(size_x) res_bbox = list() for i in range(pscore.shape[0]): best_pscore_id = pscore[i,...].argmax() pred_in_crop = delta[i, :, best_pscore_id] # / scale_x lr = pscore_size[i, best_pscore_id] * p.lr # lr for OTB target_sz_in_crop = size_x[i] * scale_x[i] res_cx = int(pred_in_crop[0] + 127) res_cy = int(pred_in_crop[1] + 127) res_w = int(target_sz_in_crop[0] * (1 - lr) + pred_in_crop[2] * lr) res_h = int(target_sz_in_crop[1] * (1 - lr) + pred_in_crop[3] * lr) res_x = int(res_cx - res_w / 2) res_y = int(res_cy - res_h / 2) res_bbox.append(((res_x, res_y, res_w, res_h))) return pscore, delta, pscore_size, np.array(res_bbox) def get_label(self, track_bbox, thr_iou=0.2, need_iou=False): '''Input track_bbox: np.array of size (B, 4) Return np.array type ''' anchors = self.model.anchor.all_anchors[1].reshape(4, -1).transpose(1, 0) anchor_num = anchors.shape[0] cls_list, delta_list, iou_list = list(), list(), list() for i in range(track_bbox.shape[0]): tx, ty, tw, th = track_bbox[i] tcx, tcy = tx+tw/2, ty+th/2 cx, cy, w, h = anchors[:,0]+127, anchors[:,1]+127, anchors[:,2], anchors[:,3] clss = np.zeros((anchor_num,), dtype=np.int64) delta = np.zeros((4, anchor_num), dtype=np.float32) # delta delta[0] = (tcx - cx) / w delta[1] = (tcy - cy) / h delta[2] = np.log(tw / w) delta[3] = np.log(th / h) # IoU overlap = IoU(center2corner(np.array((cx,cy,w,h))), center2corner(np.array((tcx,tcy,tw,th)))) pos = np.where(overlap > thr_iou) clss[pos] = 1 cls_list.append(clss) delta_list.append(delta) iou_list.append(overlap) # # fig = plt.figure('Label') # for i in range(track_bbox.shape[0]): # ax = fig.add_subplot(1, track_bbox.shape[0], i+1) # tx, ty, tw, th = track_bbox[i] # ax.imshow(kornia.tensor_to_image(self.model.search_cropped[i].byte())) # rect = patches.Rectangle((tx, ty), tw, th, linewidth=2, edgecolor='r', facecolor='none') # ax.add_patch(rect) # for i in range(anchors.shape[0]): # cx, cy, w, h = anchors[i,0], anchors[i,1], anchors[i,2], anchors[i,3] # bb_center = patches.Circle((cx+127, cy+127), color='b', radius=0.2) # ax.add_patch(bb_center) # for i in range(anchors.shape[0]): # if clss[i]==1: # cx, cy, w, h = anchors[i,0], anchors[i,1], anchors[i,2], anchors[i,3] # bb_center = patches.Circle((cx+127, cy+127), color='r', radius=0.2) # ax.add_patch(bb_center) # plt.show() if not need_iou: return np.array(cls_list), np.array(delta_list) else: return np.array(cls_list), np.array(delta_list), np.array(iou_list) def loss(self, pscore, margin=0.7): ''' Note that delta is from model.rpn_pred_loc Loss = max(L1(delta, target), margin), among topK bboxs. Input: pscore (B, 3125) ''' delta = self.model.rpn_pred_loc.view((-1, 4, 3125)) # (B, 4, 3125) # target = torch.tensor([1.0, 1.0, -1.0, -1.0], device=self.device) # diff = delta.permute(0,2,1)[...] - target # (B, 3125, 4) target = torch.tensor([1.0, 1.0], device=self.device) diff = delta.permute(0,2,1)[..., 2:] - target # (B, 3125, 2) diff = torch.max(diff.abs(), torch.tensor(margin, device=self.device)) diff = diff.mean(dim=2) # (B, 3125) idx = torch.topk(pscore, k=15, dim=1)[1] diffs = list() for i in range(diff.shape[0]): diffs.append(diff[i].take(idx[i]) ) loss_delta = torch.stack(diffs).mean() return loss_delta def attack(self): device = self.device # Setup attacker cfg mu, sigma = 127, 5 patch_sz = (200, 400) label_thr_iou = 0.2 pert_sz_ratio = (0.6, 0.6) shift_pos, shift_wh = (-0.2, 0.2), (-0.2, 1.0) loss_delta_margin = 0.7 loss_tv_margin = 1.5 para_trans_color = {'brightness': 0.1, 'contrast': 0.1, 'saturation': 0.1, 'hue': 0.1} para_trans_affine = {'degrees': 2, 'translate': [0.01, 0.01], 'scale': [0.95, 1.05], 'shear': [-2, 2] } para_gauss = {'kernel_size': (9, 9), 'sigma': (5,5)} para_trans_affine_t = {'degrees': 2, 'translate': [0.01, 0.01], 'scale': [0.95, 1.05], 'shear': [-2, 2] } adam_lr = 10 BATCHSIZE = 25 n_epochs = 1000 video = 'data/Phone1' train_nFrames = 100 # Transformation Aug trans_color = kornia.augmentation.ColorJitter(**para_trans_color) trans_affine = kornia.augmentation.RandomAffine(**para_trans_affine) trans_affine_t = kornia.augmentation.RandomAffine(**para_trans_affine_t) avg_filter = kornia.filters.GaussianBlur2d(**para_gauss) total_variation = kornia.losses.TotalVariation() # Setup Dataset dataset = AttackDataset(video, n_frames=train_nFrames) dataloader = DataLoader(dataset, batch_size=BATCHSIZE, shuffle=True) # Generate patch and setup optimizer patch = (mu + sigma * torch.randn(3, patch_sz[0], patch_sz[1])).clamp(0.1,255) # patch = kornia.image_to_tensor(cv2.imread('patch_sm.png')).to(torch.float).clamp(0.1, 255) patch = patch.clone().detach().to(self.device).requires_grad_(True) # (3, H, W) optimizer = torch.optim.Adam([patch], lr=adam_lr) for epoch in range(n_epochs): for data in dataloader: # Move tensor to device template_img, template_bbox, search_img, search_bbox = tuple(map(lambda x: x.to(device), data)) # Gen tracking bbox track_bbox = rand_shift(template_img.shape[-2:], search_bbox, shift_pos, shift_wh) # Tracking and get label # data_track = (template_img, template_bbox, search_img, track_bbox) # pscore, delta, pscore_size, bbox_src = self.get_tracking_result(*data_track, out_layer='bbox') # Calc patch position patch_pos_temp = scale_bbox(template_bbox, pert_sz_ratio) patch_pos_search = scale_bbox(search_bbox, pert_sz_ratio) # Transformation on patch, (N, W, H) --> (B, N, W, H) patch_c = patch.expand(template_img.shape[0], -1, -1, -1) patch_c = trans_color(patch_c / 255.0) * 255.0 patch_warpped_t = warp_patch(patch_c, template_img, patch_pos_temp) patch_warpped_s = warp_patch(patch_c, search_img, patch_pos_search) patch_warpped_t = trans_affine_t(patch_warpped_t) patch_warpped_s = trans_affine(patch_warpped_s) patch_template = torch.where(patch_warpped_t==0, template_img, patch_warpped_t) patch_search = torch.where(patch_warpped_s==0, search_img, patch_warpped_s) # self.show_patch_warpped_t(patch_template, patch_search) # Forward pert_data = (patch_template, template_bbox, patch_search, track_bbox) pscore, delta, pscore_size, bbox = self.get_tracking_result(*pert_data, out_layer='bbox') loss_delta = self.loss(pscore, loss_delta_margin) tv = 0.05 * total_variation(patch)/torch.numel(patch) loss_tv = torch.max(tv, torch.tensor(loss_tv_margin).to(device)) loss = loss_delta + loss_tv # self.show_pscore_delta(pscore, self.model.rpn_pred_loc, bbox_src) # self.show_attack_plt(pscore, bbox, bbox_src, patch) # plt.pause(0.001) optimizer.zero_grad() loss.backward() optimizer.step() patch.data = (patch.data).clamp(0.1, 255) print('epoch {:} Batch End -> loss_delta: {:.5f}, tv: {:.5f}, loss: {:.5f} '.format(\ epoch, loss_delta.cpu().data.numpy(), tv.cpu().data.numpy(), loss.cpu().data.numpy() )) cv2.imwrite('patch_sm.png', kornia.tensor_to_image(patch.detach().byte())) return kornia.tensor_to_image(patch.detach().byte()) def show_pscore_delta(self, pscore, delta, track_bbox, fig_num='pscore_delta'): if torch.is_tensor(delta): delta = delta.detach().cpu().numpy() if not len(delta.shape) == 3: delta = delta.reshape((-1, 4, 3125)) anchor = self.model.all_anchors.detach().cpu().numpy() cx = delta[:, 0, :] * anchor[:, 2] + anchor[:, 0] cy = delta[:, 1, :] * anchor[:, 3] + anchor[:, 1] w = np.exp(delta[:, 2, :]) * anchor[:, 2] h = np.exp(delta[:, 3, :]) * anchor[:, 3] iou_list = list() for i in range(track_bbox.shape[0]): tx, ty, tw, th = track_bbox[i] tcx, tcy = tx+tw/2, ty+th/2 overlap = IoU(center2corner(np.array((cx[i]+127,cy[i]+127,w[i],h[i]))), center2corner(np.array((tcx,tcy,tw,th)))) iou_list.append(overlap) ious = np.array(iou_list) # (B, 3125) ious_img = ious.mean(axis=0).reshape(-1, 25)# (B*5, 25) fig, axes = plt.subplots(1,2,num=fig_num) ax = axes[0] ax.set_title('pscore') ax.imshow(pscore.detach().reshape(-1, 3125).mean(dim=0).reshape(-1, 25).cpu().numpy(), vmin=0, vmax=1) ax = axes[1] ax.set_title('iou: {:.2f}'.format(ious.max())) ax.imshow(ious_img, vmin=0, vmax=1) plt.pause(0.001) return ious, ious_img def show_attack_plt(self, pscore, bbox, bbox_src, patch): fig, axes = plt.subplots(1,3,num='attacking') ax = axes[0] ax.set_title('patch') ax.imshow(kornia.tensor_to_image(patch.byte())) ax = axes[1] ax.set_title('template') ax.imshow(kornia.tensor_to_image(self.model.template_cropped.byte()).reshape(-1, 127, 3)) ax = axes[2] ax.set_title('result') ax.imshow(kornia.tensor_to_image(self.model.search_cropped.byte()).reshape(-1, 255, 3)) for i, xywh in enumerate(bbox): x, y, w, h = xywh rect = patches.Rectangle((x, y+i*255), w, h, linewidth=1, edgecolor='b', facecolor='none') ax.add_patch(rect) for i, xywh in enumerate(bbox_src): x, y, w, h = xywh rect = patches.Rectangle((x, y+i*255), w, h, linewidth=1, edgecolor='r', facecolor='none') ax.add_patch(rect) plt.pause(0.01) def show_patch_warpped_t(self, patch_template, patch_search): cv2.namedWindow("patch_template", cv2.WND_PROP_FULLSCREEN) cv2.namedWindow("patch_search", cv2.WND_PROP_FULLSCREEN) img_w = patch_template.shape[-1] cv2.imshow('patch_template', kornia.tensor_to_image(patch_template.byte()).reshape(-1, img_w, 3)) cv2.imshow('patch_search', kornia.tensor_to_image(patch_search.byte()).reshape(-1, img_w, 3)) cv2.waitKey(0) def generate_patch(self, size=(300, 400)): """ Generate a random patch as a starting point for optimization. """ # adv_patch_cpu = (mu + sigma * torch.randn(3, size[0], size[1])).clamp(0,255) adv_patch_cpu = cv2.resize(cv2.imread('data/patchnew0.jpg'), (size[1], size[0])) # W, H adv_patch_cpu = kornia.image_to_tensor(patch).to(torch.float) return adv_patch_cpu if __name__ == '__main__': import matplotlib.patches as patches args.resume = "../SiamMask/experiments/siammask_sharp/SiamMask_DAVIS.pth" args.config = "../SiamMask/experiments/siammask_sharp/config_davis.json" trainer = PatchTrainer(args) patch = trainer.attack() # cv2.imwrite('patch_sm.png', patch)<file_sep>python demo.py \ --resume ../SiamMask/experiments/siammask_sharp/SiamMask_DAVIS.pth \ --config ../SiamMask/experiments/siammask_sharp/config_davis.json \ --gt_file groundtruth_rect.txt \ --base_path ../DylanTrack/dataset/OTB/Car24/img/<file_sep>import torch from torch import nn if __name__=='__main__': import cv2 import kornia from matplotlib import pyplot as plt patch = cv2.imread('data/patchnew0.jpg') patch = kornia.image_to_tensor(patch).to(torch.float)#.unsqueeze(dim=0) # ColorJitter # trans = kornia.augmentation.ColorJitter(0.1, 0.1, 0.1, 0.1) # fig, axes = plt.subplots(1,2,num=type(trans).__name__) # for i in range(100): # res = trans(patch/255.0) # ax = axes[0] # ax.set_title('patch') # ax.imshow(kornia.tensor_to_image(patch.byte())) # ax = axes[1] # ax.set_title('res') # ax.imshow(kornia.tensor_to_image(res)) # plt.pause(0.001) # RandomAffine trans = kornia.augmentation.RandomAffine(degrees=5, translate=[0.1, 0.1], scale=[0.9, 1.1], shear=[-5, 5]) for i in range(100): res = trans(patch) fig, axes = plt.subplots(1,2,num=type(trans).__name__) ax = axes[0] ax.set_title('patch') ax.imshow(kornia.tensor_to_image(patch.byte())) ax = axes[1] ax.set_title('res') ax.imshow(kornia.tensor_to_image(res.byte())) plt.pause(0.001) # RandomMotionBlur # trans = kornia.augmentation.RandomMotionBlur(9, 35, 0.5) # res = trans(patch) # fig, axes = plt.subplots(1,2,num=type(trans).__name__) # ax = axes[0] # ax.set_title('patch') # ax.imshow(kornia.tensor_to_image(patch.byte())) # ax = axes[1] # ax.set_title('res') # ax.imshow(kornia.tensor_to_image(res.byte())) # # MedianBlur # trans = kornia.filters.MedianBlur((3, 3)) # res = trans(patch) # fig, axes = plt.subplots(1,2,num=type(trans).__name__) # ax = axes[0] # ax.set_title('patch') # ax.imshow(kornia.tensor_to_image(patch.byte())) # ax = axes[1] # ax.set_title('res') # ax.imshow(kornia.tensor_to_image(res.byte())) # # RandomRotation # trans = kornia.augmentation.RandomRotation(degrees=45) # for i in range(100): # res = trans(patch) # fig, axes = plt.subplots(1,2,num=type(trans).__name__) # ax = axes[0] # ax.set_title('patch') # ax.imshow(kornia.tensor_to_image(patch.byte())) # ax = axes[1] # ax.set_title('res') # ax.imshow(kornia.tensor_to_image(res.byte())) # plt.pause(0.001) plt.show() <file_sep>import cv2 import glob import pickle from os.path import join from torch.utils.data import Dataset, DataLoader import numpy as np def permutations(iterable, max_dist=10): # generate indices pairs with distance limitation r = 2 pool = tuple(iterable) n = len(pool) r = n if r is None else r if r > n: return indices = list(range(n)) cycles = list(range(n, n-r, -1)) yield tuple(pool[i] for i in indices[:r]) while n: for i in reversed(range(r)): cycles[i] -= 1 if cycles[i] == 0: indices[i:] = indices[i+1:] + indices[i:i+1] cycles[i] = n - i else: j = cycles[i] indices[i], indices[-j] = indices[-j], indices[i] if abs(indices[1]-indices[0]) > max_dist: break yield tuple(pool[i] for i in indices[:r]) break else: return class AttackDataset(Dataset): def __init__(self, root_dir='data/Human2', n_frames=None, step=1, test=False, transform=None): self.root_dir = root_dir self.img_names = sorted(glob.glob(join(root_dir, 'imgs', '*.jp*'))) self.imgs = [np.transpose(cv2.imread(im_name).astype(np.float32), (2, 0, 1)) for im_name in self.img_names] with open(join(root_dir, 'groundtruth_rect.txt'), "r") as f: gts = f.readlines() split_flag = ',' if ',' in gts[0] else '\t' self.bbox = list(map(lambda x: list(map(int, x.rstrip().split(split_flag))), gts)) # with open(join(root_dir, 'corners.dat'), 'rb') as f: # data = pickle.load(f) # self.rets = data['ret'] # self.corners = data['corners'] if n_frames: self.imgs = self.imgs[:n_frames] # assert len(self.bbox) == len(self.img_names) == self.rets.shape[0] ==self.corners.shape[0] assert len(self.bbox) == len(self.img_names) self.transform = transform self.step = step self.test = test def gen_ind_combinations(self): n_imgs = len(self.img_names) list(permutations(n_imgs, 5)) def __len__(self): return len(self.imgs) - self.step def __getitem__(self, idx): template_idx = 0 if self.test else np.random.randint(self.__len__()) search_idx = idx + self.step # print(self.img_names[template_idx], self.img_names[search_idx]) template_img = self.imgs[template_idx] search_img = self.imgs[search_idx] template_bbox = np.array(self.bbox[template_idx]) search_bbox = np.array(self.bbox[search_idx]) return template_img, template_bbox, search_img, search_bbox if __name__ =='__main__': import kornia dataset = AttackDataset(step=1) dataloader = DataLoader(dataset, batch_size=2) cv2.namedWindow("template", cv2.WND_PROP_FULLSCREEN) cv2.namedWindow("search", cv2.WND_PROP_FULLSCREEN) for data in dataloader: data = list(map(lambda x: x.split(1), data)) for template_img, template_bbox, search_img, search_bbox in zip(*data): x, y, w, h = template_bbox.squeeze() template_img = np.ascontiguousarray(kornia.tensor_to_image(template_img.byte())) cv2.rectangle(template_img, (x, y), (x+w, y+h), (0, 0, 255), 4) cv2.imshow('template', template_img) cv2.waitKey(1) x, y, w, h = search_bbox.squeeze() search_img = np.ascontiguousarray(kornia.tensor_to_image(search_img.byte())) cv2.rectangle(search_img, (x, y), (x+w, y+h), (0, 255, 0), 4) cv2.imshow('search', search_img) cv2.waitKey(0)<file_sep>import torch import numpy as np from matplotlib import pyplot as plt from matplotlib import patches def rand_shift(img_hw, bbox, shift_pos=(-0.2, 0.2), shift_wh=(-0.9, 0.1), cor=0.3): ''' Random shift and scale the bbox shift_pos and shift_wh is offset range cor is the correlation coefficient of delta_w and delta_h ''' device = bbox.device B = bbox.shape[0] x, y, w, h = bbox.detach().split(1, dim=1) cx, cy = x+w//2, y+h//2 delta_x = shift_pos[0] + (shift_pos[1] - shift_pos[0]) * torch.rand((B,1)).to(device) delta_y = shift_pos[0] + (shift_pos[1] - shift_pos[0]) * torch.rand((B,1)).to(device) # delta_w = shift_wh[0] + (shift_wh[1] - shift_wh[0]) * torch.rand((B,1), device=device) # ratio = 1.6*w//h # delta_h = ratio * delta_w + cor * (torch.rand((B, 1), device=device)*2 -1) # delta_h = delta_h.clamp(shift_wh[0], shift_wh[1]) delta_w = shift_wh[0] + (shift_wh[1] - shift_wh[0]) * torch.rand((B,1)).to(device) delta_h = shift_wh[0] + (shift_wh[1] - shift_wh[0]) * torch.rand((B,1)).to(device) cx = cx + w * delta_x cy = cy + h * delta_y w = w * (1 + delta_w) h = h * (1 + delta_h) x = cx - w//2 y = cy - h//2 # Limi img_h, img_w = img_hw x = x.clamp(0, img_w-1) y = y.clamp(0, img_h-1) w = torch.min(w, img_w-x) h = torch.min(h, img_h-y) return torch.cat([x, y, w, h], dim=1).to(bbox.dtype) if __name__ == "__main__": search_bbox = torch.tensor([[201, 291, 102, 312]], device='cuda:0') # search_bbox = torch.tensor([[201, 291, 102, 312], [257, 274, 154, 456]], device='cuda:0') img_hw = (960, 540) fig, ax = plt.subplots(1,1,num='bbox') for i in range(100): track_box = rand_shift(img_hw, search_bbox, (-0.3, 0.3), (-0.8, 0.2)) ax.imshow(np.zeros((img_hw[0], img_hw[1], 3))) for i in range(search_bbox.shape[0]): x, y, w, h = search_bbox[i].cpu().numpy() rect = patches.Rectangle((x, y), w, h, linewidth=1, edgecolor='r', facecolor='none') ax.add_patch(rect) x, y, w, h = track_box[i].cpu().numpy() rect = patches.Rectangle((x, y), w, h, linewidth=5, edgecolor='y', facecolor='none') ax.add_patch(rect) plt.pause(0.001) rect.remove() plt.show() # from matplotlib.pyplot import scatter # shift_wh=(-0.5, 0.8) # for i in range(1000): # delta_w = shift_wh[0] + (shift_wh[1] - shift_wh[0]) * torch.rand((1)) # delta_h = (delta_w + 0.2 * (torch.rand(1)*2 -1)).clamp(shift_wh[0], shift_wh[1]) # scatter(delta_w, delta_h) # # plt.pause(0.001) # plt.show()<file_sep>import glob import argparse import torch import cv2 import kornia import numpy as np from os.path import join, isdir, isfile from torch.utils.data import DataLoader from utils.config_helper import load_config from utils.load_helper import load_pretrain from utils.tracker_config import TrackerConfig from tracker import Tracker, bbox2center_sz from attack_dataset import AttackDataset from masks import warp_patch, scale_bbox, get_bbox_mask_tv parser = argparse.ArgumentParser(description='PyTorch Tracking Demo') args = parser.parse_args() def init(model, template_img, template_bbox): pos_z, size_z = bbox2center_sz(template_bbox) model.template(template_img.to(device), pos_z.to(device), size_z.to(device)) template_img = np.ascontiguousarray(kornia.tensor_to_image(template_img.byte())) x, y, w, h = template_bbox.squeeze().cpu().numpy() x2, y2 = x+w, y+h cv2.rectangle(template_img, (x, y), (x2, y2), (0, 255, 0), 4) cv2.imshow('template', template_img) def track(model, p, search_img, search_bbox): pos_x, size_x = bbox2center_sz(search_bbox) pscore, delta, pscore_size = model.track(search_img.to(device), pos_x.to(device), size_x.to(device)) scale_x = model.penalty.get_scale_x(size_x) assert pscore.shape[0]==1 tuple(map(lambda x: x.squeeze_().cpu().numpy(), [pos_x, size_x, search_bbox])) search_img = np.ascontiguousarray(kornia.tensor_to_image(search_img.byte())) best_pscore_id = np.argmax(pscore.squeeze().detach().cpu().numpy()) pred_in_img = delta.squeeze().detach().cpu().numpy()[:, best_pscore_id] / scale_x.cpu().numpy() lr = pscore_size.squeeze().detach().cpu().numpy()[best_pscore_id] * p.lr # lr for OTB res_x = pred_in_img[0] + pos_x[0] res_y = pred_in_img[1] + pos_x[1] res_w = size_x[0] * (1 - lr) + pred_in_img[2] * lr res_h = size_x[1] * (1 - lr) + pred_in_img[3] * lr target_pos = np.array([res_x, res_y]) target_sz = np.array([res_w, res_h]) im_h, im_w = search_img.shape[0], search_img.shape[1] target_pos[0] = max(0, min(im_w, target_pos[0])) target_pos[1] = max(0, min(im_h, target_pos[1])) target_sz[0] = max(10, min(im_w, target_sz[0])) target_sz[1] = max(10, min(im_h, target_sz[1])) x, y = (target_pos - target_sz/2).astype(int) x2, y2 = (target_pos + target_sz/2).astype(int) cv2.rectangle(search_img, (x, y), (x2, y2), (0, 255, 0), 8) cv2.imshow('SiamMask', search_img) key = cv2.waitKey(1) global i, save_img i += 1 if save_img: status = cv2.imwrite('./results/res_{:03d}.jpg'.format(i), cv2.resize(search_img, (384, 216))) print(status, 'results//res_{:03d}.jpg'.format(i)) return x, y, x2-x, y2-y if __name__ == '__main__': # Setup cf and model file args.resume = "../SiamMask/experiments/siammask_sharp/SiamMask_DAVIS.pth" args.config = "../SiamMask/experiments/siammask_sharp/config_davis.json" cv2.namedWindow("template", cv2.WND_PROP_FULLSCREEN) cv2.namedWindow("SiamMask", cv2.WND_PROP_FULLSCREEN) # Setup device device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') torch.backends.cudnn.benchmark = True # Setup Model cfg = load_config(args) p = TrackerConfig() p.renew() siammask = Tracker(p=p, anchors=cfg['anchors']) if args.resume: assert isfile(args.resume), 'Please download {} first.'.format(args.resume) siammask = load_pretrain(siammask, args.resume) siammask.eval().to(device) model = siammask # Setup Dataset dataloader = DataLoader(AttackDataset(root_dir='data/Phone1', step=1, test=True), batch_size=100) # Load Patch pert_sz_ratio = (0.5, 0.5) patch = cv2.imread('patch_sm.png') patch = kornia.image_to_tensor(patch).to(torch.float) # (3, H, W) patch = patch.clone().detach().requires_grad_(False) # (3, H, W) # For save tracking result as img file i = 0 save_img = False # Random Transformation para_trans_color = {'brightness': 0.1, 'contrast': 0.1, 'saturation': 0.1, 'hue': 0.1} para_trans_affine = {'degrees': 2, 'translate': [0.01, 0.01], 'scale': [0.95, 1.05], 'shear': [-2, 2] } para_gauss = {'kernel_size': (9, 9), 'sigma': (5,5)} para_trans_affine_t = {'degrees': 2, 'translate': [0.01, 0.01], 'scale': [0.95, 1.05], 'shear': [-2, 2] } # Transformation Aug trans_color = kornia.augmentation.ColorJitter(**para_trans_color) trans_affine = kornia.augmentation.RandomAffine(**para_trans_affine) trans_affine_t = kornia.augmentation.RandomAffine(**para_trans_affine_t) avg_filter = kornia.filters.GaussianBlur2d(**para_gauss) bbox = None for data in dataloader: data = list(map(lambda x: x.split(1), data)) for template_img, template_bbox, search_img, search_bbox in zip(*data): # Move tensor to device data_slice = (template_img, template_bbox, search_img, search_bbox, patch) template_img, template_bbox, search_img, search_bbox, patch = tuple(map(lambda x: x.to(device), data_slice)) # Generate masks patch_pos_temp = scale_bbox(template_bbox, pert_sz_ratio) patch_pos_search = scale_bbox(search_bbox, pert_sz_ratio) # Transformation on patch patch_c = patch.expand(template_img.shape[0], -1, -1, -1) patch_c = trans_color(patch_c / 255.0) * 255.0 patch_warpped_t = warp_patch(patch_c, template_img, patch_pos_temp) patch_warpped_s = warp_patch(patch_c, search_img, patch_pos_search) patch_warpped_t = trans_affine_t(patch_warpped_t) patch_warpped_s = trans_affine(patch_warpped_s) patch_template = torch.where(patch_warpped_t==0, template_img, patch_warpped_t) patch_search = torch.where(patch_warpped_s==0, search_img, patch_warpped_s) # Init template if i==0: init(model, patch_template, template_bbox ) # Tracking track_bbox = torch.tensor(bbox).unsqueeze_(dim=0) if bbox else template_bbox bbox = track(model, p, patch_search, track_bbox) <file_sep>from tools.test import * from custom import Custom from torchvision import transforms from matplotlib import pyplot as plt import numpy as np import torch import torch.nn.functional as F import attacker class Custom_(Custom): def __init__(self, pretrain=False, **kwargs): super(Custom_, self).__init__(pretrain=pretrain, **kwargs) def track(self, search, template): # Dylan --> Override Custom.track self.zf = self.features(template) # <-- search = self.features(search) rpn_pred_cls, rpn_pred_loc = self.rpn(self.zf, search) return rpn_pred_cls, rpn_pred_loc def get_subwindow_tracking_(im, pos, model_sz, original_sz, avg_chans): """get differentiable subwindow wrt content subimage around pos. To do: --> F.pad only suport the scalar value padding. --> How resize mode matters? """ if isinstance(pos, float): pos = [pos, pos] sz = original_sz N, C, H, W = im.shape c = (original_sz + 1) / 2 context_xmin = round(pos[0] - c) context_xmax = context_xmin + sz - 1 context_ymin = round(pos[1] - c) context_ymax = context_ymin + sz - 1 left_pad = int(max(0., -context_xmin)) top_pad = int(max(0., -context_ymin)) right_pad = int(max(0., context_xmax - W + 1)) bottom_pad = int(max(0., context_ymax - H + 1)) context_xmin = max(int(context_xmin), 0) context_xmax = min(int(context_xmax), W-1) context_ymin = max(int(context_ymin), 0) context_ymax = min(int(context_ymax), H-1) im = torch.narrow(im, 2, context_ymin, context_ymax-context_ymin+1) im = torch.narrow(im, 3, context_xmin, context_xmax-context_xmin+1) im_sub = F.pad(im, pad=(left_pad, right_pad, top_pad, bottom_pad), mode='constant', value=avg_chans) im_sub = F.interpolate(im_sub, size=(model_sz, model_sz), mode='bilinear') return im_sub def siamese_init(im, target_pos, target_sz, model, hp=None, device='cpu'): state = dict() state['im_h'] = im.shape[0] state['im_w'] = im.shape[1] p = TrackerConfig() p.update(hp, model.anchors) p.renew() net = model p.scales = model.anchors['scales'] p.ratios = model.anchors['ratios'] p.anchor_num = model.anchor_num p.anchor = generate_anchor(model.anchors, p.score_size) avg_chans = np.mean(im, axis=(0, 1)) wc_z = target_sz[0] + p.context_amount * sum(target_sz) hc_z = target_sz[1] + p.context_amount * sum(target_sz) s_z = round(np.sqrt(wc_z * hc_z)) # initialize the exemplar z_crop = get_subwindow_tracking(im, target_pos, p.exemplar_size, s_z, avg_chans) z = Variable(z_crop.unsqueeze(0)) net.template(z.to(device)) if p.windowing == 'cosine': window = np.outer(np.hanning(p.score_size), np.hanning(p.score_size)) elif p.windowing == 'uniform': window = np.ones((p.score_size, p.score_size)) window = np.tile(window.flatten(), p.anchor_num) state['p'] = p state['net'] = net state['avg_chans'] = avg_chans state['window'] = window state['target_pos'] = target_pos state['target_sz'] = target_sz # Dylan -> Add template and n_frame to state dict state['template'] = z.to(device) state['n_frame'] = 0 state['first_im'] = im state['pos_z'] = target_pos state['s_z'] = s_z # <-- return state def siamese_track(state, im, mask_enable=False, refine_enable=False, device='cpu', debug=False): p = state['p'] net = state['net'] avg_chans = state['avg_chans'] window = state['window'] target_pos = state['target_pos'] target_sz = state['target_sz'] wc_x = target_sz[1] + p.context_amount * sum(target_sz) hc_x = target_sz[0] + p.context_amount * sum(target_sz) s_x = np.sqrt(wc_x * hc_x) scale_x = p.exemplar_size / s_x d_search = (p.instance_size - p.exemplar_size) / 2 pad = d_search / scale_x s_x = s_x + 2 * pad crop_box = [target_pos[0] - round(s_x) / 2, target_pos[1] - round(s_x) / 2, round(s_x), round(s_x)] if debug: im_debug = im.copy() crop_box_int = np.int0(crop_box) cv2.rectangle(im_debug, (crop_box_int[0], crop_box_int[1]), (crop_box_int[0] + crop_box_int[2], crop_box_int[1] + crop_box_int[3]), (255, 0, 0), 2) cv2.imshow('search area', im_debug) cv2.waitKey(0) # extract scaled crops for search region x at previous target position x_crop = Variable(get_subwindow_tracking(im, target_pos, p.instance_size, round(s_x), avg_chans).unsqueeze(0)) # # Dylan --> attack on first frame # state['n_frame'] += 1 # state['im'] = im # attackerWraper = attacker.AttackWrapper(x_crop.to(device), state, scale_x, round(s_x)) # template, x_crop = attackerWraper.attack() # # fig, ax = plt.subplots(1,2,num='template_pert & xcrop_pert') # # ax[0].set_title('template_pert') # # ax[0].imshow(template.data.squeeze().permute(1,2,0).cpu().numpy().astype(int)) # # ax[1].set_title('x_crop') # # ax[1].imshow(x_crop.data.squeeze().permute(1,2,0).cpu().numpy().astype(int)) # # plt.pause(0.01) # # # <-- if mask_enable: score, delta, mask = net.track_mask(x_crop.to(device)) else: # Dylan --> add 'template' to net.track input score, delta = net.track(x_crop.to(device), state['template']) # score, delta = net.track(x_crop.to(device), template.to(device)) # <-- delta = delta.permute(1, 2, 3, 0).contiguous().view(4, -1).data.cpu().numpy() score = F.softmax(score.permute(1, 2, 3, 0).contiguous().view(2, -1).permute(1, 0), dim=1).data[:, 1].cpu().numpy() delta[0, :] = delta[0, :] * p.anchor[:, 2] + p.anchor[:, 0] delta[1, :] = delta[1, :] * p.anchor[:, 3] + p.anchor[:, 1] delta[2, :] = np.exp(delta[2, :]) * p.anchor[:, 2] delta[3, :] = np.exp(delta[3, :]) * p.anchor[:, 3] def change(r): return np.maximum(r, 1. / r) def sz(w, h): pad = (w + h) * 0.5 sz2 = (w + pad) * (h + pad) return np.sqrt(sz2) def sz_wh(wh): pad = (wh[0] + wh[1]) * 0.5 sz2 = (wh[0] + pad) * (wh[1] + pad) return np.sqrt(sz2) # size penalty target_sz_in_crop = target_sz*scale_x s_c = change(sz(delta[2, :], delta[3, :]) / (sz_wh(target_sz_in_crop))) # scale penalty r_c = change((target_sz_in_crop[0] / target_sz_in_crop[1]) / (delta[2, :] / delta[3, :])) # ratio penalty penalty = np.exp(-(r_c * s_c - 1) * p.penalty_k) pscore = penalty * score # cos window (motion model) pscore = pscore * (1 - p.window_influence) + window * p.window_influence best_pscore_id = np.argmax(pscore) pred_in_crop = delta[:, best_pscore_id] / scale_x lr = penalty[best_pscore_id] * score[best_pscore_id] * p.lr # lr for OTB res_x = pred_in_crop[0] + target_pos[0] res_y = pred_in_crop[1] + target_pos[1] res_w = target_sz[0] * (1 - lr) + pred_in_crop[2] * lr res_h = target_sz[1] * (1 - lr) + pred_in_crop[3] * lr target_pos = np.array([res_x, res_y]) target_sz = np.array([res_w, res_h]) # for Mask Branch if mask_enable: best_pscore_id_mask = np.unravel_index(best_pscore_id, (5, p.score_size, p.score_size)) delta_x, delta_y = best_pscore_id_mask[2], best_pscore_id_mask[1] if refine_enable: mask = net.track_refine((delta_y, delta_x)).to(device).sigmoid().squeeze().view( p.out_size, p.out_size).cpu().data.numpy() else: mask = mask[0, :, delta_y, delta_x].sigmoid(). \ squeeze().view(p.out_size, p.out_size).cpu().data.numpy() def crop_back(image, bbox, out_sz, padding=-1): a = (out_sz[0] - 1) / bbox[2] b = (out_sz[1] - 1) / bbox[3] c = -a * bbox[0] d = -b * bbox[1] mapping = np.array([[a, 0, c], [0, b, d]]).astype(np.float) crop = cv2.warpAffine(image, mapping, (out_sz[0], out_sz[1]), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=padding) return crop s = crop_box[2] / p.instance_size sub_box = [crop_box[0] + (delta_x - p.base_size / 2) * p.total_stride * s, crop_box[1] + (delta_y - p.base_size / 2) * p.total_stride * s, s * p.exemplar_size, s * p.exemplar_size] s = p.out_size / sub_box[2] back_box = [-sub_box[0] * s, -sub_box[1] * s, state['im_w'] * s, state['im_h'] * s] mask_in_img = crop_back(mask, back_box, (state['im_w'], state['im_h'])) target_mask = (mask_in_img > p.seg_thr).astype(np.uint8) if cv2.__version__[-5] == '4': contours, _ = cv2.findContours(target_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) else: _, contours, _ = cv2.findContours(target_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) cnt_area = [cv2.contourArea(cnt) for cnt in contours] if len(contours) != 0 and np.max(cnt_area) > 100: contour = contours[np.argmax(cnt_area)] # use max area polygon polygon = contour.reshape(-1, 2) # pbox = cv2.boundingRect(polygon) # Min Max Rectangle prbox = cv2.boxPoints(cv2.minAreaRect(polygon)) # Rotated Rectangle # box_in_img = pbox rbox_in_img = prbox else: # empty mask location = cxy_wh_2_rect(target_pos, target_sz) rbox_in_img = np.array([[location[0], location[1]], [location[0] + location[2], location[1]], [location[0] + location[2], location[1] + location[3]], [location[0], location[1] + location[3]]]) target_pos[0] = max(0, min(state['im_w'], target_pos[0])) target_pos[1] = max(0, min(state['im_h'], target_pos[1])) target_sz[0] = max(10, min(state['im_w'], target_sz[0])) target_sz[1] = max(10, min(state['im_h'], target_sz[1])) state['target_pos'] = target_pos state['target_sz'] = target_sz state['score'] = score[best_pscore_id] state['mask'] = mask_in_img if mask_enable else [] state['ploygon'] = rbox_in_img if mask_enable else [] return state <file_sep>import glob import argparse import torch import cv2 import kornia import numpy as np from os.path import join, isdir, isfile from torch.utils.data import DataLoader from utils.config_helper import load_config from utils.load_helper import load_pretrain from utils.tracker_config import TrackerConfig from tracker import Tracker, bbox2center_sz from attack_dataset import AttackDataset parser = argparse.ArgumentParser(description='PyTorch Tracking Demo') parser.add_argument('--resume', default='', type=str, required=True, metavar='PATH',help='path to latest checkpoint (default: none)') parser.add_argument('--config', dest='config', default='config_davis.json', help='hyper-parameter of SiamMask in json format') parser.add_argument('--base_path', default='../../data/tennis', help='datasets') parser.add_argument('--gt_file', default=None, type=str, help='ground truth txt file') parser.add_argument('--cpu', action='store_true', help='cpu mode') args = parser.parse_args() def track(model, p, template_img, template_bbox, search_img, search_bbox): pos_z, size_z = bbox2center_sz(template_bbox) pos_x, size_x = bbox2center_sz(search_bbox) model.template(template_img.to(device), pos_z.to(device), size_z.to(device)) pscore, delta, pscore_size = model.track(search_img.to(device), pos_x.to(device), size_x.to(device)) scale_x = model.penalty.get_scale_x(size_x) assert pscore.shape[0]==1 tuple(map(lambda x: x.squeeze_().numpy(), [pos_x, size_x, template_bbox, search_bbox])) template_img = np.ascontiguousarray(kornia.tensor_to_image(template_img.byte())) search_img = np.ascontiguousarray(kornia.tensor_to_image(search_img.byte())) best_pscore_id = np.argmax(pscore.squeeze().detach().cpu().numpy()) pred_in_img = delta.squeeze().detach().cpu().numpy()[:, best_pscore_id] / scale_x lr = pscore_size.squeeze().detach().cpu().numpy()[best_pscore_id] * p.lr # lr for OTB res_x = pred_in_img[0] + pos_x[0] res_y = pred_in_img[1] + pos_x[1] res_w = size_x[0] * (1 - lr) + pred_in_img[2] * lr res_h = size_x[1] * (1 - lr) + pred_in_img[3] * lr target_pos = np.array([res_x, res_y]) target_sz = np.array([res_w, res_h]) im_h, im_w = template_img.shape[0], template_img.shape[1] target_pos[0] = max(0, min(im_w, target_pos[0])) target_pos[1] = max(0, min(im_h, target_pos[1])) target_sz[0] = max(10, min(im_w, target_sz[0])) target_sz[1] = max(10, min(im_h, target_sz[1])) x, y, w, h = template_bbox x2, y2 = x+w, y+h cv2.rectangle(template_img, (x, y), (x2, y2), (0, 255, 0), 4) cv2.imshow('template', template_img) x, y = (target_pos - target_sz/2).astype(int) x2, y2 = (target_pos + target_sz/2).astype(int) cv2.rectangle(search_img, (x, y), (x2, y2), (0, 255, 0), 8) cv2.imshow('SiamMask', search_img) key = cv2.waitKey(1) return x, y, x2-x, y2-y if __name__ == '__main__': # Setup device device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') torch.backends.cudnn.benchmark = True # Setup Model cfg = load_config(args) p = TrackerConfig() p.renew() siammask = Tracker(p=p, anchors=cfg['anchors']) if args.resume: assert isfile(args.resume), 'Please download {} first.'.format(args.resume) siammask = load_pretrain(siammask, args.resume) siammask.eval().to(device) model = siammask # Setup Dataset dataloader = DataLoader(AttackDataset(root_dir='data/Human2', step=1), batch_size=100) cv2.namedWindow("SiamMask", cv2.WND_PROP_FULLSCREEN) cv2.namedWindow("template", cv2.WND_PROP_FULLSCREEN) bbox = None for data in dataloader: data = list(map(lambda x: x.split(1), data)) for template_img, template_bbox, search_img, search_bbox in zip(*data): track_bbox = torch.tensor(bbox).unsqueeze_(dim=0) if bbox else template_bbox bbox = track(model, p, template_img, template_bbox, search_img, track_bbox) <file_sep>#!/bin/sh cd ../SiamMask export SiamMask=$PWD export PYTHONPATH=$PWD:$PYTHONPATH cd $SiamMask/experiments/siammask_sharp export PYTHONPATH=$PWD:$PYTHONPATH cd ../../../attackTrack # export DISPLAY=saimServer2:10.0 # export CUDA_VISIBLE_DEVICES=1 <file_sep>import glob import argparse import torch import cv2 import numpy as np from os.path import join, isdir, isfile from utils.config_helper import load_config from utils.load_helper import load_pretrain from utils.tracker_config import TrackerConfig from tracker import Tracker, tracker_init, tracker_track parser = argparse.ArgumentParser(description='PyTorch Tracking Demo') parser.add_argument('--resume', default='', type=str, required=True, metavar='PATH',help='path to latest checkpoint (default: none)') parser.add_argument('--config', dest='config', default='config_davis.json', help='hyper-parameter of SiamMask in json format') parser.add_argument('--base_path', default='../../data/tennis', help='datasets') parser.add_argument('--gt_file', default=None, type=str, help='ground truth txt file') parser.add_argument('--cpu', action='store_true', help='cpu mode') args = parser.parse_args() if __name__ == '__main__': # Setup device device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') torch.backends.cudnn.benchmark = True # Setup Model cfg = load_config(args) p = TrackerConfig() p.renew() siammask = Tracker(p=p, anchors=cfg['anchors']) if args.resume: assert isfile(args.resume), 'Please download {} first.'.format(args.resume) siammask = load_pretrain(siammask, args.resume) siammask.eval().to(device) # Parse Image file img_files = sorted(glob.glob(join(args.base_path, '*.jp*'))) ims = [cv2.imread(imf) for imf in img_files] # Select ROI cv2.namedWindow("SiamMask", cv2.WND_PROP_FULLSCREEN) x, y, w, h = 305, 112, 163, 253 if args.gt_file: with open(args.base_path + '/../' + args.gt_file, "r") as f: gts = f.readlines() split_flag = ',' if ',' in gts[0] else '\t' gts = list(map(lambda x: list(map(int, x.rstrip().split(split_flag))), gts)) x, y, w, h = gts[0] else: try: init_rect = cv2.selectROI('SiamMask', ims[0], False, False) gts = None x, y, w, h = init_rect except: exit() toc = 0 for f, im in enumerate(ims): tic = cv2.getTickCount() if f == 0: # init target_pos = np.array([x + w / 2, y + h / 2]) target_sz = np.array([w, h]) state = tracker_init(im, target_pos, target_sz, siammask, device=device) # init tracker state['gts'] = gts state['device'] = device elif f > 0: # tracking state = tracker_track(state, im, siammask, device=device) # track target_pos, target_sz =state['target_pos'], state['target_sz'] x, y = (target_pos - target_sz/2).astype(int) x2, y2 = (target_pos + target_sz/2).astype(int) cv2.rectangle(im, (x, y), (x2, y2), (0, 255, 0), 4) cv2.imshow('SiamMask', im) key = cv2.waitKey(1) if key == ord('q'): break toc += cv2.getTickCount() - tic toc /= cv2.getTickFrequency() fps = f / toc print('SiamMask Time: {:02.1f}s Speed: {:3.1f}fps (with visulization!)'.format(toc, fps)) <file_sep>import torch import kornia import torch.nn.functional as F import numpy as np from custom import Custom class SubWindow(torch.nn.Module): """ Crop image at pos with size_wh: Croppping + Padding + Resizing. Forward Input: im: input images, torch.tensor of shape ([B,] C, H, W) pos: crop postions, torch.tensor of shape ([B,] 2) size_wh: crop sizes, torch.tensor of shape ([B,] ) out_size: 127 or 255 Forward Output: cropped images (B, C, model_sz, model_sz) To do: --> Looping through each image seems like stupid --> How resize mode matters? """ def __init__(self): super(SubWindow, self).__init__() def forward(self, im_, pos_, size_wh_, out_size=127): if len(im_.shape) == 3: im_.unsqueeze_(dim=0) pos_.unsqueeze_(dim=0) size_wh_.unsqueeze_(dim=0) B, C, H, W = im_.shape ims = im_.split(1) poss = pos_.split(1) size_whs = size_wh_.split(1) out_size = (out_size, out_size) out_ims = [] for im, pos, sz in zip(ims, poss, size_whs): avg = im.mean().detach() c = (sz + 1) / 2 context_xmin = torch.round(pos[0,0] - c) context_xmax = context_xmin + sz - 1 context_ymin = torch.round(pos[0,1] - c) context_ymax = context_ymin + sz - 1 left_pad = int(max(0., -context_xmin)) top_pad = int(max(0., -context_ymin)) right_pad = int(max(0., context_xmax - W + 1)) bottom_pad = int(max(0., context_ymax - H + 1)) context_xmin = max(int(context_xmin), 0) context_xmax = min(int(context_xmax), W-1) context_ymin = max(int(context_ymin), 0) context_ymax = min(int(context_ymax), H-1) im = torch.narrow(im, 2, context_ymin, context_ymax-context_ymin+1) im = torch.narrow(im, 3, context_xmin, context_xmax-context_xmin+1) im_sub = F.pad(im, pad=(left_pad, right_pad, top_pad, bottom_pad), mode='constant', value=avg) im_sub = F.interpolate(im_sub, size=out_size, mode='bilinear', align_corners=False) out_ims.append(im_sub) return torch.cat(out_ims) class PenaltyLayer(torch.nn.Module): ''' Penal size change and moving Forward Input: score: (B, 10, 25, 25) delta: (B, 20, 25, 25) target_sz: (B, 2) Forward Output: ''' def __init__(self, anchor, p): super(PenaltyLayer, self).__init__() self.anchor = torch.nn.Parameter(anchor, requires_grad=False) self.penalty_k = p.penalty_k self.window_influence = p.window_influence if p.windowing == 'cosine': window = np.outer(np.hanning(p.score_size), np.hanning(p.score_size)) elif p.windowing == 'uniform': window = np.ones((p.score_size, p.score_size)) window = np.tile(window.flatten(), p.anchor_num) self.window = torch.nn.Parameter(torch.from_numpy(window), requires_grad=False) self.context_amount = p.context_amount self.exemplar_size = p.exemplar_size def forward(self, score, delta, target_sz): B = score.shape[0] ''' detach delta tensor here???? ''' delta = delta.clone().detach().view(B, 4, -1) score = F.softmax(score.view(B, 2, -1), dim=1)[:,1] anchor = self.anchor delta[:, 0, :] = delta[:, 0, :] * anchor[:, 2] + anchor[:, 0] delta[:, 1, :] = delta[:, 1, :] * anchor[:, 3] + anchor[:, 1] delta[:, 2, :] = torch.exp(delta[:, 2, :]) * anchor[:, 2] delta[:, 3, :] = torch.exp(delta[:, 3, :]) * anchor[:, 3] def change(r): return torch.max(r, 1. / r) def sz(w, h): pad = (w + h) * 0.5 sz2 = (w + pad) * (h + pad) return torch.sqrt(sz2) def sz_wh(wh): pad = (wh[:,0] + wh[:,1]) * 0.5 sz2 = (wh[:,0] + pad) * (wh[:,1] + pad) return torch.sqrt(sz2) # size penalty scale_x = self.get_scale_x(target_sz) target_sz_in_crop = (target_sz.T*scale_x).T.clone().detach() s_c = change(sz(delta[:, 2, :], delta[:, 3, :]).T / sz_wh(target_sz_in_crop)).T # scale penalty r_c = change((target_sz_in_crop[:,0] / target_sz_in_crop[:,1]) / (delta[:, 2, :] / delta[:, 3, :]).T).T # ratio penalty penalty = torch.exp(-(r_c * s_c - 1) * self.penalty_k) pscore_size = penalty * score # cos window (motion model) pscore = pscore_size * (1 - self.window_influence) + self.window * self.window_influence return pscore, delta, pscore_size def get_scale_x(self, target_sz): device = target_sz.device target_sz = target_sz.cpu().numpy() if len(target_sz.shape) == 1: target_sz = np.expand_dims(target_sz, axis=0) wc = target_sz[:,0] + self.context_amount * target_sz.sum(axis=1) hc = target_sz[:,1] + self.context_amount * target_sz.sum(axis=1) crop_sz = np.sqrt(wc * hc).round() scale_x = self.exemplar_size / crop_sz return torch.from_numpy(scale_x).requires_grad_(False).to(device) class Tracker(Custom): def __init__(self, p, pretrain=False, **kwargs): super(Tracker, self).__init__(pretrain=False, **kwargs) self.p = p self.get_subwindow = SubWindow() self.set_all_anchors(0, size=p.score_size) self.penalty = PenaltyLayer(anchor=self.all_anchors, p=p) def set_all_anchors(self, image_center, size): self.anchor.generate_all_anchors(image_center, size) all_anchors = self.anchor.all_anchors[1].reshape(4, -1).transpose(1, 0) self.all_anchors = torch.from_numpy(all_anchors).float() def get_crop_sz(self, target_sz, is_search=False): device = target_sz.device target_sz = target_sz.cpu().numpy() if len(target_sz.shape) == 1: target_sz = np.expand_dims(target_sz, axis=0) wc = target_sz[:,0] + self.p.context_amount * target_sz.sum(axis=1) hc = target_sz[:,1] + self.p.context_amount * target_sz.sum(axis=1) crop_sz = np.sqrt(wc * hc).round() if is_search: scale_x = self.p.exemplar_size / crop_sz d_search = (self.p.instance_size - self.p.exemplar_size) / 2 pad = d_search / scale_x crop_sz = crop_sz + 2 * pad return torch.from_numpy(crop_sz).requires_grad_(False).to(device) def template(self, template_img, template_pos, template_sz): crop_sz = self.get_crop_sz(template_sz) self.template_cropped = self.get_subwindow(template_img, template_pos, crop_sz, out_size=self.p.exemplar_size) self.zf = self.features(self.template_cropped) def track(self, search_img, target_pos, target_sz): crop_sz = self.get_crop_sz(target_sz, is_search=True) self.search_cropped = self.get_subwindow(search_img, target_pos, crop_sz, out_size=self.p.instance_size) search = self.features(self.search_cropped) rpn_pred_cls, rpn_pred_loc = self.rpn(self.zf, search) self.rpn_pred_cls, self.rpn_pred_loc = rpn_pred_cls, rpn_pred_loc pscore, delta, pscore_size = self.penalty(rpn_pred_cls, rpn_pred_loc, target_sz) return pscore, delta, pscore_size def bbox2center_sz(bbox): x, y, w, h = bbox.split(1, dim=1) pos = torch.cat([x+w//2, y+h//2], dim=1) sz = torch.cat([w, h], dim=1) return pos, sz def tracker_init(im, target_pos, target_sz, model, device='cpu'): state = dict() state['im_h'] = im.shape[0] state['im_w'] = im.shape[1] # initialize the exemplar model.template(kornia.image_to_tensor(im).to(device).float(), torch.from_numpy(target_pos).to(device), torch.from_numpy(target_sz).to(device) ) state['target_pos'] = target_pos state['target_sz'] = target_sz return state def tracker_track(state, im, model, device='cpu', debug=False): target_pos = state['target_pos'] target_sz = state['target_sz'] p = model.p wc_x = target_sz[1] + p.context_amount * sum(target_sz) hc_x = target_sz[0] + p.context_amount * sum(target_sz) s_x = np.sqrt(wc_x * hc_x) scale_x = p.exemplar_size / s_x pscore, delta, pscore_size = model.track(kornia.image_to_tensor(im).unsqueeze(dim=0).to(device).float(), torch.from_numpy(target_pos).unsqueeze(dim=0).to(device), torch.from_numpy(target_sz).unsqueeze(dim=0).to(device)) best_pscore_id = np.argmax(pscore.squeeze().detach().cpu().numpy()) pred_in_crop = delta.squeeze().detach().cpu().numpy()[:, best_pscore_id] / scale_x lr = pscore_size.squeeze().detach().cpu().numpy()[best_pscore_id] * p.lr # lr for OTB res_x = pred_in_crop[0] + target_pos[0] res_y = pred_in_crop[1] + target_pos[1] res_w = target_sz[0] * (1 - lr) + pred_in_crop[2] * lr res_h = target_sz[1] * (1 - lr) + pred_in_crop[3] * lr target_pos = np.array([res_x, res_y]) target_sz = np.array([res_w, res_h]) target_pos[0] = max(0, min(state['im_w'], target_pos[0])) target_pos[1] = max(0, min(state['im_h'], target_pos[1])) target_sz[0] = max(10, min(state['im_w'], target_sz[0])) target_sz[1] = max(10, min(state['im_h'], target_sz[1])) state['target_pos'] = target_pos state['target_sz'] = target_sz return state if __name__ == "__main__": import glob from os.path import join import cv2 # setup device device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') torch.backends.cudnn.benchmark = True # load images and gt fpath = '/DataServer/car/car-1/img/' N_IMS = 2 img_files = sorted(glob.glob(join(fpath, '*.jp*'))) ims = [cv2.imread(imf) for imf in img_files[:N_IMS]] ims = torch.tensor(ims, device=device, dtype=float).permute(0,3,1,2) with open(fpath + '/../groundtruth.txt', "r") as f: gts = f.readlines() split_flag = ',' if ',' in gts[0] else '\t' gts = list(map(lambda x: list(map(int, x.rstrip().split(split_flag))), gts)) gts = np.array(gts)[:N_IMS] pos = torch.tensor(gts[:,:2] + gts[:,2:]/2, device=device) sz = torch.tensor(gts[:,2:], device=device).max(dim=1)[0] # test SubWindow model = SubWindow() out = model(ims, pos, sz) for i in range(out.shape[0]): cv2.imshow('im_ori', kornia.tensor_to_image(ims[i].byte())) cv2.imshow('im', kornia.tensor_to_image(out[i].byte())) cv2.waitKey(0)<file_sep>import cv2 import glob import pickle import numpy as np from os.path import join def findChessboard(img, cnrx, cnry): chessboard_flags = cv2.CALIB_CB_ADAPTIVE_THRESH + cv2.CALIB_CB_NORMALIZE_IMAGE ret, corners = cv2.findChessboardCorners(img, (cnrx, cnry), flags=chessboard_flags) if ret: print("Checkerboard found") # Refining corners position with sub-pixels based algorithm subpix_criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.01) corners = cv2.cornerSubPix(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), corners, (5, 5), (-1, -1), subpix_criteria) else: print("Failed to parse checkerboard pattern in image") return ret, corners def main(img_root, save_fpath=None, display=True, cnrx =5, cnry=7): im_names = sorted(glob.glob(join(img_root, '*.jp*'))) if save_fpath: data_ret, data_corners = [], [] for im_name in im_names: print(im_name) img = cv2.imread(im_name) ret, corners = findChessboard(img, cnrx=cnrx, cnry=cnry) if save_fpath: if not ret: corners = np.zeros((cnrx*cnry, 1, 2)) data_ret.append(ret) data_corners.append(corners) if display: cv2.drawChessboardCorners(img, (cnrx, cnry), corners, ret) cv2.imshow('img', img) cv2.waitKey(1) if save_fpath: data = {'ret': np.array(data_ret), 'corners': np.array(data_corners)} with open(save_fpath, 'wb') as f: pickle.dump(data, f) print('Results saved in ', save_fpath) if __name__ == '__main__': import fire fire.Fire(main) # python script/findChessboard.py data/Human2/imgs/ --display=False --save_fpath=data/Human2/corners.dat <file_sep>from datasets.siam_rpn_dataset import AnchorTargetLayer from utils.anchors import Anchors from utils.tracker_config import TrackerConfig from utils.bbox_helper import IoU, corner2center, center2corner from models.siammask_sharp import select_cross_entropy_loss, get_cls_loss, weight_l1_loss from masks import get_bbox_mask, get_circle_mask, scale_bbox, warp, warp_patch import test from torch.autograd import Variable from torchvision import transforms import torch.nn.functional as F import torch import cv2 import kornia import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches from collections import namedtuple Corner = namedtuple('Corner', 'x1 y1 x2 y2') Center = namedtuple('Center', 'x y w h') class AttackWrapper(object): def __init__(self, x_crop, state, scale_x, s_x): self.x_crop = x_crop self.s_x = s_x self.state = state self.model = state['net'] self.scale_x = scale_x def attack(self): if self.state['n_frame'] == 1: return self.gen_template() else: return self.gen_xcrop() def gen_template(self): num_iters = 500 adam_lr = 10 mu, sigma = 127, 5 label_thr_iou = 0.2 pert_sz_ratio = (0.6, 0.3) # Load state state = self.state device = state['device'] p = state['p'] s_z = state['s_z'] # Get imgs and mask tensor im_shape = state['im'].shape[0:2] bbox_pert_temp = scale_bbox(state['gts'][0], pert_sz_ratio) bbox_pert_xcrop = scale_bbox(state['gts'][state['n_frame']], pert_sz_ratio) mask_template = get_bbox_mask(shape=im_shape, bbox=bbox_pert_temp, mode='tensor').to(device) mask_xcrop = get_bbox_mask(shape=im_shape, bbox=bbox_pert_xcrop, mode='tensor').to(device) im_template = kornia.image_to_tensor(state['first_im']).to(device) im_xcrop = kornia.image_to_tensor(state['im']).to(device) # Get Label track_res, score_res, pscore_res = self.get_tracking_result(state['template'], self.x_crop) labels = self.get_label(track_res, thr_iou=label_thr_iou, need_iou=True) im_template = im_template.unsqueeze(dim=0).to(torch.float) im_xcrop = im_xcrop.unsqueeze(dim=0).to(torch.float) bbox_pert_temp = torch.tensor(bbox_pert_temp).unsqueeze(dim=0).to(device) bbox_pert_xcrop = torch.tensor(bbox_pert_xcrop).unsqueeze(dim=0).to(device) pert_sz = (100, 75) # pert = (mu + sigma * torch.randn(3, pert_sz[0], pert_sz[1])).clamp(0,255) pert = cv2.resize(cv2.imread('data/patchnew0.jpg'), (pert_sz[1], pert_sz[0])) # W, H pert = kornia.image_to_tensor(pert).to(torch.float) pert = pert.clone().detach().to(device).requires_grad_(True).to(im_template.device) # (3, H, W) optimizer = torch.optim.Adam([pert], lr=adam_lr) for i in range(num_iters): patch_warped_template = warp_patch(pert, im_template, bbox_pert_temp) patch_warped_search = warp_patch(pert, im_xcrop, bbox_pert_xcrop) patch_template = torch.where(mask_template==1, patch_warped_template, im_template) patch_search = torch.where(mask_xcrop==1, patch_warped_search, im_xcrop) template = test.get_subwindow_tracking_(patch_template, state['pos_z'], p.exemplar_size, round(state['s_z']), 0) x_crop = test.get_subwindow_tracking_(patch_search, state['target_pos'], p.instance_size, round(self.s_x), 0) score, delta = self.model.track(x_crop, template) ################### Show Loss and Delta Change ###################### # if i%10==0: # score_data = F.softmax(score.view(score.shape[0], 2, -1), dim=1)[:,1] # delta_data = delta.view(delta.shape[0], 4, -1).data # res_cx, res_cy, res_w, res_h = track_res # track_res_data = (res_cx-res_w/2, res_cy-res_h/2, res_w, res_h) # self.show_pscore_delta(score_data, delta_data, track_res_data) # self.show_attacking(track_res, score_res, pscore_res, template, x_crop) loss = self.loss2(score, delta, pscore_res, labels) optimizer.zero_grad() loss.backward() optimizer.step() pert.data = (pert.data).clamp(0, 255) # fig, ax = plt.subplots(1,2,num='x_crop & template') # ax[0].set_title('template') # ax[0].imshow(kornia.tensor_to_image(template.byte())) # ax[1].set_title('x_crop') # ax[1].imshow(kornia.tensor_to_image(x_crop.byte())) # plt.pause(0.01) state['pert'] = pert.detach() state['pert_template'] = template.detach() state['pert_sz_ratio'] = pert_sz_ratio # self.show_label(labels, track_res) # self.show_attacking(track_res, score_res, pscore_res, template, x_crop) plt.show() return template, x_crop def gen_xcrop(self): # state = self.state # im_pert_template = state['im_pert_template'] # pert_sz_ratio = state['pert_sz_ratio'] # p = state['p'] # im_shape = state['im'].shape[0:2] # bbox_pert_xcrop = scale_bbox(state['gts'][state['n_frame']], pert_sz_ratio) # mask_xcrop = get_bbox_mask(shape=im_shape, bbox=bbox_pert_xcrop, mode='tensor').to(state['device']) # bbox_pert_temp = scale_bbox(state['gts'][0], pert_sz_ratio) # bbox_pert_xcrop = scale_bbox(state['gts'][state['n_frame']], pert_sz_ratio) # im_pert_warped = warp(im_pert_template, bbox_pert_temp, bbox_pert_xcrop) # im_xcrop = kornia.image_to_tensor(state['im']).to(state['device']) # im_pert_xcrop = im_xcrop * (1-mask_xcrop) + im_pert_warped * mask_xcrop # x_crop = test.get_subwindow_tracking_(im_pert_xcrop, state['target_pos'], p.instance_size, round(self.s_x), 0) state = self.state pert = state['pert'] pert_sz_ratio = state['pert_sz_ratio'] p = state['p'] device = state['device'] im_shape = state['im'].shape[0:2] bbox_pert_xcrop = scale_bbox(state['gts'][state['n_frame']], pert_sz_ratio) mask_xcrop = get_bbox_mask(shape=im_shape, bbox=bbox_pert_xcrop, mode='tensor').to(device) bbox_pert_xcrop = torch.tensor(bbox_pert_xcrop).unsqueeze(dim=0).to(device) im_xcrop = kornia.image_to_tensor(state['im']).to(torch.float).unsqueeze(dim=0).to(device) patch_warped_search = warp_patch(pert, im_xcrop, bbox_pert_xcrop) patch_search = torch.where(mask_xcrop==1, patch_warped_search, im_xcrop) x_crop = test.get_subwindow_tracking_(patch_search, state['target_pos'], p.instance_size, round(self.s_x), 0) cv2.imshow('template', kornia.tensor_to_image(state['pert_template'].byte())) cv2.imshow('x_crop', kornia.tensor_to_image(x_crop.byte())) cv2.waitKey(1) return state['pert_template'], x_crop def get_crop_box(self): state = self.state p = state['p'] x, y, w, h = state['gts'][state['n_frame']] target_pos = np.array([x + w / 2, y + h / 2]) target_sz = np.array([w, h]) wc_x = target_sz[1] + p.context_amount * sum(target_sz) hc_x = target_sz[0] + p.context_amount * sum(target_sz) s_x = np.sqrt(wc_x * hc_x) scale_x = p.exemplar_size / s_x d_search = (p.instance_size - p.exemplar_size) / 2 pad = d_search / scale_x s_x = s_x + 2 * pad crop_box = [target_pos[0] - round(s_x) / 2, target_pos[1] - round(s_x) / 2, round(s_x), round(s_x)] return tuple(map(int, crop_box)) def get_tracking_result(self, template, x_crop=None): p = self.state['p'] window = self.state['window'] target_pos = self.state['target_pos'] target_sz = self.state['target_sz'] if x_crop is None: x_crop = self.x_crop score_, delta = self.model.track(x_crop, template) delta = delta.permute(1, 2, 3, 0).contiguous().view(4, -1).data.cpu().numpy() score = F.softmax(score_.permute(1, 2, 3, 0).contiguous().view(2, -1).permute(1, 0), dim=1).data[:, 1].cpu().numpy() delta[0, :] = delta[0, :] * p.anchor[:, 2] + p.anchor[:, 0] delta[1, :] = delta[1, :] * p.anchor[:, 3] + p.anchor[:, 1] delta[2, :] = np.exp(delta[2, :]) * p.anchor[:, 2] delta[3, :] = np.exp(delta[3, :]) * p.anchor[:, 3] # size penalty target_sz_in_crop = target_sz*self.scale_x s_c = change(sz(delta[2, :], delta[3, :]) / (sz_wh(target_sz_in_crop))) # scale penalty r_c = change((target_sz_in_crop[0] / target_sz_in_crop[1]) / (delta[2, :] / delta[3, :])) # ratio penalty penalty = np.exp(-(r_c * s_c - 1) * p.penalty_k) pscore = penalty * score # cos window (motion model) pscore = pscore * (1 - p.window_influence) + window * p.window_influence best_pscore_id = np.argmax(pscore) pred_in_crop = delta[:, best_pscore_id] # / scale_x lr = penalty[best_pscore_id] * score[best_pscore_id] * p.lr # lr for OTB res_cx = int(pred_in_crop[0] + 127) res_cy = int(pred_in_crop[1] + 127) res_w = int(target_sz_in_crop[0] * (1 - lr) + pred_in_crop[2] * lr) res_h = int(target_sz_in_crop[1] * (1 - lr) + pred_in_crop[3] * lr) return (res_cx, res_cy, res_w, res_h), score, pscore def get_label(self, track_res, thr_iou=0.2, need_iou=False): anchors = self.state['p'].anchor anchor_num = anchors.shape[0] clss = np.zeros((anchor_num,), dtype=np.int64) delta = np.zeros((4, anchor_num), dtype=np.float32) tcx, tcy, tw, th = track_res cx, cy, w, h = anchors[:,0]+127, anchors[:,1]+127, anchors[:,2], anchors[:,3] x1, y1, x2, y2 = center2corner(np.array((cx,cy,w,h))) # delta delta[0] = (tcx - cx) / w delta[1] = (tcy - cy) / h delta[2] = np.log(tw / w) delta[3] = np.log(th / h) # IoU overlap = IoU([x1, y1, x2, y2], center2corner(track_res)) pos = np.where(overlap > thr_iou) clss[pos] = 1 if not need_iou: return clss, delta else: return clss, delta, overlap def loss(self, score, delta, pscore_res, labels): clss_label, deltas_label, ious = labels clss_label = torch.from_numpy(clss_label).cuda() deltas_lable = torch.tensor(deltas_label, device='cuda').reshape((1, 4, 5, 25, 25)) clss_pred = self.model.softmax(score).view(-1, 2) pos = Variable(clss_label.data.eq(1).nonzero().squeeze()).cuda() neg = Variable(clss_label.data.eq(0).nonzero().squeeze()).cuda() loss_clss_pos = get_cls_loss(clss_pred, clss_label, pos) loss_clss_neg = get_cls_loss(clss_pred, clss_label, neg) deltas_pred = delta loss_weight = torch.Tensor(pscore_res).cuda().reshape(1, 5, 25, 25) loss_delta = weight_l1_loss(deltas_pred, deltas_lable, loss_weight) loss = loss_clss_pos + loss_clss_neg + loss_delta print('Loss -> clss_pos: {:.2f}, clss_neg: {:.2f}, delta: {:.2f}'\ .format(loss_clss_pos.cpu().data.numpy(),\ loss_clss_neg.cpu().data.numpy(),\ loss_delta.cpu().data.numpy())) return loss def loss2(self, score, delta, pscore_res, labels): clss_label, deltas_label, ious = labels # clss_label = torch.from_numpy(clss_label).cuda() # pos = clss_label.data.eq(1).nonzero().squeeze().cuda() # neg = clss_label.data.eq(0).nonzero().squeeze().cuda() # deltas_label = torch.tensor(deltas_label, device='cuda') # ###################################### # b, a2, h, w = score.size() # assert b==1 # score = score.view(b, 2, a2//2, h, w).permute(0, 2, 3, 4, 1).contiguous() # # clss_pred = F.softmax(score, dim=4).view(-1,2)[...,1] # clss_pred = F.log_softmax(score, dim=4).view(-1,2) # loss_clss = F.nll_loss(clss_pred, clss_label) # pred_pos = torch.index_select(clss_pred, 0, pos) # pred_neg = torch.index_select(clss_pred, 0, neg) # # loss_clss = torch.max(pred_neg) - torch.max(pred_pos) # ###################################### # deltas_pred = delta.view(4,-1) # diff = (deltas_pred - deltas_label).abs().sum(dim=0) # loss_delta = torch.index_select(diff, 0, pos).mean() # print('Loss -> pred_pos: {:.2f}, pred_neg: {:.2f}, clss: {:.2f}, delta: {:.5f}'\ # .format(torch.max(pred_pos).cpu().data.numpy(),\ # torch.max(pred_neg).cpu().data.numpy(),\ # loss_clss.cpu().data.numpy(),\ # loss_delta.cpu().data.numpy())) target = np.array([1, 1]) deltas_pred = delta.view(-1,4) diff = deltas_pred[..., 2:] - torch.from_numpy(target).cuda() diff = diff.abs().mean(dim=1) # (3125) pscore_res = torch.from_numpy(pscore_res).cuda() idx = torch.topk(pscore_res, k=10, dim=0)[1] loss_delta = diff.take(idx).mean() print('loss_delta: {:.5f} '.format(loss_delta.cpu().data.numpy())) return loss_delta def show_label(self, labels, gt_bbox): clss, _, ious = labels p = self.state['p'] res_cx, res_cy, res_w, res_h = gt_bbox fig = plt.figure('Label') ax = fig.add_subplot(121) plt.imshow(np.sum(ious.reshape(5,25,25), axis=0)) ax = fig.add_subplot(122) ax.imshow(self.x_crop.data.squeeze().cpu().numpy().transpose(1,2,0).astype(int)) rect = patches.Rectangle((res_cx-res_w/2, res_cy-res_h/2), res_w, res_h, linewidth=2, edgecolor='r', facecolor='none') ax.add_patch(rect) for i in range(p.anchor.shape[0]): cx, cy, w, h = p.anchor[i,0], p.anchor[i,1], p.anchor[i,2], p.anchor[i,3] bb_center = patches.Circle((cx+127, cy+127), color='b', radius=0.5) ax.add_patch(bb_center) for i in range(p.anchor.shape[0]): if clss[i]==1: cx, cy, w, h = p.anchor[i,0], p.anchor[i,1], p.anchor[i,2], p.anchor[i,3] bb_center = patches.Circle((cx+127, cy+127), color='r', radius=0.5) ax.add_patch(bb_center) plt.pause(0.01) def show_attacking(self, track_res, score, pscore, template, x_crop=None): fig, axes = plt.subplots(2,3, num='Attacking') ax = axes[0,0] ax.set_title('Result') res_cx, res_cy, res_w, res_h = track_res ax.imshow(x_crop.data.squeeze().cpu().numpy().transpose(1,2,0).astype(int)) rect = patches.Rectangle((res_cx-res_w/2, res_cy-res_h/2), res_w, res_h, linewidth=1, edgecolor='r', facecolor='none') ax.add_patch(rect) ax = axes[0,1] ax.set_title('Pscore_bef') ax.imshow(pscore.reshape(5,25,25).sum(axis=0)) ax = axes[0,2] ax.set_title('score_bef') ax.imshow(0.2*score.reshape(5,25,25).sum(axis=0)) if x_crop is None: x_crop = self.x_crop track_res, score, pscore = self.get_tracking_result(template, x_crop) ax = axes[0,0] res_cx, res_cy, res_w, res_h = track_res rect = patches.Rectangle((res_cx-res_w/2, res_cy-res_h/2), res_w, res_h, linewidth=1, edgecolor='y', facecolor='none') ax.add_patch(rect) ax = axes[1,0] ax.set_title('template') ax.imshow(template.data.squeeze().cpu().numpy().transpose(1,2,0).astype(int)) ax = axes[1,1] ax.set_title('Pscore') ax.imshow(pscore.reshape(5,25,25).sum(axis=0)) ax = axes[1,2] ax.set_title('score') ax.imshow(0.2*score.reshape(5,25,25).sum(axis=0)) plt.pause(0.01) def show_pscore_delta(self, pscore, delta, track_bbox, fig_num='pscore_delta'): if torch.is_tensor(delta): delta = delta.detach().cpu().numpy() if not len(delta.shape) == 3: delta = delta.reshape((-1, 4, 3125)) if type(track_bbox) != np.array: track_bbox = np.array(track_bbox).reshape(-1, 4) # anchor = self.model.all_anchors.detach().cpu().numpy() anchor = self.state['p'].anchor cx = delta[:, 0, :] * anchor[:, 2] + anchor[:, 0] cy = delta[:, 1, :] * anchor[:, 3] + anchor[:, 1] w = np.exp(delta[:, 2, :]) * anchor[:, 2] h = np.exp(delta[:, 3, :]) * anchor[:, 3] iou_list = list() for i in range(track_bbox.shape[0]): tx, ty, tw, th = track_bbox[i] tcx, tcy = tx+tw/2, ty+th/2 overlap = IoU(center2corner(np.array((cx[i]+127,cy[i]+127,w[i],h[i]))), center2corner(np.array((tcx,tcy,tw,th)))) iou_list.append(overlap) ious = np.array(iou_list) # (B, 3125) ious_img = ious.mean(axis=0).reshape(-1, 25)# (B*5, 3125) fig, axes = plt.subplots(1,2,num=fig_num) ax = axes[0] ax.set_title('score') ax.imshow(pscore.detach().reshape(-1, 3125).mean(dim=0).reshape(-1, 25).cpu().numpy(), vmin=0, vmax=1) ax = axes[1] ax.set_title('delta') ax.imshow(ious_img, vmin=0, vmax=1) plt.pause(0.001) return ious, ious_img def norms(Z): """Compute norms over all but the first dimension""" return Z.view(Z.shape[0], -1).norm(dim=1)[:,None,None,None] def change(r): return np.maximum(r, 1. / r) def sz(w, h): pad = (w + h) * 0.5 sz2 = (w + pad) * (h + pad) return np.sqrt(sz2) def sz_wh(wh): pad = (wh[0] + wh[1]) * 0.5 sz2 = (wh[0] + pad) * (wh[1] + pad) return np.sqrt(sz2) def get_bbox_in_searchWindow(orig_w, orig_h, target_wh, patch_wh): w = int(orig_w * patch_wh / target_wh) h = int(orig_h * patch_wh / target_wh) x = int(patch_wh/2 - w/2) y = int(patch_wh/2 - h/2) return x, y, w, h if __name__ == "__main__": import matplotlib.patches as patches import numpy as np img = cv2.imread('../SiamMask/data/tennis/00000.jpg') img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img_h, img_w = img.shape[0:2] x, y, w, h = 305, 112, 163, 253 # crop the search region -> z_crop target_pos = np.array([x + w / 2, y + h / 2]) target_sz = np.array([w, h]) avg_chans = np.mean(img) wc_x = target_sz[0] + 0.5 * sum(target_sz) hc_x = target_sz[1] + 0.5 * sum(target_sz) s_x = round(np.sqrt(wc_x * hc_x)) scale_x = 127 / s_x d_search = 127 pad = d_search / scale_x s_x = s_x + 2 * pad z_crop = test.get_subwindow_tracking_(img, target_pos, 255, s_x, avg_chans) plt.figure() ax = plt.subplot(221) ax.imshow(z_crop.astype(int)) x_, y_, w_, h_ = get_bbox_in_searchWindow(w, h, s_x, 255) rect = patches.Rectangle((x_,y_),w_,h_,linewidth=1,edgecolor='r',facecolor='none') ax.add_patch(rect) ax = plt.subplot(222) ax.imshow(img) rect = patches.Rectangle((x,y),w,h,linewidth=1,edgecolor='r',facecolor='none') ax.add_patch(rect) mask = circle_mask(shape=img.shape[0:2], loc=target_pos.astype(int), diameter=int(target_sz.min()/5)) ax = plt.subplot(223) ax.imshow(mask) mask ax = plt.subplot(224) ax.imshow plt.show() <file_sep>docker build . --build-arg SSH_PUBKEY="$(cat ~/.ssh/id_rsa.pub)" -t li-attack docker run -ti \ -p 6024:22 \ -p 6025:6006 \ --hostname attackSer2 \ --name li-attack \ --gpus 'all' \ --shm-size 16g \ -v /home/li:/workspace \ -v /mnt/DataServer/li:/DataServer \ li-attack<file_sep>import cv2 from pathlib import Path def main(video_file, resize=None, rotate=False): dir_path = Path(video_file) # import pdb; pdb.set_trace() Path(dir_path.parents[0]).joinpath('imgs').mkdir(parents=True, exist_ok=True) vc = cv2.VideoCapture(video_file) c = 1 if vc.isOpened(): rval, frame = vc.read() else: rval = False while rval: rval, frame = vc.read() if not rval: break if resize: img_h, img_w = frame.shape[:2] img_h = int(img_h * resize) img_w = int(img_w * resize) print(img_h, img_w) frame = cv2.resize(frame, (img_w, img_h)) if rotate: frame = frame.transpose(1,0,2) out = cv2.imwrite(str(dir_path.parents[0])+'/imgs/' + '{0:04d}'.format(c) + '.jpg', frame) print(out, c, str(dir_path.parents[0])+'/imgs/' + '{0:04d}'.format(c) + '.jpg') c = c + 1 vc.release() if __name__ == '__main__': import fire fire.Fire(main) <file_sep># attackTrack Adversarial Attack on Visual Object Tracking ## Setup SiamMask 1. Clone the repository **on the ../ path** ``` git clone https://github.com/foolwood/SiamMask.git ``` 2. Download the SiamMask pretrained model ``` cd ../SiamMask/experiments/siammask_sharp wget http://www.robots.ox.ac.uk/~qwang/SiamMask_VOT.pth wget http://www.robots.ox.ac.uk/~qwang/SiamMask_DAVIS.pth ``` ## Setup PythonPath in attackTrack ``` . export.sh ``` ## Run Demo ``` python demo.py \ --resume ../SiamMask/experiments/siammask_sharp/SiamMask_DAVIS.pth \ --config ../SiamMask/experiments/siammask_sharp/config_davis.json \ --gt_file groundtruth_rect.txt \ --base_path ../DylanTrack/dataset/OTB/Car24/img/ ``` ## Kornia Bug Fix ``` # kornia.color.hsv.py L140: # avoid gradient to NAN when Backward s: torch.Tensor = deltac / (v + 1e-20) ```<file_sep>import imageio import glob from os.path import join if __name__ == "__main__": root_dir = './results' filenames = sorted(glob.glob(join(root_dir, '*.jp*'))) images = [] for filename in filenames: images.append(imageio.imread(filename)) imageio.mimwrite(join(root_dir,'movie.gif'), images, duration=0.01) # # For longer movies, use the streaming approach: # with imageio.get_writer('/path/to/movie.gif', mode='I') as writer: # for filename in filenames: # image = imageio.imread(filename) # writer.append_data(image)<file_sep>import numpy as np import torch import kornia import torch.nn.functional as F def get_circle_mask(shape=(127,127), loc=(64,64), diameter=12, sharpness=40): """Return a circular mask of a given shape""" x1 = loc[0]-diameter y1 = loc[1]-diameter x2 = loc[0]+diameter y2 = loc[1]+diameter assert x1>=0 and y1>=0 and x2<=shape[0] and y2<=shape[1] x = np.linspace(-1, 1, 2*diameter) y = np.linspace(-1, 1, 2*diameter) xx, yy = np.meshgrid(x, y, sparse=True) z = (xx**2 + yy**2) ** sharpness circle = 1 - np.clip(z, -1, 1) mask = np.zeros(shape) mask[y1:y2, x1:x2] = circle mask = np.expand_dims(mask, axis=2) mask = np.broadcast_to(mask, (shape[0],shape[1],3)).astype(np.float32) return mask def get_bbox_mask(shape=(127,127), bbox=(50,50,20,20), mode='numpy'): """Return a rectangle mask of a given shape""" if type(bbox) == torch.Tensor: bbox = bbox.cpu() bbox = np.array(bbox).reshape(-1,4) masks = list() for i in range(bbox.shape[0]): x,y,w,h = bbox[i] assert (x+w)<shape[1] and (y+h)<shape[0] mask = np.zeros(shape) mask[y:y+h, x:x+w] = 1 mask = np.expand_dims(mask, axis=2) masks.append(np.broadcast_to(mask, (shape[0],shape[1],3)).astype(np.float32)) return np.array(masks) if mode=='numpy' else torch.tensor(masks).permute(0,3,1,2) def get_bbox_mask_tv(shape=(127,127), bbox=(50,50,20,20)): """Return a rectangle mask of a given shape""" masks = list() for i in range(bbox.shape[0]): x,y,w,h = bbox[i] assert (x+w)<shape[1] and (y+h)<shape[0] mask = torch.zeros(shape, device='cuda') mask[y:y+h, x:x+w] = 1 mask = mask.expand(3,-1,-1) masks.append(mask) return torch.stack(masks, dim=0) def scale_bbox(bbox, scale_wh): # todo: unify operation on tensor and int list if type(bbox) == np.ndarray or type(bbox) == torch.Tensor: bbox = bbox.clone().detach() c_x = bbox[:, 0] + bbox[:, 2]//2 c_y = bbox[:, 1] + bbox[:, 3]//2 scale_w, scale_h = scale_wh bbox[:, 2] = bbox[:, 2] * scale_w bbox[:, 3] = bbox[:, 3] * scale_h bbox[:, 0] = c_x - bbox[:, 2]//2 bbox[:, 1] = c_y - bbox[:, 3]//2 return bbox else: x, y, w, h = bbox c_x = x + w//2 c_y = y + h//2 scale_w, scale_h = scale_wh w *= scale_w h *= scale_h x = c_x - w//2 y = c_y - h//2 return tuple(map(int, (x, y, w, h))) def warp(pert_tensor, bbox_src, bbox_dest): ''' Input: pert_tensor : Tensor (3, W, H) bbox_src and bbox_dest: (B, 4) Output: Tensor (B, 3, W, H) ''' if type(bbox_src) == torch.Tensor: bbox_src = bbox_src.cpu() bbox_dest = bbox_dest.cpu() bbox_src = np.array(bbox_src).reshape(-1,4) bbox_dest = np.array(bbox_dest).reshape(-1,4) masks = list() for i in range(bbox_src.shape[0]): x, y, w, h = bbox_src[i] points_src = torch.FloatTensor([[[x, y], [x+w, y], [x, y+h], [x+w, y+h],]]) x, y, w, h = bbox_dest[i] points_dst = torch.FloatTensor([[[x, y], [x+w, y], [x, y+h], [x+w, y+h],]]) M = kornia.get_perspective_transform(points_src, points_dst).to(pert_tensor.device) size = pert_tensor.shape[-2:] masks.append(kornia.warp_perspective(pert_tensor, M, size)) return torch.cat(masks) def warp_patch(patch_tensor, img_tensor, bbox_dest): ''' Apply the patch to images. Input: patch_tensor : Tensor ([B, ]3, h0, w0) img_tensor: Tensor(B, 3, H, W) bbox_dest: Tensor(B, 4) Output: Tensor (B, 3, H, W) ''' B = bbox_dest.shape[0] x, y, w, h = 0, 0, patch_tensor.shape[-1], patch_tensor.shape[-2] points_src = torch.FloatTensor([[[x, y], [x+w-1, y], [x, y+h-1], [x+w-1, y+h-1],]]) points_src = points_src.expand(bbox_dest.shape[0],4,2).to(img_tensor.device) xy = torch.stack((bbox_dest[:,0],bbox_dest[:,1]), dim=1) x2y = torch.stack((bbox_dest[:,0]+bbox_dest[:,2]-1, bbox_dest[:,1]),dim=1) xy2 = torch.stack((bbox_dest[:,0], bbox_dest[:,1]+bbox_dest[:,3]-1),dim=1) x2y2 = torch.stack((bbox_dest[:,0]+bbox_dest[:,2]-1, bbox_dest[:,1]+bbox_dest[:,3]-1),dim=1) points_dst = torch.stack([xy, x2y, xy2, x2y2], dim=1).to(torch.float32) M = kornia.get_perspective_transform(points_src, points_dst).to(img_tensor.device) if len(patch_tensor.shape) == 3: patch_tensor = patch_tensor.expand(B, -1, -1, -1) patch_warped = kornia.warp_perspective(patch_tensor, M, (img_tensor.shape[2], img_tensor.shape[3])) # res_img = torch.where((patch_warped==0), img_tensor, patch_warped) return patch_warped def pad_patch(patch_tensor, img_tensor, bbox_dest): ''' Pad the patch to the size of img_tensor. Input: patch_tensor : Tensor ([B, ]3, h, w) img_tensor: Tensor(B, 3, H, W) bbox_dest: Tensor(B, 4) Output: Tensor (B, 3, H, W) ''' B = bbox_dest.shape[0] if len(patch_tensor.shape) == 3: patch_tensor = patch_tensor.expand(B, -1, -1, -1) size = img_tensor.shape[-2:] pad_h, pad_w = (np.array(size) - np.array(patch_tensor.shape[-2:]) ) / 2 patch_paded = F.pad(patch_tensor, pad=(int(pad_w+0.5), int(pad_w), int(pad_h+0.5), int(pad_h)), value=0) return patch_paded if __name__ == '__main__': import cv2 img = cv2.imread('data/Human1/imgs/0001.jpg') img2 = cv2.imread('data/Human1/imgs/0100.jpg') H, W = 400, 300 patch1 = cv2.resize(cv2.imread('data/patchnew0.jpg'), (W,H)) patch2 = cv2.resize(cv2.imread('patches/patch_sm.png'), (W,H)) bbox = [[200,200,207,395], [310,157,220,250]] cv2.namedWindow('img', cv2.WND_PROP_FULLSCREEN) x, y, w, h = bbox[0] cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 4) cv2.imshow('img', img) cv2.namedWindow('img2', cv2.WND_PROP_FULLSCREEN) x, y, w, h = bbox[1] cv2.rectangle(img2, (x, y), (x+w, y+h), (0, 255, 0), 4) cv2.imshow('img2', img2) cv2.imshow('patch1', patch1) cv2.imshow('patch2', patch2) img_tensor = kornia.image_to_tensor(img).unsqueeze(0).to(torch.float32) img_tensor2 = kornia.image_to_tensor(img2).unsqueeze(0).to(torch.float32) patch_tensor1 = kornia.image_to_tensor(patch1).to(torch.float32) patch_tensor2 = kornia.image_to_tensor(patch2).to(torch.float32) bbox = torch.tensor(bbox) bbox_dest = scale_bbox(bbox, (0.6, 0.3)) mask = get_bbox_mask_tv(img_tensor.shape[-2:], bbox) cv2.namedWindow('mask1', cv2.WND_PROP_FULLSCREEN) cv2.namedWindow('mask2', cv2.WND_PROP_FULLSCREEN) cv2.imshow('mask1', kornia.tensor_to_image(mask[0])) cv2.imshow('mask2', kornia.tensor_to_image(mask[1])) res_img = warp_patch(torch.stack([patch_tensor1, patch_tensor2], 0), torch.cat([img_tensor, img_tensor2], 0), bbox_dest) cv2.namedWindow('res_img1', cv2.WND_PROP_FULLSCREEN) cv2.namedWindow('res_img2', cv2.WND_PROP_FULLSCREEN) cv2.imshow('res_img1', kornia.tensor_to_image(res_img[0].byte())) cv2.imshow('res_img2', kornia.tensor_to_image(res_img[1].byte())) cv2.waitKey(0)
b9cba5586d18599d9b81877239f142e863945454
[ "Markdown", "Python", "Shell" ]
19
Python
enkiwang/attackTrack
3578873fd3aec33e3b58e5aee9d372139e993d93
055b749c778986cad902c65015c0ce709dc0d776
refs/heads/master
<file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #include "common/environment_internal.h" #pragma warning(disable: 4172) namespace pmwcas { unique_ptr_t<IEnvironment> Environment::environment_; Status Environment::Initialize(std::function<Status(IEnvironment*&)> create, std::function<void(IEnvironment*)> destroy) { if(environment_.get()) { return Status::Corruption("Environment has already been initialized."); } IEnvironment* environment; RETURN_NOT_OK(create(environment)); environment_ = unique_ptr_t<IEnvironment>(environment, destroy); return Status::OK(); } std::unordered_map<std::thread::id, Thread::TlsList*> Thread::registry_; std::mutex Thread::registryMutex_; void Thread::RegisterTls(uint64_t *ptr, uint64_t val) { auto id = std::this_thread::get_id(); std::unique_lock<std::mutex> lock(registryMutex_); if (registry_.find(id) == registry_.end()) { registry_.emplace(id, new TlsList); } registry_[id]->emplace_back(ptr, val); } void Thread::ClearTls(bool destroy) { std::unique_lock<std::mutex> lock(registryMutex_); auto iter = registry_.find(id_); if (iter != registry_.end()) { auto *list = iter->second; for (auto &entry : *list) { *entry.first = entry.second; } if (destroy) { delete list; registry_.erase(id_); } else { list->clear(); } } } void Thread::ClearRegistry(bool destroy) { std::unique_lock<std::mutex> lock(registryMutex_); for (auto &r : registry_) { auto *list = r.second; for (auto &entry : *list) { *entry.first = entry.second; } if (destroy) { delete list; } else { list->clear(); } } if (destroy) { registry_.clear(); } } } // namespace pmwcas <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #include "common/allocator_internal.h" #include "common/environment_internal.h" #include "include/pmwcas.h" namespace pmwcas { Status InitLibrary(std::function<Status(IAllocator*&)> create_allocator, std::function<void(IAllocator*)> destroy_allocator) { return Allocator::Initialize(create_allocator, destroy_allocator); } Status InitLibrary(std::function<Status(IAllocator*&)> create_allocator, std::function<void(IAllocator*)> destroy_allocator, std::function<Status(IEnvironment*&)> create_environment, std::function<void(IEnvironment*)> destroy_environment) { RETURN_NOT_OK(Allocator::Initialize(create_allocator, destroy_allocator)); return Environment::Initialize(create_environment, destroy_environment); } void UninitLibrary() { Environment::Uninitialize(); Allocator::Uninitialize(); } } // namespace pmwcas <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once #include "common/allocator_internal.h" #include "mwcas/mwcas.h" #include "util/atomics.h" #include "util/macros.h" #include "util/random_number_generator.h" namespace pmwcas { struct DListNode { const static int kCacheLineSize = 64; // Put prev and next in the same cacheline so that a single NVRAM::Flush is // enough. DListNode* prev; // 8-byte DListNode* next; // 8-byte uint32_t payload_size; // 4-byte char padding[kCacheLineSize - sizeof(DListNode*) * 2 - sizeof(uint32_t)]; DListNode(DListNode* p, DListNode* n, uint32_t s) : prev(p), next(n), payload_size(s) { } DListNode() : DListNode(nullptr, nullptr, 0) { } inline char* GetPayload() { return (char *)this + sizeof(*this); } }; class IDList { public: static DListNode* NewNode(DListNode* prev, DListNode* next, uint32_t payload_size) { DListNode *node = nullptr; Allocator::Get()->Allocate((void **) &node, sizeof(DListNode) + payload_size); new (node) DListNode(prev, next, payload_size); return node; } static const int kSyncUnknown = 0; static const int kSyncMwCAS = 1; static const int kSyncCAS = 2; IDList(int sync) : head_(nullptr, &tail_, 0), tail_(&head_, nullptr, 0), sync_method_(sync) { } ~IDList() {} /// Insert [node] right before [next] virtual Status InsertBefore(DListNode* next, DListNode* node, bool already_protected) = 0; /// Insert [node] right after [prev] virtual Status InsertAfter(DListNode* prev, DListNode* node, bool already_protected) = 0; /// Delete [node] virtual Status Delete(DListNode* node, bool already_protected) = 0; /// Figure out the node lined up after [node] virtual DListNode* GetNext(DListNode* node, bool already_protected = false) = 0; virtual DListNode* GetPrev(DListNode* node, bool already_protected = false) = 0; inline DListNode* GetHead() { return &head_; } inline DListNode* GetTail() { return &tail_; } inline int GetSyncMethod() { return sync_method_; } /// Verify the links between each pair of nodes (including head and tail). /// For single-threaded cases only, no CC whatsoever. void SingleThreadSanityCheck(); protected: DListNode head_; DListNode tail_; int sync_method_; }; /// A lock-free doubly linked list using single-word CAS, /// based off of the following paper: /// <NAME> and <NAME>. 2008. /// Lock-free deques and doubly linked lists. /// J. Parallel Distrib. Comput. 68, 7 (July 2008), 1008-1020. class CASDList : public IDList { private: /// MSB of the next pointer to indicate the underlying node is logically /// deleted. static const uint64_t kNodeDeleted = ((uint64_t)1 << 60); /// An RNG for back off RandomNumberGenerator rng{}; inline void backoff() { uint64_t loops = rng.Generate(500); while(loops--) {} }; public: #ifdef PMEM /// The same dirty bit as in persistent MwCAS. static const uint64_t kDirtyFlag = Descriptor::kDirtyFlag; #endif CASDList() : IDList(kSyncCAS), rng(__rdtsc(), 0, 500) {} /// Insert [node] in front of [next] - [node] might end up before another node /// in case [prev] is being deleted or due to concurrent insertions at the /// same spot. virtual Status InsertBefore(DListNode* next, DListNode* node, bool already_protected = false) override; /// Similar to InsertBefore, but try to insert [node] after [prev]. virtual Status InsertAfter(DListNode* prev, DListNode* node, bool already_protected = false) override; /// Delete [node] virtual Status Delete(DListNode* node, bool already_protected = false) override; virtual DListNode* GetNext(DListNode* node, bool already_protected = false) override; virtual DListNode* GetPrev(DListNode* node, bool) override; /// Set the deleted bit on the given node inline void MarkNodePointer(DListNode** node) { #ifdef PMEM uint64_t flags = kNodeDeleted | kDirtyFlag; #else uint64_t flags = kNodeDeleted; #endif while (true) { DListNode* node_ptr = *node; RAW_CHECK(node != &head_.next, "cannot mark head node's next pointer"); if (((uint64_t)node_ptr & kNodeDeleted) || node_ptr == CompareExchange64Ptr(node, (DListNode*)((uint64_t)node_ptr | flags), node_ptr)) { break; } } } inline DListNode* ReadPersist(DListNode** node) { auto* node_ptr = *node; #ifdef PMEM if(((uint64_t)node_ptr & kDirtyFlag)) { NVRAM::Flush(sizeof(uint64_t), node); CompareExchange64Ptr(node, (DListNode*)((uint64_t)node_ptr & ~kDirtyFlag), node_ptr); } return (DListNode*)((uint64_t)node_ptr & ~kDirtyFlag); #else return node_ptr; #endif } /// Extract the real underlying node (masking out the MSB and flush if needed) inline DListNode* DereferenceNodePointer(DListNode** node) { DListNode* ret = nullptr; #ifdef PMEM ret = ReadPersist(node); #else ret = *node; #endif return (DListNode*)((uint64_t)ret & ~kNodeDeleted); } inline static bool MarkedNext(DListNode* node) { return (uint64_t)node->next & kNodeDeleted; } inline static bool MarkedPrev(DListNode* node) { return (uint64_t)node->prev & kNodeDeleted; } private: DListNode* CorrectPrev(DListNode* prev, DListNode* node); }; /// A lock-free doubly-linked list using multi-word CAS class MwCASDList : public IDList { private: DescriptorPool* descriptor_pool_; /// MSB of the next pointer to indicate the underlying node is logically /// deleted. static const uint64_t kNodeDeleted = ((uint64_t)1 << 60); public: MwCASDList(DescriptorPool* pool) : IDList(kSyncMwCAS), descriptor_pool_(pool) {} /// Insert [node] in front of [next] - [node] might end up before another node /// in case [prev] is being deleted or due to concurrent insertions at the /// same spot. virtual Status InsertBefore(DListNode* next, DListNode* node, bool already_protected) override; /// Similar to InsertBefore, but try to insert [node] after [prev]. virtual Status InsertAfter(DListNode* prev, DListNode* node, bool already_protected) override; /// Delete [node] virtual Status Delete(DListNode* node, bool already_protected) override; inline virtual DListNode* GetNext(DListNode* node, bool already_protected = false) override { node = (DListNode*)((uint64_t)node & ~kNodeDeleted); DListNode* next = ResolveNodePointer(&node->next, already_protected); return (DListNode*)((uint64_t)next & ~kNodeDeleted); } inline virtual DListNode* GetPrev(DListNode* node, bool already_protected = false) override { node = (DListNode*)((uint64_t)node & ~kNodeDeleted); DListNode* prev = ResolveNodePointer(&node->prev, already_protected); return (DListNode*)((uint64_t)prev & ~kNodeDeleted); } inline EpochManager* GetEpoch() { return descriptor_pool_->GetEpoch(); } private: /// Return a stable value using MwCAS's GetValue(). /// Note: [node] must be a pointer to a pointer to a node, /// where it denotes the node pointer's real location, as /// we're casting it to an MwCAS field. E.g., it cannot be /// the address of a pointer parameter passed in to the caller. inline DListNode* ResolveNodePointer(DListNode** node, bool already_protected) { int64_t stable_ptr = 0; if(already_protected) { stable_ptr = ((MwcTargetField<uint64_t> *)node)->GetValueProtected(); } else { stable_ptr = ((MwcTargetField<uint64_t> *)node)->GetValue( descriptor_pool_->GetEpoch()); } return (DListNode*)stable_ptr; } }; class DListCursor { private: IDList* list_; DListNode* current_node_; bool unprot; public: DListCursor(IDList* list) : list_(list), current_node_(list->GetHead()) { if(list->GetSyncMethod() == IDList::kSyncMwCAS) { auto* epoch = ((MwCASDList*)list_)->GetEpoch(); unprot = !epoch->IsProtected(); if(unprot) { epoch->Protect(); } } } ~DListCursor() { if(unprot && list_->GetSyncMethod() == IDList::kSyncMwCAS) { ((MwCASDList*)list_)->GetEpoch()->Unprotect(); } } inline void Reset() { current_node_ = list_->GetHead(); } inline DListNode* Next() { current_node_ = list_->GetNext(current_node_, true); return current_node_; } inline DListNode* Prev() { current_node_ = list_->GetPrev(current_node_, true); return current_node_; } }; } // namespace pmwcas <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #ifdef WIN32 #include <Windows.h> #undef ERROR // Avoid collision of ERROR definition in Windows.h with glog #endif #include "include/pmwcas.h" #include "mwcas/mwcas.h" #include "util/atomics.h" namespace pmwcas { bool MwCASMetrics::enabled = false; CoreLocal<MwCASMetrics*> MwCASMetrics::instance; DescriptorPartition::DescriptorPartition(EpochManager* epoch, DescriptorPool* pool) : desc_pool(pool), allocated_desc(0) { free_list = nullptr; garbage_list = new GarbageListUnsafe; auto s = garbage_list->Initialize(epoch, pool->GetDescPerPartition()); RAW_CHECK(s.ok(), "garbage list initialization failure"); } DescriptorPartition::~DescriptorPartition() { garbage_list->Uninitialize(); delete garbage_list; } DescriptorPool::DescriptorPool( uint32_t requested_pool_size, uint32_t requested_partition_count, bool enable_stats) : pool_size_(0), desc_per_partition_(0), partition_count_(0), partition_table_(nullptr), next_partition_(0) { MwCASMetrics::enabled = enable_stats; if (enable_stats) { auto s = MwCASMetrics::Initialize(); RAW_CHECK(s.ok(), "failed initializing metric objects"); } auto s = epoch_.Initialize(); RAW_CHECK(s.ok(), "epoch initialization failure"); // Round up pool size to the nearest power of 2 pool_size_ = 1; while (requested_pool_size > pool_size_) { pool_size_ *= 2; } // Round partitions to a power of two but no higher than 1024 partition_count_ = 1; for(uint32_t exp = 1; exp < 10; exp++) { if(requested_partition_count <= partition_count_) { break; } partition_count_ *= 2; } desc_per_partition_ = pool_size_ / partition_count_; RAW_CHECK(desc_per_partition_ > 0, "descriptor per partition is 0"); partition_table_ = (DescriptorPartition*)malloc(sizeof(DescriptorPartition)*partition_count_); RAW_CHECK(nullptr != partition_table_, "out of memory"); for(uint32_t i = 0; i < partition_count_; ++i) { new(&partition_table_[i]) DescriptorPartition(&epoch_, this); } // A new descriptor pool area always comes zeroed. RAW_CHECK(pool_size_ > 0, "invalid pool size"); // Create a new pool Allocator::Get()->AllocateAligned( (void **) &descriptors_, sizeof(Descriptor) * pool_size_, kCacheLineSize); RAW_CHECK(descriptors_, "out of memory"); #ifdef PMDK // Set the new pmdk_pool addr pmdk_pool_ = (uint64_t) reinterpret_cast<PMDKAllocator*>(Allocator::Get())->GetPool(); #endif InitDescriptors(); } #ifdef PMEM void DescriptorPool::Recovery(bool enable_stats) { MwCASMetrics::enabled = enable_stats; auto s = MwCASMetrics::Initialize(); RAW_CHECK(s.ok(), "failed initializing metric objects"); new(&epoch_) EpochManager; s = epoch_.Initialize(); RAW_CHECK(s.ok(), "epoch initialization failure"); RAW_CHECK(partition_count_ > 0, "invalid partition count"); partition_table_ = (DescriptorPartition *) malloc(sizeof(DescriptorPartition) * partition_count_); RAW_CHECK(nullptr != partition_table_, "out of memory"); for (uint32_t i = 0; i < partition_count_; ++i) { new(&partition_table_[i]) DescriptorPartition(&epoch_, this); } RAW_CHECK(descriptors_, "invalid descriptor array pointer"); RAW_CHECK(pool_size_ > 0, "invalid pool size"); #ifdef PMDK auto new_pmdk_pool = reinterpret_cast<PMDKAllocator *>(Allocator::Get())->GetPool(); uint64_t adjust_offset = (uint64_t) new_pmdk_pool - pmdk_pool_; descriptors_ = reinterpret_cast<Descriptor *>((uint64_t) descriptors_ + adjust_offset); #else Metadata *metadata = (Metadata*)((uint64_t)this - sizeof(Metadata)); RAW_CHECK((uint64_t)metadata->initial_address == (uint64_t)metadata, "invalid initial address"); RAW_CHECK(metadata->descriptor_count == pool_size_, "wrong descriptor pool size"); #endif // PMEM // begin recovery process // If it is an existing pool, see if it has anything in it uint64_t in_progress_desc = 0, redo_words = 0, undo_words = 0; if (descriptors_[0].status_ != Descriptor::kStatusInvalid) { // Must not be a new pool which comes with everything zeroed for (uint32_t i = 0; i < pool_size_; ++i) { auto &desc = descriptors_[i]; if (desc.status_ == Descriptor::kStatusInvalid) { // Must be a new pool - comes with everything zeroed but better // find this as we look at the first descriptor. RAW_CHECK(i == 0, "corrupted descriptor pool/data area"); break; } desc.assert_valid_status(); #ifdef PMDK // Let's set the real addresses first for (int w = 0; w < desc.count_; ++w) { auto &word = desc.words_[w]; if((uint64_t)word.address_ == Descriptor::kAllocNullAddress) { continue; } word.address_ = (uint64_t *) ((uint64_t) word.address_ + adjust_offset); } #endif // Otherwise do recovery uint32_t status = desc.status_ & ~Descriptor::kStatusDirtyFlag; if (status == Descriptor::kStatusFinished) { continue; } else if (status == Descriptor::kStatusUndecided || status == Descriptor::kStatusFailed) { in_progress_desc++; for (int w = 0; w < desc.count_; ++w) { auto &word = desc.words_[w]; if((uint64_t)word.address_ == Descriptor::kAllocNullAddress){ continue; } uint64_t val = Descriptor::CleanPtr(*word.address_); #ifdef PMDK val += adjust_offset; #endif if (val == (uint64_t) &desc || val == (uint64_t) &word) { // If it's a CondCAS descriptor, then MwCAS descriptor wasn't // installed/persisted, i.e., new value (succeeded) or old value // (failed) wasn't installed on the field. If it's an MwCAS // descriptor, then the final value didn't make it to the field // (status is Undecided). In both cases we should roll back to old // value. *word.address_ = word.old_value_; #ifdef PMEM word.PersistAddress(); #endif undo_words++; LOG(INFO) << "Applied old value 0x" << std::hex << word.old_value_ << " at 0x" << word.address_; } } } else { RAW_CHECK(status == Descriptor::kStatusSucceeded, "invalid status"); in_progress_desc++; for (int w = 0; w < desc.count_; ++w) { auto &word = desc.words_[w]; if((uint64_t)word.address_ == Descriptor::kAllocNullAddress){ continue; } uint64_t val = Descriptor::CleanPtr(*word.address_); #ifdef PMDK val += adjust_offset; #endif RAW_CHECK(val != (uint64_t) &word, "invalid field value"); if (val == (uint64_t) &desc) { *word.address_ = word.new_value_; #ifdef PMEM word.PersistAddress(); #endif redo_words++; LOG(INFO) << "Applied new value 0x" << std::hex << word.new_value_ << " at 0x" << word.address_; } } } for (int w = 0; w < desc.count_; ++w) { if((uint64_t)desc.words_[w].address_ == Descriptor::kAllocNullAddress){ continue; } int64_t val = *desc.words_[w].address_; RAW_CHECK((val & ~Descriptor::kDirtyFlag) != ((int64_t) &desc | Descriptor::kMwCASFlag), "invalid word value"); RAW_CHECK((val & ~Descriptor::kDirtyFlag) != ((int64_t) &desc | Descriptor::kCondCASFlag), "invalid word value"); } } LOG(INFO) << "Found " << in_progress_desc << " in-progress descriptors, rolled forward " << redo_words << " words, rolled back " << undo_words << " words"; } #ifdef PMDK // Set the new pmdk_pool addr pmdk_pool_ = (uint64_t) reinterpret_cast<PMDKAllocator *>(Allocator::Get())->GetPool(); #endif InitDescriptors(); } #endif void DescriptorPool::InitDescriptors() { // (Re-)initialize descriptors. Any recovery business should be done by now, // start as a clean slate. RAW_CHECK(descriptors_, "null descriptor pool"); memset(descriptors_, 0, sizeof(Descriptor) * pool_size_); // Distribute this many descriptors per partition RAW_CHECK(pool_size_ > partition_count_, "provided pool size is less than partition count"); for (uint32_t i = 0; i < partition_count_; ++i) { DescriptorPartition *p = partition_table_ + i; for (uint32_t d = 0; d < desc_per_partition_; ++d) { Descriptor *desc = descriptors_ + i * desc_per_partition_ + d; new (desc) Descriptor(p); desc->next_ptr_ = p->free_list; p->free_list = desc; } } } DescriptorPool::~DescriptorPool() { MwCASMetrics::Uninitialize(); } Descriptor* DescriptorPool::AllocateDescriptor(Descriptor::AllocateCallback ac, Descriptor::FreeCallback fc) { thread_local DescriptorPartition* tls_part = nullptr; if(!tls_part) { // Sometimes e.g., benchmark data loading will create new threads when // starting real work. So % partition_count_ here is safe. This is so far // the only safe case allowed. auto index = next_partition_.fetch_add(1, std::memory_order_seq_cst) % partition_count_; // TODO: Currently we actually require strictly TLS partitions - there is no // CC whatsoever for partitions. tls_part = &partition_table_[index]; // Track the partition pointer handed out to this thread. Thread::RegisterTls((uint64_t*)&tls_part, (uint64_t)nullptr); } Descriptor* desc = tls_part->free_list; while(!desc) { // See if we can scavenge some descriptors from the garbage list tls_part->garbage_list->GetEpoch()->BumpCurrentEpoch(); auto scavenged = tls_part->garbage_list->Scavenge(); tls_part->allocated_desc -= scavenged; desc = tls_part->free_list; RAW_CHECK(scavenged > 0 || !desc, "scavenged but still not descriptor"); MwCASMetrics::AddDescriptorScavenge(); } tls_part->free_list = desc->next_ptr_; MwCASMetrics::AddDescriptorAlloc(); RAW_CHECK(desc, "null descriptor pointer"); desc->allocate_callback_ = ac ? ac : Descriptor::DefaultAllocateCallback; desc->free_callback_ = fc ? fc : Descriptor::DefaultFreeCallback; return desc; } Descriptor::Descriptor(DescriptorPartition* partition) : owner_partition_(partition) { Initialize(); } void Descriptor::Initialize() { status_ = kStatusFinished; count_ = 0; next_ptr_ = nullptr; #ifndef NDEBUG memset(words_, 0, sizeof(WordDescriptor) * DESC_CAP); #endif } void* Descriptor::DefaultAllocateCallback(size_t size) { void *mem = nullptr; Allocator::Get()->AllocateAligned(&mem, size, kCacheLineSize); return mem; } void Descriptor::DefaultFreeCallback(void* context, void* p) { Allocator::Get()->FreeAligned(p); } uint32_t Descriptor::AddEntry(uint64_t* addr, uint64_t oldval, uint64_t newval, uint32_t recycle_policy) { // IsProtected() checks are quite expensive, use DCHECK instead of RAW_CHECK. DCHECK(owner_partition_->garbage_list->GetEpoch()->IsProtected()); DCHECK(IsCleanPtr(oldval)); DCHECK(IsCleanPtr(newval) || newval == kNewValueReserved); int insertpos = GetInsertPosition(addr); RAW_CHECK(insertpos >= 0, "invalid insert position"); words_[insertpos].address_ = addr; words_[insertpos].old_value_ = oldval; words_[insertpos].new_value_ = newval; words_[insertpos].status_address_ = &status_; words_[insertpos].recycle_policy_ = recycle_policy; ++count_; return insertpos; } uint32_t Descriptor::AllocateAndAddEntry(uint64_t* addr, uint64_t oldval, size_t size, uint32_t recycle_policy) { // IsProtected() checks are quite expensive, use DCHECK instead of RAW_CHECK. DCHECK(owner_partition_->garbage_list->GetEpoch()->IsProtected()); DCHECK(IsCleanPtr(oldval)); int insertpos = GetInsertPosition(addr); RAW_CHECK(insertpos >= 0, "invalid insert position"); words_[insertpos].address_ = addr; words_[insertpos].old_value_ = oldval; words_[insertpos].new_value_ = (uint64_t)allocate_callback_(size); RAW_CHECK(words_[insertpos].new_value_, "allocation failed"); words_[insertpos].status_address_ = &status_; words_[insertpos].recycle_policy_ = recycle_policy; ++count_; return insertpos; } int Descriptor::GetInsertPosition(uint64_t* addr) { DCHECK(uint64_t(addr) % sizeof(uint64_t) == 0); RAW_CHECK(count_ < DESC_CAP, "too many words"); int insertpos = count_; for(int i = count_ - 1; i >= 0; i--) { if((uint64_t)addr != Descriptor::kAllocNullAddress && words_[i].address_ == addr) { // Can't allow duplicate addresses because it makes the desired result of // the operation ambigous. If two different new values are specified for // the same address, what is the correct result? Also, if the operation // fails we can't guarantee that the old values will be correctly // restored. return -2; } } return insertpos; } #ifdef PMEM uint32_t Descriptor::ReadPersistStatus() { auto curr_status = *& status_; uint32_t stable_status = curr_status & ~kStatusDirtyFlag; if(curr_status & kStatusDirtyFlag) { // We have a persistent descriptor that includes all the old and new values // needed for recovery, so only persist the new status. PersistStatus(); // Now we can clear the dirty bit; this has to be a CAS, somebody else might // be doing the same and already proceeded to further phases. CompareExchange32(&status_, stable_status, curr_status); } return stable_status; } #endif /// Installing mwcas descriptor must be a conditional CAS (double-compare /// single-swap, RDCSS): a thread can only CAS in a pointer to the mwcas /// descriptor if the mwcas operation is still in Undecided status. Otherwise /// if a thread delays the CAS until another thread T1 (as a helper) has /// finished the mwcas operation, and another thread T2 conducted yet another /// mwcas to change the value back to the original value, T1 when resumes /// would produce incorrect result. An example: /// /// T1 mwcas(A1 [1 - 2], A2 [3 - 4]) /// Suppose T1 went to sleep after installed descriptor on A1. /// T2 comes to help the mwcas operation and finished. /// Now A1=2, A2=4. /// Suppose T3 now conducted an mwcas that reversed the previous mwcas: /// Now A1=1, A2=3 again. /// Suppose T1 now resumes execution, it will continue to install /// descriptor on A2, which will succeed because it has value 3. /// T1 then continues to CAS in new values, which fails for A1 but the /// algo will think it's ok (assuming some other thread did it). The /// installation for A2, however, will succeeded because it contains /// a descriptor. Now A1=1, A2=4, an inconsistent state. uint64_t Descriptor::CondCAS(uint32_t word_index, uint64_t dirty_flag) { auto* w = &words_[word_index]; uint64_t cond_descptr = SetFlags((uint64_t)w, kCondCASFlag); retry: uint64_t ret = CompareExchange64(w->address_, cond_descptr, w->old_value_); if(IsCondCASDescriptorPtr(ret)) { // Already a CondCAS descriptor (ie a WordDescriptor pointer) WordDescriptor* wd = (WordDescriptor*)CleanPtr(ret); RAW_CHECK(wd->address_ == w->address_, "wrong address"); uint64_t dptr = SetFlags(wd->GetDescriptor(), kMwCASFlag | dirty_flag); uint64_t desired = *wd->status_address_ == kStatusUndecided ? dptr : wd->old_value_; if(*(volatile uint64_t*)wd->address_ != ret) { goto retry; } auto rval = CompareExchange64( wd->address_, *wd->status_address_ == kStatusUndecided ? dptr : wd->old_value_, ret); if(rval == ret) { if(desired == dptr) { // Another competing operation succeeded, return return dptr; } } // Retry this operation goto retry; } else if(ret == w->old_value_) { uint64_t mwcas_descptr = SetFlags(this, kMwCASFlag | dirty_flag); CompareExchange64(w->address_, status_ == kStatusUndecided ? mwcas_descptr : w->old_value_, cond_descptr); } // ret could be a normal value or a pointer to a MwCAS descriptor return ret; } #ifdef RTM bool Descriptor::RTMInstallDescriptors(uint64_t dirty_flag) { uint64_t mwcas_descptr = SetFlags(this, kMwCASFlag | dirty_flag); uint64_t tries = 0; static const uint64_t kMaxTries = 10000; retry: if(_XBEGIN_STARTED == _xbegin()) { for(uint32_t i = 0; i < count_; ++i) { WordDescriptor* wd = &words_[i]; if(*wd->address_ != wd->old_value_) { _xabort(0); } *wd->address_ = mwcas_descptr; } _xend(); return true; } if(tries++ < kMaxTries) { goto retry; } return false; } #endif #ifndef PMEM bool Descriptor::VolatileMwCAS(uint32_t calldepth) { DCHECK(owner_partition_->garbage_list->GetEpoch()->IsProtected()); if(status_ != kStatusUndecided) { if(calldepth > 0) { // Short circuit and return if the operation has already concluded. MwCASMetrics::AddBailedHelp(); return status_ == kStatusSucceeded; } else { return Cleanup(); } } uint64_t descptr = SetFlags(this, kMwCASFlag); uint32_t my_status = kStatusSucceeded; // Try to swap a pointer to this descriptor into all target addresses using // CondCAS #ifdef RTM // If this operation is helping along, go to phase 2 directly if(calldepth == 0 && !RTMInstallDescriptors()) { my_status = kStatusFailed; } #else for(uint32_t i = 0; i < count_ && my_status == kStatusSucceeded; i++) { WordDescriptor* wd = &words_[i]; if((uint64_t)wd->address_ == Descriptor::kAllocNullAddress){ continue; } retry_entry: auto rval = CondCAS(i); // Ok if a) we succeeded to swap in a pointer to this descriptor or b) some // other thread has already done so. if(rval == wd->old_value_ || rval == descptr) { continue; } // Do we need to help another MWCAS operation? if(IsMwCASDescriptorPtr(rval)) { // Clashed with another MWCAS; help complete the other MWCAS if it is // still being worked on. Descriptor* otherMWCAS = (Descriptor*)CleanPtr(rval); otherMWCAS->VolatileMwCAS(calldepth + 1); MwCASMetrics::AddHelpAttempt(); goto retry_entry; } else { // rval must be another value, we failed my_status = kStatusFailed; } } #endif CompareExchange32(&status_, my_status, kStatusUndecided); bool succeeded = (status_ == kStatusSucceeded); for(int i = 0; i < count_; i++) { WordDescriptor* wd = &words_[i]; if((uint64_t)wd->address_ == Descriptor::kAllocNullAddress){ continue; } CompareExchange64(wd->address_, succeeded ? wd->new_value_ : wd->old_value_, descptr); } if(calldepth == 0) { return Cleanup(); } else { return succeeded; } } bool Descriptor::VolatileMwCASWithFailure(uint32_t calldepth, bool complete_descriptor_install) { DCHECK(owner_partition_->garbage_list->GetEpoch()->IsProtected()); if(status_ != kStatusUndecided) { if(calldepth > 0) { MwCASMetrics::AddBailedHelp(); return status_ == kStatusSucceeded; } else { return Cleanup(); } } uint64_t descptr = SetFlags(this, kMwCASFlag); uint32_t my_status = kStatusSucceeded; // Try to swap a pointer to this descriptor into all target addresses using // CondCAS #ifdef RTM // If I'm helping, go to phase 2 directly if(calldepth == 0 && !RTMInstallDescriptors()) { my_status = kStatusFailed; } #else for(uint32_t i = 0; i < count_ && my_status == kStatusSucceeded; i++) { WordDescriptor* wd = &words_[i]; if((uint64_t)wd->address_ == Descriptor::kAllocNullAddress){ continue; } retry_entry: auto rval = CondCAS(i); // Ok if a) we succeeded to swap in a pointer to this descriptor or b) some // other thread has already done so. if(rval == wd->old_value_ || rval == descptr) { continue; } // Do we need to help another MWCAS operation? if(IsMwCASDescriptorPtr(rval)) { // Clashed with another MWCAS; help complete the other MWCAS if it is // still being worked on Descriptor* otherMWCAS = (Descriptor*)CleanPtr(rval); otherMWCAS->VolatileMwCAS(calldepth + 1); MwCASMetrics::AddHelpAttempt(); goto retry_entry; } else { // rval must be another value, we failed my_status = kStatusFailed; } } #endif // The compare exchange below will determine whether the mwcas will roll // forward or back on recovery. If we are told to not complete descriptor // install, exit the function before updating the operation status. Otherwise // update the status but do not perform the final phase of the mwcas // (installing final values in place of the descriptors and memory cleanup). if (!complete_descriptor_install) { return false; } CompareExchange32(&status_, my_status, kStatusUndecided); // Always return false in this function, since operation is not supposed to // fully succeed. return false; } #endif #ifdef PMEM bool Descriptor::PersistentMwCAS(uint32_t calldepth) { DCHECK(owner_partition_->garbage_list->GetEpoch()->IsProtected()); // Not visible to anyone else, persist before making the descriptor visible if(calldepth == 0) { RAW_CHECK(status_ == kStatusUndecided, "invalid status"); NVRAM::Flush(sizeof(Descriptor), this); } auto status = status_; if(status & kStatusDirtyFlag) { PersistStatus(); CompareExchange32(&status_, status & ~kStatusDirtyFlag, status); status &= ~kStatusDirtyFlag; } if(status != kStatusUndecided) { if(calldepth > 0) { // Operation has already concluded, return. MwCASMetrics::AddBailedHelp(); return status == kStatusSucceeded; } else { return Cleanup(); } } uint64_t descptr = SetFlags(this, kMwCASFlag | kDirtyFlag); uint32_t my_status = kStatusSucceeded; #ifdef RTM // Go to phase 2 directly if helping along. if(calldepth > 0 && !RTMInstallDescriptors(kDirtyFlag)) { my_status = kStatusFailed; } #else std::sort(words_, words_ + count_, [this](WordDescriptor &a, WordDescriptor &b)->bool{ return a.address_ < b.address_; }); for(uint32_t i = 0; i < count_ && my_status == kStatusSucceeded; ++i) { WordDescriptor* wd = &words_[i]; if((uint64_t)wd->address_ == Descriptor::kAllocNullAddress){ continue; } retry_entry: auto rval = CondCAS(i, kDirtyFlag); // Ok if a) we succeeded to swap in a pointer to this descriptor or b) some // other thread has already done so. Need to persist all fields (which point // to descriptors) before switching to final status, so that recovery will // know reliably whether to roll forward or back for this descriptor. if(rval == wd->old_value_ || CleanPtr(rval) == (uint64_t)this) { continue; } if (rval & kDirtyFlag){ goto retry_entry; } // Do we need to help another MWCAS operation? if(IsMwCASDescriptorPtr(rval)) { if(rval & kDirtyFlag) { wd->PersistAddress(); CompareExchange64(wd->address_, rval & ~kDirtyFlag, rval); } // Clashed with another MWCAS; help complete the other MWCAS if it is // still in flight. Descriptor* otherMWCAS = (Descriptor*)CleanPtr(rval); otherMWCAS->PersistentMwCAS(calldepth + 1); MwCASMetrics::AddHelpAttempt(); goto retry_entry; } else { // rval must be another value, we failed my_status = kStatusFailed; } } #endif // Persist all target fields if we successfully installed mwcas descriptor on // all fields. if(my_status == kStatusSucceeded) { for (uint32_t i = 0; i < count_; ++i) { WordDescriptor* wd = &words_[i]; if((uint64_t)wd->address_ == Descriptor::kAllocNullAddress){ continue; } uint64_t val = *wd->address_; if(val == descptr) { wd->PersistAddress(); CompareExchange64(wd->address_, descptr & ~kDirtyFlag, descptr); } } } // Switch to the final state, the MwCAS concludes after this point CompareExchange32(&status_, my_status | kStatusDirtyFlag, kStatusUndecided); // Now the MwCAS is concluded - status is either succeeded or failed, and // no observers will try to help finish it, so do a blind flush and reset // the dirty bit. RAW_CHECK((status_ & ~kStatusDirtyFlag) != kStatusUndecided, "invalid status"); PersistStatus(); status_ &= ~kStatusDirtyFlag; // No need to flush again, recovery does not care about the dirty bit bool succeeded = (status_ == kStatusSucceeded); for(uint32_t i = 0; i < count_; i++) { WordDescriptor* wd = &words_[i]; if((uint64_t)wd->address_ == Descriptor::kAllocNullAddress){ continue; } uint64_t val = succeeded ? wd->new_value_ : wd->old_value_; val |= kDirtyFlag; uint64_t clean_descptr = descptr & ~kDirtyFlag; if(clean_descptr == CompareExchange64(wd->address_, val, descptr)) { // Retry if someone else already cleared the dirty bit CompareExchange64(wd->address_, val, clean_descptr); } wd->PersistAddress(); RAW_CHECK(val & kDirtyFlag, "invalid final value"); CompareExchange64(wd->address_, val & ~kDirtyFlag, val); } if(calldepth == 0) { return Cleanup(); } else { return succeeded; } } bool Descriptor::PersistentMwCASWithFailure(uint32_t calldepth, bool complete_descriptor_install) { DCHECK(owner_partition_->garbage_list->GetEpoch()->IsProtected()); // Not visible to anyone else, persist before making the descriptor visible if(calldepth == 0) { RAW_CHECK(status_ == kStatusUndecided, "invalid status"); NVRAM::Flush(sizeof(Descriptor), this); } auto status = status_; if(status & kStatusDirtyFlag) { PersistStatus(); CompareExchange32(&status_, status & ~kStatusDirtyFlag, status); status &= ~kStatusDirtyFlag; } if(status != kStatusUndecided) { if(calldepth > 0) { MwCASMetrics::AddBailedHelp(); return status == kStatusSucceeded; } else { return Cleanup(); } } uint64_t descptr = SetFlags(this, kMwCASFlag | kDirtyFlag); uint32_t my_status = kStatusSucceeded; #ifdef RTM if(calldepth > 0 && !RTMInstallDescriptors(kDirtyFlag)) { my_status = kStatusFailed; } #else for(uint32_t i = 0; i < count_ && my_status == kStatusSucceeded; ++i) { WordDescriptor* wd = &words_[i]; retry_entry: auto rval = CondCAS(i, kDirtyFlag); // Ok if a) we succeeded to swap in a pointer to this descriptor or b) // some other thread has already done so. Need to persist all fields (which // point to descriptors) before switching to final status, so that recovery // will know reliably whether to roll forward or back for this descriptor. if(rval == wd->old_value_ || CleanPtr(rval) == (uint64_t)this) { continue; } if (rval & kDirtyFlag){ goto retry_entry; } // Do we need to help another MWCAS operation? if(IsMwCASDescriptorPtr(rval)) { if(rval & kDirtyFlag) { wd->PersistAddress(); CompareExchange64(wd->address_, rval & ~kDirtyFlag, rval); } // Clashed with another MWCAS; help complete the other MWCAS if it is // still being worked on. Descriptor* otherMWCAS = (Descriptor*)CleanPtr(rval); otherMWCAS->PersistentMwCAS(calldepth + 1); MwCASMetrics::AddHelpAttempt(); goto retry_entry; } else { // rval must be another value, we failed my_status = kStatusFailed; } } #endif // Persist all target fields if we successfully installed mwcas descriptor on // all fields. if(my_status == kStatusSucceeded) { for (uint32_t i = 0; i < count_; ++i) { WordDescriptor* wd = &words_[i]; uint64_t val = *wd->address_; if(val == descptr) { wd->PersistAddress(); CompareExchange64(wd->address_, descptr & ~kDirtyFlag, descptr); } } } // The compare exchange below will determine whether the mwcas will roll // forward or back on recovery. If we are told to not complete descriptor // install, exit the function before updating the operation status. Otherwise // update the status but do not perform the final phase of the mwcas // (installing final values in place of the descriptors and memory cleanup). if (!complete_descriptor_install) { return false; } // Switch to the final state, the MwCAS concludes after this point CompareExchange32(&status_, my_status | kStatusDirtyFlag, kStatusUndecided); RAW_CHECK((status_ & ~kStatusDirtyFlag) != kStatusUndecided, "invalid status"); PersistStatus(); status_ &= ~kStatusDirtyFlag; // Always return false, since this function is used to test failure paths. return false; } #endif bool Descriptor::Cleanup() { // Remeber outcome so we can return it. // We are sure here Status doesn't have dirty flag set RAW_CHECK((status_ & kStatusDirtyFlag) == 0, "invalid status"); RAW_CHECK(status_ == kStatusFailed || status_ == kStatusSucceeded, "invalid status"); bool success = (status_ == kStatusSucceeded); if(success) { MwCASMetrics::AddSucceededUpdate(); } else { MwCASMetrics::AddFailedUpdate(); } // There will be no new accessors once we have none of the target fields // contain a pointer to this descriptor; this is the point we can put this // descriptor in the garbage list. Note that multiple threads might be working // on the same descriptor at the same time, and only one thread can push to // the garbage list, so we can only change to kStatusFinished state after no // one is using the descriptor, i.e., in FreeDescriptor(), and let the // original owner (calldepth=0, i.e., the op that calls Cleanup()) push the // descriptor to the garbage list. // // Note: It turns out frequently Protect() and Unprotect() is expensive, so // let the user determine when to do it (e.g., exit/re-enter every X mwcas // operations). Inside any mwcas-related operation we assume it's already // protected. auto s = owner_partition_->garbage_list->Push(this, Descriptor::FreeDescriptor, nullptr); RAW_CHECK(s.ok(), "garbage list push() failed"); DCHECK(owner_partition_->garbage_list->GetEpoch()->IsProtected()); return success; } Status Descriptor::Abort() { RAW_CHECK(status_ == kStatusFinished, "cannot abort under current status"); status_ = kStatusFailed; auto s = owner_partition_->garbage_list->Push(this, Descriptor::FreeDescriptor, nullptr); RAW_CHECK(s.ok(), "garbage list push() failed"); return s; } void Descriptor::DeallocateMemory() { // Free the memory associated with the descriptor if needed for(uint32_t i = 0; i < count_; ++i) { auto& word = words_[i]; auto status = status_; switch(word.recycle_policy_) { case kRecycleNever: case kRecycleOnRecovery: break; case kRecycleAlways: if(status == kStatusSucceeded) { if(word.old_value_ != kNewValueReserved) { free_callback_(nullptr, (void*)word.old_value_); } } else { RAW_CHECK(status == kStatusFailed || status == kStatusFinished, "incorrect status found on used/discarded descriptor"); if(word.new_value_ != kNewValueReserved) { free_callback_(nullptr, (void*)word.new_value_); } } break; case kRecycleOldOnSuccess: if(status == kStatusSucceeded) { if(word.old_value_ != kNewValueReserved) { free_callback_(nullptr, (void*)word.old_value_); } } break; case kRecycleNewOnFailure: if(status != kStatusSucceeded) { if(word.new_value_ != kNewValueReserved) { free_callback_(nullptr, (void*)word.new_value_); } } break; default: LOG(FATAL) << "invalid recycle policy"; } } count_ = 0; } void Descriptor::FreeDescriptor(void* context, void* desc) { MARK_UNREFERENCED(context); Descriptor* desc_to_free = reinterpret_cast<Descriptor*>(desc); desc_to_free->DeallocateMemory(); desc_to_free->Initialize(); RAW_CHECK(desc_to_free->status_ == kStatusFinished, "invalid status"); desc_to_free->next_ptr_ = desc_to_free->owner_partition_->free_list; desc_to_free->owner_partition_->free_list = desc_to_free; } } // namespace pmwcas <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #include "doubly_linked_list.h" #include "glog/raw_logging.h" namespace pmwcas { void IDList::SingleThreadSanityCheck() { RAW_CHECK(head_.prev == nullptr, "head.prev doesn't point to null"); RAW_CHECK(head_.next, "head.next is null"); RAW_CHECK(tail_.prev, "tail.prev is null"); RAW_CHECK(tail_.next == nullptr, "tail.next doesn't point to null"); #ifdef PMEM head_.next = (DListNode*)((uint64_t)head_.next & ~CASDList::kDirtyFlag); #endif DListNode* node = head_.next; DListNode* prev = &head_; int i = 0; do { #ifdef PMEM node->next = (DListNode*)((uint64_t)node->next & ~CASDList::kDirtyFlag); node->prev = (DListNode*)((uint64_t)node->prev & ~CASDList::kDirtyFlag); #endif RAW_CHECK(node, "null dlist node"); RAW_CHECK(prev->next == node, "node.prev doesn't match prev.next"); RAW_CHECK(node->prev == prev, "node.prev doesn't match prev.next"); prev = node; node = node->next; } while (node && node->next != &tail_); } DListNode* CASDList::GetNext(DListNode* node, bool) { while (node != &tail_) { RAW_CHECK(node, "null current node"); auto* next = DereferenceNodePointer(&node->next); RAW_CHECK(next, "null next pointer in list"); #ifdef PMEM RAW_CHECK(!((uint64_t)next & kDirtyFlag), "dirty pointer"); auto* next_next = ReadPersist(&next->next); #else auto* next_next = next->next; #endif if ((uint64_t)next_next & kNodeDeleted) { // The next pointer of the node behind me has the deleted mark set #ifdef PMEM auto* node_next = ReadPersist(&node->next); #else auto* node_next = node->next; #endif if ((uint64_t)node_next != ((uint64_t)next | kNodeDeleted)) { // But my next pointer isn't pointing the next with the deleted bit set, // so we set the deleted bit in next's prev pointer. MarkNodePointer(&next->prev); // Now try to unlink the deleted next node #ifdef PMEM next_next = (DListNode*)((uint64_t)next_next | kDirtyFlag); #endif CompareExchange64Ptr(&node->next, (DListNode*)((uint64_t)next_next & ~kNodeDeleted), next); continue; } } node = next; if(((uint64_t)next_next & kNodeDeleted) == 0) { return next; } } return nullptr; // nothing after tail } DListNode* CASDList::GetPrev(DListNode* node, bool) { while(node != &head_) { RAW_CHECK(node, "null current node"); auto* prev = DereferenceNodePointer(&node->prev); RAW_CHECK(prev, "null prev pointer in list"); #ifdef PMEM RAW_CHECK(!((uint64_t)prev & kDirtyFlag), "dirty pointer"); auto* prev_next = ReadPersist(&prev->next); auto* next = ReadPersist(&node->next); #else auto* prev_next = prev->next; auto* next = node->next; #endif if(prev_next == node && ((uint64_t)next & kNodeDeleted) == 0) { return prev; } else if((uint64_t)next & kNodeDeleted) { node = GetNext(node); } else { prev = CorrectPrev(prev, node); } } return nullptr; } Status CASDList::InsertBefore(DListNode* next, DListNode* node, bool) { RAW_CHECK(!((uint64_t)next & kNodeDeleted), "invalid next pointer state"); #ifdef PMEM RAW_CHECK(!((uint64_t)node & kDirtyFlag), "dirty node pointer"); RAW_CHECK(!((uint64_t)next & kDirtyFlag), "dirty next pointer"); #endif if (next == &head_) { return InsertAfter(next, node); } DListNode* prev = nullptr; // Persist the payload #ifdef PMEM NVRAM::Flush(node->payload_size, node->GetPayload()); #endif while (true) { prev = DereferenceNodePointer(&next->prev); // If the guy supposed to be behind me got deleted, fast // forward to its next node and retry #ifdef PMEM auto* next_next = ReadPersist(&next->next); #else auto* next_next = next->next; #endif if ((uint64_t)next_next & kNodeDeleted) { next = GetNext(next); #ifdef PMEM RAW_CHECK(!((uint64_t)next & kDirtyFlag), "dirty next pointer"); #endif prev = CorrectPrev(prev, next); // using the new next #ifdef PMEM RAW_CHECK(!((uint64_t)prev & kDirtyFlag), "dirty prev pointer"); #endif continue; } node->prev = (DListNode*)((uint64_t)prev & ~kNodeDeleted); node->next = (DListNode*)((uint64_t)next & ~kNodeDeleted); #ifdef PMEM // Flush node.prev and node.next before installing NVRAM::Flush(sizeof(node->prev) + sizeof(node->next), &node->prev); #endif // Install [node] on prev->next DListNode* expected = (DListNode*)((uint64_t)next & ~kNodeDeleted); if (expected == CompareExchange64Ptr(&prev->next, node, expected)) { break; } // Failed, get a new hopefully-correct prev prev = CorrectPrev(prev, next); backoff(); } RAW_CHECK(prev, "invalid prev pointer"); CorrectPrev(prev, next); return Status::OK(); } Status CASDList::InsertAfter(DListNode* prev, DListNode* node, bool) { RAW_CHECK(!((uint64_t)prev & kNodeDeleted), "invalid prev pointer state"); #ifdef PMEM RAW_CHECK(!((uint64_t)node & kDirtyFlag), "dirty node pointer"); RAW_CHECK(!((uint64_t)prev & kDirtyFlag), "dirty next pointer"); #endif if (prev == &tail_) { return InsertBefore(prev, node); } DListNode* prev_next = nullptr; // Persist the payload #ifdef PMEM NVRAM::Flush(node->payload_size, node->GetPayload()); #endif while (true) { #ifdef PMEM prev_next = ReadPersist(&prev->next); #else prev_next = prev->next; #endif node->prev = (DListNode*)((uint64_t)prev & ~kNodeDeleted); node->next = (DListNode*)((uint64_t)prev_next & ~kNodeDeleted); #ifdef PMEM // Flush node.prev and node.next before installing NVRAM::Flush(sizeof(node->prev) + sizeof(node->next), &node->prev); #endif // Install [node] after [next] DListNode* expected = (DListNode*)((uint64_t)prev_next & ~kNodeDeleted); if (expected == CompareExchange64Ptr(&prev->next, node, expected)) { break; } if ((uint64_t)prev_next & kNodeDeleted) { Delete(node); return InsertBefore(prev, node); } backoff(); } RAW_CHECK(prev_next, "invalid prev_next pointer"); CorrectPrev(prev, prev_next); return Status::OK(); } Status CASDList::Delete(DListNode* node, bool) { #ifdef PMEM RAW_CHECK(!((uint64_t)node & kDirtyFlag), "dirty node pointer"); #endif if (node == &head_ || node == &tail_) { RAW_CHECK(((uint64_t)node->next & kNodeDeleted) == 0, "invalid next pointer"); RAW_CHECK(((uint64_t)node->prev & kNodeDeleted) == 0, "invalid next pointer"); return Status::OK(); } while (true) { #ifdef PMEM DListNode* node_next = ReadPersist(&node->next); #else auto* node_next = node->next; #endif if ((uint64_t)node_next & kNodeDeleted) { return Status::OK(); } // Try to set the deleted bit in node->next #ifdef PMEM auto* desired = (DListNode*)((uint64_t)node_next | kNodeDeleted | kDirtyFlag); #else auto* desired = (DListNode*)((uint64_t)node_next | kNodeDeleted); #endif DListNode* rnode = CompareExchange64Ptr( &node->next, desired, node_next); if (rnode == node_next) { DListNode* node_prev = nullptr; while (true) { #ifdef PMEM node_prev = ReadPersist(&node->prev); #else node_prev = node->prev; #endif if ((uint64_t)node_prev & kNodeDeleted) { break; } #ifdef PMEM auto* desired = (DListNode*)((uint64_t)node_prev | kNodeDeleted | kDirtyFlag); #else auto* desired = (DListNode*)((uint64_t)node_prev | kNodeDeleted); #endif if (node_prev == CompareExchange64Ptr( &node->prev, desired, node_prev)) { break; } } RAW_CHECK(node_prev, "invalid node_prev pointer"); RAW_CHECK(((uint64_t)head_.next & kNodeDeleted) == 0, "invalid next pointer"); CorrectPrev((DListNode*)((uint64_t)node_prev & ~kNodeDeleted), node_next); return Status::OK(); } } } DListNode* CASDList::CorrectPrev(DListNode* prev, DListNode* node) { RAW_CHECK(((uint64_t)node & kNodeDeleted) == 0, "node has deleted mark"); #ifdef PMEM RAW_CHECK(!((uint64_t)node & kDirtyFlag), "dirty node pointer"); #endif DListNode* last_link = nullptr; while (true) { #ifdef PMEM auto* link1 = ReadPersist(&node->prev); #else auto* link1 = node->prev; #endif if ((uint64_t)link1 & kNodeDeleted) { break; } DListNode* prev_cleared = (DListNode*)((uint64_t)prev & ~kNodeDeleted); #ifdef PMEM auto* prev_next = ReadPersist(&prev_cleared->next); #else auto* prev_next = prev_cleared->next; #endif if ((uint64_t)prev_next & kNodeDeleted) { if (last_link) { MarkNodePointer(&prev_cleared->prev); #ifdef PMEM auto* desired = (DListNode*)(((uint64_t)prev_next & ~kNodeDeleted) | kDirtyFlag); #else auto* desired = (DListNode*)(((uint64_t)prev_next & ~kNodeDeleted)); #endif CompareExchange64Ptr(&last_link->next, desired, prev); prev = last_link; last_link = nullptr; continue; } #ifdef PMEM prev_next = ReadPersist(&prev_cleared->prev); #else prev_next = prev_cleared->prev; #endif prev = prev_next; RAW_CHECK(prev, "invalid prev pointer"); continue; } RAW_CHECK(((uint64_t)prev_next & kNodeDeleted) == 0, "invalid next field in predecessor"); if (prev_next != node) { last_link = prev_cleared; prev = prev_next; continue; } #ifdef PMEM DListNode* p = (DListNode*)(((uint64_t)prev & ~kNodeDeleted) | kDirtyFlag); #else DListNode* p = (DListNode*)(((uint64_t)prev & ~kNodeDeleted)); #endif if (link1 == CompareExchange64Ptr(&node->prev, p, link1)) { #ifdef PMEM auto* prev_cleared_prev = ReadPersist(&prev_cleared->prev); #else auto* prev_cleared_prev = prev_cleared->prev; #endif if ((uint64_t)prev_cleared_prev & kNodeDeleted) { continue; } break; } backoff(); } #ifdef PMEM RAW_CHECK(!((uint64_t)prev & kDirtyFlag), "dirty prev pointer"); #endif return prev; } Status MwCASDList::InsertBefore(DListNode* next, DListNode* node, bool already_protected) { if (next == &head_) { return InsertAfter(next, node, already_protected); } EpochGuard guard(GetEpoch(), !already_protected); // Persist the payload #ifdef PMEM NVRAM::Flush(node->payload_size, node->GetPayload()); #endif while (true) { RAW_CHECK(((uint64_t)next & kNodeDeleted) == 0, "invalid prev pointer"); auto* prev = ResolveNodePointer(&next->prev, true); auto* next_next = ResolveNodePointer(&next->next, true); if (((uint64_t)prev & kNodeDeleted) || (uint64_t)next_next & kNodeDeleted) { next = GetNext(next, true); continue; } auto* prev_next = ResolveNodePointer(&prev->next, true); if ((uint64_t)prev_next & kNodeDeleted) { continue; } node->next = next; node->prev = prev; #ifdef PMEM // Persist node NVRAM::Flush(sizeof(node->prev) + sizeof(node->next), &node->prev); #endif RAW_CHECK(MwcTargetField<uint64_t>::IsCleanPtr((uint64_t)prev), "prev is not normal value"); RAW_CHECK(MwcTargetField<uint64_t>::IsCleanPtr((uint64_t)next), "next is not normal value"); auto* desc = descriptor_pool_->AllocateDescriptor(); RAW_CHECK(desc, "null MwCAS descriptor"); desc->AddEntry( (uint64_t*)&node->prev->next, (uint64_t)node->next, (uint64_t)node); desc->AddEntry( (uint64_t*)&next->prev, (uint64_t)node->prev, (uint64_t)node); if(desc->MwCAS()) { return Status::OK(); } } return Status::OK(); } Status MwCASDList::InsertAfter(DListNode* prev, DListNode* node, bool already_protected) { if (prev == &tail_) { return InsertBefore(prev, node, already_protected); } EpochGuard guard(GetEpoch(), !already_protected); // Persist the payload #ifdef PMEM NVRAM::Flush(node->payload_size, node->GetPayload()); #endif while (true) { RAW_CHECK(((uint64_t)prev & kNodeDeleted) == 0, "invalid prev pointer"); auto* next = ResolveNodePointer(&prev->next, true); if ((uint64_t)next & kNodeDeleted) { prev = GetPrev(prev, true); continue; } auto* next_next = ResolveNodePointer(&next->next, true); if ((uint64_t)next_next & kNodeDeleted) { continue; } RAW_CHECK(((uint64_t)next & kNodeDeleted) == 0, "deleted prev node"); RAW_CHECK(MwcTargetField<uint64_t>::IsCleanPtr((uint64_t)prev), "next is not normal value"); RAW_CHECK(MwcTargetField<uint64_t>::IsCleanPtr((uint64_t)next), "next is not normal value"); node->prev = prev; node->next = next; #ifdef PMEM // Persist node NVRAM::Flush(sizeof(node->prev) + sizeof(node->next), &node->prev); #endif auto* desc = descriptor_pool_->AllocateDescriptor(); RAW_CHECK(desc, "null descriptor pointer"); desc->AddEntry((uint64_t*)&prev->next, (uint64_t)node->next, (uint64_t)node); desc->AddEntry((uint64_t*)&node->next->prev, (uint64_t)node->prev, (uint64_t)node); if(desc->MwCAS()) { return Status::OK(); } } return Status::OK(); } Status MwCASDList::Delete(DListNode* node, bool already_protected) { EpochGuard guard(GetEpoch(), !already_protected); while (((uint64_t)node->next & kNodeDeleted) == 0) { if (node == &head_ || node == &tail_) { RAW_CHECK(((uint64_t)node->next & kNodeDeleted) == 0, "invalid next pointer"); RAW_CHECK(((uint64_t)node->prev & kNodeDeleted) == 0, "invalid next pointer"); break; } DListNode* prev = ResolveNodePointer(&node->prev, true); DListNode* next = ResolveNodePointer(&node->next, true); if (prev->next != node || next->prev != node) { continue; } auto* desc = descriptor_pool_->AllocateDescriptor(); RAW_CHECK(desc, "null MwCAS descriptor"); desc->AddEntry((uint64_t*)&prev->next, (uint64_t)node, (uint64_t)next); desc->AddEntry((uint64_t*)&next->prev, (uint64_t)node, (uint64_t)prev); desc->AddEntry((uint64_t*)&node->next, (uint64_t)next, (uint64_t)next | kNodeDeleted); if(desc->MwCAS()) { return Status::OK(); } } return Status::OK(); } } // namespace pmwcas <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once #include <cstdint> #include "include/status.h" namespace pmwcas { /// Interface for custom memory allocator plug-in. The PMwCAS library does not1 /// assume a particular allocator, and will use whatever is behind IAllocator to /// allocate memory. See pmwcas::InitLibrary in /include/pmwcas.h. class IAllocator { public: virtual void Allocate(void **mem, size_t size) = 0; virtual void AllocateAligned(void **mem, size_t size, uint32_t alignment) = 0; virtual void AllocateAlignedOffset(void **mem, size_t size, size_t alignment, size_t offset) = 0; virtual void AllocateHuge(void **mem, size_t size) = 0; virtual void CAlloc(void **mem, size_t count, size_t size) = 0; virtual void Free(void* bytes) = 0; virtual void FreeAligned(void* bytes) = 0; virtual uint64_t GetAllocatedSize(void* bytes) = 0; virtual Status Validate(void* bytes) = 0; }; } // namespace pmwcas <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once #include <mutex> #include <atomic> #include "common/allocator_internal.h" #include "common/epoch.h" #include "common/garbage_list.h" #include "util/macros.h" #include "util/atomics.h" #include "include/allocator.h" namespace pmwcas { /// Exactly the same as GarbageList, except that this one doesn't use any /// synchronization mechanism for getting a slot etc. It is only intended /// to be used as a thread-local list. The only user so far (20160811) is /// the MwCAS library (for descriptor allocation/reuse). class GarbageListUnsafe : public IGarbageList { public: /// Holds a pointer to an object in the garbage list along with the Epoch /// in which it was removed and a chain field so that it can be linked into /// a queue. struct Item { /// Epoch in which the #m_removedItem was removed from the data /// structure. In practice, due to delay between the actual removal /// operation and the push onto the garbage list, #m_removalEpoch may /// be later than when the actual remove happened, but that is safe /// since the invariant is that the epoch stored here needs to be /// greater than or equal to the current global epoch in which the /// item was actually removed. Epoch removal_epoch; /// Function provided by user on Push() called when an object /// that was pushed to the list is safe for reclamation. When invoked the /// function is passed a pointer to an object that is safe to destroy and /// free along with #m_pbDestroyCallbackContext. The function must /// perform all needed destruction and release any resources associated /// with the object. DestroyCallback destroy_callback; /// Passed along with a pointer to the object to destroy to /// #m_destroyCallback; it threads state to destroyCallback calls so they /// can access, for example, the allocator from which the object was /// allocated. void* destroy_callback_context; /// Point to the object that is enqueued for destruction. Concurrent /// accesses may still be ongoing to the object, so absolutely no /// changes should be made to the value it refers to until /// #m_removalEpoch is deemed safe for reclamation by the /// EpochManager. void* removed_item; }; static_assert(std::is_pod<Item>::value, "Item should be POD"); /// Construct a GarbageList in an uninitialized state. GarbageListUnsafe() : epoch_manager_{} , tail_{} , item_count_{} , items_{} { } /// Uninitialize the GarbageList (if still initialized) and destroy it. virtual ~GarbageListUnsafe() { Uninitialize(); } /// Initialize the GarbageList and associate it with an EpochManager. /// This must be called on a newly constructed instance before it /// is safe to call other methods. If the GarbageList is already /// initialized then it will have no effect. /// /// \param pEpochManager /// EpochManager that is used to determine when it is safe to reclaim /// items pushed onto the list. Must not be nullptr. /// \param nItems /// Number of addresses that can be held aside for pointer stability. /// If this number is too small the system runs the risk of deadlock. /// Must be a power of two. /// /// \retval S_OK /// The instance is now initialized and ready for use. /// \retval S_FALSE /// The instance was already initialized; no effect. /// \retval E_INVALIDARG /// \a nItems wasn't a power of two. virtual Status Initialize(EpochManager* epoch_manager, size_t item_count = 128 * 1024) { if(epoch_manager_) return Status::OK(); if(!epoch_manager) return Status::InvalidArgument("Null pointer"); if(!item_count || !IS_POWER_OF_TWO(item_count)) { return Status::InvalidArgument("items not a power of two"); } size_t nItemArraySize = sizeof(*items_) * item_count; posix_memalign((void **)&items_, 64, nItemArraySize); if (!items_) return Status::Corruption("Out of memory"); for(size_t i = 0; i < item_count; ++i) new(&items_[i]) Item{}; item_count_ = item_count; tail_ = 0; epoch_manager_ = epoch_manager; return Status::OK(); } /// Uninitialize the GarbageList and disassociate from its EpochManager; /// for each item still on the list call its destructor and free it. /// Careful: objects freed by this call will NOT obey the epoch protocol, /// so it is important that this thread is only called when it is clear /// that no other threads may still be concurrently accessing items /// on the list. /// /// \retval S_OK /// The instance is now uninitialized; resources were released. /// \retval S_FALSE /// The instance was already uninitialized; no effect. virtual Status Uninitialize() { if(!epoch_manager_) return Status::OK(); for(size_t i = 0; i < item_count_; ++i) { Item& item = items_[i]; if(item.removed_item) { item.destroy_callback( item.destroy_callback_context, item.removed_item); item.removed_item = nullptr; item.removal_epoch = 0; } } free(items_); items_ = nullptr; tail_ = 0; item_count_ = 0; epoch_manager_ = nullptr; return Status::OK(); } /// Append an item to the reclamation queue; the item will be stamped /// with an epoch and will not be reclaimed until the EpochManager confirms /// that no threads can ever access the item again. Once an item is ready /// for removal the destruction callback passed to Initialize() will be /// called which must free all resources associated with the object /// INCLUDING the memory backing the object. /// /// \param removed_item /// Item to place on the list; it will remain live until /// the EpochManager indicates that no threads will ever access it /// again, after which the destruction callback will be invoked on it. /// \param callback /// Function to call when the object that was pushed to the list is safe /// for reclamation. When invoked the, function is passed a pointer to /// an object that is safe to destroy and free along with /// \a pvDestroyCallbackContext. The function must perform /// all needed destruction and release any resources associated with /// the object. Must not be nullptr. /// \param context /// Passed along with a pointer to the object to destroy to /// \a destroyCallback; it threads state to destroyCallback calls so /// they can access, for example, the allocator from which the object /// was allocated. Left uninterpreted, so may be nullptr. virtual Status Push(void* removed_item, DestroyCallback callback, void* context) { Epoch removal_epoch = epoch_manager_->GetCurrentEpoch(); const uint64_t invalid_epoch = ~0llu; for(;;) { // Consistent from my own point of view, no other observers int64_t slot = (tail_++) & (item_count_ - 1); // Everytime we work through 25% of the capacity of the list roll // the epoch over. if(((slot << 2) & (item_count_ - 1)) == 0) epoch_manager_->BumpCurrentEpoch(); Item& item = items_[slot]; Epoch priorItemEpoch = item.removal_epoch; RAW_CHECK(priorItemEpoch != invalid_epoch, "invalid priorItemEpoch"); // No synchronization for a single thread; guaranteed to succeed item.removal_epoch = invalid_epoch; // Ensure it is safe to free the old entry. if(priorItemEpoch) { if(!epoch_manager_->IsSafeToReclaim(priorItemEpoch)) { // Uh-oh, we couldn't free the old entry. Things aren't looking // good, but maybe it was just the result of a race. Replace the // epoch number we mangled and try elsewhere. *((volatile Epoch*) &item.removal_epoch) = priorItemEpoch; continue; } item.destroy_callback(item.destroy_callback_context, item.removed_item); } // Now populate the entry with the new item. item.destroy_callback = callback; item.destroy_callback_context = context; item.removed_item = removed_item; item.removal_epoch = removal_epoch; return Status::OK(); } } /// Scavenge items that are safe to be reused - useful when the user cannot /// wait until the garbage list is full. Currently (May 2016) the only user is /// MwCAS' descriptor pool which we'd like to keep small. Tedious to tune the /// descriptor pool size vs. garbage list size, so there is this function. int32_t Scavenge() { const uint64_t invalid_epoch = ~0llu; auto max_slot = tail_; int32_t scavenged = 0; for(int64_t slot = 0; slot < item_count_; ++slot) { auto& item = items_[slot]; Epoch priorItemEpoch = item.removal_epoch; if(priorItemEpoch == 0 || priorItemEpoch == invalid_epoch) { // Someone is modifying this slot. Try elsewhere. continue; } // No synchronization for a single thread; guaranteed to succeed item.removal_epoch = invalid_epoch; if(priorItemEpoch) { if(!epoch_manager_->IsSafeToReclaim(priorItemEpoch)) { // Uh-oh, we couldn't free the old entry. Things aren't looking // good, but maybe it was just the result of a race. Replace the // epoch number we mangled and try elsewhere. *((volatile Epoch*) &item.removal_epoch) = priorItemEpoch; continue; } item.destroy_callback(item.destroy_callback_context, item.removed_item); } // Now reset the entry item.destroy_callback = nullptr; item.destroy_callback_context = nullptr; item.removed_item = nullptr; *((volatile Epoch*) &item.removal_epoch) = 0; ++scavenged; } return scavenged; } /// Returns (a pointer to) the epoch manager associated with this garbage list. EpochManager* GetEpoch() { return epoch_manager_; } private: /// EpochManager instance that is used to determine when it is safe to /// free up items. Specifically, it is used to stamp items during Push() /// with the current epoch, and it is used in to ensure /// that deletion of each item on the list is safe. EpochManager* epoch_manager_; /// Point in the #m_items ring where the next pushed address will be placed. /// Also indicates the next address that will be freed on the next push. /// Atomically incremented within Push(). int64_t tail_; /// Size of the #m_items array. Must be a power of two. size_t item_count_; /// Ring of addresses the addresses pushed to the list and metadata about /// them needed to determine when it is safe to free them and how they /// should be freed. This is filled as a ring; when a new Push() comes that /// would replace an already occupied slot the entry in the slot is freed, /// if possible. Item* items_; }; } // namespace pmwcas <file_sep>set(UTIL_HEADERS doubly_linked_list.h ) set(UTIL_SOURCES doubly_linked_list.cc ) add_library(double-linked-list STATIC ${UTIL_SOURCES} ${UTIL_HEADERS}) target_link_libraries(double-linked-list ${GFLAGS_LIB} ${GLOG_LIB}) ADD_PMWCAS_TEST(doubly_linked_list_tests) <file_sep>set(BENCHMARK_HEADERS ../util/random_number_generator.h ) ADD_PMWCAS_BENCHMARK(mwcas_benchmark) ADD_PMWCAS_BENCHMARK(mwcas_shm_server) ADD_PMWCAS_BENCHMARK(doubly_linked_list_benchmark) <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #include <condition_variable> #include <mutex> #ifdef WIN32 #include <conio.h> #endif #include "mwcas_benchmark.h" using namespace pmwcas::benchmark; DEFINE_uint64(array_size, 100, "size of the word array for mwcas benchmark"); DEFINE_uint64(descriptor_pool_size, 262144, "number of total descriptors"); DEFINE_string(shm_segment, "mwcas", "name of the shared memory segment for" " descriptors and data (for persistent MwCAS only)"); using namespace pmwcas; // Start a process to create a shared memory segment and sleep int main(int argc, char* argv[]) { google::InitGoogleLogging(argv[0]); google::ParseCommandLineFlags(&argc, &argv, true); LOG(INFO) << "Array size: " << FLAGS_array_size; LOG(INFO) << "Descriptor pool size: " << FLAGS_descriptor_pool_size; LOG(INFO) << "Segment name: " << FLAGS_shm_segment; #ifdef WIN32 pmwcas::InitLibrary(pmwcas::DefaultAllocator::Create, pmwcas::DefaultAllocator::Destroy, pmwcas::WindowsEnvironment::Create, pmwcas::WindowsEnvironment::Destroy); #else pmwcas::InitLibrary(pmwcas::DefaultAllocator::Create, pmwcas::DefaultAllocator::Destroy, pmwcas::LinuxEnvironment::Create, pmwcas::LinuxEnvironment::Destroy); #endif uint64_t size = sizeof(DescriptorPool::Metadata) + sizeof(Descriptor) * FLAGS_descriptor_pool_size + // descriptors area sizeof(CasPtr) * FLAGS_array_size; // data area SharedMemorySegment* segment = nullptr; auto s = Environment::Get()->NewSharedMemorySegment(FLAGS_shm_segment, size, false, &segment); RAW_CHECK(s.ok() && segment, "Error creating memory segment"); s = segment->Attach(); RAW_CHECK(s.ok(), "cannot attach"); memset(segment->GetMapAddress(), 0, size); segment->Detach(); std::mutex mutex; std::unique_lock<std::mutex> lock(mutex); std::condition_variable cv; std::cout << "Created shared memory segment" << std::endl; cv.wait(lock); return 0; } <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once #include <cstdint> #include <random> namespace pmwcas { /// A fast random (32-bit) number generator, for a uniform distribution (all /// numbers in the range are equally likely). class RandomNumberGenerator { public: RandomNumberGenerator(uint32_t seed = 0, uint32_t min = 0, uint32_t max = 0) : max_{ max } { if(seed == 0) { std::random_device rd{}; x_ = rd() & 0x0FFFFFFF; } else { x_ = seed; } y_ = 362436069; z_ = 521288629; w_ = 88675123; } uint32_t Generate() { uint32_t t; t = (x_ ^ (x_ << 11)); x_ = y_; y_ = z_; z_ = w_; uint32_t result = (w_ = (w_ ^ (w_ >> 19)) ^ (t ^ (t >> 8))); return (max_ > 0) ? result % max_ : result; } uint32_t Generate(uint32_t max) { return Generate() % max; } private: uint32_t max_; uint32_t x_; uint32_t y_; uint32_t z_; uint32_t w_; }; /// A random number generator, for a Zipfian distribution (smaller numbers are /// most likely.) "The algorithm used here is from 'Quickly Generating /// Billion-Record Synthetic Databases', <NAME> et al, SIGMOD 1994." class ZipfRandomNumberGenerator { public: /// Create a zipfian generator for items between min and max. ZipfRandomNumberGenerator(uint32_t seed, uint32_t min, uint32_t max) : rng_{ seed }, items_{ max - min + 1 }, base_{ min }, zipfianconstant_{ 0.99 }, zetan_{ zetastatic(items_, zipfianconstant_) }, half2theta_{} { init(); } double zeta(uint32_t n, double theta) { countforzeta_ = n; return zetastatic(n, theta); } /// Compute the zeta constant needed for the distribution. Do this from /// scratch for a distribution with n items, using the zipfian constant theta. /// This is a static version of the function which will not remember n. static double zetastatic(uint32_t n, double theta) { return zetastatic(0, n, theta, 0); } /// Compute the zeta constant needed for the distribution. Do this /// incrementally for a distribution that has n items now but used to have /// st items. Use the zipfian constant theta. Remember the new value of n so /// that if we change the itemcount, we'll know to recompute zeta. double zeta(int64_t st, uint32_t n, double theta, double initialsum) { countforzeta_ = n; return zetastatic(st, n, theta, initialsum); } /// Compute the zeta constant needed for the distribution. Do this /// incrementally for a distribution that has n items now but used to have st /// items. Use the zipfian constant theta. Remember the new value of n so that /// if we change the itemcount, we'll know to recompute zeta. static double zetastatic(uint32_t start, uint32_t n, double theta, double initialsum) { double sum = initialsum; for (uint32_t i = start; i < n; ++i) { sum += 1 / (pow((double)(i + 1), theta)); } return sum; } /// Generate the next value, skewed by the Zipfian distribution. The 0th item /// will be the most popular, followed by the 1st, followed by the 2nd, etc. /// (Or, if min != 0, the min-th item is the most popular, the min+1th item /// the next most popular, etc.) If you want the popular items scattered /// throughout the item space, use ScrambledZipfianGenerator instead. uint32_t Generate() { // From "Quickly Generating Billion-Record Synthetic Databases", // <NAME> et al, SIGMOD 1994 double u = static_cast<double>(rng_.Generate()) / (1llu << 32); double uz = u * zetan_; if (uz < 1.0) { return 0; } else if (uz < 1.0 + half2theta_) { return 1; } else { return base_ + static_cast<uint32_t>((items_)* pow(eta_*u - eta_ + 1, alpha_)); } } protected: void init() { theta_ = zipfianconstant_; half2theta_ = pow(0.5, theta_); zeta2theta_ = zeta(2, theta_); alpha_ = 1.0 / (1.0 - theta_); countforzeta_ = items_; eta_ = (1 - pow(2.0 / items_, 1 - theta_)) / (1 - zeta2theta_ / zetan_); Generate(); } protected: /// Number of items. uint32_t items_; /// Min item to generate. uint32_t base_; /// The zipfian constant to use. double zipfianconstant_; /// Computed parameters for generating the distribution. double alpha_; double zetan_; double eta_; double theta_; double half2theta_; double zeta2theta_; /// The number of items used to compute zetan the last time. uint32_t countforzeta_; RandomNumberGenerator rng_; }; /// Same as ZipfianRandomNumberGenerator, except favors larger numbers rather /// than smaller numbers. class ReverseZipfRandomNumberGenerator : public ZipfRandomNumberGenerator { public: /// Create a zipfian generator for items between min and max. ReverseZipfRandomNumberGenerator(uint32_t seed, uint32_t min, uint32_t max) : ZipfRandomNumberGenerator(seed, min, max) { } /// Generate the next value, skewed by the reverse-Zipfian distribution. The /// largest item will be the most popular, followed by the next largest, etc. uint32_t Generate() { uint32_t result = ZipfRandomNumberGenerator::Generate(); return base_ + items_ - 1 - result; } }; class ScrambledZipfRandomNumberGenerator : public ZipfRandomNumberGenerator { public: /// Create a zipfian generator for items between min and max. ScrambledZipfRandomNumberGenerator(uint32_t seed, uint32_t min, uint32_t max) : ZipfRandomNumberGenerator(seed, min, max) { } /// Generate the next value, skewed by the reverse-Zipfian distribution. The /// largest item will be the most popular, followed by the next largest, etc. uint32_t Generate() { uint32_t result = ZipfRandomNumberGenerator::Generate(); return base_ + FnvHash64(result) % items_; } private: static uint64_t FnvHash64(uint64_t val) { //from http://en.wikipedia.org/wiki/Fowler_Noll_Vo_hash int64_t hashval = 0xCBF29CE484222325LL; for (int i = 0; i < 8; i++) { int32_t octet = val & 0x00ff; val = val >> 8; hashval = hashval ^ octet; hashval = hashval * 1099511628211LL; } return std::abs(hashval); } }; } // namespace pmwcas <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once #ifdef WIN32 #define NOMINMAX #include <Windows.h> #undef ERROR // Avoid collision of ERROR definition in Windows.h with logging framework #include <intrin.h> #else #include <semaphore.h> #endif #include <atomic> #include "macros.h" namespace pmwcas { const static uintptr_t kAtomicAlignment = 4; // The minimum alignment to guarantee atomic operations on a platform for both // value types and pointer types // The maximum size to guarantee atomic operations with the primitives below #if defined (_M_I386) #define AtomicAlignment 4 #define PointerAlignment 4 #define AtomicMaxSize 4 #else #define AtomicAlignment 4 #define PointerAlignment 8 #define AtomicMaxSize 8 #endif // Identical for WIN32 and Linux template <typename T> T LdImm(T const* const source) { static_assert(sizeof(T) <= AtomicMaxSize, "Type must be aligned to native pointer alignment."); DCHECK((((uintptr_t)source) & (kAtomicAlignment - 1)) == 0); // The volatile qualifier has the side effect of being a load-aquire on IA64. // That's a result of overloading the volatile keyword. return *((volatile T*)source); } /// A load with acquire semantics for a type T template <typename T> inline T LdAq(T const* const source) { static_assert(sizeof(T) <= AtomicMaxSize, "Type must be aligned to native pointer alignment."); assert((((uintptr_t)source) & (AtomicAlignment - 1)) == 0); #ifdef WIN32 // COMPILER-WISE: // a volatile read is not compiler reorderable w/r to reads. However, // we put in a _ReadBarrier() just to make sure // PROCESSOR-WISE: // Common consensus is that X86 and X64 do NOT reorder loads. // IA64 volatile emits ld.aq,which ensures all loads complete before this one _ReadBarrier(); #else _mm_lfence(); #endif return *((volatile T*)source); } template <typename T> void StRel(T* destination, T value) { static_assert(sizeof(T) <= AtomicMaxSize, "Type must be aligned to native pointer alignment."); DCHECK((((uintptr_t)destination) & (AtomicAlignment - 1)) == 0); // COMPILER-WISE: // A volatile write is not compiler reorderable w/r to writes // PROCESSOR-WISE: // X86 and X64 do not reorder stores. IA64 volatile emits st.rel, // which ensures all stores complete before this one *((volatile T*)destination) = value; } #ifdef WIN32 template <typename T> T CompareExchange64(T* destination, T new_value, T comparand) { static_assert(sizeof(T) == 8, "CompareExchange64 only works on 64 bit values"); return ::InterlockedCompareExchange64( reinterpret_cast<LONGLONG*>(destination), new_value, comparand); } template <typename T> T* CompareExchange64Ptr(T** destination, T* new_value, T* comparand) { return (T*)(::InterlockedCompareExchangePointer( reinterpret_cast<void**>(destination), new_value, comparand)); } template <typename T> T CompareExchange32(T* destination, T new_value, T comparand) { static_assert(sizeof(T) == 4, "CompareExchange32 only works on 32 bit values"); return ::InterlockedCompareExchange(reinterpret_cast<LONG*>(destination), new_value, comparand); } template <typename T> T FetchAdd64(T* destination, T add_value) { static_assert(sizeof(T) <= AtomicMaxSize, "Type must be aligned to native pointer alignment."); return ::InterlockedAdd(reinterpret_cast<LONG*>(destination), add_value); } template <typename T> T Decrement64(T* destination) { static_assert(sizeof(T) <= AtomicMaxSize, "Type must be aligned to native pointer alignment."); return ::InterlockedDecrement64(destination); } template <typename T> T Decrement32(T* destination) { static_assert(sizeof(T) <= AtomicMaxSize, "Type must be aligned to native pointer alignment."); return ::InterlockedDecrement(destination); } class Barrier { public: Barrier(uint64_t thread_count) : wait_count_{ thread_count } , thread_count_{ thread_count } , windows_semaphore_{ ::CreateSemaphore(0, 0, 1024, 0) } { } ~Barrier() { ::CloseHandle(windows_semaphore_); } void CountAndWait() { if(0 == --wait_count_) { wait_count_.store(thread_count_, std::memory_order_release); ::ReleaseSemaphore(windows_semaphore_, static_cast<LONG>(thread_count_ - 1), 0); } else { ::WaitForSingleObject(windows_semaphore_, INFINITE); } } private: std::atomic<uint64_t> wait_count_; const uint64_t thread_count_; const HANDLE windows_semaphore_; }; #else template <typename T> T CompareExchange64(T* destination, T new_value, T comparand) { static_assert(sizeof(T) == 8, "CompareExchange64 only works on 64 bit values"); ::__atomic_compare_exchange_n(destination, &comparand, new_value, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); return comparand; } template <typename T> T* CompareExchange64Ptr(T** destination, T* new_value, T* comparand) { ::__atomic_compare_exchange_n(destination, &comparand, new_value, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); return comparand; } template <typename T> T CompareExchange32(T* destination, T new_value, T comparand) { static_assert(sizeof(T) == 4, "CompareExchange32 only works on 32 bit values"); ::__atomic_compare_exchange_n(destination, &comparand, new_value, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); return comparand; } template <typename T> T FetchAdd64(T* destination, T add_value) { static_assert(sizeof(T) <= AtomicMaxSize, "Type must be aligned to native pointer alignment."); return ::__atomic_fetch_add(destination, add_value, __ATOMIC_SEQ_CST); } template <typename T> T Decrement64(T* destination) { static_assert(sizeof(T) <= AtomicMaxSize, "Type must be aligned to native pointer alignment."); return ::__atomic_sub_fetch(destination, 1); } template <typename T> T Decrement32(T* destination) { static_assert(sizeof(T) <= AtomicMaxSize, "Type must be aligned to native pointer alignment."); return ::__atomic_sub_fetch(destination, 1); } class Barrier { public: Barrier(uint64_t thread_count) : wait_count_{ thread_count } { } ~Barrier() {} void CountAndWait() { uint64_t c = --wait_count_; while(wait_count_ != 0) {} } private: std::atomic<uint64_t> wait_count_; }; #endif } // namespace pmwcas <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once #ifdef WIN32 #define NOMINMAX #endif #ifndef WIN32 #include <x86intrin.h> #endif #include <memory> #include <assert.h> #include <cstdio> #include <stddef.h> #include <string.h> #include <algorithm> namespace pmwcas { class Slice { public: /// Create an empty slice. Slice() : data_(""), size_(0) { } /// Create a slice that refers to d[0,n-1]. Slice(const char* d, size_t n) : data_(d), size_(n) { } /// Create a slice that refers to the contents of "s" Slice(const std::string& s) : data_(s.data()), size_(s.size()) { } /// Create a slice that refers to s[0,strlen(s)-1] Slice(const char* s) : data_(s), size_(strlen(s)) { } /// Create a single slice from SliceParts using buf as storage. /// buf must exist as long as the returned Slice exists. Slice(const struct SliceParts& parts, std::string* buf); /// Return a pointer to the beginning of the referenced data const char* data() const { return data_; } /// Return the length (in bytes) of the referenced data size_t size() const { return size_; } /// Return true iff the length of the referenced data is zero bool empty() const { return size_ == 0; } /// Return the ith byte in the referenced data. /// REQUIRES: n < size() char operator[](size_t n) const { assert(n < size()); return data_[n]; } /// Change this slice to refer to an empty array void clear() { data_ = ""; size_ = 0; } /// Drop the first "n" bytes from this slice. void remove_prefix(size_t n) { assert(n <= size()); data_ += n; size_ -= n; } /// Drop the last "n" bytes from this slice. void remove_suffix(size_t n) { assert(n <= size()); size_ -= n; } /// Return a string that contains the copy of the referenced data. std::string ToString(bool hex = false) const; /// Copies the slice to the specified destination. void copy(char* dest, size_t dest_size) const { assert(dest_size >= size_); memcpy(dest, data_, size_); } /// Copies the specified number of bytes of the slice to the specified /// destination. void copy(char* dest, size_t dest_size, size_t count) const { assert(count <= size_); assert(dest_size >= count); memcpy(dest, data_, count); } /// Three-way comparison. Returns value: /// < 0 iff "*this" < "b", /// == 0 iff "*this" == "b", /// > 0 iff "*this" > "b" int compare(const Slice& b) const; /// Besides returning the comparison value, also sets out parameter "index" to /// be the least index /// such that "this[index]" != "b[index]". int compare_with_index(const Slice& b, size_t& index) const; /// Compares the first "len" bytes of "this" with the first "len" bytes of "b". int compare(const Slice& b, size_t len) const; /// Besides returning the comparison value, also sets out parameter "index" to /// be the least index such that "this[index]" != "b[index]". int compare_with_index(const Slice& b, size_t len, size_t& index) const; /// Return true iff "x" is a prefix of "*this" bool starts_with(const Slice& x) const { return ((size_ >= x.size_) && (memcmp(data_, x.data_, x.size_) == 0)); } /// Performs a memcmp() and also sets "index" to the index of the first /// disagreement (if any) between the buffers being compared. static int memcmp_with_index(const void* buf1, const void* buf2, size_t size, size_t& index) { // Currently using naive implementation, since this is called only during // consolidate/split. for(index = 0; index < size; ++index) { uint8_t byte1 = reinterpret_cast<const uint8_t*>(buf1)[index]; uint8_t byte2 = reinterpret_cast<const uint8_t*>(buf2)[index]; if(byte1 != byte2) { return (byte1 < byte2) ? -1 : +1; } } return 0; } public: const char* data_; size_t size_; }; inline bool operator==(const Slice& x, const Slice& y) { return ((x.size() == y.size()) && (memcmp(x.data(), y.data(), x.size()) == 0)); } inline bool operator!=(const Slice& x, const Slice& y) { return !(x == y); } inline int Slice::compare(const Slice& b) const { const size_t min_len = (std::min)(size_, b.size_); int r = memcmp(data_, b.data_, min_len); if(r == 0) { if(size_ < b.size_) r = -1; else if(size_ > b.size_) r = +1; } return r; } inline int Slice::compare_with_index(const Slice& b, size_t& index) const { const size_t min_len = (std::min)(size_, b.size_); int r = memcmp_with_index(data_, b.data_, min_len, index); if(r == 0) { if(size_ < b.size_) r = -1; else if(size_ > b.size_) r = +1; } return r; } inline int Slice::compare(const Slice& b, size_t len) const { const size_t min_len = (std::min)(size_, b.size_); int r = memcmp(data_, b.data_, (std::min)(min_len, len)); if(r == 0 && min_len < len) { if(size_ < b.size_) r = -1; else if(size_ > b.size_) r = +1; } return r; } inline int Slice::compare_with_index(const Slice& b, size_t len, size_t& index) const { const size_t min_len = (std::min)(size_, b.size_); int r = memcmp_with_index(data_, b.data_, (std::min)(min_len, len), index); if(r == 0 && min_len < len) { if(size_ < b.size_) r = -1; else if(size_ > b.size_) r = +1; } return r; } } // namespace pmwcas <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #include "common/epoch.h" #include "common/environment_internal.h" #include "util/hash.h" namespace pmwcas { EpochManager::EpochManager() : current_epoch_{ 1 } , safe_to_reclaim_epoch_{ 0 } , epoch_table_{ nullptr } { } EpochManager::~EpochManager() { Uninitialize(); } /** * Initialize an uninitialized EpochManager. This method must be used before * it is safe to use an instance via any other members. Calling this on an * initialized instance has no effect. * * \retval S_OK Initialization was successful and instance is ready for use. * \retval S_FALSE This instance was already initialized; no action was taken. * \retval E_OUTOFMEMORY Initialization failed due to lack of heap space, the * instance was left safely in an uninitialized state. */ Status EpochManager::Initialize() { if(epoch_table_) return Status::OK(); MinEpochTable* new_table = new MinEpochTable(); if(new_table == nullptr) return Status::Corruption("Out of memory"); RETURN_NOT_OK(new_table->Initialize()); current_epoch_ = 1; safe_to_reclaim_epoch_ = 0; epoch_table_ = new_table; return Status::OK(); } /** * Uninitialize an initialized EpochManager. This method must be used before * it is safe to destroy or re-initialize an EpochManager. The caller is * responsible for ensuring no threads are protected (have started a Protect() * without having completed an Unprotect() and that no threads will call * Protect()/Unprotect() while the manager is uninitialized; failing to do * so results in undefined behavior. Calling Uninitialize() on an uninitialized * instance has no effect. * * \return Success or or may return other error codes indicating a * failure deallocating the thread local storage used by the EpochManager * internally. Even for returns other than success the object is safely * left in an uninitialized state, though some thread local resources may * not have been reclaimed properly. * \retval S_OK Success. * \retval S_FALSE Success; instance was already uninitialized, so no effect. */ Status EpochManager::Uninitialize() { if(!epoch_table_) return Status::OK(); Status s = epoch_table_->Uninitialize(); // Keep going anyway. Even if the inner table fails to completely // clean up we want to clean up as much as possible. delete epoch_table_; epoch_table_ = nullptr; current_epoch_ = 1; safe_to_reclaim_epoch_ = 0; return s; } /** * Increment the current epoch; this should be called "occasionally" to * ensure that items removed from client data structures can eventually be * removed. Roughly, items removed from data structures cannot be reclaimed * until the epoch in which they were removed ends and all threads that may * have operated in the protected region during that Epoch have exited the * protected region. As a result, the current epoch should be bumped whenever * enough items have been removed from data structures that they represent * a significant amount of memory. Bumping the epoch unnecessarily may impact * performance, since it is an atomic operation and invalidates a read-hot * object in the cache of all of the cores. * * Only called by GarbageList. */ void EpochManager::BumpCurrentEpoch() { Epoch newEpoch = current_epoch_.fetch_add(1, std::memory_order_seq_cst); ComputeNewSafeToReclaimEpoch(newEpoch); } // - private - /** * Looks at all of the threads in the protected region and the current * Epoch and updates the Epoch that is guaranteed to be safe for * reclamation (stored in #m_safeToReclaimEpoch). This must be called * occasionally to ensure the system makes garbage collection progress. * For now, it's called every time bumpCurrentEpoch() is called, which * might work as a reasonable heuristic for when this should be called. */ void EpochManager::ComputeNewSafeToReclaimEpoch(Epoch currentEpoch) { safe_to_reclaim_epoch_.store( epoch_table_->ComputeNewSafeToReclaimEpoch(currentEpoch), std::memory_order_release); } // --- EpochManager::MinEpochTable --- /// Create an uninitialized table. EpochManager::MinEpochTable::MinEpochTable() : table_{ nullptr }, size_{} { } /** * Initialize an uninitialized table. This method must be used before * it is safe to use an instance via any other members. Calling this on an * initialized instance has no effect. * * \param size The initial number of distinct threads to support calling * Protect()/Unprotect(). This must be a power of two. If the table runs * out of space to track threads, then calls may stall. Internally, the * table may allocate additional tables to solve this, or it may reclaim * entries in the table after a long idle periods of by some threads. * If this number is too large it may slow down threads performing * space reclamation, since this table must be scanned occasionally to * make progress. * TODO(stutsman) Table growing and entry reclamation are not yet implemented. * Currently, the manager supports precisely size distinct threads over the * lifetime of the manager until it begins permanently spinning in all calls to * Protect(). * * \retval S_OK Initialization was successful and instance is ready for use. * \retval S_FALSE Instance was already initialized; instance is ready for use. * \retval E_INVALIDARG \a size was not a power of two. * \retval E_OUTOFMEMORY Initialization failed due to lack of heap space, the * instance was left safely in an uninitialized state. * \retval HRESULT_FROM_WIN32(TLS_OUT_OF_INDEXES) Initialization failed because * TlsAlloc() failed; the table was safely left in an uninitialized state. */ Status EpochManager::MinEpochTable::Initialize(uint64_t size) { if(table_) return Status::OK(); if(!IS_POWER_OF_TWO(size)) return Status::InvalidArgument( "size not a power of two"); Entry* new_table = new Entry[size]; if(!new_table) return Status::Corruption("Out of memory"); // Ensure the table is cacheline size aligned. assert(!(reinterpret_cast<uintptr_t>(new_table)& (CACHELINE_SIZE - 1))); table_ = new_table; size_ = size; return Status::OK(); } /** * Uninitialize an initialized table. This method must be used before * it is safe to destroy or re-initialize an table. The caller is * responsible for ensuring no threads are protected (have started a Protect() * without having completed an Unprotect() and that no threads will call * Protect()/Unprotect() while the manager is uninitialized; failing to do * so results in undefined behavior. Calling Uninitialize() on an uninitialized * instance has no effect. * * \return May return other error codes indicating a failure deallocating the * thread local storage used by the table internally. Even for returns * other than success the object is safely left in an uninitialized state, * though some thread local resources may not have been reclaimed * properly. * \retval S_OK Success; resources were reclaimed and table is uninitialized. * \retval S_FALSE Success; no effect, since table was already uninitialized. */ Status EpochManager::MinEpochTable::Uninitialize() { if(!table_) return Status::OK(); size_ = 0; delete[] table_; table_ = nullptr; return Status::OK(); } /** * Enter the thread into the protected code region, which guarantees * pointer stability for records in client data structures. After this * call, accesses to protected data structure items are guaranteed to be * safe, even if the item is concurrently removed from the structure. * * Behavior is undefined if Protect() is called from an already * protected thread. Upon creation, threads are unprotected. * * \param currentEpoch A sequentially consistent snapshot of the current * global epoch. It is okay that this may be stale by the time it * actually gets entered into the table. * \return S_OK indicates thread may now enter the protected region. Any * other return indicates a fatal problem accessing the thread local * storage; the thread may not enter the protected region. Most likely * the library has entered some non-serviceable state. */ Status EpochManager::MinEpochTable::Protect(Epoch current_epoch) { Entry* entry = nullptr; RETURN_NOT_OK(GetEntryForThread(&entry)); entry->last_unprotected_epoch = 0; #if 1 entry->protected_epoch.store(current_epoch, std::memory_order_release); // TODO: For this to really make sense according to the spec we // need a (relaxed) load on entry->protected_epoch. What we want to // ensure is that loads "above" this point in this code don't leak down // and access data structures before it is safe. // Consistent with http://preshing.com/20130922/acquire-and-release-fences/ // but less clear whether it is consistent with stdc++. std::atomic_thread_fence(std::memory_order_acquire); #else entry->m_protectedEpoch.exchange(currentEpoch, std::memory_order_acq_rel); #endif return Status::OK(); } /** * Exit the thread from the protected code region. The thread must * promise not to access pointers to elements in the protected data * structures beyond this call. * * Behavior is undefined if Unprotect() is called from an already * unprotected thread. * * \param currentEpoch A any rough snapshot of the current global epoch, so * long as it is greater than or equal to the value used on the thread's * corresponding call to Protect(). * \return S_OK indicates thread successfully exited protected region. Any * other return indicates a fatal problem accessing the thread local * storage; the thread may not have successfully exited the protected * region. Most likely the library has entered some non-serviceable * state. */ Status EpochManager::MinEpochTable::Unprotect(Epoch currentEpoch) { Entry* entry = nullptr; RETURN_NOT_OK(GetEntryForThread(&entry)); DCHECK(entry->thread_id.load() == Environment::Get()->GetThreadId()); entry->last_unprotected_epoch = currentEpoch; std::atomic_thread_fence(std::memory_order_release); entry->protected_epoch.store(0, std::memory_order_relaxed); return Status::OK(); } /** * Looks at all of the threads in the protected region and \a currentEpoch * and returns the latest Epoch that is guaranteed to be safe for reclamation. * That is, all items removed and tagged with a lower Epoch than returned by * this call may be safely reused. * * \param currentEpoch A snapshot of the current global Epoch; it is okay * that the snapshot may lag the true current epoch slightly. * \return An Epoch that can be compared to Epochs associated with items * removed from data structures. If an Epoch associated with a removed * item is less or equal to the returned value, then it is guaranteed * that no future thread will access the item, and it can be reused * (by calling, free() on it, for example). The returned value will * never be equal to or greater than the global epoch at any point, ever. * That ensures that removed items in one Epoch can never be freed * within the same Epoch. */ Epoch EpochManager::MinEpochTable::ComputeNewSafeToReclaimEpoch( Epoch current_epoch) { Epoch oldest_call = current_epoch; for(uint64_t i = 0; i < size_; ++i) { Entry& entry = table_[i]; // If any other thread has flushed a protected epoch to the cache // hierarchy we're guaranteed to see it even with relaxed access. Epoch entryEpoch = entry.protected_epoch.load(std::memory_order_acquire); if(entryEpoch != 0 && entryEpoch < oldest_call) { oldest_call = entryEpoch; } } // The latest safe epoch is the one just before the earlier unsafe one. return oldest_call - 1; } // - private - /** * Get a pointer to the thread-specific state needed for a thread to * Protect()/Unprotect(). If no thread-specific Entry has been allocated * yet, then one it transparently allocated and its address is stashed * in the thread's local storage. * * \param[out] entry Points to an address that is populated with * a pointer to the thread's Entry upon return. It is illegal to * pass nullptr. * \return S_OK if the thread's entry was discovered or allocated; in such * a successful call \a entry points to a pointer to the Entry. * Any other return value means there was a problem accessing or * setting values in the thread's local storage. The value pointed * to by entry remains unchanged, but the library may have entered * a non-serviceable state. */ Status EpochManager::MinEpochTable::GetEntryForThread(Entry** entry) { thread_local Entry *tls = nullptr; if(tls) { *entry = tls; return Status::OK(); } // No entry index was found in TLS, so we need to reserve a new entry // and record its index in TLS Entry* reserved = ReserveEntryForThread(); tls = *entry = reserved; Thread::RegisterTls((uint64_t*)&tls, (uint64_t)nullptr); return Status::OK(); } uint32_t Murmur3(uint32_t h) { h ^= h >> 16; h *= 0x85ebca6b; h ^= h >> 13; h *= 0xc2b2ae35; h ^= h >> 16; return h; } /** * Allocate a new Entry to track a thread's protected/unprotected status and * return a pointer to it. This should only be called once for a thread. */ EpochManager::MinEpochTable::Entry* EpochManager::MinEpochTable::ReserveEntryForThread() { uint64_t current_thread_id = Environment::Get()->GetThreadId(); uint64_t startIndex = Murmur3_64(current_thread_id); return ReserveEntry(startIndex, current_thread_id); } /** * Does the heavy lifting of reserveEntryForThread() and is really just * split out for easy unit testing. This method relies on the fact that no * thread will ever have ID on Windows 0. * http://msdn.microsoft.com/en-us/library/windows/desktop/ms686746(v=vs.85).aspx */ EpochManager::MinEpochTable::Entry* EpochManager::MinEpochTable::ReserveEntry(uint64_t start_index, uint64_t thread_id) { for(;;) { // Reserve an entry in the table. for(uint64_t i = 0; i < size_; ++i) { uint64_t indexToTest = (start_index + i) & (size_ - 1); Entry& entry = table_[indexToTest]; if(entry.thread_id == 0) { uint64_t expected = 0; // Atomically grab a slot. No memory barriers needed. // Once the threadId is in place the slot is locked. bool success = entry.thread_id.compare_exchange_strong(expected, thread_id, std::memory_order_relaxed); if(success) { return &table_[indexToTest]; } // Ignore the CAS failure since the entry must be populated, // just move on to the next entry. } } ReclaimOldEntries(); } } bool EpochManager::MinEpochTable::IsProtected() { Entry* entry = nullptr; Status s = GetEntryForThread(&entry); CHECK_EQ(s.ok(), true); // It's myself checking my own protected_epoch, safe to use relaxed return entry->protected_epoch.load(std::memory_order_relaxed) != 0; } void EpochManager::MinEpochTable::ReleaseEntryForThread() { } void EpochManager::MinEpochTable::ReclaimOldEntries() { } } // namespace pmwcas <file_sep>cmake_minimum_required (VERSION 2.8.12 FATAL_ERROR) if (POLICY CMP0042) cmake_policy (SET CMP0042 NEW) endif () # ---------------------------------------------------------------------------- # includes set (CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") include (utils) # ---------------------------------------------------------------------------- # package information set (PACKAGE_NAME "gflags") set (PACKAGE_VERSION "2.2.0") set (PACKAGE_STRING "${PACKAGE_NAME} ${PACKAGE_VERSION}") set (PACKAGE_TARNAME "${PACKAGE_NAME}-${PACKAGE_VERSION}") set (PACKAGE_BUGREPORT "https://github.com/schuhschuh/gflags/issues") project (${PACKAGE_NAME} CXX) if (CMAKE_VERSION VERSION_LESS 100) # C language still needed because the following required CMake modules # (or their dependencies, respectively) are not correctly handling # the case where only CXX is enabled. # - CheckTypeSize.cmake (fixed in CMake 3.1, cf. http://www.cmake.org/Bug/view.php?id=14056) # - FindThreads.cmake (--> CheckIncludeFiles.cmake <--) enable_language (C) endif () version_numbers ( ${PACKAGE_VERSION} PACKAGE_VERSION_MAJOR PACKAGE_VERSION_MINOR PACKAGE_VERSION_PATCH ) set (PACKAGE_SOVERSION "${PACKAGE_VERSION_MAJOR}") # ---------------------------------------------------------------------------- # options if (NOT GFLAGS_NAMESPACE) # maintain binary backwards compatibility with gflags library version <= 2.0, # but at the same time enable the use of the preferred new "gflags" namespace set (GFLAGS_NAMESPACE "google;${PACKAGE_NAME}" CACHE STRING "Name(s) of library namespace (separate multiple options by semicolon)") mark_as_advanced (GFLAGS_NAMESPACE) endif () set (GFLAGS_NAMESPACE_SECONDARY "${GFLAGS_NAMESPACE}") list (REMOVE_DUPLICATES GFLAGS_NAMESPACE_SECONDARY) if (NOT GFLAGS_NAMESPACE_SECONDARY) message (FATAL_ERROR "GFLAGS_NAMESPACE must be set to one (or more) valid C++ namespace identifier(s separated by semicolon \";\").") endif () foreach (ns IN LISTS GFLAGS_NAMESPACE_SECONDARY) if (NOT ns MATCHES "^[a-zA-Z][a-zA-Z0-9_]*$") message (FATAL_ERROR "GFLAGS_NAMESPACE contains invalid namespace identifier: ${ns}") endif () endforeach () list (GET GFLAGS_NAMESPACE_SECONDARY 0 GFLAGS_NAMESPACE) list (REMOVE_AT GFLAGS_NAMESPACE_SECONDARY 0) option (BUILD_SHARED_LIBS "Request build of shared libraries." OFF) option (BUILD_STATIC_LIBS "Request build of static libraries (default if BUILD_SHARED_LIBS is OFF)." OFF) option (BUILD_gflags_LIB "Request build of the multi-threaded gflags library." ON) option (BUILD_gflags_nothreads_LIB "Request build of the single-threaded gflags library." ON) option (BUILD_PACKAGING "Enable build of distribution packages using CPack." OFF) option (BUILD_TESTING "Enable build of the unit tests and their execution using CTest." OFF) option (INSTALL_HEADERS "Request packaging of headers and other development files." ON) mark_as_advanced (CLEAR CMAKE_INSTALL_PREFIX) mark_as_advanced (CMAKE_CONFIGURATION_TYPES BUILD_STATIC_LIBS INSTALL_HEADERS) if (APPLE) mark_as_advanced(CMAKE_OSX_ARCHITECTURES CMAKE_OSX_DEPLOYMENT_TARGET CMAKE_OSX_SYSROOT) endif () if (NOT BUILD_SHARED_LIBS AND NOT BUILD_STATIC_LIBS) set (BUILD_STATIC_LIBS ON) endif () if (NOT BUILD_gflags_LIB AND NOT BUILD_gflags_nothreads_LIB) message (FATAL_ERROR "At least one of BUILD_gflags_LIB and BUILD_gflags_nothreads_LIB must be ON.") endif () if (NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CXX_FLAGS) set_property (CACHE CMAKE_BUILD_TYPE PROPERTY VALUE Release) endif () if (NOT GFLAGS_INCLUDE_DIR) set (GFLAGS_INCLUDE_DIR "${PACKAGE_NAME}" CACHE STRING "Name of include directory of installed header files") mark_as_advanced (GFLAGS_INCLUDE_DIR) else () if (IS_ABSOLUTE GFLAGS_INCLUDE_DIR) message (FATAL_ERROR "GFLAGS_INCLUDE_DIR must be a path relative to CMAKE_INSTALL_PREFIX/include") endif () if (GFLAGS_INCLUDE_DIR MATCHES "^\\.\\.[/\\]") message (FATAL_ERROR "GFLAGS_INCLUDE_DIR must not start with parent directory reference (../)") endif () endif () # ---------------------------------------------------------------------------- # system checks include (CheckTypeSize) include (CheckIncludeFileCXX) include (CheckCXXSymbolExists) if (WIN32 AND NOT CYGWIN) set (OS_WINDOWS 1) else () set (OS_WINDOWS 0) endif () if (MSVC) set (HAVE_SYS_TYPES_H 1) set (HAVE_STDINT_H 1) set (HAVE_STDDEF_H 1) # used by CheckTypeSize module set (HAVE_INTTYPES_H 0) set (HAVE_UNISTD_H 0) set (HAVE_SYS_STAT_H 1) set (HAVE_SHLWAPI_H 1) else () foreach (fname IN ITEMS unistd stdint inttypes sys/types sys/stat fnmatch) string (TOUPPER "${fname}" FNAME) string (REPLACE "/" "_" FNAME "${FNAME}") if (NOT HAVE_${FNAME}_H) check_include_file_cxx ("${fname}.h" HAVE_${FNAME}_H) endif () endforeach () # the following are used in #if directives not #ifdef bool_to_int (HAVE_STDINT_H) bool_to_int (HAVE_SYS_TYPES_H) bool_to_int (HAVE_INTTYPES_H) if (NOT HAVE_FNMATCH_H AND OS_WINDOWS) check_include_file_cxx ("shlwapi.h" HAVE_SHLWAPI_H) endif () endif () set (GFLAGS_INTTYPES_FORMAT "" CACHE STRING "Format of integer types: \"C99\" (uint32_t), \"BSD\" (u_int32_t), \"VC7\" (__int32)") set_property (CACHE GFLAGS_INTTYPES_FORMAT PROPERTY STRINGS "C99;BSD;VC7") mark_as_advanced (GFLAGS_INTTYPES_FORMAT) if (NOT GFLAGS_INTTYPES_FORMAT) set (TYPES uint32_t u_int32_t) if (MSVC) list (INSERT TYPES 0 __int32) endif () foreach (type IN LISTS TYPES) check_type_size (${type} ${type} LANGUAGE CXX) if (HAVE_${type}) break () endif () endforeach () if (HAVE_uint32_t) set_property (CACHE GFLAGS_INTTYPES_FORMAT PROPERTY VALUE C99) elseif (HAVE_u_int32_t) set_property (CACHE GFLAGS_INTTYPES_FORMAT PROPERTY VALUE BSD) elseif (HAVE___int32) set_property (CACHE GFLAGS_INTTYPES_FORMAT PROPERTY VALUE VC7) else () mark_as_advanced (CLEAR GFLAGS_INTTYPES_FORMAT) message (FATAL_ERROR "Do not know how to define a 32-bit integer quantity on your system!" " Neither uint32_t, u_int32_t, nor __int32 seem to be available." " Set GFLAGS_INTTYPES_FORMAT to either C99, BSD, or VC7 and try again.") endif () endif () # use of special characters in strings to circumvent bug #0008226 if ("^${GFLAGS_INTTYPES_FORMAT}$" STREQUAL "^WIN$") set_property (CACHE GFLAGS_INTTYPES_FORMAT PROPERTY VALUE VC7) endif () if (NOT GFLAGS_INTTYPES_FORMAT MATCHES "^(C99|BSD|VC7)$") message (FATAL_ERROR "Invalid value for GFLAGS_INTTYPES_FORMAT! Choose one of \"C99\", \"BSD\", or \"VC7\"") endif () set (GFLAGS_INTTYPES_FORMAT_C99 0) set (GFLAGS_INTTYPES_FORMAT_BSD 0) set (GFLAGS_INTTYPES_FORMAT_VC7 0) set ("GFLAGS_INTTYPES_FORMAT_${GFLAGS_INTTYPES_FORMAT}" 1) if (MSVC) set (HAVE_strtoll 0) set (HAVE_strtoq 0) else () check_cxx_symbol_exists (strtoll stdlib.h HAVE_STRTOLL) if (NOT HAVE_STRTOLL) check_cxx_symbol_exists (strtoq stdlib.h HAVE_STRTOQ) endif () endif () set (CMAKE_THREAD_PREFER_PTHREAD TRUE) find_package (Threads) if (Threads_FOUND AND CMAKE_USE_PTHREADS_INIT) set (HAVE_PTHREAD 1) check_type_size (pthread_rwlock_t RWLOCK LANGUAGE CXX) else () set (HAVE_PTHREAD 0) endif () if (UNIX AND NOT HAVE_PTHREAD AND BUILD_gflags_LIB) if (CMAKE_HAVE_PTHREAD_H) set (what "library") else () set (what ".h file") endif () message (FATAL_ERROR "Could not find pthread${what}. Check the log file" "\n\t${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log" "\nor disable the build of the multi-threaded gflags library (BUILD_gflags_LIB=OFF).") endif () # ---------------------------------------------------------------------------- # source files - excluding root subdirectory and/or .in suffix set (PUBLIC_HDRS "gflags.h" "gflags_declare.h" "gflags_completions.h" ) if (GFLAGS_NAMESPACE_SECONDARY) set (INCLUDE_GFLAGS_NS_H "// Import gflags library symbols into alternative/deprecated namespace(s)") foreach (ns IN LISTS GFLAGS_NAMESPACE_SECONDARY) string (TOUPPER "${ns}" NS) set (gflags_ns_h "${PROJECT_BINARY_DIR}/include/${GFLAGS_INCLUDE_DIR}/gflags_${ns}.h") configure_file ("${PROJECT_SOURCE_DIR}/src/gflags_ns.h.in" "${gflags_ns_h}" @ONLY) list (APPEND PUBLIC_HDRS "${gflags_ns_h}") set (INCLUDE_GFLAGS_NS_H "${INCLUDE_GFLAGS_NS_H}\n#include \"gflags_${ns}.h\"") endforeach () else () set (INCLUDE_GFLAGS_NS_H) endif () set (PRIVATE_HDRS "config.h" "util.h" "mutex.h" ) set (GFLAGS_SRCS "gflags.cc" "gflags_reporting.cc" "gflags_completions.cc" ) if (OS_WINDOWS) list (APPEND PRIVATE_HDRS "windows_port.h") list (APPEND GFLAGS_SRCS "windows_port.cc") endif () # ---------------------------------------------------------------------------- # configure source files if (CMAKE_COMPILER_IS_GNUCXX) set (GFLAGS_ATTRIBUTE_UNUSED "__attribute((unused))") else () set (GFLAGS_ATTRIBUTE_UNUSED) endif () # whenever we build a shared library (DLL on Windows), configure the public # headers of the API for use of this library rather than the optionally # also build statically linked library; users can override GFLAGS_DLL_DECL if (BUILD_SHARED_LIBS) set (GFLAGS_IS_A_DLL 1) else () set (GFLAGS_IS_A_DLL 0) endif () configure_headers (PUBLIC_HDRS ${PUBLIC_HDRS}) configure_sources (PRIVATE_HDRS ${PRIVATE_HDRS}) configure_sources (GFLAGS_SRCS ${GFLAGS_SRCS}) # ---------------------------------------------------------------------------- # output directories set (CMAKE_RUNTIME_OUTPUT_DIRECTORY "bin") set (CMAKE_LIBRARY_OUTPUT_DIRECTORY "lib") set (CMAKE_ARCHIVE_OUTPUT_DIRECTORY "lib") # ---------------------------------------------------------------------------- # installation directories if (OS_WINDOWS) set (RUNTIME_INSTALL_DIR Bin) set (LIBRARY_INSTALL_DIR Lib) set (INCLUDE_INSTALL_DIR Include) set (CONFIG_INSTALL_DIR CMake) else () set (RUNTIME_INSTALL_DIR bin) # The LIB_INSTALL_DIR and LIB_SUFFIX variables are used by the Fedora # package maintainers. Also package maintainers of other distribution # packages need to be able to specify the name of the library directory. if (NOT LIB_INSTALL_DIR) set (LIB_INSTALL_DIR "lib${LIB_SUFFIX}") endif () set (LIBRARY_INSTALL_DIR "${LIB_INSTALL_DIR}" CACHE PATH "Directory of installed libraries, e.g., \"lib64\"" ) mark_as_advanced (LIBRARY_INSTALL_DIR) set (INCLUDE_INSTALL_DIR include) set (CONFIG_INSTALL_DIR ${LIBRARY_INSTALL_DIR}/cmake/${PACKAGE_NAME}) endif () # ---------------------------------------------------------------------------- # add library targets set (TARGETS) # static vs. shared foreach (TYPE IN ITEMS STATIC SHARED) if (BUILD_${TYPE}_LIBS) # whether or not targets are a DLL if (OS_WINDOWS AND "^${TYPE}$" STREQUAL "^SHARED$") set (GFLAGS_IS_A_DLL 1) else () set (GFLAGS_IS_A_DLL 0) endif () string (TOLOWER "${TYPE}" type) # multi-threaded vs. single-threaded foreach (opts IN ITEMS "" _nothreads) if (BUILD_gflags${opts}_LIB) add_library (gflags${opts}-${type} ${TYPE} ${GFLAGS_SRCS} ${PRIVATE_HDRS} ${PUBLIC_HDRS}) set (include_dirs "$<BUILD_INTERFACE:${PROJECT_BINARY_DIR}/include>") if (INSTALL_HEADERS) list (APPEND include_dirs "$<INSTALL_INTERFACE:${INCLUDE_INSTALL_DIR}>") endif () target_include_directories (gflags${opts}-${type} PUBLIC "${include_dirs}" PRIVATE "${PROJECT_SOURCE_DIR}/src;${PROJECT_BINARY_DIR}/include/${GFLAGS_INCLUDE_DIR}" ) if (opts MATCHES "nothreads") set (defines "GFLAGS_IS_A_DLL=${GFLAGS_IS_A_DLL};NOTHREADS") else () set (defines "GFLAGS_IS_A_DLL=${GFLAGS_IS_A_DLL}") if (CMAKE_USE_PTHREADS_INIT) target_link_libraries (gflags${opts}-${type} ${CMAKE_THREAD_LIBS_INIT}) endif () endif () set_target_properties ( gflags${opts}-${type} PROPERTIES COMPILE_DEFINITIONS "${defines}" OUTPUT_NAME "gflags${opts}" VERSION "${PACKAGE_VERSION}" SOVERSION "${PACKAGE_SOVERSION}" ) if (HAVE_SHLWAPI_H) target_link_libraries (gflags${opts}-${type} shlwapi.lib) endif () if (NOT TARGET gflags${opts}) add_library (gflags${opts} ALIAS gflags${opts}-${type}) else () add_dependencies (gflags${opts} gflags${opts}-${type}) endif () list (APPEND TARGETS gflags${opts}-${type}) endif () endforeach () endif () endforeach () # ---------------------------------------------------------------------------- # installation rules file (RELATIVE_PATH INSTALL_PREFIX_REL2CONFIG_DIR "${CMAKE_INSTALL_PREFIX}/${CONFIG_INSTALL_DIR}" "${CMAKE_INSTALL_PREFIX}") configure_file (cmake/config.cmake.in "${PROJECT_BINARY_DIR}/${PACKAGE_NAME}-config-install.cmake" @ONLY) configure_file (cmake/version.cmake.in "${PROJECT_BINARY_DIR}/${PACKAGE_NAME}-config-version.cmake" @ONLY) install (TARGETS ${TARGETS} DESTINATION ${LIBRARY_INSTALL_DIR} EXPORT gflags-lib) if (INSTALL_HEADERS) install (FILES ${PUBLIC_HDRS} DESTINATION ${INCLUDE_INSTALL_DIR}/${GFLAGS_INCLUDE_DIR}) install ( FILES "${PROJECT_BINARY_DIR}/${PACKAGE_NAME}-config-install.cmake" RENAME ${PACKAGE_NAME}-config.cmake DESTINATION ${CONFIG_INSTALL_DIR} ) install ( FILES "${PROJECT_BINARY_DIR}/${PACKAGE_NAME}-config-version.cmake" DESTINATION ${CONFIG_INSTALL_DIR} ) install (EXPORT gflags-lib DESTINATION ${CONFIG_INSTALL_DIR} FILE ${PACKAGE_NAME}-export.cmake) if (UNIX) install (PROGRAMS src/gflags_completions.sh DESTINATION ${RUNTIME_INSTALL_DIR}) endif () endif () # ---------------------------------------------------------------------------- # support direct use of build tree set (INSTALL_PREFIX_REL2CONFIG_DIR .) export (TARGETS ${TARGETS} FILE "${PROJECT_BINARY_DIR}/${PACKAGE_NAME}-export.cmake") export (PACKAGE gflags) configure_file (cmake/config.cmake.in "${PROJECT_BINARY_DIR}/${PACKAGE_NAME}-config.cmake" @ONLY) # ---------------------------------------------------------------------------- # testing - MUST follow the generation of the build tree config file if (BUILD_TESTING) include (CTest) enable_testing () add_subdirectory (test) endif () # ---------------------------------------------------------------------------- # packaging if (BUILD_PACKAGING) if (NOT BUILD_SHARED_LIBS AND NOT INSTALL_HEADERS) message (WARNING "Package will contain static libraries without headers!" "\nRecommended options for generation of runtime package:" "\n BUILD_SHARED_LIBS=ON" "\n BUILD_STATIC_LIBS=OFF" "\n INSTALL_HEADERS=OFF" "\nRecommended options for generation of development package:" "\n BUILD_SHARED_LIBS=ON" "\n BUILD_STATIC_LIBS=ON" "\n INSTALL_HEADERS=ON") endif () # default package generators if (APPLE) set (PACKAGE_GENERATOR "PackageMaker") set (PACKAGE_SOURCE_GENERATOR "TGZ;ZIP") elseif (UNIX) set (PACKAGE_GENERATOR "DEB;RPM") set (PACKAGE_SOURCE_GENERATOR "TGZ;ZIP") else () set (PACKAGE_GENERATOR "ZIP") set (PACKAGE_SOURCE_GENERATOR "ZIP") endif () # used package generators set (CPACK_GENERATOR "${PACKAGE_GENERATOR}" CACHE STRING "List of binary package generators (CPack).") set (CPACK_SOURCE_GENERATOR "${PACKAGE_SOURCE_GENERATOR}" CACHE STRING "List of source package generators (CPack).") mark_as_advanced (CPACK_GENERATOR CPACK_SOURCE_GENERATOR) # some package generators (e.g., PackageMaker) do not allow .md extension configure_file ("${CMAKE_CURRENT_LIST_DIR}/README.md" "${CMAKE_CURRENT_BINARY_DIR}/README.txt" COPYONLY) # common package information set (CPACK_PACKAGE_VENDOR "<NAME>") set (CPACK_PACKAGE_CONTACT "<EMAIL>") set (CPACK_PACKAGE_NAME "${PACKAGE_NAME}") set (CPACK_PACKAGE_VERSION "${PACKAGE_VERSION}") set (CPACK_PACKAGE_VERSION_MAJOR "${PACKAGE_VERSION_MAJOR}") set (CPACK_PACKAGE_VERSION_MINOR "${PACKAGE_VERSION_MINOR}") set (CPACK_PACKAGE_VERSION_PATCH "${PACKAGE_VERSION_PATCH}") set (CPACK_PACKAGE_DESCRIPTION_SUMMARY "A commandline flags library that allows for distributed flags.") set (CPACK_RESOURCE_FILE_WELCOME "${CMAKE_CURRENT_BINARY_DIR}/README.txt") set (CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_LIST_DIR}/COPYING.txt") set (CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_CURRENT_BINARY_DIR}/README.txt") set (CPACK_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}") set (CPACK_OUTPUT_FILE_PREFIX packages) set (CPACK_PACKAGE_RELOCATABLE TRUE) set (CPACK_MONOLITHIC_INSTALL TRUE) # RPM package information -- used in cmake/package.cmake.in also for DEB set (CPACK_RPM_PACKAGE_GROUP "Development/Libraries") set (CPACK_RPM_PACKAGE_LICENSE "BSD") set (CPACK_RPM_PACKAGE_URL "http://schuhschuh.github.com/gflags") set (CPACK_RPM_CHANGELOG_FILE "${CMAKE_CURRENT_LIST_DIR}/ChangeLog.txt") if (INSTALL_HEADERS) set (CPACK_RESOURCE_FILE_README "${CMAKE_CURRENT_LIST_DIR}/doc/index.html") else () set (CPACK_RESOURCE_FILE_README "${CMAKE_CURRENT_LIST_DIR}/cmake/README_runtime.txt") endif () # system/architecture if (WINDOWS) if (CMAKE_CL_64) set (CPACK_SYSTEM_NAME "win64") else () set (CPACK_SYSTEM_NAME "win32") endif () set (CPACK_PACKAGE_ARCHITECTURE) elseif (APPLE) set (CPACK_PACKAGE_ARCHITECTURE darwin) else () string (TOLOWER "${CMAKE_SYSTEM_NAME}" CPACK_SYSTEM_NAME) if (CMAKE_CXX_FLAGS MATCHES "-m32") set (CPACK_PACKAGE_ARCHITECTURE i386) else () execute_process ( COMMAND dpkg --print-architecture RESULT_VARIABLE RV OUTPUT_VARIABLE CPACK_PACKAGE_ARCHITECTURE ) if (RV EQUAL 0) string (STRIP "${CPACK_PACKAGE_ARCHITECTURE}" CPACK_PACKAGE_ARCHITECTURE) else () execute_process (COMMAND uname -m OUTPUT_VARIABLE CPACK_PACKAGE_ARCHITECTURE) if (CPACK_PACKAGE_ARCHITECTURE MATCHES "x86_64") set (CPACK_PACKAGE_ARCHITECTURE amd64) else () set (CPACK_PACKAGE_ARCHITECTURE i386) endif () endif () endif () endif () # source package settings set (CPACK_SOURCE_TOPLEVEL_TAG "source") set (CPACK_SOURCE_PACKAGE_FILE_NAME "${CPACK_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}") set (CPACK_SOURCE_IGNORE_FILES "/\\\\.git/;\\\\.swp$;\\\\.#;/#;\\\\.*~;cscope\\\\.*;/[Bb]uild[.+-_a-zA-Z0-9]*/") # default binary package settings set (CPACK_INCLUDE_TOPLEVEL_DIRECTORY TRUE) set (CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}-${CPACK_SYSTEM_NAME}") if (CPACK_PACKAGE_ARCHITECTURE) set (CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}-${CPACK_PACKAGE_ARCHITECTURE}") endif () # generator specific configuration file # # allow package maintainers to use their own configuration file # $ cmake -DCPACK_PROJECT_CONFIG_FILE:FILE=/path/to/package/config if (NOT CPACK_PROJECT_CONFIG_FILE) configure_file ( "${CMAKE_CURRENT_LIST_DIR}/cmake/package.cmake.in" "${PROJECT_BINARY_DIR}/${PACKAGE_NAME}-package.cmake" @ONLY ) set (CPACK_PROJECT_CONFIG_FILE "${PROJECT_BINARY_DIR}/${PACKAGE_NAME}-package.cmake") endif () include (CPack) endif () # BUILD_PACKAGING <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #include "include/environment.h" #include "common/allocator_internal.h" #include "util/auto_ptr.h" namespace pmwcas { unique_ptr_t<RandomReadWriteAsyncFile> RandomReadWriteAsyncFile::make_unique_ptr_t(RandomReadWriteAsyncFile* p) { return unique_ptr_t<RandomReadWriteAsyncFile>(p, [](RandomReadWriteAsyncFile* p) { Status s = p->Close(); ALWAYS_ASSERT(s.ok()); Allocator::Get()->Free(p); }); } } <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #define NOMINMAX #include <string> #include <inttypes.h> #include <gtest/gtest.h> #include "gflags/gflags.h" #include "glog/logging.h" #include "glog/raw_logging.h" #include "benchmarks/benchmark.h" #ifdef WIN32 #include "environment/environment_windows.h" #else #include "environment/environment_linux.h" #endif #include "include/pmwcas.h" #include "util/auto_ptr.h" #include "util/core_local.h" #include "double-linked-list/doubly_linked_list.h" #include "util/random_number_generator.h" using namespace pmwcas::benchmark; DEFINE_uint64(seed, 1234, "base random number generator seed, the thread index is added to this " "number to form the full seed"); DEFINE_uint64(metrics_dump_interval, 0, "if greater than 0, the benchmark " "driver dumps metrics at this fixed interval (in seconds)"); DEFINE_int32(insert_pct, 100, "percentage of insert"); DEFINE_int32(delete_pct, 0, "percentage of delete"); DEFINE_int32(search_pct, 0, "percentage of search"); DEFINE_int32(read_heavy, 0, "whether to run the read-heavy experiment"); DEFINE_uint64(read_heavy_modify_range, 0, "maximum how far away to randomly choose a location for insert/delete"); DEFINE_int32(initial_size, 0, "initial number of nodes in the list"); DEFINE_string(sync, "cas", "syncronization method: cas, pcas, mwcas, or pmwcas"); DEFINE_int32(affinity, 1, "affinity to use in scheduling threads"); DEFINE_uint64(threads, 2, "number of threads to use for multi-threaded tests"); DEFINE_uint64(seconds, 10, "default time to run a benchmark"); DEFINE_uint64(mwcas_desc_pool_size, 10000000, "number of total descriptors"); #ifdef PMEM DEFINE_uint64(write_delay_ns, 0, "NVRAM write delay (ns)"); DEFINE_bool(emulate_write_bw, false, "Emulate write bandwidth"); DEFINE_bool(clflush, false, "Use CLFLUSH, instead of spinning delays." "write_dealy_ns and emulate_write_bw will be ignored."); #ifdef PMDK DEFINE_string(pmdk_pool, "/mnt/pmem0/doubly_linked_list_benchmark_pool", "path to pmdk pool"); #endif #endif //DEFINE_uint64(payload_size, 8, "payload size of each node"); namespace pmwcas { /// Maximum number of threads that the benchmark driver supports. const size_t kMaxNumThreads = 64; /// Dumps args in a format that can be extracted by an experiment script void DumpArgs() { printf("> Args sync %s\n", FLAGS_sync.c_str()); printf("> Args insert %d%%\n", FLAGS_insert_pct); printf("> Args delete %d%%\n", FLAGS_delete_pct); printf("> Args search %d%%\n", FLAGS_search_pct); printf("> Args initial_size %d\n", FLAGS_initial_size); std::cout << "> Args threads " << FLAGS_threads << std::endl; std::cout << "> Args seconds " << FLAGS_seconds << std::endl; std::cout << "> Args affinity " << FLAGS_affinity << std::endl; std::cout << "> Args read_heavy " << FLAGS_read_heavy << std::endl; std::cout << "> Args mwcas_desc_pool_size " << FLAGS_mwcas_desc_pool_size << std::endl; #ifdef PMEM if(FLAGS_clflush) { printf("> Args using clflush\n"); } else { std::cout << "> Args write_delay_ns " << FLAGS_write_delay_ns << std::endl; std::cout << "> Args emulate_write_bw " << FLAGS_emulate_write_bw << std::endl; } #ifdef PMDK std::cout<<"> Args pmdk_pool "<<FLAGS_pmdk_pool<<std::endl; #endif #endif if(FLAGS_insert_pct + FLAGS_delete_pct + FLAGS_search_pct != 100) { LOG(FATAL) << "wrong operation mix"; } } struct DllStats { uint64_t n_insert; uint64_t n_delete; uint64_t n_search; uint64_t n_effective_insert; uint64_t n_effective_delete; uint64_t n_effective_search; DllStats() : n_insert(0), n_delete(0), n_search(0), n_effective_insert(0), n_effective_delete(0), n_effective_search(0) {} friend DllStats& operator+(DllStats &left, const DllStats& right) { left += right; return left; } DllStats& operator+=(const DllStats& other) { n_insert += other.n_insert; n_delete += other.n_delete; n_search += other.n_search; n_effective_insert += other.n_effective_insert; n_effective_delete += other.n_effective_delete; n_effective_search += other.n_effective_search; return *this; } DllStats& operator-=(const DllStats& other) { n_insert -= other.n_insert; n_delete -= other.n_delete; n_search -= other.n_search; n_effective_insert -= other.n_effective_insert; n_effective_delete -= other.n_effective_delete; n_effective_search -= other.n_effective_search; return *this; } }; struct DListBench : public Benchmark { DListBench() : Benchmark{} , cumulative_mwcas_stats {} , cumulative_dll_stats {} { } IDList* dll; MwCASMetrics cumulative_mwcas_stats; DllStats cumulative_dll_stats; CoreLocal<DllStats *> stats; uint32_t initial_local_insert; void Setup(size_t thread_count) { stats.Initialize(); if(FLAGS_sync == "cas") { dll = new CASDList; } else if(FLAGS_sync == "pcas") { #ifdef PMEM if(FLAGS_clflush) { NVRAM::InitializeClflush(); } else { NVRAM::InitializeSpin(FLAGS_write_delay_ns, FLAGS_emulate_write_bw); } dll = new CASDList(); #else LOG(FATAL) << "PMEM undefined"; #endif } else if(FLAGS_sync == "mwcas") { DescriptorPool* pool = new DescriptorPool( FLAGS_mwcas_desc_pool_size, FLAGS_threads); dll = new MwCASDList(pool); } else if(FLAGS_sync == "pmwcas") { #ifdef PMEM Descriptor* pool_va = nullptr; if(FLAGS_clflush) { NVRAM::InitializeClflush(); } else { NVRAM::InitializeSpin(FLAGS_write_delay_ns, FLAGS_emulate_write_bw); } DescriptorPool* pool = new DescriptorPool( FLAGS_mwcas_desc_pool_size, FLAGS_threads); dll = new MwCASDList(pool); #else LOG(FATAL) << "PMEM undefined"; #endif } else { LOG(FATAL) << "wrong sync method"; } // Populate the list on behalf of each thread uint64_t thread_index = 0; uint64_t local_insert = 0; if(dll->GetSyncMethod() == IDList::kSyncMwCAS) { MwCASMetrics::ThreadInitialize(); } int32_t inserted = 0; for(int32_t i = 0; i < FLAGS_initial_size; ++i) { if(dll->GetSyncMethod() == IDList::kSyncMwCAS) { ((MwCASDList*)dll)->GetEpoch()->Protect(); } uint64_t payload_base = thread_index << 32; auto* node = IDList::NewNode(nullptr, nullptr, sizeof(uint64_t)); uint64_t val = local_insert | payload_base; memcpy(node->GetPayload(), (char *)&val, sizeof(uint64_t)); local_insert += ++thread_index % FLAGS_threads == 0 ? 1 : 0; thread_index %= FLAGS_threads; auto s = dll->InsertBefore(dll->GetTail(), node, false); RAW_CHECK(s.ok(), "loading failed"); inserted++; if(inserted % 10000 == 0) { LOG(INFO) << "Inserted " << inserted; } if(dll->GetSyncMethod() == IDList::kSyncMwCAS) { ((MwCASDList*)dll)->GetEpoch()->Unprotect(); } } initial_local_insert = local_insert; if(dll->GetSyncMethod() == IDList::kSyncMwCAS) { MwCASMetrics::Uninitialize(); MwCASMetrics::Initialize(); } } void Main(size_t thread_index) { DllStats *local_stats = new DllStats; *stats.MyObject() = local_stats; if(dll->GetSyncMethod() == IDList::kSyncMwCAS) { MwCASMetrics::ThreadInitialize(); } // WARNING: do not change the way these four variables are added // unless you know what you are doing. uint32_t insert_pct = FLAGS_insert_pct; uint32_t delete_pct = insert_pct + FLAGS_delete_pct; uint32_t search_pct = delete_pct + FLAGS_search_pct; uint64_t payload_base = (uint64_t)thread_index << 32; RandomNumberGenerator rng{}; const uint64_t kEpochThreshold = 1000; const uint64_t kPreallocNodes = 600000000 / FLAGS_threads; #ifdef WIN32 DListNode* nodes = (DListNode*)_aligned_malloc( (sizeof(DListNode) + sizeof(uint64_t)) * kPreallocNodes, kCacheLineSize); #else DListNode* nodes = nullptr; int n = posix_memalign((void**)&nodes, kCacheLineSize, (sizeof(DListNode) + sizeof(uint64_t)) * kPreallocNodes); #endif RAW_CHECK(nodes, "out of memory"); uint64_t next_node = 0; WaitForStart(); auto* node = dll->GetHead(); bool mwcas = dll->GetSyncMethod() == IDList::kSyncMwCAS; DListCursor cursor((IDList*)dll); uint64_t epochs = 0; if(FLAGS_read_heavy) { while(!IsShutdown()) { cursor.Reset(); if(mwcas && ++epochs == kEpochThreshold) { ((MwCASDList*)dll)->GetEpoch()->Unprotect(); ((MwCASDList*)dll)->GetEpoch()->Protect(); epochs = 0; } uint32_t op = rng.Generate(100); uint64_t range = FLAGS_read_heavy_modify_range; if(FLAGS_read_heavy_modify_range == 0) { // Find a random position // (est. total_insert = local_insert * number of threads) range = FLAGS_initial_size + (local_stats->n_insert - local_stats->n_delete) * FLAGS_threads; range = std::max(range, (uint64_t)0); } int32_t pos = rng.Generate(range); if(op < insert_pct) { while(pos-- > 0) { node = cursor.Next(); if(node == dll->GetTail()) { cursor.Reset(); } } RAW_CHECK(node, "invalid node pointer"); uint64_t val = (initial_local_insert + local_stats->n_insert) | payload_base; auto* new_node = &nodes[next_node++]; RAW_CHECK(next_node < kPreallocNodes, "No more nodes"); new(new_node) DListNode(nullptr, nullptr, sizeof(uint64_t)); memcpy(new_node->GetPayload(), (char *)&val, sizeof(uint64_t)); Status s; if (rng.Generate(2) == 0) { s = dll->InsertAfter(node, new_node, true); } else { s = dll->InsertBefore(node, new_node, true); } if(s.ok()) { ++local_stats->n_effective_insert; } ++local_stats->n_insert; } else { if(FLAGS_read_heavy_modify_range == 0) { uint32_t thread_index = rng.Generate(FLAGS_threads); uint32_t local_index = rng.Generate( initial_local_insert + local_stats->n_insert + 1); uint64_t expected_value = ((uint64_t)thread_index << 32) | local_index; auto* node = dll->GetNext(dll->GetHead()); bool found = false; while(!found && node != dll->GetTail()) { if(expected_value == *(uint64_t*)node->GetPayload()) { found = true; } else { node = cursor.Next(); } } if(op < delete_pct) { auto s = dll->Delete(node, true); ++local_stats->n_delete; if(s.ok()) { ++local_stats->n_effective_delete; } } else { ++local_stats->n_search; if(found) { ++local_stats->n_effective_search; } } } else { while(pos-- > 0) { node = cursor.Next(); if(node == dll->GetTail()) { cursor.Reset(); } } // Must be delete, search is not supported here RAW_CHECK(op < delete_pct, "search is not supported for the current setting"); auto s = dll->Delete(node, true); ++local_stats->n_delete; if(s.ok()) { ++local_stats->n_effective_delete; } } } } } else { // This one resembles the original DLL paper's experiment while(!IsShutdown()) { if(mwcas && ++epochs == kEpochThreshold) { ((MwCASDList*)dll)->GetEpoch()->Unprotect(); ((MwCASDList*)dll)->GetEpoch()->Protect(); epochs = 0; } uint32_t op = rng.Generate(100); bool forward = true; if (op < insert_pct) { uint64_t val = (initial_local_insert + local_stats->n_insert) | payload_base; auto* new_node = &nodes[next_node++]; RAW_CHECK(next_node < kPreallocNodes, "no more nodes"); new(new_node) DListNode(nullptr, nullptr, sizeof(uint64_t)); memcpy(new_node->GetPayload(), (char *)&val, sizeof(uint64_t)); Status s; if (rng.Generate(2) == 0) { s = dll->InsertAfter(node, new_node, true); } else { s = dll->InsertBefore(node, new_node, true); } if(s.ok()) { ++local_stats->n_effective_insert; } ++local_stats->n_insert; } else if(op < delete_pct) { auto s = dll->Delete(node, true); ++local_stats->n_delete; if(s.ok()) { ++local_stats->n_effective_delete; } } else { // Search if(node == dll->GetTail()) { forward = false; } else if (node == dll->GetHead()) { forward = true; } else { uint64_t payload = *(uint64_t*)node->GetPayload(); } if(forward) { node = cursor.Next(); } else { node = cursor.Prev(); } ++local_stats->n_search; ++local_stats->n_effective_search; } } } } virtual void Dump(size_t thread_count, uint64_t run_ticks, uint64_t dump_id, bool final_dump) { MARK_UNREFERENCED(thread_count); Benchmark::Dump(thread_count, run_ticks, dump_id, final_dump); if(dll->GetSyncMethod() == IDList::kSyncMwCAS) { MwCASMetrics mstats; MwCASMetrics::Sum(mstats); if(!final_dump) { mstats -= cumulative_mwcas_stats; cumulative_mwcas_stats += mstats; } mstats.Print(); } DllStats sum; SumDllStats(sum); if(final_dump) { std::cout << "> Benchmark " << dump_id << " InsertPerSecond " << (double)sum.n_insert / FLAGS_seconds << std::endl; std::cout << "> Benchmark " << dump_id << " DeletePerSecond " << (double)sum.n_delete / FLAGS_seconds << std::endl; std::cout << "> Benchmark " << dump_id << " SearchPerSecond " << (double)sum.n_search / FLAGS_seconds << std::endl; std::cout << "> Benchmark " << dump_id << " EffectiveInsertPerSecond " << (double)sum.n_effective_insert / FLAGS_seconds << std::endl; std::cout << "> Benchmark " << dump_id << " EffectiveDeletePerSecond " << (double)sum.n_effective_delete / FLAGS_seconds << std::endl; std::cout << "> Benchmark " << dump_id << " EffectiveSearchPerSecond " << (double)sum.n_effective_search / FLAGS_seconds << std::endl; } else { sum -= cumulative_dll_stats; cumulative_dll_stats += sum; std::cout << "> Benchmark " << dump_id << " Insert " << sum.n_insert << std::endl; std::cout << "> Benchmark " << dump_id << " Delete " << sum.n_delete << std::endl; std::cout << "> Benchmark " << dump_id << " Search " << sum.n_search << std::endl; std::cout << "> Benchmark " << dump_id << " EffectiveInsert " << sum.n_effective_insert << std::endl; std::cout << "> Benchmark " << dump_id << " EffectiveDelete " << sum.n_effective_delete << std::endl; std::cout << "> Benchmark " << dump_id << " EffectiveSearch " << sum.n_effective_search << std::endl; } } void Teardown() { stats.Uninitialize(); } void SumDllStats(DllStats& sum) { for (uint32_t i = 0; i < stats.NumberOfObjects(); ++i) { auto* thread_metric = *stats.GetObject(i); sum += *thread_metric; } } uint64_t GetOperationCount() { if(dll->GetSyncMethod() == IDList::kSyncMwCAS) { MwCASMetrics metrics; MwCASMetrics::Sum(metrics); return metrics.GetUpdateAttemptCount(); } return 0; } }; } // namespace pmwcas int main(int argc, char* argv[]) { google::InitGoogleLogging(argv[0]); google::ParseCommandLineFlags(&argc, &argv, true); #ifdef WIN32 pmwcas::InitLibrary(pmwcas::DefaultAllocator::Create, pmwcas::DefaultAllocator::Destroy, pmwcas::WindowsEnvironment::Create, pmwcas::WindowsEnvironment::Destroy); #else #ifdef PMDK pmwcas::InitLibrary(pmwcas::PMDKAllocator::Create(FLAGS_pmdk_pool.c_str(), "doubly_linked_bench_layout", static_cast<uint64_t>(1024) * 1024 * 1204 * 1), pmwcas::PMDKAllocator::Destroy, pmwcas::LinuxEnvironment::Create, pmwcas::LinuxEnvironment::Destroy); #else pmwcas::InitLibrary(pmwcas::TlsAllocator::Create, pmwcas::TlsAllocator::Destroy, pmwcas::LinuxEnvironment::Create, pmwcas::LinuxEnvironment::Destroy); #endif #endif pmwcas::DumpArgs(); pmwcas::DListBench test{}; test.Run(FLAGS_threads, FLAGS_seconds, static_cast<pmwcas::AffinityPattern>(FLAGS_affinity), FLAGS_metrics_dump_interval); return 0; } <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once #include <numa.h> #include <sys/mman.h> #include <sys/stat.h> #include <cstdint> #include <iostream> #include <atomic> #include <memory> #include <string> #include <unordered_map> #ifdef PMDK #include <libpmemobj.h> #endif #include "include/environment.h" #include "include/allocator.h" #include "include/status.h" #include "util/auto_ptr.h" #include "util/macros.h" namespace pmwcas { class LinuxSharedMemorySegment : public SharedMemorySegment { public: LinuxSharedMemorySegment(); ~LinuxSharedMemorySegment(); static Status Create(unique_ptr_t<SharedMemorySegment>& segment); virtual Status Initialize(const std::string& segname, uint64_t size, bool open_existing) override; virtual Status Attach(void* base_address = nullptr) override; virtual Status Detach() override; virtual void* GetMapAddress() override; //virtual DumpToFile(const std::string& filename) override; private: std::string segment_name_; uint64_t size_; int map_fd_; void* map_address_; }; class LinuxEnvironment : public IEnvironment { public: LinuxEnvironment(); virtual ~LinuxEnvironment() {} static Status Create(IEnvironment*& environment) { int n = posix_memalign(reinterpret_cast<void**>(&environment), kCacheLineSize, sizeof(LinuxEnvironment)); if(!environment || n != 0) return Status::Corruption("Out of memory"); new(environment)LinuxEnvironment(); return Status::OK(); } static void Destroy(IEnvironment* e) { LinuxEnvironment* environment = static_cast<LinuxEnvironment*>(e); environment->~LinuxEnvironment(); free(environment); } virtual uint64_t NowMicros() override; virtual uint64_t NowNanos() override; virtual uint32_t GetCoreCount() override; virtual void Sleep(uint32_t ms_to_sleep) override; virtual Status NewRandomReadWriteAsyncFile(const std::string& filename, const FileOptions& options, ThreadPool* threadpool, RandomReadWriteAsyncFile** file, bool* exists = nullptr) override ; virtual Status NewSharedMemorySegment(const std::string& segname, uint64_t size, bool open_existing, SharedMemorySegment** seg) override; virtual Status NewThreadPool(uint32_t max_threads, ThreadPool** pool) override; virtual Status SetThreadAffinity(uint64_t core, AffinityPattern affinity_pattern) override; virtual Status GetWorkingDirectory(std::string& directory) override; virtual Status GetExecutableDirectory(std::string& directory) override; private: Status SetThreadAffinity(pthread_t thread, uint64_t core, AffinityPattern affinity_pattern); }; /// A simple thread-local allocator that implements the IAllocator interface. /// Memory is never returned to the OS, but always retained in thread-local /// sets to be reused later. Each piece of user-facing memory is accompanied by /// header that describes the size of the memory block. All memory blocks of /// the same size are chained together in a hash table that maps memory block /// sizes to memory block chains of the specified size. class TlsAllocator : public IAllocator { public: static const uint64_t MB = 1024 * 1024; static const uint64_t kNumaMemorySize = 4096 * MB; char** numa_memory_; uint64_t* numa_allocated_; // The hidden part of each allocated block of memory struct Header { uint64_t size; Header* next; char padding[kCacheLineSize - sizeof(size) - sizeof(next)]; Header() : size(0), next(nullptr) {} inline void* GetData() { return (void*)((char*)this + sizeof(*this)); } }; // Chain of all memory blocks of the same size struct BlockList { Header* head; Header* tail; BlockList() : head(nullptr), tail(nullptr) {} BlockList(Header* h, Header* t) : head(h), tail(t) {} inline void* Get() { if(head) { Header* alloc = head; if(alloc == tail) { head = tail = nullptr; } else { head = head->next; } return alloc->GetData(); } return nullptr; } inline void Put(Header* header) { if(!head) { DCHECK(!tail); head = tail = header; } else { Header* old_tail = tail; old_tail->next = header; tail = header; header->next = nullptr; } DCHECK(head->size == header->size); } }; inline Header* ExtractHeader(void* pBytes) { return (Header*)((char*)pBytes - sizeof(Header)); } inline std::unordered_map<size_t, BlockList>& GetTlsMap() { thread_local std::unordered_map<size_t, BlockList> tls_blocks; return tls_blocks; } struct Slab { static const uint64_t kSlabSize = 512 * 1024 * 1024; // 512MB TlsAllocator* tls_allocator; uint64_t allocated; void* memory; Slab() : allocated(0), memory(nullptr) {} ~Slab() {} inline void* Allocate(size_t n) { retry: if(memory && allocated + n <= kSlabSize) { uint64_t off = allocated; allocated += n; return (void*)((char*)memory + off); } else { // Slab full or not initialized yet auto node = numa_node_of_cpu(sched_getcpu()); uint64_t off = __atomic_fetch_add(&tls_allocator->numa_allocated_[node], kSlabSize, __ATOMIC_SEQ_CST); memory = tls_allocator->numa_memory_[node] + off; ALWAYS_ASSERT(off < tls_allocator->kNumaMemorySize); allocated = 0; goto retry; } DCHECK(false); return nullptr; } }; inline Slab& GetTlsSlab() { thread_local Slab slab; thread_local bool initialized = false; if(!initialized) { slab.tls_allocator = this; initialized = true; } return slab; } /// Try to get something from the TLS set inline void* TlsAllocate(size_t nSize) { // Align to cache line size nSize = (nSize + sizeof(Header) + kCacheLineSize - 1) / kCacheLineSize * kCacheLineSize; auto& tls_map = GetTlsMap(); auto block_list = tls_map.find(nSize - sizeof(Header)); void* pBytes = nullptr; if(block_list != tls_map.end()) { pBytes = block_list->second.Get(); } if(!pBytes) { // Nothing in the map, try my local memory auto& tls_slab = GetTlsSlab(); pBytes = tls_slab.Allocate(nSize); if(pBytes) { ((Header*)pBytes)->size = nSize - sizeof(Header); ((Header*)pBytes)->next = nullptr; pBytes = (void*)((char*)pBytes + sizeof(Header)); } } DCHECK(pBytes); return pBytes; } public: TlsAllocator() { int nodes = numa_max_node() + 1; numa_memory_ = (char**)malloc(sizeof(char*) * nodes); numa_allocated_ = (uint64_t*)malloc(sizeof(uint64_t) * nodes); for(int i = 0; i < nodes; ++i) { numa_set_preferred(i); numa_memory_[i] = (char *)mmap( nullptr, kNumaMemorySize, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_HUGETLB | MAP_POPULATE, -1, 0); numa_allocated_[i] = 0; } } ~TlsAllocator() { int nodes = numa_max_node(); for(int i = 0; i < nodes; ++i) { numa_free(numa_memory_[i], kNumaMemorySize); } } static Status Create(IAllocator*& allocator) { int n = posix_memalign(reinterpret_cast<void**>(&allocator), kCacheLineSize, sizeof(TlsAllocator)); if(n || !allocator) return Status::Corruption("Out of memory"); new(allocator) TlsAllocator(); //uint64_t MB = 1024 * 1024; //void *m = malloc(8192 * MB); //free(m); return Status::OK(); } static void Destroy(IAllocator* a) { TlsAllocator* allocator = static_cast<TlsAllocator*>(a); allocator->~TlsAllocator(); free(allocator); } void Allocate(void **mem, size_t nSize) override { *mem= TlsAllocate(nSize); DCHECK(*mem); } void CAlloc(void **mem, size_t count, size_t size) override { /// TODO(tzwang): not implemented yet } void Free(void* pBytes) override { auto& tls_map = GetTlsMap(); // Extract the hidden size info Header* pHeader = ExtractHeader(pBytes); pHeader->next = nullptr; DCHECK(pHeader->size); auto block_list = tls_map.find(pHeader->size); if(block_list == tls_map.end()) { tls_map.emplace(pHeader->size, BlockList(pHeader, pHeader)); } else { block_list->second.Put(pHeader); } } void AllocateAligned(void **mem, size_t nSize, uint32_t nAlignment) override { /// TODO(tzwang): take care of aligned allocations RAW_CHECK(nAlignment == kCacheLineSize, "unsupported alignment."); Allocate(mem, nSize); } void FreeAligned(void* pBytes) override { /// TODO(tzwang): take care of aligned allocations return Free(pBytes); } void AllocateAlignedOffset(void **mem, size_t size, size_t alignment, size_t offset) override{ /// TODO(tzwang): not implemented yet } void AllocateHuge(void **mem, size_t size) override { /// TODO(tzwang): not implemented yet } Status Validate(void* pBytes) override { /// TODO(tzwang): not implemented yet return Status::OK(); } uint64_t GetAllocatedSize(void* pBytes) override { /// TODO(tzwang): not implemented yet return 0; } int64_t GetTotalAllocationCount() { /// TODO(tzwang): not implemented yet return 0; } }; // A simple wrapper for posix_memalign class DefaultAllocator : IAllocator { public: DefaultAllocator() {} ~DefaultAllocator() {} static Status Create(IAllocator*& allocator) { int n = posix_memalign(reinterpret_cast<void**>(&allocator), kCacheLineSize, sizeof(DefaultAllocator)); if(n || !allocator) return Status::Corruption("Out of memory"); new(allocator) DefaultAllocator(); return Status::OK(); } static void Destroy(IAllocator* a) { DefaultAllocator * allocator = static_cast<DefaultAllocator*>(a); allocator->~DefaultAllocator(); free(allocator); } void Allocate(void **mem, size_t nSize) override { int n = posix_memalign(mem, kCacheLineSize, nSize); RAW_CHECK(n == 0, "allocator error."); } void CAlloc(void **mem, size_t count, size_t size) override{ /// TODO(tzwang): not implemented yet return; } void Free(void* pBytes) override { free(pBytes); } void AllocateAligned(void **mem, size_t nSize, uint32_t nAlignment) override { RAW_CHECK(nAlignment == kCacheLineSize, "unsupported alignment."); return Allocate(mem, nSize); } void FreeAligned(void* pBytes) override { return Free(pBytes); } void AllocateAlignedOffset(void **mem, size_t size, size_t alignment, size_t offset) override { /// TODO(tzwang): not implemented yet return; } void AllocateHuge(void **mem, size_t size) override { /// TODO(tzwang): not implemented yet return; } Status Validate(void* pBytes) override { /// TODO(tzwang): not implemented yet return Status::OK(); } uint64_t GetAllocatedSize(void* pBytes) override { /// TODO(tzwang): not implemented yet return 0; } int64_t GetTotalAllocationCount() { /// TODO(tzwang): not implemented yet return 0; } }; #ifdef PMDK #define CREATE_MODE_RW (S_IWUSR | S_IRUSR) POBJ_LAYOUT_BEGIN(allocator); POBJ_LAYOUT_TOID(allocator, char) POBJ_LAYOUT_END(allocator) /// A wrapper for using PMDK allocator class PMDKAllocator : IAllocator { public: PMDKAllocator(PMEMobjpool *pop, const char *file_name): pop(pop), file_name(file_name) {} ~PMDKAllocator() { pmemobj_close(pop); } static std::function<Status(IAllocator *&)> Create(const char *pool_name, const char *layout_name, uint64_t pool_size) { return [pool_name, layout_name, pool_size](IAllocator *&allocator) { int n = posix_memalign(reinterpret_cast<void **>(&allocator), kCacheLineSize, sizeof(DefaultAllocator)); if (n || !allocator) return Status::Corruption("Out of memory"); PMEMobjpool *tmp_pool; if (!FileExists(pool_name)) { tmp_pool = pmemobj_create(pool_name, layout_name, pool_size, CREATE_MODE_RW); LOG_ASSERT(tmp_pool != nullptr); } else { tmp_pool = pmemobj_open(pool_name, layout_name); LOG_ASSERT(tmp_pool != nullptr); } new(allocator) PMDKAllocator(tmp_pool, pool_name); return Status::OK(); }; } static bool FileExists(const char *pool_path) { struct stat buffer; return (stat(pool_path, &buffer) == 0); } static void Destroy(IAllocator *a) { auto* allocator= static_cast<PMDKAllocator*>(a); allocator->~PMDKAllocator(); free(allocator); } void Allocate(void **mem, size_t nSize) override { TX_BEGIN(pop) { if(*mem != nullptr) { pmemobj_tx_add_range_direct(mem, sizeof(uint64_t)); } *mem = pmemobj_direct(pmemobj_tx_alloc(nSize, TOID_TYPE_NUM(char))); } TX_ONABORT { std::cout<<"Allocate: TXN Allocation Error, mem cannot be a DRAM address: "<< mem << std::endl; } TX_END } template<typename T> inline T *GetDirect(T *pmem_offset) { return reinterpret_cast<T *>( reinterpret_cast<uint64_t>(pmem_offset) + reinterpret_cast<char *>(GetPool())); } template<typename T> inline T *GetOffset(T *pmem_direct) { return reinterpret_cast<T *>( reinterpret_cast<char *>(pmem_direct) - reinterpret_cast<char *>(GetPool())); } void AllocateDirect(void **mem, size_t nSize) { Allocate(mem, nSize); } void* GetRoot(size_t nSize) { return pmemobj_direct(pmemobj_root(pop, nSize)); } PMEMobjpool *GetPool(){ return pop; } void PersistPtr(const void *ptr, uint64_t size){ pmemobj_persist(pop, ptr, size); } void CAlloc(void **mem, size_t count, size_t size) override { // not implemented } void Free(void* pBytes) override { auto oid_ptr = pmemobj_oid(pBytes); TOID(char) ptr_cpy; TOID_ASSIGN(ptr_cpy, oid_ptr); POBJ_FREE(&ptr_cpy); } void AllocateAligned(void **mem, size_t nSize, uint32_t nAlignment) override { RAW_CHECK(nAlignment == kCacheLineSize, "unsupported alignment."); return Allocate(mem, nSize); } void FreeAligned(void* pBytes) override { return Free(pBytes); } void AllocateAlignedOffset(void **mem, size_t size, size_t alignment, size_t offset) override { // not implemented } void AllocateHuge(void **mem, size_t size) override{ // not implemented } Status Validate(void* pBytes) override { return Status::OK(); } uint64_t GetAllocatedSize(void* pBytes) override { return 0; } int64_t GetTotalAllocationCount() { return 0; } private: PMEMobjpool *pop; const char *file_name; }; #endif // PMDK } <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #include <gtest/gtest.h> #include "include/status.h" #include "include/allocator.h" #include "include/pmwcas.h" #include "include/environment.h" #include "common/allocator_internal.h" #include "common/garbage_list.h" #include "util/random_number_generator.h" #include "util/auto_ptr.h" namespace pmwcas { namespace test { class AllocatorTest : public ::testing::Test { public: const uint64_t kAllocationCount = 1000; protected: virtual void SetUp() {} virtual void TearDown() { Thread::ClearRegistry(true); } }; #ifdef WIN32 TEST_F(AllocatorTest, Alloc__Free) { RandomNumberGenerator rng; unique_ptr_t<void*> allocations_guard = alloc_unique<void*>( kAllocationCount * sizeof(void*)); void** allocations = allocations_guard.get(); for(uint64_t i = 0; i < kAllocationCount; ++i) { allocations[i] = nullptr; } #ifdef _DEBUG uint64_t allocation_count = static_cast<DefaultAllocator*>(Allocator::Get())->GetTotalAllocationCount(); #endif for(uint64_t i = 0; i < kAllocationCount; ++i) { uint64_t size = rng.Generate(200); allocations[i] = Allocator::Get()->Allocate(size); ASSERT_NE(nullptr, allocations[i]); } for(uint64_t idx = 0; idx < 1000; ++idx) { Allocator::Get()->Free(allocations[idx]); } #ifdef _DEBUG ASSERT_EQ(allocation_count, static_cast<DefaultAllocator*>( Allocator::Get())->GetTotalAllocationCount()); #endif } TEST_F(AllocatorTest, AllocAligned__FreeAligned) { RandomNumberGenerator rng; unique_ptr_t<void*> allocations_guard = alloc_unique<void*>( kAllocationCount * sizeof(void*)); void** allocations = allocations_guard.get(); for(uint64_t i = 0; i < kAllocationCount; ++i) { allocations[i] = nullptr; } #ifdef _DEBUG uint64_t allocation_count = static_cast<DefaultAllocator*>(Allocator::Get())->GetTotalAllocationCount(); #endif for(uint64_t i = 0; i < kAllocationCount; ++i) { uint64_t size = rng.Generate(200); uint64_t alignment = std::exp2(rng.Generate(8)); allocations[i] = Allocator::Get()->AllocateAligned(size, alignment); ASSERT_NE(nullptr, allocations[i]); ASSERT_EQ((size_t)0, reinterpret_cast<size_t>(allocations[i]) % alignment); } for(uint64_t idx = 0; idx < 1000; ++idx) { Allocator::Get()->FreeAligned(allocations[idx]); } #ifdef _DEBUG ASSERT_EQ(allocation_count, static_cast<DefaultAllocator*>( Allocator::Get())->GetTotalAllocationCount()); #endif } TEST_F(AllocatorTest, AllocAlignedOffset__FreeAligned) { RandomNumberGenerator rng; unique_ptr_t<void*> allocations_guard = alloc_unique<void*>( kAllocationCount * sizeof(void*)); void** allocations = allocations_guard.get(); for(uint64_t i = 0; i < kAllocationCount; ++i) { allocations[i] = nullptr; } #ifdef _DEBUG uint64_t allocation_count = static_cast<DefaultAllocator*>(Allocator::Get())->GetTotalAllocationCount(); #endif for(uint64_t i = 0; i < kAllocationCount; ++i) { uint64_t size = rng.Generate(200); uint64_t alignment = std::exp2(rng.Generate(8)); uint64_t offset = size != 0 ? rng.Generate(size) : 0; // _aligned_malloc() requires allocation size >= alignment. allocations[i] = Allocator::Get()->AllocateAlignedOffset(size, alignment, offset); ASSERT_NE(nullptr, allocations[i]); ASSERT_EQ((size_t)0, (reinterpret_cast<size_t>(allocations[i]) + offset) % alignment); } for(uint64_t idx = 0; idx < 1000; ++idx) { Allocator::Get()->FreeAligned(allocations[idx]); } #ifdef _DEBUG ASSERT_EQ(allocation_count, static_cast<DefaultAllocator*>( Allocator::Get())->GetTotalAllocationCount()); #endif } #endif } // namespace test } // namespace pmwcas int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); #ifdef WIN32 pmwcas::InitLibrary(pmwcas::DefaultAllocator::Create, pmwcas::DefaultAllocator::Destroy); #endif return RUN_ALL_TESTS(); } <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. // // Implements variants of the multi-word compare-and-swap (MwCAS) primitive // that can work for volatile DRAM and persistent memory. The operation is // lock-free and non-blocking. It requires flag bits on each word. Currently // Intel and AMD implements 48 out of the 64 bits for addresses, so these // bits reside in the most significant 16 bits. // // The basic MwCAS algorithm is based on ideas in: // Harris, <NAME>., Fraser, Keir, Pratt, <NAME>., // A Practical Multi-word Compare-and-Swap Operation", DISC 2002, 265-279 // // It requires using a conditional CAS (RDCSS) to install MwCAS descriptors, // RDCSS itself in turn needs descriptors. This requires two bits in the MSBs. // // The persistence support employes an extra bit to indicate if the word is // possbily dirty (not reflected in NVRAM yet). // // |--63---|----62---|---61--|--rest bits--| // |-MwCAS-|-CondCAS-|-Dirty-|-------------| // // Any application that uses this MwCAS primitive thus cannot use the 3 MSBs // (e.g., the deletion marker of a linked list has to be at bit 60 or lower). // // Interactions with user data memory to prevent persistent memory leaks: // Assume a persistent allocator is already in place, and it provides the // following semantics: // 1. Allocation is done through a posix_memalign-like interface which accepts // a reference to the location which stores the address of the allocated // memory. This provided 'reference' must be part of the allocation's // persistent data structure, or any place that the application can read // during recovery. // 2. Upon recovery, the allocator will examine (by actively remembering all // memory it allocated through e.g., a hashtab or upon request from the // application) each reference provided. If it contains null, then the memory // should be freed internally (i.e., ownership didn't transfer to // application); otherwise the application should decide what to do with the // memory. Ownership is transferred. // // With the above interface/guarantees, the application can pass a reference of // the 'new value' fields in each word to the allocator. The allocator will // examine these places upon recovery. In general, MwCAS's recovery routine will // deallocate the 'old values' for successful mwcas ops, and deallocate the 'new // values' for failed mwcas ops. See kRecycle* for all possible policies. After // freeing memory, the recovery routine resets the descriptor fields to null. // // Note: this requires the allocator to do double-free detection in case there // is repeated failure. // // (If an persistent allocator can provide a drop-in replacement to malloc, then // it's up to the application to decide what to do.) // // During forward processing, the application can choose to piggy back on // MwCAS's epoch manager for pointer stability. Depending on whether the mwcas // succeeded, the descriptor free routine will deallocate memory addresses // stored in 'old value' or 'new value'. This means the application also need // not handle pointer stability itself, the MwCAS's epoch manager does it // transparently. // // The application can specify the callbacks for allocating and deallocating // memory when allocating MwCAS descriptors. Each word can be specified to // whether use mwcas's mechanism for memory deallocation. #pragma once #ifdef WIN32 #include <Windows.h> #undef ERROR // Avoid collision of ERROR definition in Windows.h with glog #endif #ifndef DESC_CAP #define DESC_CAP 4 #warning "DESC_CAP not defined - setting to 4" #endif #include <stdio.h> #include <assert.h> #include <cstdint> #include <mutex> #include "common/allocator_internal.h" #include "common/environment_internal.h" #include "common/epoch.h" #include "common/garbage_list_unsafe.h" #include "include/environment.h" #include "metrics.h" #include "util/nvram.h" #ifdef GOOGLE_FRAMEWORK #include <gtest/gtest_prod.h> #endif namespace pmwcas { // Forward references struct DescriptorPartition; class Descriptor; class DescriptorPool; class alignas(kCacheLineSize) Descriptor { template<typename T> friend class MwcTargetField; public: /// Signifies a dirty word requiring cache line write back static const uint64_t kDirtyFlag = (uint64_t)1 << 61; /// Garbage list recycle policy: only free [new_value] upon restart static const uint32_t kRecycleOnRecovery = 0x1; /// Garbage list recycle policy: leave the memory alone static const uint32_t kRecycleNever = 0x2; /// Garbage list recycle policy: free [old/new_value] if succeeded/failed static const uint32_t kRecycleAlways = 0x3; /// Garbage list recycle policy: free only [old value] if succeeded static const uint32_t kRecycleOldOnSuccess = 0x4; /// Garbage list recycle policy: free only [new value] if succeeded static const uint32_t kRecycleNewOnFailure = 0x5; /// Recycle and installation policy: neither install nor recycle /// only used for allocation purpose static const uint32_t kAllocNullAddress = 0x0; /// Signaure for garbage free callback (see free_callback_ below) typedef void (*FreeCallback)(void* context, void* word); /// Signature for NVM allocation callback (see allocate_callback_ below) typedef void* (*AllocateCallback)(size_t size); /// The default NVM allocate callback used if no callback is specified by the user static void* DefaultAllocateCallback(size_t size); /// The default free callback used if no callback is specified by the user static void DefaultFreeCallback(void* context, void* p); /// Specifies what word to update in the mwcas, storing before/after images so /// others may help along. This also servers as the descriptor for conditional /// CAS(RDCSS in the Harris paper). status_address_ points to the parent /// Descriptor's status_ field which determines whether a CAS that wishes to /// make address_ point to WordDescriptor can happen. struct WordDescriptor { /// The target address uint64_t* address_; /// The original old value stored at /a Address uint64_t old_value_; /// The new value to be stored at /a Address uint64_t new_value_; /// The parent Descriptor's status uint32_t* status_address_; /// Whether to invoke the user-provided memory free callback to free the /// memory when recycling this descriptor. This must be per-word - the /// application could mix pointer and non-pointer changes in a single mwcas, /// e.g., in the bwtree we might use a single mwcas to change both the root /// lpid and other memory page pointers along the way. uint32_t recycle_policy_; /// Returns the parent descriptor for this particular word inline Descriptor* GetDescriptor() { return (Descriptor*)((uint64_t)status_address_ - offsetof(Descriptor, status_)); } #ifdef PMEM /// Persist the content of address_ inline void PersistAddress() { NVRAM::Flush(sizeof(uint64_t*), (void*)&address_); } #endif }; /// Default constructor Descriptor() = delete; Descriptor(DescriptorPartition* partition); /// Function for initializing a newly allocated Descriptor. void Initialize(); /// Executes the multi-word compare and swap operation. bool MwCAS() { RAW_CHECK(status_ == kStatusFinished, "status of descriptor is not kStatusFinished"); status_ = kStatusUndecided; #ifdef PMEM return PersistentMwCAS(0); #else return VolatileMwCAS(0); #endif } /// Retrieves the new value for the given word index in the PMwCAS inline uint64_t GetNewValue(uint32_t index) { return words_[index].new_value_; } /// Retrieves the pointer to the new value slot for a given word in the PMwCAS inline uint64_t* GetNewValuePtr(uint32_t index) { return &words_[index].new_value_; } /// Adds information about a new word to be modifiec by the MwCAS operator. /// Word descriptors are stored sorted on the word address to prevent /// livelocks. Return value is negative if the descriptor is full. /// @free_on_recycle: use the user-provided callback to free the address /// stored in [oldval] (if mwcas succeeded) or [newval] (if mwcas failed). /// Pre-requisite: the application is using mwcas to change memory pointers, /// although technically the application can abuse this mechanism to do /// anything. uint32_t AddEntry(uint64_t* addr, uint64_t oldval, uint64_t newval, uint32_t recycle_policy = kRecycleNever); /// Allocate [size] bytes of memory and store the address in [newval]. Assume /// the allocator features an interface similar to posix_memalign's which /// accepts a reference to the location that will store the address of /// allocated memory. In our case it's [newval]. Note: applies only if the /// MwCAS is intended to change pointer values. uint32_t AllocateAndAddEntry(uint64_t* addr, uint64_t oldval, size_t size, uint32_t recycle_policy = kRecycleNever); /// Reserve a slot in the words array, but don't know what the new value is /// yet. The application should use GetNewValue[Ptr] to fill in later. inline uint32_t ReserveAndAddEntry(uint64_t* addr, uint64_t oldval, uint32_t recycle_policy = kRecycleNever) { return AddEntry(addr, oldval, kNewValueReserved, recycle_policy); } /// Abort the MwCAS operation, can be used only before the operation starts. Status Abort(); private: #if defined(GOOGLE_FRAMEWORK) && defined(APPS) /// Allow tests to access privates for failure injection purposes. FRIEND_TEST(PMwCASTest, SingleThreadedRecovery); #endif friend class DescriptorPool; /// Value signifying an internal reserved value for a new entry static const uint64_t kNewValueReserved = ~0ull; /// Internal helper function to conduct a double-compare, single-swap /// operation on an target field depending on the value of the status_ field /// in Descriptor. The conditional CAS tries to install a pointer to the MwCAS /// descriptor derived from one of words_, expecting the status_ field /// indicates Undecided. [dirty_flag] will be applied on the MwCAS descriptor /// address if specified. uint64_t CondCAS(uint32_t word_index, uint64_t dirty_flag = 0); /// A version of the MwCAS function that will fail/abort during execution. /// This is a private function that should only be used for testing failure /// modes and recovery. bool MwCASWithFailure(uint32_t calldepth = 0, bool complete_descriptor_install = false) { RAW_CHECK(status_ == kStatusFinished, "status of descriptor is not kStatusFinished"); status_ = kStatusUndecided; #ifdef PMEM return PersistentMwCASWithFailure(calldepth, complete_descriptor_install); #else return VolatileMwCASWithFailure(calldepth, complete_descriptor_install); #endif } #ifdef RTM bool RTMInstallDescriptors(uint64_t dirty_flag = 0); #endif /// Retrieve the index position in the descriptor of the given address. int GetInsertPosition(uint64_t* addr); #ifndef PMEM /// Execute the multi-word compare and swap operation. bool VolatileMwCAS(uint32_t calldepth = 0); /// Volatile version of the multi-word CAS with failure injection. bool VolatileMwCASWithFailure(uint32_t calldepth = 0, bool complete_descriptor_install = false); #endif #ifdef PMEM /// Execute the multi-word compare and swap operation on persistent memory. bool PersistentMwCAS(uint32_t calldepth = 0); /// Persistent version of the multi-word CAS with failure injection. bool PersistentMwCASWithFailure(uint32_t calldepth = 0, bool complete_descriptor_install = false); /// Flush only the Status field to persistent memory. inline void PersistStatus() { NVRAM::Flush(sizeof(status_), &status_); } // Read and persist the status field (if its dirty bit is set). // The caller must ensure that the descriptor is already persistent. // The returned value is guaranteed to be persistent in PM. uint32_t ReadPersistStatus(); #endif /// Flag signifying an multi-word CAS is underway for the target word. static const uint64_t kMwCASFlag = (uint64_t)1 << 63; /// Flag signifying a conditional CAS is underway for the target word. static const uint64_t kCondCASFlag = (uint64_t)1 << 62; /// Returns whether the value given is an MwCAS descriptor or not. inline static bool IsMwCASDescriptorPtr(uint64_t value) { return value & kMwCASFlag; } /// Returns whether the value given is a CondCAS descriptor or not. inline static bool IsCondCASDescriptorPtr(uint64_t value) { return value & kCondCASFlag; } /// Returns whether the underlying word is dirty (not surely persisted). inline static bool IsDirtyPtr(uint64_t value) { return value & kDirtyFlag; } /// Returns true if the target word has no pmwcas management flags set. inline static bool IsCleanPtr(uint64_t value) { return (value & (kCondCASFlag | kMwCASFlag | kDirtyFlag)) == 0; } /// Clear the descriptor flag for the provided /a ptr static inline uint64_t CleanPtr(uint64_t ptr) { return ptr & ~(kMwCASFlag | kCondCASFlag | kDirtyFlag); } /// Bitwise-or the given flags to the given value inline static uint64_t SetFlags(uint64_t value, uint64_t flags) { RAW_CHECK((flags & ~(kMwCASFlag | kCondCASFlag | kDirtyFlag)) == 0, "invalid flags"); return value | flags; } /// Set the given flags for a target descriptor word. inline static uint64_t SetFlags(Descriptor* desc, uint64_t flags) { return SetFlags((uint64_t)desc, flags); } /// Mask to indicate the status field is dirty, any reader should first flush /// it before use. static const uint32_t kStatusDirtyFlag = 1ULL << 31; /// Cleanup steps of MWCAS common to both persistent and volatile versions. bool Cleanup(); /// Deallocate the memory associated with the MwCAS if needed. void DeallocateMemory(); /// Places a descriptor back on the descriptor free pool (partitioned). This /// can be used as the callback function for the epoch manager/garbage list to /// reclaim this descriptor for reuse after we are sure no one is using or /// could possibly access this descriptor. static void FreeDescriptor(void* context, void* desc); /// Descriptor states. Valid transitions are as follows: /// kStatusUndecided->kStatusSucceeded->kStatusFinished->kStatusUndecided /// \-->kStatusFailed-->kStatusFinished->kStatusUndecided static const uint32_t kStatusInvalid = 0U; static const uint32_t kStatusFinished = 1U; static const uint32_t kStatusSucceeded = 2U; static const uint32_t kStatusFailed = 3U; static const uint32_t kStatusUndecided = 4U; inline void assert_valid_status() { auto s = status_ & ~kStatusDirtyFlag; RAW_CHECK(s == kStatusFinished || s == kStatusFailed || s == kStatusSucceeded || s == kStatusUndecided, "invalid status"); } /// Free list pointer for managing free pre-allocated descriptor pools Descriptor* next_ptr_; /// Back pointer to owning partition so the descriptor can be returned to its /// howm partition when it is freed. DescriptorPartition* owner_partition_; /// Tracks the current status of the descriptor. uint32_t status_; /// Count of actual descriptors held in #WordDesc uint32_t count_; /// A callback for freeing the words listed in [words_] when recycling the /// descriptor. Optional: only for applications that use it. FreeCallback free_callback_; /// A callback for allocating memory in AllocateAndAddEntry; the address of /// the allocated memory will be store in [new_value]. AllocateCallback allocate_callback_; /// Array of word descriptors bounded DESC_CAP WordDescriptor words_[DESC_CAP]; }; /// A partitioned pool of Descriptors used for fast allocation of descriptors. /// The pool of descriptors will be bounded by the number of threads actively /// performing an mwcas operation. struct alignas(kCacheLineSize)DescriptorPartition { DescriptorPartition() = delete; DescriptorPartition(EpochManager* epoch, DescriptorPool* pool); ~DescriptorPartition(); /// Pointer to the free list head (currently managed by lock-free list) Descriptor *free_list; /// Back pointer to the owner pool DescriptorPool* desc_pool; /// Garbage list holding freed pointers/words waiting to clear epoch /// protection before being truly recycled. GarbageListUnsafe* garbage_list; /// Number of allocated descriptors uint32_t allocated_desc; }; class DescriptorPool { private: /// Total number of descriptors in the pool uint32_t pool_size_; /// Number of descriptors per partition uint32_t desc_per_partition_; /// Points to all descriptors Descriptor* descriptors_; /// Number of partitions in the partition_table_ uint32_t partition_count_; /// Descriptor partitions (per thread) DescriptorPartition* partition_table_; /// The next partition to assign (round-robin) for a new thread joining the /// pmwcas library. std::atomic<uint32_t> next_partition_; /// Epoch manager controling garbage/access to descriptors. EpochManager epoch_; /// Track the pmdk pool for recovery purpose uint64_t pmdk_pool_; void InitDescriptors(); public: /// Metadata that prefixes the actual pool of descriptors for persistence struct Metadata { /// Number of descriptors uint64_t descriptor_count; /// Address of the area got after initializing the area first-time uintptr_t initial_address; /// Pad to cacheline size char padding[kCacheLineSize - sizeof(uint64_t) - sizeof(uintptr_t)]; Metadata() : descriptor_count(0), initial_address(0) {} }; static_assert(sizeof(Metadata) == kCacheLineSize, "Metadata not of cacheline size"); DescriptorPool(uint32_t pool_size, uint32_t partition_count, bool enable_stats = false); Descriptor* GetDescriptor(){ return descriptors_; } #ifdef PMEM void Recovery(bool enable_stats); #endif ~DescriptorPool(); inline uint32_t GetDescPerPartition() { return desc_per_partition_; } /// Returns a pointer to the epoch manager associated with this pool. /// MwcTargetField::GetValue() needs it. EpochManager* GetEpoch() { return &epoch_; } // Get a free descriptor from the pool. Descriptor* AllocateDescriptor(Descriptor::AllocateCallback ac, Descriptor::FreeCallback fc); // Allocate a free descriptor from the pool using default allocate and // free callbacks. inline Descriptor* AllocateDescriptor() { return AllocateDescriptor(nullptr, nullptr); } }; /// Represents an 8-byte word that is a target for a compare-and-swap. Used to /// abstract away and hide all the low-level bit manipulation to track internal /// status of the word. By default use the 2 LSBs as flags, assuming the values /// point to word-aligned addresses. template <class T> class MwcTargetField { static_assert(sizeof(T) == 8, "MwCTargetField type is not of size 8 bytes"); public: static const uint64_t kMwCASFlag = Descriptor::kMwCASFlag; static const uint64_t kCondCASFlag = Descriptor::kCondCASFlag; static const uint64_t kDescriptorMask = kMwCASFlag | kCondCASFlag; static const uint64_t kDirtyFlag = Descriptor::kDirtyFlag; MwcTargetField(void* desc = nullptr) { value_ = T(desc); } /// Enter epoch protection and then return the value. inline T GetValue(EpochManager* epoch) { #ifdef PMEM return GetValuePersistent(epoch); #else return GetValueVolatile(epoch); #endif } /// Get value assuming epoch protection. inline T GetValueProtected() { #ifdef PMEM return GetValueProtectedPersistent(); #else return GetValueProtectedVolatile(); #endif } /// Returns true if the given word does not have any internal management /// flags set, false otherwise. static inline bool IsCleanPtr(uint64_t ptr) { return (ptr & (kCondCASFlag | kMwCASFlag | kDirtyFlag)) == 0; } /// Returns true if the value does not have any internal management flags set, /// false otherwise. inline bool IsCleanPtr() { return (value_ & (kCondCASFlag | kMwCASFlag | kDirtyFlag)) == 0; } #ifdef PMEM /// Persist the value_ to be read inline void PersistValue() { NVRAM::Flush(sizeof(uint64_t), (const void*)&value_); } #endif /// Return an integer representation of the target word operator uint64_t() { return uint64_t(value_); } /// Copy operator MwcTargetField<T>& operator= (MwcTargetField<T>& rhval) { value_ = rhval.value_; return *this; } /// Address-of operator T* operator& () { return const_cast<T*>(&value_); } /// Assignment operator MwcTargetField<T>& operator= (T rhval) { value_ = rhval; return *this; } /// Content-of operator T& operator* () { return *value_; } /// Dereference operator T* operator-> () { return value_; } private: #ifndef PMEM /// Return the value in this word. If the value is a descriptor there is a CAS /// in progress, so help along completing the CAS before returning the value /// in the target word. inline T GetValueVolatile(EpochManager* epoch) { MwCASMetrics::AddRead(); EpochGuard guard(epoch, !epoch->IsProtected()); retry: uint64_t val = (uint64_t)value_; #ifndef RTM if(val & kCondCASFlag) { Descriptor::WordDescriptor* wd = (Descriptor::WordDescriptor*)Descriptor::CleanPtr(val); uint64_t dptr = Descriptor::SetFlags(wd->GetDescriptor(), kMwCASFlag); RAW_CHECK((char*)this == (char*)wd->address_, "wrong addresses"); CompareExchange64( wd->address_, *wd->status_address_ == Descriptor::kStatusUndecided ? dptr : wd->old_value_, val); goto retry; } #endif if(val & kMwCASFlag) { // While the address contains a descriptor, help along completing the CAS Descriptor* desc = (Descriptor*)Descriptor::CleanPtr(val); RAW_CHECK(desc, "invalid descriptor pointer"); desc->VolatileMwCAS(1); goto retry; } return val; } /// Same as GetValue, but guaranteed to be Protect()'ed already. inline T GetValueProtectedVolatile() { MwCASMetrics::AddRead(); retry: uint64_t val = (uint64_t)value_; #ifndef RTM if(val & kCondCASFlag) { Descriptor::WordDescriptor* wd = (Descriptor::WordDescriptor*)Descriptor::CleanPtr(val); uint64_t dptr = Descriptor::SetFlags(wd->GetDescriptor(), kMwCASFlag); RAW_CHECK((char*)this == (char*)wd->address_, "wrong addresses"); CompareExchange64( wd->address_, *wd->status_address_ == Descriptor::kStatusUndecided ? dptr : wd->old_value_, val); goto retry; } #endif if(val & kMwCASFlag) { // While the address contains a descriptor, help along completing the CAS Descriptor* desc = (Descriptor*)Descriptor::CleanPtr(val); RAW_CHECK(desc, "invalid descriptor pointer"); desc->VolatileMwCAS(1); goto retry; } return val; } #endif #ifdef PMEM // The persistent variant of GetValue(). T GetValuePersistent(EpochManager* epoch) { MwCASMetrics::AddRead(); EpochGuard guard(epoch, !epoch->IsProtected()); retry: uint64_t val = (uint64_t)value_; #ifndef RTM if(val & kCondCASFlag) { RAW_CHECK((val & kDirtyFlag) == 0, "dirty flag set on CondCAS descriptor"); Descriptor::WordDescriptor* wd = (Descriptor::WordDescriptor*)Descriptor::CleanPtr(val); uint64_t dptr = Descriptor::SetFlags(wd->GetDescriptor(), kMwCASFlag | kDirtyFlag); CompareExchange64( wd->address_, *wd->status_address_ == Descriptor::kStatusUndecided ? dptr : wd->old_value_, val); goto retry; } #endif if(val & kDirtyFlag) { PersistValue(); CompareExchange64((uint64_t*)&value_, val & ~kDirtyFlag, val); val &= ~kDirtyFlag; } RAW_CHECK((val & kDirtyFlag) == 0, "dirty flag set on return value"); if(val & kMwCASFlag) { // While the address contains a descriptor, help along completing the CAS Descriptor* desc = (Descriptor*)Descriptor::CleanPtr(val); RAW_CHECK(desc, "invalid descriptor pointer"); desc->PersistentMwCAS(1); goto retry; } RAW_CHECK(IsCleanPtr(val), "dirty flag set on return value"); return val; } // The "protected" variant of GetPersistValue(). T GetValueProtectedPersistent() { MwCASMetrics::AddRead(); retry: uint64_t val = (uint64_t)value_; #ifndef RTM if(val & kCondCASFlag) { RAW_CHECK((val & kDirtyFlag) == 0, "dirty flag set on CondCAS descriptor"); Descriptor::WordDescriptor* wd = (Descriptor::WordDescriptor*)Descriptor::CleanPtr(val); uint64_t dptr = Descriptor::SetFlags(wd->GetDescriptor(), kMwCASFlag | kDirtyFlag); CompareExchange64( wd->address_, *wd->status_address_ == Descriptor::kStatusUndecided ? dptr : wd->old_value_, val); goto retry; } #endif if(val & kDirtyFlag) { PersistValue(); CompareExchange64((uint64_t*)&value_, val & ~kDirtyFlag, val); val &= ~kDirtyFlag; } RAW_CHECK((val & kDirtyFlag) == 0, "dirty flag set on return value"); if(val & kMwCASFlag) { // While the address contains a descriptor, help along completing the CAS Descriptor* desc = (Descriptor*)Descriptor::CleanPtr(val); RAW_CHECK(desc, "invalid descriptor pointer"); desc->PersistentMwCAS(1); goto retry; } RAW_CHECK(IsCleanPtr(val), "dirty flag set on return value"); return val; } #endif /// The 8-byte target word volatile T value_; }; } // namespace pmwcas <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #include <memory> #include <gtest/gtest.h> #include "util/performance_test.h" #include "include/status.h" #include "include/allocator.h" #include "include/pmwcas.h" #include "common/epoch.h" #include "common/garbage_list.h" #ifdef WIN32 #include "environment/environment_windows.h" #else #include "environment/environment_linux.h" #endif namespace pmwcas { namespace test { struct MockItem { public: MockItem() : deallocations{ 0 } { } static void Destroy(void* destroyContext, void* p) { ++(reinterpret_cast<MockItem*>(p))->deallocations; } std::atomic<uint64_t> deallocations; }; class GarbageListTest : public ::testing::Test { public: GarbageListTest() {} protected: EpochManager epoch_manager_; GarbageList garbage_list_; std::stringstream out_; virtual void SetUp() { out_.str(""); ASSERT_TRUE(epoch_manager_.Initialize().ok()); ASSERT_TRUE(garbage_list_.Initialize(&epoch_manager_, 1024).ok()); } virtual void TearDown() { EXPECT_TRUE(garbage_list_.Uninitialize().ok()); EXPECT_TRUE(epoch_manager_.Uninitialize().ok()); Thread::ClearRegistry(true); } }; struct GarbageListSmokeTest : public PerformanceTest { GarbageListSmokeTest(IGarbageList* garbage_list, MockItem* mock_item, uint64_t item_count) : PerformanceTest{} , garbage_list_{ garbage_list } , mock_item_{ mock_item } , iterations_{ item_count } { } void Teardown() { } void Entry(size_t thread_index) { WaitForStart(); for(uint64_t index = 0; index < iterations_; ++index) { EXPECT_TRUE(garbage_list_->Push(mock_item_, MockItem::Destroy, nullptr).ok()); } } IGarbageList* garbage_list_; MockItem* mock_item_; uint64_t iterations_; }; TEST_F(GarbageListTest, Uninitialize) { MockItem items[2]; EXPECT_TRUE(garbage_list_.Push(&items[0], MockItem::Destroy, nullptr).ok()); EXPECT_TRUE(garbage_list_.Push(&items[1], MockItem::Destroy, nullptr).ok()); EXPECT_TRUE(garbage_list_.Uninitialize().ok()); EXPECT_EQ(1, items[0].deallocations); EXPECT_EQ(1, items[1].deallocations); } TEST_F(GarbageListTest, Smoke) { uint64_t iterations = 1 << 15; MockItem item{}; GarbageListSmokeTest test{ static_cast<IGarbageList*>(&garbage_list_), &item, iterations }; size_t core_count = Environment::Get()->GetCoreCount(); test.Run(core_count); EXPECT_TRUE(garbage_list_.Uninitialize().ok()); EXPECT_EQ((core_count*iterations), item.deallocations); } } // namespace test } // namespace pmwcas int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); #ifdef WIN32 pmwcas::InitLibrary(pmwcas::DefaultAllocator::Create, pmwcas::DefaultAllocator::Destroy, pmwcas::WindowsEnvironment::Create, pmwcas::WindowsEnvironment::Destroy); #else pmwcas::InitLibrary(pmwcas::TlsAllocator::Create, pmwcas::TlsAllocator::Destroy, pmwcas::LinuxEnvironment::Create, pmwcas::LinuxEnvironment::Destroy); #endif return RUN_ALL_TESTS(); } <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once #include "include/allocator.h" #include "include/status.h" namespace pmwcas { class IAsyncContext { public: IAsyncContext() : from_deep_copy_{ false } { } virtual ~IAsyncContext() { } /// Duplicate this context on the heap and return a pointer to it. Used /// by blocking calls to create a copy of this context that is guaranteed /// to persist across the operation even when the call stack that /// induced the blocking operation is unwound. /// /// For performance purposes, contexts are initially stack allocated so as to /// avoid allocation overhead if the operation does not go async. DeepCopy /// is called only if the operation is preparing to go async. /// /// WARNING: there are two serious subtleties to this call that callers and /// implementors should be aware of: /// 1. If this context contains contexts nested within those DeepCopy is /// invoked on those as well, so that all of the contexts transitively /// nested within are copied. /// 2. If this context already came from a prior DeepCopy, then the call /// should return this same context without copying it. This is to handle /// the case that this context was already copied to the heap by a prior /// operation that went asynchronous but which didn't invoke the callback /// that cleans up the copy of the context. For example, this can happen /// if an operation is restarted after an asynchronous IO: if the /// operation goes asynchronous again, then the callback context /// shouldn't be copied to the heap a second time. /// /// \param context_copy /// Will be populated with a copy of this object. Must not be nullptr. /// If 'this' was already a product of a prior DeepCopy, then it is /// returned rather than a copy. /// /// \return /// Ok status if this context was copied, error otherwise. virtual Status DeepCopy(IAsyncContext** context_copy) = 0; /// Delete this context from the heap and all of the ICallerAsyncContexts /// that it refers to. Used by blocking calls to delete a deep copy of the /// context in the case that the callback can't be called. Specifically, /// this is used to destroy a chain of contexts in the case that DeepCopy() /// was successful, but some other part of scheduling an asynchronus /// operation failed. This should only be called when the user can still be /// notified of the failure on the synchronous code path. Silently deleting /// a callback chain when user code is expecting a callback will result in /// deadlock. /// /// \return /// Ok status if this context was copied, error otherwise. virtual Status DeepDelete() = 0; /// Whether the internal state for the async context has been copied to a /// heap-allocated memory block. bool from_deep_copy_; }; } // namespace deuteornomy <file_sep>## gflags CMake configuration file # library version information set (@PACKAGE_NAME@_VERSION_STRING "@PACKAGE_VERSION@") set (@PACKAGE_NAME@_VERSION_MAJOR @PACKAGE_VERSION_MAJOR@) set (@PACKAGE_NAME@_VERSION_MINOR @PACKAGE_VERSION_MINOR@) set (@PACKAGE_NAME@_VERSION_PATCH @PACKAGE_VERSION_PATCH@) # import targets include ("${CMAKE_CURRENT_LIST_DIR}/@[email protected]") # installation prefix get_filename_component (CMAKE_CURRENT_LIST_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH) get_filename_component (_INSTALL_PREFIX "${CMAKE_CURRENT_LIST_DIR}/@INSTALL_PREFIX_REL2CONFIG_DIR@" ABSOLUTE) # include directory # # Newer versions of CMake set the INTERFACE_INCLUDE_DIRECTORIES property # of the imported targets. It is hence not necessary to add this path # manually to the include search path for targets which link to gflags. set (@PACKAGE_NAME@_INCLUDE_DIR "${_INSTALL_PREFIX}/@INCLUDE_INSTALL_DIR@") # default settings if (NOT DEFINED @PACKAGE_NAME@_SHARED) if (TARGET @PACKAGE_NAME@-static OR TARGET @PACKAGE_NAME@_nothreads-static) set (@PACKAGE_NAME@_SHARED FALSE) else () set (@PACKAGE_NAME@_SHARED TRUE) endif () endif () if (NOT DEFINED @PACKAGE_NAME@_NOTHREADS) if (TARGET @PACKAGE_NAME@-static OR TARGET @PACKAGE_NAME@-shared) set (@PACKAGE_NAME@_NOTHREADS FALSE) else () set (@PACKAGE_NAME@_NOTHREADS TRUE) endif () endif () # choose imported library target if (NOT @PACKAGE_NAME@_TARGET) if (@PACKAGE_NAME@_SHARED) if (@PACKAGE_NAME@_NOTHREADS) set (@PACKAGE_NAME@_TARGET @PACKAGE_NAME@_nothreads-shared) else () set (@PACKAGE_NAME@_TARGET @PACKAGE_NAME@-shared) endif () else () if (@PACKAGE_NAME@_NOTHREADS) set (@PACKAGE_NAME@_TARGET @PACKAGE_NAME@_nothreads-static) else () set (@PACKAGE_NAME@_TARGET @PACKAGE_NAME@-static) endif () endif () endif () if (NOT TARGET ${@PACKAGE_NAME@_TARGET}) message (FATAL_ERROR "Your @PACKAGE_NAME@ installation does not contain a ${@PACKAGE_NAME@_TARGET} library target!" " Try a different combination of @PACKAGE_NAME@_SHARED and @PACKAGE_NAME@_NOTHREADS.") endif () # add more convenient "@PACKAGE_NAME@" import target if (NOT TARGET @PACKAGE_NAME@) if (@PACKAGE_NAME@_SHARED) add_library (@PACKAGE_NAME@ SHARED IMPORTED) else () add_library (@PACKAGE_NAME@ STATIC IMPORTED) endif () # INTERFACE_INCLUDE_DIRECTORIES get_target_property (_@PACKAGE_NAME@_INCLUDES ${@PACKAGE_NAME@_TARGET} INTERFACE_INCLUDE_DIRECTORIES) if (_@PACKAGE_NAME@_INCLUDES) set_target_properties(@PACKAGE_NAME@ PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${_@PACKAGE_NAME@_INCLUDES}" ) endif () unset (_@PACKAGE_NAME@_INCLUDES) # set configuration specific properties get_target_property (_@PACKAGE_NAME@_CONFIGURATIONS ${@PACKAGE_NAME@_TARGET} IMPORTED_CONFIGURATIONS) set_target_properties (@PACKAGE_NAME@ PROPERTIES IMPORTED_CONFIGURATIONS "${_@PACKAGE_NAME@_CONFIGURATIONS}") foreach (_@PACKAGE_NAME@_CONFIG IN LISTS _@PACKAGE_NAME@_CONFIGURATIONS) # IMPORTED_LOCATION_<config> get_target_property (_@PACKAGE_NAME@_LOCATION ${@PACKAGE_NAME@_TARGET} IMPORTED_LOCATION_${_@PACKAGE_NAME@_CONFIG}) if (_@PACKAGE_NAME@_LOCATION) set_target_properties(@PACKAGE_NAME@ PROPERTIES IMPORTED_LOCATION_${_@PACKAGE_NAME@_CONFIG} "${_@PACKAGE_NAME@_LOCATION}" ) endif () unset (_@PACKAGE_NAME@_LOCATION) # IMPORTED_LINK_INTERFACE_LANGUAGES_<config> (static) get_target_property (_@PACKAGE_NAME@_LANGUAGES ${@PACKAGE_NAME@_TARGET} IMPORTED_LINK_INTERFACE_LANGUAGES_${_@PACKAGE_NAME@_CONFIG}) if (_@PACKAGE_NAME@_LANGUAGES) set_target_properties(@PACKAGE_NAME@ PROPERTIES IMPORTED_LINK_INTERFACE_LANGUAGES_${_@PACKAGE_NAME@_CONFIG} "${_@PACKAGE_NAME@_LANGUAGES}" ) endif () unset (_@PACKAGE_NAME@_LANGUAGES) # IMPORTED_SONAME_<config> (shared) get_target_property (_@PACKAGE_NAME@_SONAME ${@PACKAGE_NAME@_TARGET} IMPORTED_SONAME_${_@PACKAGE_NAME@_CONFIG}) if (_@PACKAGE_NAME@_SONAME) set_target_properties(@PACKAGE_NAME@ PROPERTIES IMPORTED_SONAME_${_@PACKAGE_NAME@_CONFIG} "${_@PACKAGE_NAME@_SONAME}" ) endif () unset (_@PACKAGE_NAME@_SONAME) endforeach () unset (_@PACKAGE_NAME@_CONFIGURATIONS) endif () # alias for default import target to be compatible with older CMake package configurations set (@PACKAGE_NAME@_LIBRARIES "${@PACKAGE_NAME@_TARGET}") # unset private variables unset (_INSTALL_PREFIX) <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once #include "common/allocator_internal.h" #ifndef WIN32 #include <unistd.h> #endif namespace pmwcas { /// A container that keeps one instance of an object per core on the machine. /// Get() tries to intelligently return the same instance to the same thread /// each time. Contained objects avoid false sharing; each object is guaranteed /// to be aligned on cache line boundaries and it doesn't share any lines with /// other objects. template <class T> class CoreLocal { static const uint64_t kCacheLineSize = 64; public: CoreLocal() : objects_(nullptr), core_count_(0), next_free_object_(0) { } Status Initialize() { RAW_CHECK(!objects_, "already initialized"); #ifdef WIN32 SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); core_count_ = sysinfo.dwNumberOfProcessors; #else core_count_ = sysconf(_SC_NPROCESSORS_ONLN); #endif RAW_CHECK(core_count_, "invalid core count"); uint64_t size = core_count_ * ((sizeof(T) + kCacheLineSize - 1) & ~(kCacheLineSize - 1)); Allocator::Get()->AllocateAligned((void **) &objects_, size, kCacheLineSize); if (!objects_) { return Status::OutOfMemory(); } memset(objects_, 0, size); return Status::OK(); } Status Uninitialize() { if (!objects_) { return Status::Corruption("not initialized?"); } Allocator::Get()->FreeAligned(objects_); objects_ = nullptr; next_free_object_ = 0; return Status::OK(); } /// Returns the object beloning to the calling thread T* MyObject() { thread_local bool initialized = false; thread_local uint32_t idx = 0; void *value = nullptr; if (initialized) { value = (void*)&objects_[idx]; } if (value) { // value should point to one of the objects_ RAW_CHECK((uintptr_t)value >= (uintptr_t)objects_, "invalid tls value"); RAW_CHECK((uintptr_t)value <= (uintptr_t)(objects_ + core_count_ - 1), "invalid tls value"); RAW_CHECK(((uintptr_t)value - (uintptr_t)objects_) % sizeof(T) == 0, "invalid tls value"); return reinterpret_cast<T*>(value); } // All clear, put a pointer to my object there uint32_t obj_idx = next_free_object_.fetch_add(1); T* my_object = objects_ + obj_idx; idx = obj_idx; initialized = true; return my_object; } // Number of objects we're holding so far, not supposed to be used before // all threads finished its initialization (ie changing next_free_object_). inline uint32_t NumberOfObjects() { return next_free_object_.load(std::memory_order_relaxed); } inline T* GetObject(uint32_t core_id) { return objects_ + core_id; } private: /// Storage for the contained objects, one for each core. T* objects_; /// Max number of cores supported. uint32_t core_count_; /// Index into objects_ for the next thread who asks for an object std::atomic<uint32_t> next_free_object_; }; } // namespace pmwcas <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #define NOMINMAX #include <inttypes.h> #include <gtest/gtest.h> #include "gflags/gflags.h" #include "glog/logging.h" #include "glog/raw_logging.h" #ifdef WIN32 #include "environment/environment_windows.h" #else #include "environment/environment_linux.h" #endif #include "benchmarks/benchmark.h" #include "include/pmwcas.h" #include "mwcas/mwcas.h" #include "util/auto_ptr.h" namespace pmwcas { typedef MwcTargetField<uint64_t> CasPtr; } // namespace pmwcas <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once #include <unistd.h> #ifdef WIN32 #include <intrin.h> #endif #ifdef PMDK #include <libpmemobj.h> #endif #include "include/environment.h" namespace pmwcas { struct NVRAM { #ifdef PMEM /// How many cycles to delay for an emulated NVRAM write static uint64_t write_delay_cycles; static double write_byte_per_cycle; static bool use_clflush; static void InitializeClflush() { use_clflush = true; LOG(INFO) << "Will use CLFLUSH"; } static void InitializeSpin(uint64_t delay_ns, bool emulate_wb) { use_clflush = false; if(delay_ns) { uint64_t start = __rdtsc(); #ifdef WIN32 Sleep(1000); // 1 second #else sleep(1); #endif uint64_t end = __rdtsc(); write_delay_cycles = (double)(end - start) / 1000000000 * delay_ns; } LOG(INFO) << "Write delay: " << delay_ns << "ns (" << write_delay_cycles << " cycles)"; if(emulate_wb) { char test_array[kCacheLineSize]; unsigned int not_used = 0; uint64_t start = __rdtscp(&not_used); _mm_clflush(test_array); uint64_t end = __rdtscp(&not_used); write_byte_per_cycle = (double)kCacheLineSize / (end - start); } else { write_byte_per_cycle = 0; } LOG(INFO) << "BW emulation: " << write_byte_per_cycle << " bytes per cycle"; } static inline void Flush(uint64_t bytes, const void* data) { #ifdef PMDK auto pmdk_allocator = reinterpret_cast<PMDKAllocator*>(Allocator::Get()); pmdk_allocator->PersistPtr(data, bytes); #else if(use_clflush) { RAW_CHECK(data, "null data"); uint64_t ncachelines = (bytes + kCacheLineSize - 1) / kCacheLineSize; // Flush each cacheline in the given [data, data + bytes) range for(uint64_t i = 0; i < ncachelines; ++i) { _mm_clflush(&((char*)data)[i * ncachelines]); } } else { #if 0 // Previously this was calculated outside the [if] block, slowing down // read-only workloads (slower than with clflush). // // Update #2: perhaps the fairest way is comment out this whole else // block so it does nothing when we don't specify delays. if(write_delay_cycles > 0) { unsigned int aux = 0; uint64_t bw_cycles = write_byte_per_cycle > 0 ? bytes / write_byte_per_cycle : 0; uint64_t start = __rdtscp(&aux); while (__rdtscp(&aux) - start < write_delay_cycles + bw_cycles) { // SPIN } } #endif } #endif // PMDK } #endif // PMEM }; } // namespace pmwcas <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once #include <cstdint> #include <atomic> #include <vector> #include <deque> #include <thread> #include "common/environment_internal.h" #include "util/macros.h" namespace pmwcas { namespace benchmark { /// Glue to make running multi - threaded benchmarks easier.Classes subclass /// this and provide a Main(), Setup(), Teardown(), and Dump() method. /// Main() is called in parallel by a requested number of the threads.There /// is some magic in there to start and stop timing precisely during the /// experiment. class Benchmark { public: Benchmark() : threads_ready_{ 0 } , threads_finished_{ 0 } , start_running_{ false } , run_seconds_{} , is_shutdown_{ false } , dump_count_{} { } /// Run in parallel by the number of the threads specified to Run(). /// \a thread_index an integer between 0 and the number of threads run - 1. /// Important: Main() must call WaitForStart() once it is ready to start /// the benchmark.This gives Main() a chance to set up its stack without /// setup overhead being measured. Missing this call in a thread will /// result in deadlock. virtual void Main(size_t thread_index) = 0; /// Called during Run() before threads call Main(). Useful to initialize /// any state accessed during the test. virtual void Setup(size_t thread_count) = 0; /// Called during Run() after the benchmark is complete. Useful to /// uninitialize any state accessed during the test. virtual void Teardown() = 0; /// Returns the total operation count for the benchmark aggregated from all /// worker threads. This function is not threadsafe and should be called only /// after the workload completes. virtual uint64_t GetOperationCount() = 0; virtual void Dump(size_t thread_count, uint64_t run_ticks, uint64_t dump_id, bool final_dump) { MARK_UNREFERENCED(thread_count); MARK_UNREFERENCED(run_ticks); printf("> Benchmark %lu Dump %lu\n", dump_id, final_dump ? ~0lu : dump_count_); ++dump_count_; } /// Run \a threadCount threads running Entry() and measure how long the /// run takes.Afterward, GetLastRunSeconds() can be used to retrieve how /// long the execution took.This method will call Setup() and Teardown() /// respectively before and after the executions of Entry(). void Run(size_t thread_count, uint64_t seconds_to_run, AffinityPattern affinity, uint64_t dump_interval) { threads_finished_ = 0; threads_ready_ = 0; start_running_ = false; Setup(thread_count); // Start threads std::deque<std::thread> threads; for(size_t i = 0; i < thread_count; ++i) { threads.emplace_back(&Benchmark::entry, this, i, thread_count, affinity); } // Wait for threads to be ready while(threads_ready_.load() < thread_count); uint64_t unique_dump_id = __rdtsc(); if(dump_interval > 0) { Dump(thread_count, 0, unique_dump_id, false); } VLOG(1) << "Starting benchmark."; // Start the benchmark uint64_t start = Environment::Get()->NowMicros(); start_running_.store(true, std::memory_order_release); const uint64_t end = start + seconds_to_run * 1000000; if(dump_interval > 0) { uint64_t next_dump_ticks = 1000000 + start; uint64_t next_dump_seconds = 1; while(threads_finished_.load() < thread_count) { Environment::Get()->Sleep(10); uint64_t now = Environment::Get()->NowMicros(); if(end <= now) { is_shutdown_.store(true, std::memory_order_release); break; } if(now < next_dump_ticks) continue; // Collect metrics after the experiment end. unique_dump_id = __rdtsc(); Dump(thread_count, now - start, unique_dump_id, false); // 'Schedule' next dump. next_dump_seconds += dump_interval; next_dump_ticks = next_dump_seconds * 1000000 + start; } } else { // Sleep the required amount of time before setting the shutdown flag. Environment::Get()->Sleep((uint64_t)seconds_to_run * 1000); is_shutdown_.store(true, std::memory_order_release); // Wait for all threads to finish their workload while(threads_finished_.load() < thread_count) { Environment::Get()->Sleep(10); } } for(auto& thread : threads) { thread.join(); } while(0 == end_.load()); unique_dump_id = __rdtsc(); VLOG(1) << "Benchmark stopped."; Dump(thread_count, end_ - start, unique_dump_id, true); run_seconds_ = double(end_ - start) / double(1000000); Teardown(); } /// Must be called in Entry() after initial setup and before the real /// work of the experiment starts.This acts as a barrier; the main thread /// waits for all threads running as part of the measurement to reach this /// point and then releases them to start to body of the experiment as /// closely synchronized as possible.Forgetting to call this in Entry() /// will result in an infinite loop. void WaitForStart() { threads_ready_.fetch_add(1, std::memory_order_acq_rel); while(!start_running_.load(std::memory_order_acquire)); } /// Must be called in Entry() after initial setup.Used by the worker threads to /// test for the shutdown flag after #m_nRuntTimeBeforeShutdown seconds have /// passed. bool IsShutdown() { return is_shutdown_.load(std::memory_order_acquire); } /// Return the number of seconds Entry() ran on any of the threads starting /// just after WaitForStart() up through the end of Entry(). double GetRunSeconds() { return run_seconds_; } private: /// Internal springboard used to automatically notify the main thread of /// Entry() completion.The last thread to finish the calls stuffs a snapshot /// of the ending time so the main thread can accurately determine how long /// the run took without polling aggressively and wasting a core. void entry(size_t thread_index, size_t thread_count, AffinityPattern affinity) { if(affinity != AffinityPattern::OSScheduled) { Environment::Get()->SetThreadAffinity(thread_index, affinity); } Main(thread_index); size_t previous = threads_finished_.fetch_add(1, std::memory_order_acq_rel); if(previous + 1 == thread_count) { uint64_t end = Environment::Get()->NowMicros(); end_.store(end); } } private: /// Number of threads that have reached WaitForStart(). Used by the main /// thread to synchronize the start of the experiment. std::atomic<size_t> threads_ready_; /// Number of threads that have exited Entry(). Used by the main thread /// to determine when the experiment has completed. std::atomic<size_t> threads_finished_; /// The main thread sets this to true once #m_threadReady equals the /// number of threads that are part of the experiment. This releases all /// the threads to run the remainder of Entry() that follows the call /// to WaitForStart(). std::atomic<bool> start_running_; /// Tracks how long in seconds each collective run of Entry() took for /// a set of threads. Used in GetAllRunSeconds() and GetLastRunSeconds(). std::atomic<double> run_seconds_; /// Time in QueryPerformanceCounter ticks that the last thread finished /// its work. std::atomic<uint64_t> end_; /// Shutdown flag for timed tests. std::atomic<bool> is_shutdown_; /// Number of metrics dumps that have been done so far uint64_t dump_count_; }; } } // namespace pmwcas::benchmark <file_sep>@PACKAGE_INIT@ include ("${CMAKE_CURRENT_LIST_DIR}/glog-targets.cmake") set_and_check (glog_INCLUDE_DIR "@PACKAGE_glog_INCLUDE_DIR@") @glog_PACKAGE_DEPS@ set (glog_LIBRARY glog) set (glog_LIBRARIES ${glog_LIBRARY}) set (glog_INCLUDE_DIRS ${glog_INCLUDE_DIR}) <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once #include <iostream> #include "util/core_local.h" namespace pmwcas { class DescriptorPool; // A singleton (not a real one but works like it) for all MwCAS-related stats. // The user must call Initialize() first, each individual thread then should // call ThreadInitialize() before start. struct MwCASMetrics { friend class DescriptorPool; public: MwCASMetrics& operator+=(const MwCASMetrics& other) { succeeded_update_count += other.succeeded_update_count; failed_update_count += other.failed_update_count; read_count += other.read_count; descriptor_scavenge_count += other.descriptor_scavenge_count; help_attempt_count += other.help_attempt_count; bailed_help_count += other.bailed_help_count; descriptor_alloc_count += other.descriptor_alloc_count; return *this; } MwCASMetrics& operator-=(const MwCASMetrics& other) { succeeded_update_count -= other.succeeded_update_count; failed_update_count -= other.failed_update_count; read_count -= other.read_count; descriptor_scavenge_count -= other.descriptor_scavenge_count; help_attempt_count -= other.help_attempt_count; bailed_help_count -= other.bailed_help_count; descriptor_alloc_count -= other.descriptor_alloc_count; return *this; } friend MwCASMetrics operator+(MwCASMetrics left, const MwCASMetrics& right) { left += right; return left; } friend MwCASMetrics operator-(MwCASMetrics left, const MwCASMetrics& right) { left -= right; return left; } MwCASMetrics() : succeeded_update_count(0), failed_update_count(0), read_count(0), descriptor_scavenge_count(0), help_attempt_count(0), bailed_help_count(0), descriptor_alloc_count(0) { } uint64_t GetUpdateAttemptCount() { return succeeded_update_count + failed_update_count; } inline void Print() { if(!enabled) return; auto update_attempts = GetUpdateAttemptCount(); std::cout << "> UpdateAttempts " << update_attempts << " (success " << succeeded_update_count << " failure " << failed_update_count << ")" << std::endl; printf("> UpdateFailurePercent %2f\n", (double)failed_update_count / (double)update_attempts * 100); std::cout << "> Reads " << read_count << std::endl; std::cout << "> DescriptorScavenges " << descriptor_scavenge_count << std::endl; std::cout << "> HelpAttempts " << help_attempt_count << std::endl; std::cout << "> BailedHelpAttempts " << bailed_help_count << std::endl; std::cout << "> DecsriptorAllocations " << descriptor_alloc_count << std::endl; } // Initialize the global CoreLocal container that encapsulates an array // of MwCASMetrics, one per thread. Call this exactly once upon startup. static Status Initialize() { if(enabled) MwCASMetrics::instance.Initialize(); return Status::OK(); } static Status Uninitialize() { if(enabled) return MwCASMetrics::instance.Uninitialize(); return Status::OK(); } static Status ThreadInitialize() { if(enabled) { MwCASMetrics *tls_metrics = nullptr; Allocator::Get()->Allocate((void **)&tls_metrics, sizeof(MwCASMetrics)); if (!tls_metrics) { return Status::OutOfMemory(); } new (tls_metrics) MwCASMetrics(); *instance.MyObject() = tls_metrics; } return Status::OK(); } inline static void AddRead() { if(enabled) ++MyMetric()->read_count; }; inline static void AddSucceededUpdate() { if(enabled) ++MyMetric()->succeeded_update_count; } inline static void AddFailedUpdate() { if (enabled) ++MyMetric()->failed_update_count; } inline static void AddDescriptorScavenge() { if(enabled) ++MyMetric()->descriptor_scavenge_count; } inline static void AddHelpAttempt() { if(enabled) ++MyMetric()->help_attempt_count; } inline static void AddBailedHelp() { if (enabled) ++MyMetric()->bailed_help_count; } inline static void AddDescriptorAlloc() { if (enabled) ++MyMetric()->descriptor_alloc_count; } inline static void Sum(MwCASMetrics &sum) { for (uint32_t i = 0; (i < instance.NumberOfObjects()) && enabled; ++i) { auto *thread_metric = *instance.GetObject(i); sum += *thread_metric; } } private: inline static MwCASMetrics* MyMetric() { RAW_CHECK(enabled, "metrics is disabled"); return *MwCASMetrics::instance.MyObject(); } static bool enabled; static CoreLocal<MwCASMetrics *> instance; uint64_t succeeded_update_count; uint64_t failed_update_count; uint64_t read_count; uint64_t descriptor_scavenge_count; uint64_t help_attempt_count; uint64_t bailed_help_count; uint64_t descriptor_alloc_count; uint64_t padding; }; } // namespace pmwcas <file_sep>cmake_minimum_required (VERSION 3.2.2) if("${CMAKE_SOURCE_DIR}" STREQUAL "${CMAKE_BINARY_DIR}") message(FATAL_ERROR "In-source builds are not allowed.") endif("${CMAKE_SOURCE_DIR}" STREQUAL "${CMAKE_BINARY_DIR}") enable_testing() include(ExternalProject) project(pmwcas) if(WIN32) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /Zi /nologo /W3 /WX /EHsc /GS /fp:precise /Zc:wchar_t /Zc:forScope /Gd /TP /errorReport:queue") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /FC /d2Zi+ /wd4018 /wd4100 /wd4101 /wd4127 /wd4189 /wd4200 /wd4244 /wd4267 /wd4296 /wd4305 /wd4307 /wd4309 /wd4512 /wd4701 /wd4702 /wd4800 /wd4804 /wd4996 /wd4005 /wd4091 /wd4722") set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /Od /RTC1 /Gm /MDd") set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /O2 /Oi /Gm- /Gy /MD") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /DEBUG /OPT:REF /OPT:NOICF /INCREMENTAL:NO") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /DEBUG /OPT:REF /OPT:NOICF /INCREMENTAL:NO") else() set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG}") set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE}") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -lpthread -lrt -lnuma") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -lpthread -lrt -lnuma") endif() #Always set _DEBUG compiler directive when compiling bits regardless of target OS set_directory_properties(PROPERTIES COMPILE_DEFINITIONS_DEBUG "_DEBUG") add_definitions() # Set backend to PMDK by default to build persistent version set(PMEM_BACKEND "PMDK" CACHE STRING "Persistent memory backend type") string(TOUPPER ${PMEM_BACKEND} PMEM_BACKEND) # Both volatile and persistent versions are supported, by setting PMEM_BACKEND to: # PMDK : use PMDK for persistence # EMU : use simple shared memory for emulating persistent memory. This # should only be used for experimental and profiling purpose. No real # persistence is guaranteed. # VOLATILE: turn off persistence and build a volatile version, no persistence # whatsoever. Equivalent to the original MwCAS operation. # # If persistent memory support is turned on, in the code we define both PMEM and # the corresponding macro for the backend. Code that is agnostic to the backend # is wrapped by PMEM; code that is specific to the backend is wrapped around by # PMEMEMU (for using emulation) or PMDK (for using PMDK). if(${PMEM_BACKEND} STREQUAL "PMDK") add_definitions(-DPMEM) add_definitions(-DPMDK) message(STATUS "Persistence support: PMDK") elseif(${PMEM_BACKEND} STREQUAL "EMU") add_definitions(-DPMEM) add_definitions(-DPMEMEMU) message(STATUS "Persistence support: emulation") elseif(${PMEM_BACKEND} STREQUAL "VOLATILE") message(STATUS "Persistence support: off") else() message(FATAL_ERROR "Unsupported persistent memory backend: ${PMEM_BACKEND}") endif() # Turn off RTM by default - only allowed when persistence is turned off (i.e., # PMEM_BACKEND == VOLATILE option(WITH_RTM "Use RTM for installing descriptors" OFF) if(WITH_RTM) if(NOT (${PMEM_BACKEND} STREQUAL "VOLATILE")) message(FATAL_ERROR "Cannot use RTM with persistence.") endif() add_definitions(-DRTM) endif() # Descriptor capacity - default four words max set(DESC_CAP "4" CACHE STRING "Descriptor capacity") add_definitions(-DDESC_CAP=${DESC_CAP}) message(STATUS "Descirptor capacity: ${DESC_CAP}") option(GOOGLE_FRAMEWORK "Use glog, gflags and gtest" ON) if(${GOOGLE_FRAMEWORK}) add_definitions(-DGOOGLE_FRAMEWORK) message(STATUS "GOOGLE_FRAMEWORK is defined, will use glog, gflags and gtest") else() message(STATUS "GOOGLE_FRAMEWORK is not defined, will not use glog, gflags and gtest") endif() if(${GOOGLE_FRAMEWORK}) # Install gtest as en external project set(GTEST_PREFIX "${CMAKE_CURRENT_BINARY_DIR}/gtest") set(GTEST_LOCATION "${GTEST_PREFIX}/src/GTestExternal-build") set(GTEST_INCLUDES "${GTEST_PREFIX}/src/GTestExternal/googletest/include") set(gtest_force_shared_crt ON CACHE BOOL "Force gtest to use dynamic standard library" ) include_directories(${GTEST_INCLUDES}) # external project download and build ExternalProject_Add(GTestExternal URL ${CMAKE_CURRENT_SOURCE_DIR}/third-party/googletest PREFIX "${GTEST_PREFIX}" # cmake arguments CMAKE_ARGS -Dgtest_force_shared_crt=ON # Disable install step INSTALL_COMMAND "" # Wrap download, configure and build steps in a script to log output LOG_DOWNLOAD ON LOG_CONFIGURE ON LOG_BUILD ON ) if (MSVC) set(GTEST_IMPORTED_LOCATION IMPORTED_LOCATION_DEBUG "${GTEST_LOCATION}/googlemock/gtest/Debug/${CMAKE_STATIC_LIBRARY_PREFIX}gtestd${CMAKE_STATIC_LIBRARY_SUFFIX}" IMPORTED_LOCATION_RELEASE "${GTEST_LOCATION}/googlemock/gtest/Release/${CMAKE_STATIC_LIBRARY_PREFIX}gtest${CMAKE_STATIC_LIBRARY_SUFFIX}" ) set(GTESTMAIN_IMPORTED_LOCATION IMPORTED_LOCATION_DEBUG "${GTEST_LOCATION}/googlemock/gtest/Debug/${CMAKE_STATIC_LIBRARY_PREFIX}gtest_maind${CMAKE_STATIC_LIBRARY_SUFFIX}" IMPORTED_LOCATION_RELEASE "${GTEST_LOCATION}/googlemock/gtest/Release/${CMAKE_STATIC_LIBRARY_PREFIX}gtest_main${CMAKE_STATIC_LIBRARY_SUFFIX}" ) else() set(GTEST_IMPORTED_LOCATION IMPORTED_LOCATION "${GTEST_LOCATION}/googlemock/gtest") set(GTESTMAIN_IMPORTED_LOCATION IMPORTED_LOCATION "${GTEST_LOCATION}/googlemock/gtest_main") link_directories(${GTEST_LOCATION}) link_directories(${GTEST_LOCATION}/googlemock/gtest) endif() # the gtest include directory exists only after it is built file(MAKE_DIRECTORY ${GTEST_INCLUDES}) # define imported library GTest add_library(GTest IMPORTED STATIC GLOBAL) set_target_properties(GTest PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${GTEST_INCLUDES}" IMPORTED_LINK_INTERFACE_LIBRARIES "${CMAKE_THREAD_LIBS_INIT}" ${GTEST_IMPORTED_LOCATION} ) # define imported library GTestMain add_library(GTestMain IMPORTED STATIC GLOBAL) set_target_properties(GTestMain PROPERTIES IMPORTED_LINK_INTERFACE_LIBRARIES GTest ${GTESTMAIN_IMPORTED_LOCATION} ) # make GTest depend on GTestExternal add_dependencies(GTest GTestExternal) ############################### # variables to help keep track of gflags paths set(GFLAGS_PREFIX "${CMAKE_CURRENT_BINARY_DIR}/gflags") set(GFLAGS_LOCATION "${GFLAGS_PREFIX}/src/GFlagsExternal-build") set(GFLAGS_INCLUDES "${GFLAGS_PREFIX}/src/GFlagsExternal-build/include") # external project download and build (no install for gtest) ExternalProject_Add(GFlagsExternal URL ${CMAKE_CURRENT_SOURCE_DIR}/third-party/gflags-2.1.2/gflags PREFIX "${GFLAGS_PREFIX}" # Disable install step INSTALL_COMMAND "" # Wrap download, configure and build steps in a script to log output LOG_DOWNLOAD ON LOG_CONFIGURE ON LOG_BUILD ON ) # variables defining the import location properties for the generated gtest and # gtestmain libraries if (MSVC) set(GFLAGS_IMPORTED_LOCATION IMPORTED_LOCATION_DEBUG "${GFLAGS_LOCATION}/lib/Debug/${CMAKE_STATIC_LIBRARY_PREFIX}gflags${CMAKE_STATIC_LIBRARY_SUFFIX}" IMPORTED_LOCATION_RELEASE "${GFLAGS_LOCATION}/lib/Release/${CMAKE_STATIC_LIBRARY_PREFIX}gflags${CMAKE_STATIC_LIBRARY_SUFFIX}" ) else() set(GFLAGS_IMPORTED_LOCATION IMPORTED_LOCATION "${GFLAGS_LOCATION}/lib/${CMAKE_STATIC_LIBRARY_PREFIX}gflags${CMAKE_STATIC_LIBRARY_SUFFIX}") link_directories(${GFLAGS_LOCATION}/lib) endif() # the gtest include directory exists only after it is build, but it is used/needed # for the set_target_properties call below, so make it to avoid an error file(MAKE_DIRECTORY ${GFLAGS_INCLUDES}) # define imported library GFlags add_library(GFlags IMPORTED STATIC GLOBAL) set_target_properties(GFlags PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${GFLAGS_INCLUDES}" IMPORTED_LINK_INTERFACE_LIBRARIES "${CMAKE_THREAD_LIBS_INIT}" ${GFLAGS_IMPORTED_LOCATION} ) include_directories(${GFLAGS_INCLUDES}) add_dependencies(GFlags GFlagsExternal) ############################### # variables to help keep track of glog paths set(GLOG_PREFIX "${CMAKE_CURRENT_BINARY_DIR}/glog") set(GLOG_LOCATION "${GLOG_PREFIX}/src/GLogExternal-build") if(WIN32) set(GLOG_INCLUDES "${GLOG_PREFIX}/src/GLogExternal/src/windows") file(MAKE_DIRECTORY ${GLOG_INCLUDES}) else() set(APPEND GLOG_INCLUDES "${GLOG_PREFIX}/src/GLogExternal/src") file(MAKE_DIRECTORY "${GLOG_PREFIX}/src/GLogExternal/src") include_directories("${GLOG_PREFIX}/src/GLogExternal/src") set(APPEND GLOG_INCLUDES "${GLOG_PREFIX}/src/GLogExternal-build") file(MAKE_DIRECTORY "${GLOG_PREFIX}/src/GLogExternal-build") include_directories("${GLOG_PREFIX}/src/GLogExternal-build") endif() # external project download and build (no install for gtest) ExternalProject_Add(GLogExternal URL ${CMAKE_CURRENT_SOURCE_DIR}/third-party/glog-0.3.4 PREFIX "${GLOG_PREFIX}" DEPENDS GFlagsExternal # cmake arguments CMAKE_ARGS -DCMAKE_PREFIX_PATH=${GFLAGS_LOCATION} # Disable install step INSTALL_COMMAND "" # Wrap download, configure and build steps in a script to log output LOG_DOWNLOAD ON LOG_CONFIGURE ON LOG_BUILD ON ) if (MSVC) set(GLOG_IMPORTED_LOCATION IMPORTED_LOCATION_DEBUG "${GLOG_LOCATION}/Debug/${CMAKE_STATIC_LIBRARY_PREFIX}glog${CMAKE_STATIC_LIBRARY_SUFFIX}" IMPORTED_LOCATION_RELEASE "${GLOG_LOCATION}/Release/${CMAKE_STATIC_LIBRARY_PREFIX}glog${CMAKE_STATIC_LIBRARY_SUFFIX}" ) else() set(GLOG_IMPORTED_LOCATION IMPORTED_LOCATION "${GLOG_LOCATION}/${CMAKE_STATIC_LIBRARY_PREFIX}glog${CMAKE_STATIC_LIBRARY_SUFFIX}") link_directories(${GLOG_LOCATION}) endif() # the glog include directory exists only after it is build, but it is used/needed # for the set_target_properties call below, so make it to avoid an error #file(MAKE_DIRECTORY ${GLOG_INCLUDES}) # define imported library GFlags add_library(GLog IMPORTED STATIC GLOBAL) set_target_properties(GLog PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${GLOG_INCLUDES}" IMPORTED_LINK_INTERFACE_LIBRARIES "${CMAKE_THREAD_LIBS_INIT}" ${GLOG_IMPORTED_LOCATION} ) add_dependencies(GLog GLogExternal) set(GFLAGS_LIB GFlags) set(GLOG_LIB GLog) set(GTEST_LIB GTest) endif() include_directories(${PROJECT_SOURCE_DIR}) include_directories(${PROJECT_SOURCE_DIR}/src) ##################### PMDK #################### if(${PMEM_BACKEND} STREQUAL "PMDK") set(PMDK_LIB_PATH "/usr/local/lib" CACHE STRING "PMDK lib install path") add_library(pmemobj SHARED IMPORTED) set_property(TARGET pmemobj PROPERTY IMPORTED_LOCATION ${PMDK_LIB_PATH}/libpmemobj.so) endif() ############################################## # Set the directory targets when build in libs and binaries set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}) # Set the list of libraries that make up the pmwcas stack set (PMWCAS_LINK_LIBS pmwcas ) if(${GOOGLE_FRAMEWORK}) # Set the list of libraries that use pmwcas set (PMWCAS_APPS_LINK_LIBS glog gflags gtest double-linked-list ) endif() if(WIN32) set(WINDOWS_ENVIRONMENT_SOURCES src/environment/environment_windows.cc ) else() set(LINUX_ENVIRONMENT_SOURCES src/environment/environment_linux.cc ) endif() option(BUILD_APPS "Build tests and benchmarks based on gtest" ON) if(${BUILD_APPS}) if(NOT GOOGLE_FRAMEWORK) message(FATAL_ERROR "Must enable GOOGLE_FRAMEWORK to be able to build tests and benchmarks") endif() add_definitions(-DAPPS) # Set the link libraries to for test compilation set (PMWCAS_TEST_LINK_LIBS ${PMWCAS_LINK_LIBS} ${GTEST_LIB}) if(WIN32) set (PMWCAS_TEST_LINK_LIBS ${PMWCAS_LINK_LIBS} ${GTEST_LIB}) # shlwapi is needed for gflags when compiling on windows set (PMWCAS_TEST_LINK_LIBS ${PMWCAS_TEST_LINK_LIBS} shlwapi) else() set (PMWCAS_TEST_LINK_LIBS ${PMWCAS_LINK_LIBS}) set (PMWCAS_TEST_LINK_LIBS ${PMWCAS_TEST_LINK_LIBS} "-lpthread -lrt -lnuma") endif() # Set the link libraries to for benchmark binary compilation set (PMWCAS_BENCHMARK_LINK_LIBS ${PMWCAS_LINK_LIBS} ${GFLAGS_LIB} ${GLOG_LIB}) if(WIN32) # shlwapi is needed for gflags when compiling on windows set (PMWCAS_BENCHMARK_LINK_LIBS ${PMWCAS_BENCHMARK_LINK_LIBS} shlwapi) else() set (PMWCAS_BENCHMARK_LINK_LIBS ${PMWCAS_BENCHMARK_LINK_LIBS} "-lpthread -lrt -lnuma") endif() endif() #Function to automate building test binaries with appropriate environment sources FUNCTION(ADD_PMWCAS_TEST TEST_NAME) if(${BUILD_APPS}) if(WIN32) add_executable(${TEST_NAME} ${TEST_NAME}.cc ${PROJECT_SOURCE_DIR}/${WINDOWS_ENVIRONMENT_SOURCES}) else() add_executable(${TEST_NAME} ${TEST_NAME}.cc ${PROJECT_SOURCE_DIR}/${LINUX_ENVIRONMENT_SOURCES}) endif() target_link_libraries(${TEST_NAME} ${PMWCAS_TEST_LINK_LIBS} ${PMWCAS_APPS_LINK_LIBS}) target_include_directories(${TEST_NAME} PUBLIC ${gtest_SOURCE_DIR} ${gtest_SOURCE_DIR}/include) add_test(${TEST_NAME} ${CMAKE_BINARY_DIR}/${TEST_NAME}) endif() ENDFUNCTION() #Function to automate building benchmark binaries with appropriate environment sources FUNCTION(ADD_PMWCAS_BENCHMARK BENCHMARK_NAME) if(${BUILD_APPS}) if(WIN32) add_executable(${BENCHMARK_NAME} ${BENCHMARK_HEADERS} ${BENCHMARK_NAME}.cc ${PROJECT_SOURCE_DIR}/${WINDOWS_ENVIRONMENT_SOURCES}) else() add_executable(${BENCHMARK_NAME} ${BENCHMARK_HEADERS} ${BENCHMARK_NAME}.cc ${PROJECT_SOURCE_DIR}/${LINUX_ENVIRONMENT_SOURCES}) endif() target_link_libraries(${BENCHMARK_NAME} ${PMWCAS_BENCHMARK_LINK_LIBS} ${PMWCAS_APPS_LINK_LIBS}) endif() ENDFUNCTION() # Build each subdirectory add_subdirectory(src/util) add_subdirectory(src/environment) add_subdirectory(src/common) add_subdirectory(src/benchmarks) add_subdirectory(src/mwcas) if (${BUILD_APPS}) add_subdirectory(src/double-linked-list) endif() # Generate a shared library for applications to link if(WIN32) set_property(GLOBAL APPEND PROPERTY PMWCAS_SRC ${WINDOWS_ENVIRONMENT_SOURCES}) else() set_property(GLOBAL APPEND PROPERTY PMWCAS_SRC ${LINUX_ENVIRONMENT_SOURCES}) endif() get_property(PMWCAS_SRC GLOBAL PROPERTY PMWCAS_SRC) add_library(pmwcas SHARED ${PMWCAS_SRC}) add_library(pmwcas_static ${PMWCAS_SRC}) if(${PMEM_BACKEND} STREQUAL "PMDK") target_link_libraries(pmwcas PUBLIC pmemobj) target_link_libraries(pmwcas_static PUBLIC pmemobj) endif() if(${GOOGLE_FRAMEWORK}) add_dependencies(pmwcas GFlags) add_dependencies(pmwcas GLog) add_dependencies(pmwcas GTest) endif() <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once #define NOMINMAX #include <Windows.h> #undef ERROR // Avoid collision of ERROR definition in Windows.h with glog #include <cstdint> #include <atomic> #include <memory> #include <string> #include <unordered_map> #include <glog/logging.h> #include <glog/raw_logging.h> #include "include/environment.h" #include "include/allocator.h" #include "include/status.h" #include "util/auto_ptr.h" #include "util/macros.h" namespace pmwcas { class WindowsAsyncIOHandler : public AsyncIOHandler { public: WindowsAsyncIOHandler(); ~WindowsAsyncIOHandler(); Status Initialize(ThreadPool* threadpool, HANDLE file_handle, PTP_CALLBACK_ENVIRON environment, ThreadPoolPriority priority); virtual Status ScheduleRead(uint8_t* buffer, size_t offset, uint32_t length, AsyncIOHandler::AsyncCallback callback, IAsyncContext* context); virtual Status ScheduleWrite(uint8_t* buffer, size_t offset, uint32_t length, AsyncIOHandler::AsyncCallback callback, IAsyncContext* context); private: struct IOCallbackContext { IOCallbackContext() : overlapped{} , handler{} , caller_context{} , callback{} , bytes_transferred{} { } // WARNING: overlapped must be the first field in IOCallbackContext. It is // used for abusive pointer casting in IOCompletionSpringboard(). /// The overlapped structure for Windows IO OVERLAPPED overlapped; /// The IO threadpool handler used for this IO WindowsAsyncIOHandler* handler; /// Caller callback context forwarded by #callback IAsyncContext* caller_context; /// The caller's asynchronous callback function AsyncIOHandler::AsyncCallback callback; /// Used in the case that an IO might finish sychronously. Used to relay the /// correct amount of bytes transferred by sync IO to the task that finishes /// the IO asynchronously. size_t bytes_transferred; }; enum class OperationType : uint8_t { Read, Write }; Status ScheduleOperation(OperationType operationType, void* buffer, size_t offset, uint32_t length, AsyncIOHandler::AsyncCallback callback, IAsyncContext* context); /// Invoked whenever an asynchronous IO completes; needed because Windows /// asynchronous IOs are tied to a specific TP_IO object. As a result, /// we allocate pointers for a per-operation callback along with its /// OVERLAPPED structure. This allows us to call a specific function in /// response to each IO, without having to create a TP_IO for each of them. static void CALLBACK IOCompletionCallback(PTP_CALLBACK_INSTANCE instance, PVOID context, PVOID overlapped, ULONG ioResult, ULONG_PTR bytesTransferred, PTP_IO io); /// Used as a springboard to complete an IO asynchronously in the case that /// scheduling the IO finishes synchronously. Windows ReadFile/WriteFile could /// finish synchronously even when using the PTP IO threadpool. We have seen /// this happen on VMs but never on raw hardware. To enforce the /// "always-async" contract schedule the completion on a separate thread using /// this function. static Status FinishSyncIOAsyncTask(void* context); private: /// Reference to the file handle for IO HANDLE file_handle_; /// The windows PTP threadpool used for IO completion port polling and windows /// async IO PTP_IO io_object_; /// Back reference to the parent threadpool. Used to schedule an async /// completion in case the IO should finish synchronously ThreadPool* threadpool_; /// Priority at which IOs are scheduled on this handler ThreadPoolPriority io_priority_; }; class WindowsPtpThreadPool : public ThreadPool { public: WindowsPtpThreadPool(); ~WindowsPtpThreadPool(); static Status Create(uint32_t max_threads, unique_ptr_t<ThreadPool>& threadpool); Status Initialize(uint32_t max_threads); virtual Status Schedule(ThreadPoolPriority priority, Task task, void* task_argument); virtual Status ScheduleTimer(ThreadPoolPriority priority, Task task, void* task_argument, uint32_t ms_period, void** timer_handle); virtual Status CreateAsyncIOHandler(ThreadPoolPriority priority, const File& file, unique_ptr_t<AsyncIOHandler>& async_io); private: /// Describes a task that should be invoked. Created and enqueued in /// ScheduleTask(); dispatched and freed in TaskStartSpringboard(). struct TaskInfo { TaskInfo() : task{} , task_parameters{} { } /// The task to be invoked when the work item is issued by the pool. Task task; /// Argument passed into #m_task when it is called. void* task_parameters; }; /// Called asynchronously by a thread from #m_pool whenever the thread pool /// starts to execute a task scheduled via ScheduleTask(). Just determines /// which routine was requested for execution and calls it. static void CALLBACK TaskStartSpringboard(PTP_CALLBACK_INSTANCE instance, PVOID parameter, PTP_WORK work); TP_CALLBACK_PRIORITY TranslatePriority(ThreadPoolPriority priority); /// A Window Thread Pool object that is used to run asynchronous IO /// operations (and callbacks) and other tasks (scheduled via /// ScheduleTask()). PTP_POOL pool_; /// An environment that associates Windows Thread Pool IO and Task objects /// to #m_pool. There is one environment for each priority in the /// work queue. AsyncIOFileWrappers and scheduled tasks are associated /// with one of these environments to schedule them for execution and /// to assign them a relative priority to other enqueued tasks. TP_CALLBACK_ENVIRON callback_environments_[size_t(ThreadPoolPriority::Last)]; /// The cleanup group associated with all environments and the thread pool. PTP_CLEANUP_GROUP cleanup_group_; /// Maximum number of threads the thread pool should allocate. uint64_t max_threads_; }; class WindowsRandomReadRandomWriteFile : public RandomReadWriteAsyncFile { public: WindowsRandomReadRandomWriteFile(); ~WindowsRandomReadRandomWriteFile(); static Status Create(unique_ptr_t<RandomReadWriteAsyncFile>& file); uint64_t GetFileIdentifier() const; virtual bool DirectIO() override; virtual size_t GetAlignment() override; virtual Status Open(const std::string& filename, const FileOptions& options, ThreadPool* threadpool) override; virtual Status Close() override; virtual Status Delete() override; virtual Status Read(size_t offset, uint32_t length, uint8_t* buffer, const IAsyncContext& context, RandomReadWriteAsyncFile::AsyncCallback callback) override; virtual Status Write(size_t offset, uint32_t length, uint8_t* buffer, const IAsyncContext& context, RandomReadWriteAsyncFile::AsyncCallback callback) override; private: struct AsyncIOContext : public IAsyncContext { IAsyncContext* context; RandomReadWriteAsyncFile::AsyncCallback callback; uint8_t* buffer; size_t bytes_to_transfer; WindowsRandomReadRandomWriteFile* file; AsyncIOContext(IAsyncContext* caller_context, RandomReadWriteAsyncFile::AsyncCallback caller_callback, uint8_t* caller_buffer, size_t caller_bytes_to_transfer, WindowsRandomReadRandomWriteFile* caller_file) : IAsyncContext() , context{ caller_context } , callback{ caller_callback } , buffer{ caller_buffer } , bytes_to_transfer { caller_bytes_to_transfer } , file{ caller_file } { } virtual Status DeepCopy(IAsyncContext** context_copy) { if(from_deep_copy_) { *context_copy = this; return Status::OK(); } *context_copy = nullptr; unique_ptr_t<AsyncIOContext> io_context = alloc_unique<AsyncIOContext>(sizeof(AsyncIOContext)); if(!io_context.get()) return Status::OutOfMemory(); IAsyncContext* caller_context_copy{}; RETURN_NOT_OK(context->DeepCopy(&caller_context_copy)); io_context->file = file; io_context->bytes_to_transfer = bytes_to_transfer; io_context->from_deep_copy_ = true; io_context->context = caller_context_copy; io_context->callback = callback; io_context->buffer = buffer; *context_copy = io_context.release(); return Status::OK(); } virtual Status DeepDelete() { if(!from_deep_copy_) { return Status::OK(); } Status s = context->DeepDelete(); if(!s.ok()) return s; Allocator::Get()->Free(this); return Status::OK(); } }; struct BlockingIOContext : public IAsyncContext { HANDLE continuation_handle; WindowsRandomReadRandomWriteFile* file_instance; Status status; IAllocator* deep_copy_allocator; BlockingIOContext(HANDLE caller_handle, WindowsRandomReadRandomWriteFile* caller_file) : continuation_handle{ caller_handle } , file_instance{ caller_file } , status{} { } virtual Status DeepCopy(IAsyncContext** context_copy, IAllocator* allocator) { if(from_deep_copy_) { *context_copy = this; return Status::OK(); } *context_copy = nullptr; BlockingIOContext* io_context = reinterpret_cast<BlockingIOContext*>( allocator->Allocate(sizeof(BlockingIOContext))); if(!io_context) return Status::OutOfMemory(); unique_ptr_t<BlockingIOContext> context_guard( io_context, [=](BlockingIOContext* c) { allocator->Free(c); }); context_guard->deep_copy_allocator = allocator; context_guard->file_instance = file_instance; context_guard->continuation_handle = continuation_handle; context_guard->from_deep_copy_ = true; *context_copy = context_guard.release(); return Status::OK(); } virtual Status DeepDelete() { if(!from_deep_copy_) { return Status::OK(); } deep_copy_allocator->Free(this); return Status::OK(); } }; Status GetDeviceAlignment(const std::string& filename, size_t& alignment); static void AsyncReadCallback(IAsyncContext* context, Status status, size_t transfer_size); static void AsyncWriteCallback(IAsyncContext* context, Status status, size_t transfer_size); static void BlockingCallback(IAsyncContext* context, Status status, size_t transfer_size); bool direct_io_; HANDLE file_handle_; HANDLE map_handle_; uint8_t* map_address_; size_t device_alignment_; std::string filename_; ThreadPool* threadpool_; unique_ptr_t<AsyncIOHandler> async_io_handler_; }; class WindowsSharedMemorySegment : public SharedMemorySegment { public: WindowsSharedMemorySegment(); ~WindowsSharedMemorySegment(); static Status Create(unique_ptr_t<SharedMemorySegment>& segment); virtual Status Initialize(const std::string& segname, uint64_t size, bool open_existing) override; virtual Status Attach(void* base_address = nullptr) override; virtual Status Detach() override; virtual void* GetMapAddress() override; //virtual DumpToFile(const std::string& filename) override; private: std::string segment_name_; uint64_t size_; HANDLE map_handle_; void* map_address_; }; class WindowsEnvironment : public IEnvironment { public: WindowsEnvironment(); virtual ~WindowsEnvironment() {} static Status Create(IEnvironment*& environment) { environment = reinterpret_cast<WindowsEnvironment*>(_aligned_malloc( sizeof(WindowsEnvironment), kCacheLineSize)); if(!environment) return Status::Corruption("Out of memory"); new(environment)WindowsEnvironment(); return Status::OK(); } static void Destroy(IEnvironment* e) { WindowsEnvironment* environment = static_cast<WindowsEnvironment*>(e); environment->~WindowsEnvironment(); _aligned_free(environment); } virtual uint64_t NowMicros() override; virtual uint64_t NowNanos() override; virtual uint32_t GetCoreCount() override; virtual void Sleep(uint32_t ms_to_sleep) override; virtual Status NewRandomReadWriteAsyncFile(const std::string& filename, const FileOptions& options, ThreadPool* threadpool, RandomReadWriteAsyncFile** file, bool* exists = nullptr) override ; virtual Status NewSharedMemorySegment(const std::string& segname, uint64_t size, bool open_existing, SharedMemorySegment** seg) override; virtual Status NewThreadPool(uint32_t max_threads, ThreadPool** pool) override; virtual Status SetThreadAffinity(uint64_t core, AffinityPattern affinity_pattern) override; virtual Status GetWorkingDirectory(std::string& directory) override; virtual Status GetExecutableDirectory(std::string& directory) override; virtual Status AllocateTlsIndex(uint32_t& index) override; virtual Status FreeTlsIndex(uint32_t index) override; virtual Status GetTlsValue(uint32_t index, void** value) override; virtual Status SetTlsValue(uint32_t index, void* value) override; private: Status SetThreadAffinity(HANDLE thread, uint64_t core, AffinityPattern affinity_pattern); private: /// Holds the windows performance counter frequency used for timing methods uint64_t perf_counter_frequency_; /// Struct that contains information about the current computer system. We /// call GetSystemInfo() in the constructor, and then read the number of /// processors off this field later. SYSTEM_INFO sys_info_; }; /// A default heap allocator implementing the IMemoryManager interace. To be /// used if no user-provided allocator is passed into the pmwcas librarty during // initialization class DefaultAllocator : public IAllocator { public: DefaultAllocator() : heap_(NULL), allocation_count_{} { } ~DefaultAllocator() { } static Status Create(IAllocator*& allocator) { allocator = reinterpret_cast<DefaultAllocator*>(_aligned_malloc( sizeof(DefaultAllocator), kCacheLineSize)); if(!allocator) return Status::Corruption("Out of memory"); new(allocator)DefaultAllocator(); static_cast<DefaultAllocator*>(allocator)->heap_ = ::GetProcessHeap(); if(!static_cast<DefaultAllocator*>(allocator)->heap_) { return Status::Aborted("GetProcessHeap error: " + GetLastError()); } return Status::OK(); } static void Destroy(IAllocator* a) { DefaultAllocator* allocator = static_cast<DefaultAllocator*>(a); allocator->~DefaultAllocator(); _aligned_free(allocator); } __checkReturn void* Allocate(size_t nSize) { #ifdef _DEBUG allocation_count_ += nSize; #endif return ::HeapAlloc(heap_, 0, nSize); } void* CAlloc(size_t count, size_t size) { return calloc(count, size); } __checkReturn void Free(void* pBytes) { #ifdef _DEBUG uint64_t size = GetAllocatedSize(pBytes); allocation_count_ -= size; #endif ::HeapFree(heap_, 0, pBytes); } __checkReturn void* AllocateAligned(size_t nSize, uint32_t nAlignment) { return _aligned_malloc(nSize, nAlignment); } __checkReturn void FreeAligned(void* pBytes) { _aligned_free(pBytes); } __checkReturn uint64_t GetAllocatedSize(void* pBytes) { return ::HeapSize(heap_, 0, pBytes); } void* AllocateAlignedOffset(size_t size, size_t alignment, size_t offset) { return _aligned_offset_malloc(size, alignment, offset); } void* AllocateHuge(size_t size) { return nullptr; } __checkReturn Status Validate(__in void* pBytes) { BOOL bIsValue = ::HeapValidate(heap_, 0, pBytes); if(!bIsValue) { // Return E_FAIL, GetLastError will not work. // From http://msdn.microsoft.com/en-us/library/windows/desktop/aa366708(v=vs.85).aspx // // "The HeapValidate function does not set the thread's last error value. // There is no extended error information for this function; do not call // GetLastError." return Status::Aborted("HeapValidate error"); } return Status::OK(); } __int64 GetTotalAllocationCount() { return allocation_count_; } private: HANDLE heap_; std::atomic<uint64_t> allocation_count_; }; /// A simple thread-local allocator that overlays the default heap allocator. /// Memory is never returned to the OS, but always retained in thread-local /// sets to be reused later. Each piece of user-facing memory is accompanied by /// header that describes the size of the memory block. All memory blocks of /// the same size are chained together in a hash table that maps memory block /// sizes to memory block chains of the specified size. class TlsAllocator : public IAllocator { private: // The hidden part of each allocated block of memory struct Header { uint64_t size; Header* next; Header() : size(0), next(nullptr) {} inline void* GetData() { return (void*)((char*)this + sizeof(*this)); } }; // Chain of all memory blocks of the same size struct BlockList { Header* head; Header* tail; BlockList() : head(nullptr), tail(nullptr) {} BlockList(Header* h, Header* t) : head(h), tail(t) {} inline void* Get() { if(head) { Header* alloc = head; if(alloc == tail) { head = tail = nullptr; } else { head = head->next; } return alloc->GetData(); } return nullptr; } inline void Put(Header* header) { if(!head) { DCHECK(!tail); head = tail = header; } else { Header* old_tail = tail; old_tail->next = header; tail = header; header->next = nullptr; } DCHECK(head->size == header->size); } }; inline Header* ExtractHeader(void* pBytes) { return (Header*)((char*)pBytes - sizeof(Header)); } inline std::unordered_map<size_t, BlockList>& GetTlsMap() { thread_local std::unordered_map<size_t, BlockList> tls_blocks; return tls_blocks; } struct Slab { uint64_t allocated; uint64_t size; void* memory; Slab() : allocated(0), size(0), memory(nullptr) {} ~Slab() { /* if(memory) { VirtualFree(memory, 0, MEM_RELEASE); } */ } inline void Initialize(uint64_t s) { size = s; uint16_t node; PROCESSOR_NUMBER pnum; GetCurrentProcessorNumberEx(&pnum); bool success = GetNumaProcessorNodeEx(&pnum, &node); memory = (void*)VirtualAllocExNuma(GetCurrentProcess(), nullptr, s, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE, node); memset(memory, 0, s); LOG(INFO) << "Initialized slab"; } inline void* Allocate(size_t n) { if(allocated + n <= size) { uint64_t off = allocated; allocated += n; return (void*)((char*)memory + off); } return nullptr; } }; inline Slab& GetTlsSlab() { thread_local Slab slab; static const uint64_t kSlabSize = 512 * 1024 * 1024; // 512MB if(slab.size == 0) { //slab.Initialize(kSlabSize); slab.size = kSlabSize; slab.memory = default_->AllocateAligned(kSlabSize, kCacheLineSize); memset(slab.memory, 0, kSlabSize); } return slab; } /// Try to get something from the TLS set inline void* TlsAllocate(size_t nSize) { // Align to cache line size nSize = (nSize + sizeof(Header) + kCacheLineSize - 1) / kCacheLineSize * kCacheLineSize; auto& tls_map = GetTlsMap(); auto& block_list = tls_map.find(nSize - sizeof(Header)); void* pBytes = nullptr; if(block_list != tls_map.end()) { pBytes = block_list->second.Get(); } if(!pBytes) { // Nothing in the map, try my local memory auto& tls_slab = GetTlsSlab(); pBytes = tls_slab.Allocate(nSize); if(pBytes) { ((Header*)pBytes)->size = nSize - sizeof(Header); ((Header*)pBytes)->next = nullptr; pBytes = (void*)((char*)pBytes + sizeof(Header)); } } return pBytes; } // Allocate from the default allocator, when there's nothing in the TLS set inline void* AllocateAndInitialize(size_t nSize) { void* pBytes = default_->AllocateAligned(nSize + sizeof(Header), kCacheLineSize); ((Header*)pBytes)->size = nSize; ((Header*)pBytes)->next = nullptr; return (void*)((char*)pBytes + sizeof(Header)); } DefaultAllocator* default_; public: TlsAllocator() { Status s = DefaultAllocator::Create((IAllocator*&)default_); DCHECK(s.ok()); } ~TlsAllocator() { DefaultAllocator::Destroy(default_); } static Status Create(IAllocator*& allocator) { allocator = reinterpret_cast<TlsAllocator*>(_aligned_malloc( sizeof(TlsAllocator), kCacheLineSize)); if(!allocator) return Status::Corruption("Out of memory"); new(allocator) TlsAllocator(); return Status::OK(); } static void Destroy(IAllocator* a) { TlsAllocator* allocator = static_cast<TlsAllocator*>(a); allocator->~TlsAllocator(); _aligned_free(allocator); } __checkReturn void* Allocate(size_t nSize) { void* pBytes = TlsAllocate(nSize); if(!pBytes) { // Nothing in the tls list, allocate from the OS pBytes = AllocateAndInitialize(nSize); } DCHECK(pBytes); return pBytes; } void* CAlloc(size_t count, size_t size) { return calloc(count, size); } __checkReturn void Free(void* pBytes) { auto& tls_map = GetTlsMap(); // Extract the hidden size info Header* pHeader = ExtractHeader(pBytes); pHeader->next = nullptr; DCHECK(pHeader->size); auto& block_list = tls_map.find(pHeader->size); if(block_list == tls_map.end()) { tls_map.emplace(pHeader->size, BlockList(pHeader, pHeader)); } else { block_list->second.Put(pHeader); } } __checkReturn void* AllocateAligned(size_t nSize, uint32_t nAlignment) { RAW_CHECK(nAlignment == kCacheLineSize, "unsupported alignment."); return Allocate(nSize); } __checkReturn void FreeAligned(void* pBytes) { return Free(pBytes); } void* AllocateAlignedOffset(size_t size, size_t alignment, size_t offset) { return nullptr; } void* AllocateHuge(size_t size) { return nullptr; } __checkReturn Status Validate(__in void* pBytes) { return default_->Validate(pBytes); } __checkReturn uint64_t GetAllocatedSize(void* pBytes) { return default_->GetAllocatedSize(pBytes); } __int64 GetTotalAllocationCount() { return 0; } }; } <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #include <stdint.h> #include <stdio.h> #include "include/status.h" namespace pmwcas { #ifdef WIn32 #ifndef snprintf #define snprintf _snprintf_s #endif #endif // WIN32 const char* Status::CopyState(const char* state) { uint32_t size; memcpy(&size, state, sizeof(size)); char* result = new char[size + 4]; memcpy(result, state, size + 4); return result; } Status::Status(Code _code, const Slice& msg, const Slice& msg2) : code_(_code) { assert(code_ != kOk); const uint32_t len1 = static_cast<uint32_t>(msg.size()); const uint32_t len2 = static_cast<uint32_t>(msg2.size()); const uint32_t size = len1 + (len2 ? (2 + len2) : 0); char* result = new char[size + 4]; memcpy(result, &size, sizeof(size)); memcpy(result + 4, msg.data(), len1); if(len2) { result[4 + len1] = ':'; result[5 + len1] = ' '; memcpy(result + 6 + len1, msg2.data(), len2); } state_ = result; } std::string Status::ToString() const { char tmp[30]; const char* type; switch(code_) { case kOk: return "OK"; case kNotFound: type = "NotFound: "; break; case kCorruption: type = "Corruption: "; break; case kNotSupported: type = "Not implemented: "; break; case kInvalidArgument: type = "Invalid argument: "; break; case kIOError: type = "IO error: "; break; case kMergeInProgress: type = "Merge in progress: "; break; case kUnableToMerge: type = "Cannot merge: "; break; case kIncomplete: type = "Result incomplete: "; break; case kShutdownInProgress: type = "Shutdown in progress: "; break; case kAborted: type = "Operation aborted: "; break; case kBusy: type = "Resource busy: "; break; default: snprintf(tmp, sizeof(tmp), "Unknown code(%d): ", static_cast<int>(code())); type = tmp; break; } std::string result(type); if(state_ != nullptr) { uint32_t length; memcpy(&length, state_, sizeof(length)); result.append(state_ + 4, length); } return result; } } // namespace pmwcas <file_sep>set(COMMON_HEADERS allocator_internal.h environment_internal.h epoch.h garbage_list.h ) set(COMMON_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/allocator_internal.cc ${CMAKE_CURRENT_SOURCE_DIR}/pmwcas_internal.cc ${CMAKE_CURRENT_SOURCE_DIR}/environment_internal.cc ${CMAKE_CURRENT_SOURCE_DIR}/epoch.cc ) set_property(GLOBAL APPEND PROPERTY PMWCAS_SRC ${COMMON_SOURCES}) set(COMMON_TEST_SOURCES allocator_internal_test.cc epoch_test.cc garbage_list_test.cc unordered_map_test.cc ) ADD_PMWCAS_TEST(allocator_internal_test) ADD_PMWCAS_TEST(epoch_test) ADD_PMWCAS_TEST(garbage_list_test) <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once #include <functional> #include <memory> #include "include/allocator.h" #include "include/status.h" namespace pmwcas { // Cache line size assumed to be 64 bytes. static const size_t kCacheLineSize = 64; /// Holds a pointer to the library-wide allocator. The allocator is set when /// calling pmwcas::Initialize. class Allocator { public: /// Initializes the library-wide allocator, using the specified create /// function. The library-wide allocator is stored as a static /// std::unique_ptr; in the static destructor, the allocator will be destroyed /// using the specified destroy function. static Status Initialize(std::function<Status(IAllocator*&)> create, std::function<void(IAllocator*)> destroy); /// Get a pointer to the library-wide allocator. static IAllocator* Get() { return allocator_.get(); } /// Destroys the library-wide allocator. static void Uninitialize() { allocator_.reset(); } private: /// The active library wide allocator. static std::unique_ptr<IAllocator, std::function<void(IAllocator*)>> allocator_; Allocator() {} ~Allocator() {} Allocator(const Allocator&) = delete; Allocator& operator=(const Allocator&) = delete; Allocator(Allocator&&) = delete; Allocator& operator=(Allocator&&) = delete; }; } // namespace pmwcas <file_sep>set(ENVIRONMENT_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/environment.cc ) set_property(GLOBAL APPEND PROPERTY PMWCAS_SRC ${ENVIRONMENT_SOURCES}) ADD_PMWCAS_TEST(environment_tests) <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once #include <functional> #include <list> #include <memory> #include <mutex> #include <thread> #include <unordered_map> #include "include/environment.h" #include "include/status.h" #include "util/auto_ptr.h" namespace pmwcas { /// Holds a pointer to the library-wide environment. The environment is set when /// calling pmwcas::Initialize. class Environment { public: /// Initializes the library-wide environment, using the specified create /// function. The library-wide environment is stored as a static /// std::unique_ptr; in the static destructor, the environment will be /// destroyed using the specified destroy function. The specified destroy /// function shouldn't use the library-wide allocator, since that may have /// already been destroyed. static Status Initialize(std::function<Status(IEnvironment*&)> create, std::function<void(IEnvironment*)> destroy); /// Get a pointer to the library-wide environment. static IEnvironment* Get() { return environment_.get(); } /// Destroys the library-wide environment. static void Uninitialize() { environment_.reset(); } private: /// The active library wide environment. static unique_ptr_t<IEnvironment> environment_; Environment() {} ~Environment() {} Environment(const Environment&) = delete; Environment& operator=(const Environment&) = delete; Environment(Environment&&) = delete; Environment& operator=(Environment&&) = delete; }; /// A wrapper for std::thread that bookkeeps C++11 thread_local variables to /// handle thread/TLS variable interactions. The key problem is avoding /// leaving dangling pointers in TLS variables pointing to resource already /// destroyed (e.g., a thread re-purposed to use another descriptor pool after /// destroying a previous one in test cases). /// /// Typical uses: client code instantiates threads just like using std::thread, /// but whenever it initializes TLS variables that might need to avoid leaving /// dangling pointers, use RegisterTls. Upon thread destruction/join, the TLS /// variables are automatically reset using the default value provided through /// RegisterTls. /// /// In case of the same thread using different resources, e.g., descriptor pool, /// the thread should invoke ClearRegistry to ensure all TLS variables do not /// point to previously destroyed resources. /// /// Here we keep it always the thread that resets its own TLS variables. class Thread : public std::thread { public: /// Pairs of <pointer to variable, invalid value>, supports 8-byte word types /// only for now. typedef std::list<std::pair<uint64_t*, uint64_t> > TlsList; static std::unordered_map<std::thread::id, TlsList*> registry_; static std::mutex registryMutex_; template<typename ... Args> Thread(Args&& ... args) : std::thread(std::forward<Args>(args) ...), id_(get_id()) {} ~Thread() { ClearTls(true); } /// Overrides std::thread's join inline void join() { std::thread::join(); ClearTls(); } /// Register a thread-local variable /// @ptr - pointer to the TLS variable /// @val - default value of the TLS variable static void RegisterTls(uint64_t *ptr, uint64_t val); /// Clear/reset the entire global TLS registry covering all threads static void ClearRegistry(bool destroy = false); private: /// Clear/reset the TLS variables of this thread void ClearTls(bool destroy = false); std::thread::id id_; }; } // namespace pmwcas <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #define NOMINMAX #include <string> #include "mwcas_benchmark.h" #include "util/core_local.h" #include "util/random_number_generator.h" using namespace pmwcas::benchmark; DEFINE_string(benchmarks, "mwcas", "Comma-separated list of benchmarks to run in the specified order." " Available benchmarks:\n\tmwcas -- Configurable multi-threaded benchmark" " for multi-word cas\n"); DEFINE_uint64(array_size, 100, "size of the word array for mwcas benchmark"); DEFINE_uint64(seed, 1234, "base random number generator seed, the thread index" "is added to this number to form the full seed"); DEFINE_uint64(word_count, 4, "number of words in the multi-word compare and" " swap"); DEFINE_uint64(threads, 2, "number of threads to use for multi-threaded tests"); DEFINE_uint64(seconds, 30, "default time to run a benchmark"); DEFINE_uint64(metrics_dump_interval, 0, "if greater than 0, the benchmark " "driver dumps metrics at this fixed interval (in seconds)"); DEFINE_int32(affinity, 1, "affinity to use in scheduling threads"); DEFINE_uint64(descriptor_pool_size, 262144, "number of total descriptors"); DEFINE_string(shm_segment, "mwcas", "name of the shared memory segment for" " descriptors and data (for persistent MwCAS only)"); DEFINE_int32(enable_stats, 1, "whether to enable stats on MwCAS internal" " operations"); #ifdef PMEM DEFINE_uint64(write_delay_ns, 0, "NVRAM write delay (ns)"); DEFINE_bool(emulate_write_bw, false, "Emulate write bandwidth"); DEFINE_bool(clflush, false, "Use CLFLUSH, instead of spinning delays." "write_dealy_ns and emulate_write_bw will be ignored."); #ifdef PMDK DEFINE_string(pmdk_pool, "/mnt/pmem0/mwcas_benchmark_pool", "path to pmdk pool"); #endif #endif namespace pmwcas { /// Maximum number of threads that the benchmark driver supports. const size_t kMaxNumThreads = 64; /// Dumps args in a format that can be extracted by an experiment script void DumpArgs() { std::cout << "> Args shm_segment " << FLAGS_shm_segment.c_str() << std::endl; std::cout << "> Args threads " << FLAGS_threads << std::endl; std::cout << "> Args word_count " << FLAGS_word_count << std::endl; std::cout << "> Args array_size " << FLAGS_array_size << std::endl; std::cout << "> Args affinity " << FLAGS_affinity << std::endl; std::cout << "> Args desrciptor_pool_size " << FLAGS_descriptor_pool_size << std::endl; #ifdef PMEM if(FLAGS_clflush) { printf("> Args using clflush\n"); } else { std::cout << "> Args write_delay_ns " << FLAGS_write_delay_ns << std::endl; std::cout << "> Args emulate_write_bw " << FLAGS_emulate_write_bw << std::endl; } #ifdef PMDK std::cout << "> Args pmdk_pool " << FLAGS_pmdk_pool << std::endl; #endif #endif } struct PMDKRootObj { DescriptorPool *desc_pool_{nullptr}; CasPtr* test_array_{nullptr}; }; struct MwCas : public Benchmark { MwCas() : Benchmark{} , previous_dump_run_ticks_{} , cumulative_stats_ {} { total_success_ = 0; } void Setup(size_t thread_count) { // Ideally the descriptor pool is sized to the number of threads in the // benchmark to reduce need for new allocations, etc. #ifdef PMDK auto allocator = reinterpret_cast<PMDKAllocator*>(Allocator::Get()); auto root_obj = reinterpret_cast<PMDKRootObj*>(allocator->GetRoot(sizeof(PMDKRootObj))); Allocator::Get()->Allocate((void **)&root_obj->desc_pool_, sizeof(DescriptorPool)); // Allocate the thread array and initialize to consecutive even numbers Allocator::Get()->Allocate((void **)&root_obj->test_array_, FLAGS_array_size * sizeof(CasPtr)); // TODO: might have some memory leak here, but for benchmark we don't care (yet). descriptor_pool_ = root_obj->desc_pool_; test_array_ = root_obj->test_array_; #else Allocator::Get()->Allocate((void **)&descriptor_pool_, sizeof(DescriptorPool)); // Allocate the thread array and initialize to consecutive even numbers Allocator::Get()->Allocate((void **)&test_array_, FLAGS_array_size * sizeof(CasPtr)); #endif new (descriptor_pool_) DescriptorPool(FLAGS_descriptor_pool_size, FLAGS_threads, true); // Wrap the test array memory in an auto pointer for easy cleanup, keep the // raw pointer to avoid indirection during access test_array_guard_ = make_unique_ptr_t<CasPtr>(test_array_); // Now we can start from a clean slate (perhaps not necessary) for(uint32_t i = 0; i < FLAGS_array_size; ++i) { test_array_[i] = uint64_t(i * 4); } } void Teardown() { if(FLAGS_array_size > 100) { return; } // Check the array for correctness unique_ptr_t<int64_t> found = alloc_unique<int64_t>( sizeof(int64_t) * FLAGS_array_size); for(uint32_t i = 0; i < FLAGS_array_size; i++) { found.get()[i] = 0; } for(uint32_t i = 0; i < FLAGS_array_size; i++) { uint32_t idx = uint32_t((uint64_t(test_array_[i]) % (4 * FLAGS_array_size)) / 4); LOG(INFO) << "idx=" << idx << ", pos=" << i << ", val=" << (uint64_t)test_array_[i]; if(!(idx >= 0 && idx < FLAGS_array_size)) { LOG(INFO) << "Invalid: pos=" << i << "val=" << uint64_t(test_array_[i]); continue; } found.get()[idx]++; } uint32_t missing = 0; uint32_t duplicated = 0; for(uint32_t i = 0; i < FLAGS_array_size; i++) { if(found.get()[i] == 0) missing++; if(found.get()[i] > 1) duplicated++; } CHECK(0 == missing && 0 == duplicated) << "Failed final sanity test, missing: " << missing << " duplicated: " << duplicated; } void Main(size_t thread_index) { CasPtr* address[10] = {0,0,0,0,0,0,0,0,0,0}; CasPtr value[10] = {0,0,0,0,0,0,0,0,0,0}; RandomNumberGenerator rng(FLAGS_seed + thread_index, 0, FLAGS_array_size); auto s = MwCASMetrics::ThreadInitialize(); RAW_CHECK(s.ok(), "Error initializing thread"); WaitForStart(); const uint64_t kEpochThreshold = 100; uint64_t epochs = 0; descriptor_pool_->GetEpoch()->Protect(); uint64_t n_success = 0; while(!IsShutdown()) { if(++epochs == kEpochThreshold) { descriptor_pool_->GetEpoch()->Unprotect(); descriptor_pool_->GetEpoch()->Protect(); epochs = 0; } // Pick a random word each time for(uint32_t i = 0; i < FLAGS_word_count; ++i) { retry: uint64_t idx = rng.Generate(FLAGS_array_size); for(uint32_t j = 0; j < i; ++j) { if(address[j] == reinterpret_cast<CasPtr*>(&test_array_[idx])) { goto retry; } } address[i] = reinterpret_cast<CasPtr*>(&test_array_[idx]); value[i] = test_array_[idx].GetValueProtected(); CHECK(value[i] % (4 * FLAGS_array_size) >= 0 && (value[i] % (4 * FLAGS_array_size)) / 4 < FLAGS_array_size); } Descriptor* descriptor = descriptor_pool_->AllocateDescriptor(); CHECK_NOTNULL(descriptor); for(uint64_t i = 0; i < FLAGS_word_count; i++) { descriptor->AddEntry((uint64_t*)(address[i]), uint64_t(value[i]), uint64_t(value[FLAGS_word_count - 1 - i] + 4 * FLAGS_array_size)); } bool status = false; status = descriptor->MwCAS(); n_success += (status == true); } descriptor_pool_->GetEpoch()->Unprotect(); auto n = total_success_.fetch_add(n_success, std::memory_order_seq_cst); LOG(INFO) << "Thread " << thread_index << " success updates: " << n_success << " " << n; } uint64_t GetOperationCount() { MwCASMetrics metrics; MwCASMetrics::Sum(metrics); return metrics.GetUpdateAttemptCount(); } uint64_t GetTotalSuccess() { return total_success_.load(); } virtual void Dump(size_t thread_count, uint64_t run_ticks, uint64_t dump_id, bool final_dump) { MARK_UNREFERENCED(thread_count); uint64_t interval_ticks = 0; if(final_dump) { interval_ticks = run_ticks; } else { interval_ticks = run_ticks - previous_dump_run_ticks_; previous_dump_run_ticks_ = run_ticks; } Benchmark::Dump(thread_count, run_ticks, dump_id, final_dump); MwCASMetrics stats; MwCASMetrics::Sum(stats); if(!final_dump) { stats -= cumulative_stats_; cumulative_stats_ += stats; } stats.Print(); #ifdef WIN32 LARGE_INTEGER frequency; QueryPerformanceFrequency(&frequency); uint64_t ticks_per_second = frequency.QuadPart; #else uint64_t ticks_per_second = 1000000; #endif std::cout << "> Benchmark " << dump_id << " TicksPerSecond " << ticks_per_second << std::endl; std::cout << "> Benchmark " << dump_id << " RunTicks " << run_ticks << std::endl; double run_seconds = (double)run_ticks / ticks_per_second; std::cout << "> Benchmark " << dump_id << " RunSeconds " << run_seconds << std::endl; std::cout << "> Benchmark " << dump_id << " IntervalTicks " << interval_ticks << std::endl; double interval_seconds = (double)interval_ticks / ticks_per_second; std::cout << "> Benchmark " << dump_id << " IntervalSeconds " << interval_seconds << std::endl; } CasPtr* test_array_; unique_ptr_t<CasPtr> test_array_guard_; DescriptorPool* descriptor_pool_; uint64_t previous_dump_run_ticks_; MwCASMetrics cumulative_stats_; std::atomic<uint64_t> total_success_; }; } // namespace pmwcas using namespace pmwcas; Status RunMwCas() { MwCas test{}; std::cout << "Starting benchmark..." << std::endl; test.Run(FLAGS_threads, FLAGS_seconds, static_cast<AffinityPattern>(FLAGS_affinity), FLAGS_metrics_dump_interval); printf("mwcas: %.2f ops/sec\n", (double)test.GetOperationCount() / test.GetRunSeconds()); printf("mwcas: %.2f successful updates/sec\n", (double)test.GetTotalSuccess() / test.GetRunSeconds()); return Status::OK(); } void RunBenchmark() { std::string benchmark_name{}; std::stringstream benchmark_stream(FLAGS_benchmarks); DumpArgs(); while(std::getline(benchmark_stream, benchmark_name, ',')) { Status s{}; if("mwcas" == benchmark_name) { s = RunMwCas(); } else { fprintf(stderr, "unknown benchmark name: %s\n", benchmark_name.c_str()); } ALWAYS_ASSERT(s.ok()); } } int main(int argc, char* argv[]) { google::InitGoogleLogging(argv[0]); google::ParseCommandLineFlags(&argc, &argv, true); #ifdef WIN32 pmwcas::InitLibrary(pmwcas::DefaultAllocator::Create, pmwcas::DefaultAllocator::Destroy, pmwcas::WindowsEnvironment::Create, pmwcas::WindowsEnvironment::Destroy); #else #ifdef PMDK pmwcas::InitLibrary(pmwcas::PMDKAllocator::Create(FLAGS_pmdk_pool.c_str(), "mwcas_layout", static_cast<uint64_t>(1024) * 1024 * 1204 * 1), pmwcas::PMDKAllocator::Destroy, pmwcas::LinuxEnvironment::Create, pmwcas::LinuxEnvironment::Destroy); #else pmwcas::InitLibrary(pmwcas::TlsAllocator::Create, pmwcas::TlsAllocator::Destroy, pmwcas::LinuxEnvironment::Create, pmwcas::LinuxEnvironment::Destroy); #endif #endif RunBenchmark(); return 0; } <file_sep>/* src/config.h.in. Generated from configure.ac by autoheader. */ /* Namespace for Google classes */ #define GOOGLE_NAMESPACE google /* Stops putting the code inside the Google namespace */ #define _END_GOOGLE_NAMESPACE_ } /* Puts following code inside the Google namespace */ #define _START_GOOGLE_NAMESPACE_ namespace google { #if 0 /* Always the empty-string on non-windows systems. On windows, should be "__declspec(dllexport)". This way, when we compile the dll, we export our functions/classes. It's safe to define this here because config.h is only used internally, to compile the DLL, and every DLL source file #includes "config.h" before anything else. */ #ifndef GOOGLE_GLOG_DLL_DECL # define GOOGLE_GLOG_IS_A_DLL 1 /* not set if you're statically linking */ # define GOOGLE_GLOG_DLL_DECL __declspec(dllexport) # define GOOGLE_GLOG_DLL_DECL_FOR_UNITTESTS __declspec(dllimport) #endif #else #define GOOGLE_GLOG_DLL_DECL #endif <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #include <gtest/gtest.h> #include <stdlib.h> #include "common/allocator_internal.h" #include "include/pmwcas.h" #include "include/environment.h" #include "include/allocator.h" #include "include/status.h" #include "util/random_number_generator.h" #include "util/auto_ptr.h" #include "mwcas/mwcas.h" #ifdef WIN32 #include "environment/environment_windows.h" #else #include "environment/environment_linux.h" #endif namespace pmwcas { typedef pmwcas::MwcTargetField<uint64_t> PMwCASPtr; const uint32_t kDescriptorPoolSize = 0x400; const uint32_t kTestArraySize = 0x80; const uint32_t kWordsToUpdate = 4; const std::string kSharedMemorySegmentName = "mwcastest"; GTEST_TEST(PMwCASTest, SingleThreadedUpdateSuccess) { auto thread_count = Environment::Get()->GetCoreCount(); std::unique_ptr<pmwcas::DescriptorPool> pool( new pmwcas::DescriptorPool(kDescriptorPoolSize, thread_count)); RandomNumberGenerator rng(rand(), 0, kTestArraySize); PMwCASPtr test_array[kTestArraySize]; PMwCASPtr* addresses[kWordsToUpdate]; uint64_t values[kWordsToUpdate]; for (uint32_t i = 0; i < kWordsToUpdate; ++i) { test_array[i] = 0; addresses[i] = nullptr; values[i] = 0; } pool.get()->GetEpoch()->Protect(); for (uint32_t i = 0; i < kWordsToUpdate; ++i) { retry: uint64_t idx = rng.Generate(); for (uint32_t existing_entry = 0; existing_entry < i; ++existing_entry) { if (addresses[existing_entry] == reinterpret_cast<PMwCASPtr*>( &test_array[idx])) { goto retry; } } addresses[i] = reinterpret_cast<PMwCASPtr*>(&test_array[idx]); values[i] = test_array[idx].GetValueProtected(); } Descriptor* descriptor = pool->AllocateDescriptor(); EXPECT_NE(nullptr, descriptor); for (uint32_t i = 0; i < kWordsToUpdate; ++i) { descriptor->AddEntry((uint64_t*)addresses[i], values[i], 1ull); } EXPECT_TRUE(descriptor->MwCAS()); for (uint32_t i = 0; i < kWordsToUpdate; ++i) { EXPECT_EQ(1ull, *((uint64_t*)addresses[i])); } pool.get()->GetEpoch()->Unprotect(); Thread::ClearRegistry(true); } GTEST_TEST(PMwCASTest, SingleThreadedAbort) { auto thread_count = Environment::Get()->GetCoreCount(); std::unique_ptr<pmwcas::DescriptorPool> pool( new pmwcas::DescriptorPool(kDescriptorPoolSize, thread_count)); RandomNumberGenerator rng(rand(), 0, kTestArraySize); PMwCASPtr test_array[kTestArraySize]; PMwCASPtr* addresses[kWordsToUpdate]; for (uint32_t i = 0; i < kWordsToUpdate; ++i) { test_array[i] = 0; addresses[i] = nullptr; } for (uint32_t i = 0; i < kWordsToUpdate; ++i) { retry: uint64_t idx = rng.Generate(); for (uint32_t existing_entry = 0; existing_entry < i; ++existing_entry) { if (addresses[existing_entry] == reinterpret_cast<PMwCASPtr*>( &test_array[idx])) { goto retry; } } addresses[i] = reinterpret_cast<PMwCASPtr*>(&test_array[idx]); } pool.get()->GetEpoch()->Protect(); Descriptor* descriptor = pool->AllocateDescriptor(); EXPECT_NE(nullptr, descriptor); for (uint32_t i = 0; i < kWordsToUpdate; ++i) { descriptor->AddEntry((uint64_t*)addresses[i], 0ull, 1ull); } EXPECT_TRUE(descriptor->Abort().ok()); for (uint32_t i = 0; i < kWordsToUpdate; ++i) { EXPECT_EQ(0ull, *((uint64_t*)addresses[i])); } pool.get()->GetEpoch()->Unprotect(); Thread::ClearRegistry(true); } GTEST_TEST(PMwCASTest, SingleThreadedConflict) { auto thread_count = Environment::Get()->GetCoreCount(); std::unique_ptr<pmwcas::DescriptorPool> pool( new pmwcas::DescriptorPool(kDescriptorPoolSize, thread_count)); RandomNumberGenerator rng(rand(), 0, kTestArraySize); PMwCASPtr test_array[kTestArraySize]; PMwCASPtr* addresses[kWordsToUpdate]; for (uint32_t i = 0; i < kTestArraySize; ++i) { test_array[i] = 0ull; } for (uint32_t i = 0; i < kWordsToUpdate; ++i) { addresses[i] = nullptr; } for (uint32_t i = 0; i < kWordsToUpdate; ++i) { retry: uint64_t idx = rng.Generate(); for (uint32_t existing_entry = 0; existing_entry < i; ++existing_entry) { if (addresses[existing_entry] == reinterpret_cast<PMwCASPtr*>( &test_array[idx])) { goto retry; } } addresses[i] = reinterpret_cast<PMwCASPtr*>(&test_array[idx]); } pool.get()->GetEpoch()->Protect(); Descriptor* descriptor = pool->AllocateDescriptor(); EXPECT_NE(nullptr, descriptor); for (uint32_t i = 0; i < kWordsToUpdate; ++i) { descriptor->AddEntry((uint64_t*)addresses[i], 0ull, 1ull); } EXPECT_TRUE(descriptor->MwCAS()); for (uint32_t i = 0; i < kWordsToUpdate; ++i) { EXPECT_EQ(1ull, *((uint64_t*)addresses[i])); } pool.get()->GetEpoch()->Unprotect(); pool.get()->GetEpoch()->Protect(); descriptor = pool->AllocateDescriptor(); EXPECT_NE(nullptr, descriptor); for (uint32_t i = 0; i < kWordsToUpdate; ++i) { descriptor->AddEntry((uint64_t*)addresses[i], 0ull, 1ull); } EXPECT_FALSE(descriptor->MwCAS()); pool.get()->GetEpoch()->Unprotect(); Thread::ClearRegistry(true); } #ifdef PMEM GTEST_TEST(PMwCASTest, SingleThreadedRecovery) { auto thread_count = Environment::Get()->GetCoreCount(); RandomNumberGenerator rng(rand(), 0, kTestArraySize); PMwCASPtr* addresses[kWordsToUpdate]; PMwCASPtr* test_array = nullptr; // Round shared segment (descriptor pool and test data) up to cacheline size uint64_t segment_size = sizeof(DescriptorPool) + sizeof(DescriptorPool::Metadata) + sizeof(Descriptor) * kDescriptorPoolSize + sizeof(PMwCASPtr) * kTestArraySize; // Create a shared memory segment. This will serve as our test area for // the first PMwCAS process that "fails" and will be re-attached to a new // descriptor pool and recovered. unique_ptr_t<char> memory_segment = alloc_unique<char>(segment_size); ::memset(memory_segment.get(), 0, segment_size); void* segment_raw = memory_segment.get(); // Record descriptor count and the initial virtual address of the shm space // for recovery later DescriptorPool::Metadata *metadata = (DescriptorPool::Metadata*)segment_raw; metadata->descriptor_count = kDescriptorPoolSize; metadata->initial_address = (uintptr_t)segment_raw; DescriptorPool *pool = (DescriptorPool*)((char*)segment_raw + sizeof(DescriptorPool::Metadata)); test_array = (PMwCASPtr*)((uintptr_t)segment_raw + sizeof(DescriptorPool) + sizeof(DescriptorPool::Metadata) + sizeof(Descriptor) * kDescriptorPoolSize); // Create a new descriptor pool using an existing memory block, which will // be reused by new descriptor pools that will recover from whatever is in the // pool from previous runs. new (pool) DescriptorPool(kDescriptorPoolSize, thread_count, false); for (uint32_t i = 0; i < kTestArraySize; ++i) { test_array[i] = 0ull; } for (uint32_t i = 0; i < kWordsToUpdate; ++i) { addresses[i] = nullptr; } for (uint32_t i = 0; i < kWordsToUpdate; ++i) { retry: uint64_t idx = rng.Generate(); for (uint32_t existing_entry = 0; existing_entry < i; ++existing_entry) { if (addresses[existing_entry] == reinterpret_cast<PMwCASPtr*>( &test_array[idx])) { goto retry; } } addresses[i] = reinterpret_cast<PMwCASPtr*>(&test_array[idx]); } pool->GetEpoch()->Protect(); Descriptor* descriptor = pool->AllocateDescriptor(); EXPECT_NE(nullptr, descriptor); for (uint32_t i = 0; i < kWordsToUpdate; ++i) { descriptor->AddEntry((uint64_t*)addresses[i], 0ull, 1ull); } EXPECT_TRUE(descriptor->MwCAS()); for (uint32_t i = 0; i < kWordsToUpdate; ++i) { EXPECT_EQ(1ull, *((uint64_t*)addresses[i])); } pool->GetEpoch()->Unprotect(); Thread::ClearRegistry(true); // Create a fresh descriptor pool from the previous pools existing memory. pool->Recovery(false); // The prior MwCAS succeeded, so check whether the pool recovered correctly // by ensuring the updates are still present. for (uint32_t i = 0; i < kWordsToUpdate; ++i) { EXPECT_EQ(1ull, *((uint64_t*)addresses[i])); } pool->GetEpoch()->Protect(); descriptor = pool->AllocateDescriptor(); EXPECT_NE(nullptr, descriptor); for (uint32_t i = 0; i < kWordsToUpdate; ++i) { descriptor->AddEntry((uint64_t*)addresses[i], 1ull, 2ull); } EXPECT_FALSE(descriptor->MwCASWithFailure()); Thread::ClearRegistry(true); pool->Recovery(false); // Recovery should have rolled back the previously failed pmwcas. for (uint32_t i = 0; i < kWordsToUpdate; ++i) { EXPECT_EQ(1ull, *((uint64_t*)addresses[i])); } pool->GetEpoch()->Protect(); descriptor = pool->AllocateDescriptor(); EXPECT_NE(nullptr, descriptor); for (uint32_t i = 0; i < kWordsToUpdate; ++i) { descriptor->AddEntry((uint64_t*)addresses[i], 1ull, 2ull); } EXPECT_FALSE(descriptor->MwCASWithFailure(0, true)); Thread::ClearRegistry(true); pool->Recovery(false); // Recovery should have rolled forward the previously failed pmwcas that made // it through the first phase (installing all descriptors). for (uint32_t i = 0; i < kWordsToUpdate; ++i) { EXPECT_EQ(2ull, *((uint64_t*)addresses[i])); } Thread::ClearRegistry(true); } #endif } // namespace pmwcas int main(int argc, char** argv) { google::InitGoogleLogging(argv[0]); ::testing::InitGoogleTest(&argc, argv); FLAGS_minloglevel = 2; #ifdef WIN32 pmwcas::InitLibrary(pmwcas::DefaultAllocator::Create, pmwcas::DefaultAllocator::Destroy, pmwcas::WindowsEnvironment::Create, pmwcas::WindowsEnvironment::Destroy); #else pmwcas::InitLibrary(pmwcas::TlsAllocator::Create, pmwcas::TlsAllocator::Destroy, pmwcas::LinuxEnvironment::Create, pmwcas::LinuxEnvironment::Destroy); #endif return RUN_ALL_TESTS(); } <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once #include "include/allocator.h" #include "include/environment.h" #include "include/status.h" #include "common/allocator_internal.h" #include "common/environment_internal.h" namespace pmwcas { /// Initialize the pmwcas library, creating a library-wide allocator. Status InitLibrary(std::function<Status(IAllocator*&)> create_allocator, std::function<void(IAllocator*)> destroy_allocator); /// Initialize the pmwcas library, creating library-wide allocator and environment. Status InitLibrary(std::function<Status(IAllocator*&)> create_allocator, std::function<void(IAllocator*)> destroy_allocator, std::function<Status(IEnvironment*&)> create_environment, std::function<void(IEnvironment*)> destroy_environment); /// Explicitly uninitializes the pmwcas library, destroying the library-wide allocator and /// environment. void UninitLibrary(); } // namespace pmwcas <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once // Squelch warnings on initializing arrays; it is new (good) behavior in C++11. #pragma warning(disable: 4351) #include <atomic> #include <cstdint> #include <list> #include <mutex> #ifdef GOOGLE_FRAMEWORK #include <gtest/gtest_prod.h> #endif #include "include/status.h" #include "util/macros.h" namespace pmwcas { /// A "timestamp" that is used to determine when it is safe to reuse memory in /// data structures that are protected with an EpochManager. Epochs are /// opaque to threads and data structures that use the EpochManager. They /// may receive Epochs from some of the methods, but they never need to /// perform any computation on them, other than to pass them back to the /// EpochManager on future calls (for example, EpochManager::GetCurrentEpoch() /// and EpochManager::IsSafeToReclaim()). typedef uint64_t Epoch; /// Used to ensure that concurrent accesses to data structures don't reuse /// memory that some threads may be accessing. Specifically, for many lock-free /// data structures items are "unlinked" when they are removed. Unlinked items /// cannot be disposed until it is guaranteed that no threads are accessing or /// will ever access the memory associated with the item again. EpochManager /// makes it easy for data structures to determine if it is safe to reuse /// memory by "timestamping" removed items and the entry/exit of threads /// into the protected code region. /// /// Practically, a developer "protects" some region of code by marking it /// with calls to Protect() and Unprotect(). The developer must guarantee that /// no pointers to internal data structure items are retained beyond the /// Unprotect() call. Up until Unprotect(), pointers to internal items in /// a data structure may remain safe for access (see the specific data /// structures that use this class via IsSafeToReclaim() for documentation on /// what items are safe to hold pointers to within the protected region). /// /// Data structure developers must "swap" elements out of their structures /// atomically and with a sequentially consistent store operation. This ensures /// that all threads call Protect() in the future will not see the deleted item. /// Afterward, the removed item must be associated with the current Epoch /// (acquired via GetCurrentEpoch()). Data structures can use any means to /// track the association between the removed item and the Epoch it was /// removed during. Such removed elements must be retained and remain safe for /// access until IsSafeToReclaim() returns true (which indicates no threads are /// accessing or ever will access the item again). class EpochManager { public: EpochManager(); ~EpochManager(); Status Initialize(); Status Uninitialize(); /// Enter the thread into the protected code region, which guarantees /// pointer stability for records in client data structures. After this /// call, accesses to protected data structure items are guaranteed to be /// safe, even if the item is concurrently removed from the structure. /// /// Behavior is undefined if Protect() is called from an already /// protected thread. Upon creation, threads are unprotected. /// \return S_OK indicates thread may now enter the protected region. Any /// other return indicates a fatal problem accessing the thread local /// storage; the thread may not enter the protected region. Most likely /// the library has entered some non-serviceable state. Status Protect() { return epoch_table_->Protect( current_epoch_.load(std::memory_order_relaxed)); } /// Exit the thread from the protected code region. The thread must /// promise not to access pointers to elements in the protected data /// structures beyond this call. /// /// Behavior is undefined if Unprotect() is called from an already /// unprotected thread. /// \return S_OK indicates thread successfully exited protected region. Any /// other return indicates a fatal problem accessing the thread local /// storage; the thread may not have successfully exited the protected /// region. Most likely the library has entered some non-serviceable /// state. Status Unprotect() { return epoch_table_->Unprotect( current_epoch_.load(std::memory_order_relaxed)); } /// Get a snapshot of the current global Epoch. This is used by /// data structures to fetch an Epoch that is recorded along with /// a removed element. Epoch GetCurrentEpoch() { return current_epoch_.load(std::memory_order_seq_cst); } /// Returns true if an item tagged with \a epoch (which was returned by /// an earlier call to GetCurrentEpoch()) is safe to reclaim and reuse. /// If false is returned the caller then others threads may still be /// concurrently accessed the object inquired about. bool IsSafeToReclaim(Epoch epoch) { return epoch <= safe_to_reclaim_epoch_.load(std::memory_order_relaxed); } /// Returns true if the calling thread is already in the protected code /// region (i.e., have already called Protected()). bool IsProtected() { return epoch_table_->IsProtected(); } void BumpCurrentEpoch(); public: void ComputeNewSafeToReclaimEpoch(Epoch currentEpoch); /// Keeps track of which threads are executing in region protected by /// its parent EpochManager. This table does most of the work of the /// EpochManager. It allocates a slot in thread local storage. When /// threads enter the protected region for the first time it assigns /// the thread a slot in the table and stores its address in thread /// local storage. On Protect() and Unprotect() by a thread it updates /// the table entry that tracks whether the thread is currently operating /// in the protected region, and, if so, a conservative estimate of how /// early it might have entered. class MinEpochTable { public: /// Entries should be exactly cacheline sized to prevent contention /// between threads. enum { CACHELINE_SIZE = 64 }; /// Default number of entries managed by the MinEpochTable static const uint64_t kDefaultSize = 128; MinEpochTable(); Status Initialize(uint64_t size = MinEpochTable::kDefaultSize); Status Uninitialize(); Status Protect(Epoch currentEpoch); Status Unprotect(Epoch currentEpoch); Epoch ComputeNewSafeToReclaimEpoch(Epoch currentEpoch); /// An entry tracks the protected/unprotected state of a single /// thread. Threads (conservatively) the Epoch when they entered /// the protected region, and more loosely when they left. /// Threads compete for entries and atomically lock them using a /// compare-and-swap on the #m_threadId member. struct Entry { /// Construct an Entry in an unlocked and ready to use state. Entry() : protected_epoch{ 0 }, last_unprotected_epoch{ 0 }, thread_id{ 0 } { } /// Threads record a snapshot of the global epoch during Protect(). /// Threads reset this to 0 during Unprotect(). /// It is safe that this value may actually lag the real current /// epoch by the time it is actually stored. This value is set /// with a sequentially-consistent store, which guarantees that /// it precedes any pointers that were removed (with sequential /// consistency) from data structures before the thread entered /// the epoch. This is critical to ensuring that a thread entering /// a protected region can never see a pointer to a data item that /// was already "unlinked" from a protected data structure. If an /// item is "unlinked" while this field is non-zero, then the thread /// associated with this entry may be able to access the unlinked /// memory still. This is safe, because the value stored here must /// be less than the epoch value associated with the deleted item /// (by sequential consistency, the snapshot of the epoch taken /// during the removal operation must have happened before the /// snapshot taken just before this field was updated during /// Protect()), which will prevent its reuse until this (and all /// other threads that could access the item) have called /// Unprotect(). std::atomic<Epoch> protected_epoch; // 8 bytes /// Stores the approximate epoch under which the thread last /// completed an Unprotect(). This need not be very accurate; it /// is used to determine if a thread's slot can be preempted. Epoch last_unprotected_epoch; // 8 bytes /// ID of the thread associated with this entry. Entries are /// locked by threads using atomic compare-and-swap. See /// reserveEntry() for details. /// XXX(tzwang): on Linux pthread_t is 64-bit std::atomic<uint64_t> thread_id; // 8 bytes /// Ensure that each Entry is CACHELINE_SIZE. char ___padding[40]; // -- Allocation policy to ensure alignment -- /// Provides cacheline aligned allocation for the table. /// Note: We'll want to be even smarter for NUMA. We'll want to /// allocate slots that reside in socket-local DRAM to threads. void* operator new[](uint64_t count) { #ifdef WIN32 return _aligned_malloc(count, CACHELINE_SIZE); #else void *mem = nullptr; int n = posix_memalign(&mem, CACHELINE_SIZE, count); return mem; #endif } void operator delete[](void* p) { #ifdef WIN32 /// _aligned_malloc-specific delete. return _aligned_free(p); #else free(p); #endif } /// Don't allow single-entry allocations. We don't ever do them. /// No definition is provided so that programs that do single /// allocations will fail to link. void* operator new(uint64_t count); /// Don't allow single-entry deallocations. We don't ever do them. /// No definition is provided so that programs that do single /// deallocations will fail to link. void operator delete(void* p); }; static_assert(sizeof(Entry) == CACHELINE_SIZE, "Unexpected table entry size"); public: Status GetEntryForThread(Entry** entry); Entry* ReserveEntry(uint64_t startIndex, uint64_t threadId); Entry* ReserveEntryForThread(); void ReleaseEntryForThread(); void ReclaimOldEntries(); bool IsProtected(); private: #ifdef GOOGLE_FRAMEWORK FRIEND_TEST(EpochManagerTest, Protect); FRIEND_TEST(EpochManagerTest, Unprotect); FRIEND_TEST(EpochManagerTest, ComputeNewSafeToReclaimEpoch); FRIEND_TEST(MinEpochTableTest, Initialize); FRIEND_TEST(MinEpochTableTest, Uninitialize); FRIEND_TEST(MinEpochTableTest, Protect); FRIEND_TEST(MinEpochTableTest, Unprotect); FRIEND_TEST(MinEpochTableTest, ComputeNewSafeToReclaimEpoch); FRIEND_TEST(MinEpochTableTest, getEntryForThread); FRIEND_TEST(MinEpochTableTest, getEntryForThread_OneSlotFree); FRIEND_TEST(MinEpochTableTest, reserveEntryForThread); FRIEND_TEST(MinEpochTableTest, reserveEntry); #endif /// Thread protection status entries. Threads lock entries the first time /// the call Protect() (see reserveEntryForThread()). See documentation for /// the fields to specifics of how threads use their Entries to guarantee /// memory-stability. Entry* table_; /// The number of entries #m_table. Currently, this is fixed after /// Initialize() and never changes or grows. If #m_table runs out /// of entries, then the current implementation will deadlock threads. uint64_t size_; }; /// A notion of time for objects that are removed from data structures. /// Objects in data structures are timestamped with this Epoch just after /// they have been (sequentially consistently) "unlinked" from a structure. /// Threads also use this Epoch to mark their entry into a protected region /// (also in sequentially consistent way). While a thread operates in this /// region "unlinked" items that they may be accessing will not be reclaimed. std::atomic<Epoch> current_epoch_; /// Caches the most recent result of ComputeNewSafeToReclaimEpoch() so /// that fast decisions about whether an object can be reused or not /// (in IsSafeToReclaim()). Effectively, this is periodically computed /// by taking the minimum of the protected Epochs in #m_epochTable and /// #current_epoch_. std::atomic<Epoch> safe_to_reclaim_epoch_; /// Keeps track of which threads are executing in region protected by /// its parent EpochManager. On Protect() and Unprotect() by a thread it /// updates the table entry that tracks whether the thread is currently /// operating in the protected region, and, if so, a conservative estimate /// of how early it might have entered. See MinEpochTable for more details. MinEpochTable* epoch_table_; DISALLOW_COPY_AND_MOVE(EpochManager); }; /// Enters an epoch on construction and exits it on destruction. Makes it /// easy to ensure epoch protection boundaries tightly adhere to stack life /// time even with complex control flow. class EpochGuard { public: explicit EpochGuard(EpochManager* epoch_manager) : epoch_manager_{ epoch_manager }, unprotect_at_exit_(true) { epoch_manager_->Protect(); } /// Offer the option of having protext called on \a epoch_manager. /// When protect = false this implies "attach" semantics and the caller should /// have already called Protect. Behavior is undefined otherwise. explicit EpochGuard(EpochManager* epoch_manager, bool protect) : epoch_manager_{ epoch_manager }, unprotect_at_exit_(protect) { if(protect) { epoch_manager_->Protect(); } } ~EpochGuard() { if(unprotect_at_exit_ && epoch_manager_) { epoch_manager_->Unprotect(); } } /// Release the current epoch manger. It is up to the caller to manually /// Unprotect the epoch returned. Unprotect will not be called upon EpochGuard /// desruction. EpochManager* Release() { EpochManager* ret = epoch_manager_; epoch_manager_ = nullptr; return ret; } private: /// The epoch manager responsible for protect/unprotect. EpochManager* epoch_manager_; /// Whether the guard should call unprotect when going out of scope. bool unprotect_at_exit_; }; } // namespace pmwcas <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once #include <functional> #include <memory> #include "common/allocator_internal.h" namespace pmwcas { template<typename T> using unique_ptr_t = std::unique_ptr<T, std::function<void(T*)>>; template <typename T> unique_ptr_t<T> make_unique_ptr_t(T* p) { return unique_ptr_t<T> (p, [](T* t) { t->~T(); Allocator::Get()->Free(t); }); } template <typename T> unique_ptr_t<T> make_unique_ptr_aligned_t(T* p) { return unique_ptr_t<T> (p, [](T* t) { t->~T(); Allocator::Get()->FreeAligned(t); }); } /// Allocate memory without concern for alignment. template <typename T> unique_ptr_t<T> alloc_unique(size_t size) { T *ptr = nullptr; Allocator::Get()->Allocate((void **)&ptr, size); return make_unique_ptr_t<T>(ptr); } /// Allocate memory, aligned at the specified alignment. template <typename T> unique_ptr_t<T> alloc_unique_aligned(size_t size, size_t alignment) { T* ptr=nullptr; Allocator::Get()->AllocateAligned((void **)&ptr, size, alignment); return make_unique_ptr_aligned_t<T>(ptr); } template<typename T> using shared_ptr_t = std::shared_ptr<T>; } <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #include "common/allocator_internal.h" #include "util/auto_ptr.h" #include "util/macros.h" #pragma warning(disable: 4172) namespace pmwcas { unique_ptr_t<IAllocator> Allocator::allocator_; Status Allocator::Initialize(std::function<Status(IAllocator*&)> create, std::function<void(IAllocator*)> destroy) { if(allocator_.get()) { return Status::Corruption("Allocator has already been initialized."); } IAllocator* allocator; RETURN_NOT_OK(create(allocator)); allocator_ = unique_ptr_t<IAllocator>(allocator, destroy); return Status::OK(); } } // namespace pmwcas <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once #include <cstdint> #include <functional> #include <memory> #include <string> #include <thread> #include "include/status.h" #include "include/slice.h" #include "include/async.h" #include "include/allocator.h" #include "util/auto_ptr.h" #include "common/allocator_internal.h" #ifdef WIN32 #include <windows.h> #endif namespace pmwcas { /// Thread affinity used by the benchmark driver: /// * OSScheduled: let the OS schedule the threads. /// * PhysicalCoresFirst: schedule 1 thread per physical core first, then use //// hyperthread cores. /// * LogicalCoresFirst: schedule 1 thread per logical core (including /// hyperthread cores) first. /// * BalanceNumaNodes: spread threads evenly across all NUMA nodes; within /// each NUMA node, schedule physical cores first. enum AffinityPattern : int { OSScheduled = 0, PhysicalCoresFirst = 1, LogicalCoresFirst = 2, BalanceNumaNodes = 3 }; /// Interface for file wrapper on the target OS. class File { public: virtual uint64_t GetFileIdentifier() const = 0; }; /// Interface to handle async I/O on the target OS. Used to schedule reads and /// writes against a file. class AsyncIOHandler { public: typedef void(*AsyncCallback)(IAsyncContext* context, Status result, size_t bytes_transferred); virtual Status ScheduleRead(uint8_t* buffer, size_t offset, uint32_t length, AsyncIOHandler::AsyncCallback callback, IAsyncContext* context) = 0; virtual Status ScheduleWrite(uint8_t* buffer, size_t offset, uint32_t length, AsyncIOHandler::AsyncCallback callback, IAsyncContext* context) = 0; }; /// Schedling priority for threads in the ThreadPool class. enum class ThreadPoolPriority : uint8_t { Low = 0, Medium, High, Last }; /// Interface to abstract away environment/platform specific threadpool /// implementations. Used for tasks like performaing asyncronous IO, /// continuation of async operations, and scheduling tasks. class ThreadPool { public: /// Type of functions that can be scheduled for asynchronous work via /// ScheduleTask(); typedef Status(*Task)(void* arguments); virtual Status Schedule(ThreadPoolPriority priority, Task task, void* task_argument) = 0; virtual Status ScheduleTimer(ThreadPoolPriority priority, Task task, void* task_argument, uint32_t ms_period, void** timer_handle) = 0; virtual Status CreateAsyncIOHandler(ThreadPoolPriority priority, const File& file, unique_ptr_t<AsyncIOHandler>& async_io) = 0; }; /// Options for opening a file. Keep these as generic and OS agnostic as /// possible. struct FileOptions { public: FileOptions() : async{ false } , direct_io{ false } , truncate_if_exists{ false } { } bool async; bool direct_io; bool truncate_if_exists; }; /// Interface for implementing a async file capable of random read/write IOs. class RandomReadWriteAsyncFile : public File { public: RandomReadWriteAsyncFile() {} virtual ~RandomReadWriteAsyncFile(); virtual bool DirectIO() = 0; virtual size_t GetAlignment() = 0; virtual Status Open(const std::string& filename, const FileOptions& options, ThreadPool* threadpool) = 0; virtual Status Close() = 0; virtual Status Delete() = 0; typedef void (*AsyncCallback)(IAsyncContext* context, Status result, size_t bytes_transferred); virtual Status Read(size_t offset, uint32_t length, uint8_t* buffer, const IAsyncContext& context, AsyncCallback callback) = 0; virtual Status Write(size_t offset, uint32_t length, uint8_t* buffer, const IAsyncContext& context, AsyncCallback callback) = 0; unique_ptr_t<RandomReadWriteAsyncFile> make_unique_ptr_t( RandomReadWriteAsyncFile* p); }; /// Interface for producing a shared memory segment on the target OS. Used for /// mapping memory segment to NVRAM or simulated NVRAM memory. class SharedMemorySegment { public: SharedMemorySegment() {} virtual ~SharedMemorySegment(); virtual Status Initialize(const std::string& segname, uint64_t size, bool open_existing) = 0 ; virtual Status Attach(void* base_address = nullptr) = 0; virtual Status Detach() = 0; virtual void* GetMapAddress() = 0; }; /// Abstract away the OS specific calls for the library. This keeps the PMwCAS /// library OS agnostics and allows for cross/OS compilation. class IEnvironment { public: IEnvironment() {} virtual ~IEnvironment() {}; /// Returns the number of micro-seconds since some fixed point in time. Only /// useful for computing deltas of time. /// However, it is often used as system time such as in GenericRateLimiter /// and other places so a port needs to return system time in order to work. virtual uint64_t NowMicros() = 0; /// Returns the number of nano-seconds since some fixed point in time. Only /// useful for computing deltas of time in one run. /// Default implementation simply relies on NowMicros virtual uint64_t NowNanos() { return NowMicros() * 1000; } /// Return the unique id of the caller thread. uint64_t GetThreadId() { #ifdef WIN32 return GetCurrentThreadId(); #else return pthread_self(); #endif } /// Return the number of cores (plus hyperthreads, if enabled). Return value /// of 0 implies error. virtual uint32_t GetCoreCount() = 0; /// Put the caller thread to sleep for /a ms_to_sleep microseconds. virtual void Sleep(uint32_t ms_to_sleep) = 0; /// Produce a new async ready/write file for the target OS. virtual Status NewRandomReadWriteAsyncFile(const std::string& filename, const FileOptions& options, ThreadPool* threadpool, RandomReadWriteAsyncFile** file, bool* exists = nullptr) = 0; /// Create a shared memory segment for sharing among processes which can /// attach to it. Set [open_existing] to true for attaching to an existing shm /// segment, otherwise a new segment is created. virtual Status NewSharedMemorySegment(const std::string& segname, uint64_t size, bool open_existing, SharedMemorySegment** seg) = 0; /// Produce a new threadpool for the target OS. virtual Status NewThreadPool(uint32_t max_threads, ThreadPool** pool) = 0; /// Affinitize the active thread to the specified physical or logical core. virtual Status SetThreadAffinity(uint64_t core, AffinityPattern affinity_pattern) = 0; /// Return the working directory virtual Status GetWorkingDirectory(std::string& directory) = 0; /// Return the directory of where the executable resides virtual Status GetExecutableDirectory(std::string& directory) = 0; #ifdef WIN32 /// Allocate an index in thread local storage. virtual Status AllocateTlsIndex(uint32_t& index) = 0; /// Free the given \a index in thread local storage. virtual Status FreeTlsIndex(uint32_t index) = 0; /// Get the value stored in a given \a index in thread local storage. virtual Status GetTlsValue(uint32_t index, void** value) = 0; /// Set the value at a givevn \a index in thread local storage. virtual Status SetTlsValue(uint32_t index, void* value) = 0; #endif }; } //namespace pmwcas #ifdef WIN32 #include "environment/environment_windows.h" #else #include "environment/environment_linux.h" #endif <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once #include <cstdint> #include <cassert> #include <string> #ifdef GOOGLE_FRAMEWORK #include <glog/logging.h> #include <glog/raw_logging.h> #else #define DCHECK(...) ; #define RAW_CHECK(...) ; #define LOG(...) std::cout #define CHECK_EQ(...) std::cout #define LOG_ASSERT(...) ; #endif namespace pmwcas { #ifdef _DEBUG #define verify(exp) assert(exp) #else #define verify(exp) ((void)0) #endif #define MARK_UNREFERENCED(P) ((void)P) #define PREFETCH_KEY_DATA(key) _mm_prefetch(key.data(), _MM_HINT_T0) #define PREFETCH_NEXT_PAGE(delta) _mm_prefetch((char*)(delta->next_page), _MM_HINT_T0) // Returns true if \a x is a power of two. #define IS_POWER_OF_TWO(x) (x && (x & (x - 1)) == 0) // Prevents a type from being copied or moved, both by construction or by assignment. #define DISALLOW_COPY_AND_MOVE(className) \ className(const className&) = delete; \ className& operator=(const className&) = delete; \ className(className&&) = delete; \ className& operator=(className&&) = delete #ifndef ALWAYS_ASSERT #define ALWAYS_ASSERT(expr) (expr) ? (void)0 : abort() #endif } // namespace pmwcas <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once #include <cstdint> inline uint32_t Murmur3_32(uint32_t h) { h ^= h >> 16; h *= 0x85ebca6b; h ^= h >> 13; h *= 0xc2b2ae35; h ^= h >> 16; return h; } inline uint64_t Murmur3_64(uint64_t h) { h ^= h >> 33; h *= 0xff51afd7ed558ccd; h ^= h >> 33; h *= 0xc4ceb9fe1a85ec53; h ^= h >> 33; return h; } <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once #include <string> #include "include/slice.h" // Return the given status if it is not OK. #define RETURN_NOT_OK(s) do { \ ::pmwcas::Status _s = (s); \ if (!_s.ok()) return _s; \ } while (0); namespace pmwcas { class Status { public: // Create a success status. Status() : code_(kOk), state_(nullptr) { } ~Status() { delete[] state_; } // Copy the specified status. Status(const Status& s); void operator=(const Status& s); bool operator==(const Status& rhs) const; bool operator!=(const Status& rhs) const; // Return a success status. static Status OK() { return Status(); } // Return error status of an appropriate type. static Status NotFound(const Slice& msg, const Slice& msg2 = Slice()) { return Status(kNotFound, msg, msg2); } // Fast path for not found without malloc; static Status NotFound() { return Status(kNotFound); } static Status Corruption(const Slice& msg, const Slice& msg2 = Slice()) { return Status(kCorruption, msg, msg2); } static Status NotSupported(const Slice& msg, const Slice& msg2 = Slice()) { return Status(kNotSupported, msg, msg2); } static Status InvalidArgument(const Slice& msg, const Slice& msg2 = Slice()) { return Status(kInvalidArgument, msg, msg2); } static Status IOError(const Slice& msg, const Slice& msg2 = Slice()) { return Status(kIOError, msg, msg2); } static Status MergeInProgress() { return Status(kMergeInProgress); } static Status UnableToMerge() { return Status(kUnableToMerge); } static Status Incomplete(const Slice& msg, const Slice& msg2 = Slice()) { return Status(kIncomplete, msg, msg2); } static Status ShutdownInProgress() { return Status(kShutdownInProgress); } static Status ShutdownInProgress(const Slice& msg, const Slice& msg2 = Slice()) { return Status(kShutdownInProgress, msg, msg2); } static Status Aborted() { return Status(kAborted); } static Status Aborted(const Slice& msg, const Slice& msg2 = Slice()) { return Status(kAborted, msg, msg2); } static Status Busy() { return Status(kBusy); } static Status Busy(const Slice& msg, const Slice& msg2 = Slice()) { return Status(kBusy, msg, msg2); } static Status OutOfMemory() { return Status(kOutOfMemory); } static Status TimedOut() { return Status(kTimedOut); } static Status KeyAlreadyExists() { return Status(kKeyAlreadyExists); } static Status MwCASFailure() { return Status(kMwCASFailure); } // Returns true iff the status indicates success. bool ok() const { return code() == kOk; } // Returns true iff the status indicates a NotFound error. bool IsNotFound() const { return code() == kNotFound; } // Returns true iff the status indicates a Corruption error. bool IsCorruption() const { return code() == kCorruption; } // Returns true iff the status indicates a NotSupported error. bool IsNotSupported() const { return code() == kNotSupported; } // Returns true iff the status indicates an InvalidArgument error. bool IsInvalidArgument() const { return code() == kInvalidArgument; } // Returns true iff the status indicates an IOError. bool IsIOError() const { return code() == kIOError; } // Returns true iff the status indicates Incomplete bool IsIncomplete() const { return code() == kIncomplete; } // Returns true iff the status indicates Shutdown In progress bool IsShutdownInProgress() const { return code() == kShutdownInProgress; } bool IsTimedOut() const { return code() == kTimedOut; } bool IsAborted() const { return code() == kAborted; } bool IsOutOfMemory() const { return code() == kOutOfMemory; } bool IsKeyAlreadyExists() const { return code() == kKeyAlreadyExists; } // Returns true iff the status indicates that a resource is Busy and // temporarily could not be acquired. bool IsBusy() const { return code() == kBusy; } bool IsMwCASFailure() const { return code() == kMwCASFailure; } // Return a string representation of this status suitable for printing. // Returns the string "OK" for success. std::string ToString() const; enum Code { kOk = 0, kNotFound = 1, kCorruption = 2, kNotSupported = 3, kInvalidArgument = 4, kIOError = 5, kMergeInProgress = 6, kIncomplete = 7, kShutdownInProgress = 8, kTimedOut = 9, kAborted = 10, kBusy = 11, kOutOfMemory = 12, kKeyAlreadyExists = 13, kUnableToMerge = 14, kMwCASFailure = 15, }; Code code() const { return code_; } private: // A nullptr state_ (which is always the case for OK) means the message // is empty. // of the following form: // state_[0..3] == length of message // state_[4..] == message Code code_; const char* state_; explicit Status(Code _code) : code_(_code), state_(nullptr) {} Status(Code _code, const Slice& msg, const Slice& msg2); static const char* CopyState(const char* s); }; inline Status::Status(const Status& s) { code_ = s.code_; state_ = (s.state_ == nullptr) ? nullptr : CopyState(s.state_); } inline void Status::operator=(const Status& s) { // The following condition catches both aliasing (when this == &s), // and the common case where both s and *this are ok. code_ = s.code_; if(state_ != s.state_) { delete[] state_; state_ = (s.state_ == nullptr) ? nullptr : CopyState(s.state_); } } inline bool Status::operator==(const Status& rhs) const { return (code_ == rhs.code_); } inline bool Status::operator!=(const Status& rhs) const { return !(*this == rhs); } } // namespace pmwcas <file_sep># PMwCAS APIs ### Descriptor Pool * Constructor: ``` DescriptorPool(pool_size, // Number of descriptors in the pool partition_count, // Number of descriptor partitions (number of threads) desc_va, // Virtual address of a previously allocated pool enable_stats = false) // Enable various stats for PMwCAS ``` ### Descriptor operations * Add an entry to the descriptor: ``` Descriptor::AddEntry(addr, // Address of the target word oldval, // Expected value newval, // New value recycl_policy) // Memory recycling policy (detailed later) ``` * Allocate memory and add an entry with the new value being the allocated memory block's address: ``` Descriptor::AllocateAndAddEntry(addr, // Address of the target word oldval, // Expected value size, // Size of memory to allocate recycle_policy) // Memory recycling policy (detailed later) ``` AllocateAndAddEntry is especially useful for changing pointer values. * Reserve an entry in the descriptor with an empty new value: ``` int Descriptor::ReserveAndAddEntry(addr, // Address of the target word oldval, // Expected value recycle_policy) // Memory recycling policy (detailed later) ``` `ReserveAndAddEntry` returns the index into the word descriptors in the PMwCAS descriptor. The `newval` field will be left empty. The application may fill it in using `GetNewValuePtr`: ``` GetNewValuePtr(index) // index - index value returned by ReserveAndAddEntry ``` Note: Currently the application must call `GetNewValuePtr` before adding other new words as the index returned by `ReserveAndAddEntry` might change after adding other words. * Execute the PMwCAS (if `PMEM` is defined) or volatile MwCAS (if `PMEM` is undefined) operation: ``` bool Descriptor::MwCAS() ``` Returns true if the (P)MwCAS succeeded, false otherwise. * Discard the descriptor and abort the operation (applicable only before invoking `MwCAS`): ``` Descriptor::Abort() ``` ### Memory recycling policies `kRecycleOnRecovery` - Only free memory pointed to by [new_value] upon restart `kRecycleNever` - Leave the memory alone, do nothing (default) `kRecycleAlways` - Free the memory pointed to by [old/new_value] if the PMwCAS succeeded/failed `kRecycleOldOnSuccess` - Free only the memory pointed to by [old value] if the PMwCAS succeeded `kRecycleNewOnFailure` - Free only the memory pointed to by [new value] if the PMwCAS succeeded <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #include <string> #ifdef WIN32 #include <codecvt> #endif #include <mutex> #include <condition_variable> #include <gtest/gtest.h> #include <glog/logging.h> #include "util/performance_test.h" #include "util/auto_ptr.h" #include "util/random_number_generator.h" #include "include/status.h" #include "include/allocator.h" #include "include/environment.h" #include "include/pmwcas.h" #ifdef WIN32 #include "environment/environment_windows.h" #else #include "environment/environment_linux.h" #endif namespace pmwcas { class SharedMemoryTest : public ::testing::Test { public: const std::string test_segment_name = "pmwcas_shm_test"; protected: virtual void SetUp() {} }; #ifdef WIN32 class FileTest : public ::testing::Test { public: const std::string test_filename = "pmwcas_test.dat"; protected: unique_ptr_t<ThreadPool> threadpool_; unique_ptr_t<RandomReadWriteAsyncFile> file_; virtual void SetUp() { uint32_t core_count = Environment::Get()->GetCoreCount(); ThreadPool* new_pool{}; ASSERT_TRUE(Environment::Get()->NewThreadPool( static_cast<uint32_t>(core_count), &new_pool).ok()); threadpool_ = make_unique_ptr_t(new_pool); std::string filename{}; ASSERT_TRUE(Environment::Get()->GetExecutableDirectory(filename).ok()); filename.append("\\" + test_filename); FileOptions options{}; RandomReadWriteAsyncFile* new_file{}; ASSERT_TRUE(Environment::Get()->NewRandomReadWriteAsyncFile(filename, options, threadpool_.get(), &new_file).ok()); file_ = make_unique_ptr_t(new_file); } virtual void TearDown() { ASSERT_TRUE(file_->Close().ok()); ASSERT_TRUE(file_->Delete().ok()); file_.reset(nullptr); threadpool_.reset(nullptr); } }; struct TestIOContext : public IAsyncContext { HANDLE continuation_handle; FileTest* file_test_class; TestIOContext(HANDLE caller_handle, FileTest* caller_test_class) : IAsyncContext() , continuation_handle{ caller_handle } , file_test_class{ caller_test_class } { } virtual Status DeepCopy(IAsyncContext** context_copy) { if(from_deep_copy_) { *context_copy = this; return Status::OK(); } *context_copy = nullptr; unique_ptr_t<TestIOContext> io_context = alloc_unique<TestIOContext>(sizeof(TestIOContext)); if(!io_context.get()) return Status::OutOfMemory(); io_context->file_test_class = file_test_class; io_context->continuation_handle = continuation_handle; io_context->from_deep_copy_ = true; *context_copy = io_context.release(); return Status::OK(); } virtual Status DeepDelete() { if(!from_deep_copy_) { return Status::OK(); } Allocator::Get()->Free(this); return Status::OK(); } Status WaitOnAsync() { if(WAIT_FAILED == ::WaitForSingleObject(continuation_handle, INFINITE)) { return Status::Corruption("WaitForSingleObjectFailed"); } return Status::OK(); } }; static void TestIOCallback(IAsyncContext* context, Status status, size_t bytes_transferred) { unique_ptr_t<TestIOContext> io_context( reinterpret_cast<TestIOContext*>(context), [=](TestIOContext* c) { Allocator::Get()->Free(c); }); ::SetEvent(io_context->continuation_handle); } TEST_F(FileTest, Read) { size_t device_alignment = file_->GetAlignment(); uint32_t buffer_length = static_cast<uint32_t>(device_alignment); unique_ptr_t<uint8_t> aligned_buffer = alloc_unique_aligned<uint8_t>(buffer_length, device_alignment); memset(aligned_buffer.get(), 0, buffer_length); HANDLE continuation_handle = ::CreateEvent(NULL, FALSE, FALSE, NULL); unique_ptr_t<HANDLE> handle_guard(&continuation_handle, [=](HANDLE* h) { ::CloseHandle(*h); }); TestIOContext async_context(continuation_handle, this); // Unaligned buffer error ASSERT_TRUE(file_->Read(0, buffer_length, aligned_buffer.get() + 1, async_context, TestIOCallback).IsIOError()); // Invalid offset error ASSERT_TRUE(file_->Read(device_alignment / 2, buffer_length, aligned_buffer.get(), async_context, TestIOCallback).IsIOError()); // Invalid offset error ASSERT_TRUE(file_->Read(0, buffer_length / 2, aligned_buffer.get(), async_context, TestIOCallback).IsIOError()); Status s = file_->Write(0, buffer_length, aligned_buffer.get(), async_context, TestIOCallback); ASSERT_TRUE(s.ok()) << "error: " << s.ToString(); ASSERT_TRUE(async_context.WaitOnAsync().ok()); // Valid read s = file_->Read(0, buffer_length, aligned_buffer.get(), async_context, TestIOCallback); ASSERT_TRUE(s.ok()) << "error: " << s.ToString(); ASSERT_TRUE(async_context.WaitOnAsync().ok()); } TEST_F(FileTest, Write) { size_t device_alignment = file_->GetAlignment(); uint32_t buffer_length = static_cast<uint32_t>(device_alignment); unique_ptr_t<uint8_t> aligned_buffer = alloc_unique_aligned<uint8_t>(buffer_length, device_alignment); memset(aligned_buffer.get(), 0, buffer_length); HANDLE continuation_handle = ::CreateEvent(NULL, FALSE, FALSE, NULL); unique_ptr_t<HANDLE> handle_guard(&continuation_handle, [=](HANDLE* h) { ::CloseHandle(*h); }); TestIOContext async_context(continuation_handle, this); // Unaligned buffer error ASSERT_TRUE(file_->Write(0, buffer_length, aligned_buffer.get() + 1, async_context, TestIOCallback).IsIOError()); // Invalid offset error ASSERT_TRUE(file_->Write(device_alignment / 2, buffer_length, aligned_buffer.get(), async_context, TestIOCallback).IsIOError()); // Invalid offset error ASSERT_TRUE(file_->Write(0, buffer_length / 2, aligned_buffer.get(), async_context, TestIOCallback).IsIOError()); // Valid write Status s = file_->Write(0, buffer_length, aligned_buffer.get(), async_context, TestIOCallback); ASSERT_TRUE(s.ok()) << s.ToString(); ASSERT_TRUE(async_context.WaitOnAsync().ok()); } TEST_F(FileTest, DISABLED_ReadWrite) { size_t device_alignment = file_->GetAlignment(); ASSERT_TRUE(device_alignment > sizeof(uint64_t)); uint32_t buffer_length = static_cast<uint32_t>(device_alignment); unique_ptr_t<uint8_t> write_buffer = alloc_unique_aligned<uint8_t>(buffer_length, device_alignment); ASSERT_TRUE(write_buffer.get()) << "null write buffer"; memset(write_buffer.get(), 0, device_alignment); HANDLE continuation_handle = ::CreateEvent(NULL, FALSE, FALSE, NULL); unique_ptr_t<HANDLE> handle_guard(&continuation_handle, [=](HANDLE* h) { ::CloseHandle(*h); }); uint64_t num_writes = 100; bool async = false; for(uint64_t write = 0; write < num_writes; ++write) { size_t offset = write * buffer_length; memcpy_s(write_buffer.get(), buffer_length, &write, sizeof(write)); TestIOContext async_context(continuation_handle, this); ASSERT_TRUE(file_->Write(offset, buffer_length, write_buffer.get(), async_context, TestIOCallback).ok()); ASSERT_TRUE(async_context.WaitOnAsync().ok()); } unique_ptr_t<uint8_t> read_buffer = alloc_unique_aligned<uint8_t>(buffer_length, device_alignment); ASSERT_TRUE(nullptr != read_buffer.get()) << "null read buffer"; memset(read_buffer.get(), 0, device_alignment); for(uint64_t read = 0; read < num_writes; ++read) { size_t offset = read * buffer_length; memset(read_buffer.get(), 0, buffer_length); TestIOContext async_context(continuation_handle, this); ASSERT_TRUE(file_->Read(offset, buffer_length, read_buffer.get(), async_context, TestIOCallback).ok()); ASSERT_TRUE(async_context.WaitOnAsync().ok()); uint64_t read_value = *reinterpret_cast<uint64_t*>(read_buffer.get()); ASSERT_EQ(read_value, read); } } class ThreadpoolTest : public ::testing::Test { protected: unique_ptr_t<ThreadPool> threadpool_; virtual void SetUp() { uint32_t core_count = Environment::Get()->GetCoreCount(); ThreadPool* new_pool{}; ASSERT_TRUE(Environment::Get()->NewThreadPool( static_cast<uint32_t>(core_count), &new_pool).ok()); threadpool_ = make_unique_ptr_t(new_pool); } virtual void TearDown() { threadpool_.reset(); } }; struct TestThreadpoolContext { TestThreadpoolContext(HANDLE caller_handle, uint64_t* caller_count) : continuation_handle{ caller_handle } , count{ caller_count } { } Status WaitOnAsync() { if(WAIT_FAILED == ::WaitForSingleObject(continuation_handle, INFINITE)) { return Status::Corruption("WaitForSingleObject failed"); } return Status::OK(); } HANDLE continuation_handle; uint64_t* count; }; static Status TestThreadpoolTask(void* context) { // No need to free the context, it is assumed to be stack-allocated within the // test harness TestThreadpoolContext* tp_context = reinterpret_cast<TestThreadpoolContext*>(context); ++*tp_context->count; ::SetEvent(tp_context->continuation_handle); return Status::OK(); } TEST_F(ThreadpoolTest, DISABLED_Schedule) { uint64_t schedule_count = 128; uint64_t schedules_completed = 0; RandomNumberGenerator rng{}; HANDLE continuation_handle = ::CreateEvent(NULL, FALSE, FALSE, NULL); unique_ptr_t<HANDLE> handle_guard(&continuation_handle, [=](HANDLE* h) { ::CloseHandle(*h); }); for(int i = 0; i < schedule_count; ++i) { TestThreadpoolContext context(continuation_handle, &schedules_completed); uint8_t priority = narrow<uint8_t>(rng.Generate((uint32_t)ThreadPoolPriority::High)); ASSERT_TRUE(threadpool_->Schedule(ThreadPoolPriority(priority), TestThreadpoolTask, reinterpret_cast<void*>(&context)).ok()); ASSERT_TRUE(context.WaitOnAsync().ok()); } ASSERT_EQ(schedule_count, schedules_completed); } #endif TEST_F(SharedMemoryTest, AttachDetach) { SharedMemorySegment* new_seg = nullptr; SharedMemorySegment* existing_seg = nullptr; ASSERT_TRUE(Environment::Get()->NewSharedMemorySegment(test_segment_name, 256, false, &new_seg).ok()); ASSERT_NE(nullptr, new_seg); ASSERT_TRUE(new_seg->Attach(nullptr).ok()); void* new_mem = new_seg->GetMapAddress(); memcpy(new_mem, test_segment_name.c_str(), 10); ASSERT_TRUE(Environment::Get()->NewSharedMemorySegment(test_segment_name, 256, true, &existing_seg).ok()); ASSERT_NE(nullptr, existing_seg); ASSERT_TRUE(existing_seg->Attach(nullptr).ok()); void* existing_mem = existing_seg->GetMapAddress(); for(int i = 0; i < 10; i++) { ASSERT_EQ(test_segment_name.c_str()[i], ((char*)existing_mem)[i]); } ASSERT_TRUE(new_seg->Detach().ok()); ASSERT_TRUE(existing_seg->Detach().ok()); } } // namespace pmwcas int main(int argc, char** argv) { google::InitGoogleLogging(argv[0]); ::testing::InitGoogleTest(&argc, argv); #ifdef WIN32 pmwcas::InitLibrary(pmwcas::DefaultAllocator::Create, pmwcas::DefaultAllocator::Destroy, pmwcas::WindowsEnvironment::Create, pmwcas::WindowsEnvironment::Destroy); #else pmwcas::InitLibrary(pmwcas::TlsAllocator::Create, pmwcas::TlsAllocator::Destroy, pmwcas::LinuxEnvironment::Create, pmwcas::LinuxEnvironment::Destroy); #endif return RUN_ALL_TESTS(); } <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #include <memory> #include <thread> #include <random> #include <gtest/gtest.h> #include "include/pmwcas.h" #include "include/status.h" #include "include/allocator.h" #include "util/hash.h" #include "common/epoch.h" #ifdef WIN32 #include "environment/environment_windows.h" #else #include "environment/environment_linux.h" #endif namespace pmwcas { class EpochManagerTest : public ::testing::Test { public: EpochManagerTest() {} protected: EpochManager mgr_; virtual void SetUp() { mgr_.Initialize(); } virtual void TearDown() { mgr_.Uninitialize(); Thread::ClearRegistry(true); } }; TEST_F(EpochManagerTest, Initialize) { // Initialize() called by the unit test framework. ASSERT_EQ(Status::OK(), mgr_.Initialize()); EXPECT_EQ(1llu, mgr_.current_epoch_.load()); EXPECT_EQ(0llu, mgr_.safe_to_reclaim_epoch_.load()); // At least make sure table initializer was called. ASSERT_NE(nullptr, mgr_.epoch_table_); } TEST_F(EpochManagerTest, Uninitialize) { EXPECT_TRUE(mgr_.Uninitialize().ok()); EpochManager default_mgr; ASSERT_TRUE(default_mgr.epoch_table_ == mgr_.epoch_table_); EXPECT_EQ(nullptr, mgr_.epoch_table_); EXPECT_EQ(default_mgr.current_epoch_.load(), mgr_.current_epoch_.load()); EXPECT_EQ(default_mgr.safe_to_reclaim_epoch_.load(), mgr_.safe_to_reclaim_epoch_.load()); EXPECT_TRUE(mgr_.Uninitialize().ok()); } TEST_F(EpochManagerTest, Protect) { mgr_.BumpCurrentEpoch(); EXPECT_TRUE(mgr_.Protect().ok()); // Make sure the table is clear except the one new entry. auto* table = mgr_.epoch_table_->table_; for(uint64_t i = 0; i < mgr_.epoch_table_->size_; ++i) { const auto& entry = table[i]; if(entry.thread_id != 0) { EXPECT_EQ(Environment::Get()->GetThreadId(), entry.thread_id.load()); EXPECT_EQ(2llu, entry.protected_epoch.load()); EXPECT_EQ(0llu, entry.last_unprotected_epoch); return; } EXPECT_EQ(0lu, entry.thread_id.load()); EXPECT_EQ(0llu, entry.protected_epoch.load()); EXPECT_EQ(0llu, entry.last_unprotected_epoch); } } TEST_F(EpochManagerTest, Unprotect) { mgr_.BumpCurrentEpoch(); EXPECT_TRUE(mgr_.Protect().ok()); mgr_.BumpCurrentEpoch(); EXPECT_TRUE(mgr_.Unprotect().ok()); #ifdef WIN32 // Make sure the table is clear except the one new entry. auto* table = mgr_.epoch_table_->table_; for(size_t i = 0; i < mgr_.epoch_table_->size_; ++i) { const auto& entry = table[i]; if(entry.thread_id != 0) { EXPECT_EQ(Environment::Get()->GetThreadId(), (DWORD)entry.thread_id.load()); EXPECT_EQ(0llu, entry.protected_epoch.load()); EXPECT_EQ(3llu, entry.last_unprotected_epoch); return; } EXPECT_EQ(0lu, (DWORD)entry.thread_id.load()); EXPECT_EQ(0llu, entry.protected_epoch.load()); EXPECT_EQ(0llu, entry.last_unprotected_epoch); } #endif } TEST_F(EpochManagerTest, BumpCurrentEpoch) { EXPECT_EQ(1llu, mgr_.GetCurrentEpoch()); mgr_.BumpCurrentEpoch(); EXPECT_EQ(2llu, mgr_.GetCurrentEpoch()); } TEST_F(EpochManagerTest, ComputeNewSafeToReclaimEpoch) { mgr_.epoch_table_->table_[0].protected_epoch = 98; mgr_.current_epoch_ = 99; mgr_.ComputeNewSafeToReclaimEpoch(99); EXPECT_EQ(97llu, mgr_.safe_to_reclaim_epoch_.load()); mgr_.epoch_table_->table_[0].protected_epoch = 0; EXPECT_EQ(97llu, mgr_.safe_to_reclaim_epoch_.load()); mgr_.ComputeNewSafeToReclaimEpoch(99); EXPECT_EQ(98llu, mgr_.safe_to_reclaim_epoch_.load()); } TEST_F(EpochManagerTest, DISABLED_Smoke) { // TODO (justin): port performance test to environment and re-enable. } class MinEpochTableTest : public ::testing::Test { public: MinEpochTableTest() {} protected: typedef EpochManager::MinEpochTable MinEpochTable; MinEpochTable table_; virtual void SetUp() { table_.Initialize(); } virtual void TearDown() { table_.Uninitialize(); Thread::ClearRegistry(true); } }; TEST_F(MinEpochTableTest, Initialize) { EXPECT_NE(nullptr, table_.table_); EXPECT_TRUE(table_.Initialize().ok()); } TEST_F(MinEpochTableTest, Initialize_SizeNotAPowerOfTwo) { EXPECT_TRUE(table_.Uninitialize().ok()); Status s = table_.Initialize(3lu); EXPECT_TRUE(s.IsInvalidArgument()); } TEST_F(MinEpochTableTest, Uninitialize) { EXPECT_TRUE(table_.Uninitialize().ok()); EXPECT_EQ(0llu, table_.size_); EXPECT_EQ(nullptr, table_.table_); EXPECT_TRUE(table_.Uninitialize().ok()); } TEST_F(MinEpochTableTest, Protect) { EXPECT_TRUE(table_.Protect(99).ok()); size_t entry_slot = Murmur3_64(Environment::Get()->GetThreadId()) % table_.size_; // Make sure the slot got reserved. const MinEpochTable::Entry& entry = table_.table_[entry_slot]; EXPECT_EQ(Environment::Get()->GetThreadId(), entry.thread_id.load()); EXPECT_EQ(99llu, entry.protected_epoch.load()); EXPECT_EQ(0llu, entry.last_unprotected_epoch); // Make sure none of the other slots got touched. for(uint64_t i = 0; i < table_.size_; ++i) { const MinEpochTable::Entry& local_entry = table_.table_[i]; if(entry_slot == i) continue; EXPECT_EQ(0lu, local_entry.thread_id.load()); EXPECT_EQ(0llu, local_entry.protected_epoch.load()); EXPECT_EQ(0llu, local_entry.last_unprotected_epoch); } } TEST_F(MinEpochTableTest, Unprotect) { EXPECT_TRUE(table_.Protect(99).ok()); EXPECT_TRUE(table_.Unprotect(101).ok()); uint64_t entrySlot = Murmur3_64(Environment::Get()->GetThreadId()) % table_.size_; // Make sure the slot got released and timestamped and that // the thread still has the slot locked with it's id still there. const MinEpochTable::Entry& entry = table_.table_[entrySlot]; EXPECT_EQ(Environment::Get()->GetThreadId(), entry.thread_id.load()); EXPECT_EQ(0llu, entry.protected_epoch.load()); EXPECT_EQ(101llu, entry.last_unprotected_epoch); // Make sure none of the other slots got touched. for(uint64_t i = 0; i < table_.size_; ++i) { const MinEpochTable::Entry& local_entry = table_.table_[i]; if(entrySlot == i) continue; EXPECT_EQ(0lu, local_entry.thread_id.load()); EXPECT_EQ(0llu, local_entry.protected_epoch.load()); EXPECT_EQ(0llu, local_entry.last_unprotected_epoch); } } TEST_F(MinEpochTableTest, ComputeNewSafeToReclaimEpoch) { EXPECT_EQ(99llu, table_.ComputeNewSafeToReclaimEpoch(100)); table_.table_[0].protected_epoch = 1; EXPECT_EQ(0llu, table_.ComputeNewSafeToReclaimEpoch(100)); table_.table_[1].protected_epoch = 100; EXPECT_EQ(0llu, table_.ComputeNewSafeToReclaimEpoch(100)); table_.table_[0].protected_epoch = 0; EXPECT_EQ(99llu, table_.ComputeNewSafeToReclaimEpoch(101)); table_.table_[table_.size_ - 1].protected_epoch = 98; EXPECT_EQ(97llu, table_.ComputeNewSafeToReclaimEpoch(101)); table_.table_[0].protected_epoch = 0; table_.table_[1].protected_epoch = 0; std::random_device rd; std::default_random_engine engine(rd()); std::uniform_int_distribution<Epoch> dist(1, 1000); std::vector<Epoch> epochs; for(uint64_t i = 0; i < table_.size_; ++i) { epochs.emplace_back(dist(engine)); table_.table_[i].protected_epoch = epochs.back(); } EXPECT_EQ( *std::min_element(epochs.begin(), epochs.end()) - 1, table_.ComputeNewSafeToReclaimEpoch(1001)); } TEST_F(MinEpochTableTest, getEntryForThread) { // Make sure the table is clear. for(uint64_t i = 0; i < table_.size_; ++i) { EXPECT_EQ(0lu, table_.table_[i].thread_id.load()); EXPECT_EQ(0llu, table_.table_[i].protected_epoch.load()); EXPECT_EQ(0llu, table_.table_[i].last_unprotected_epoch); } MinEpochTable::Entry* entry = nullptr; EXPECT_TRUE(table_.GetEntryForThread(&entry).ok()); EXPECT_NE(nullptr, entry); // Make sure the table is clear except the one new entry. for(uint64_t i = 0; i < table_.size_; ++i) { if(entry == &table_.table_[i]) continue; EXPECT_EQ(0lu, table_.table_[i].thread_id.load()); EXPECT_EQ(0llu, table_.table_[i].protected_epoch.load()); EXPECT_EQ(0llu, table_.table_[i].last_unprotected_epoch); } EXPECT_EQ(Environment::Get()->GetThreadId(), entry->thread_id.load()); EXPECT_EQ(0llu, entry->protected_epoch.load()); EXPECT_EQ(0llu, entry->last_unprotected_epoch); } TEST_F(MinEpochTableTest, getEntryForThread_OneSlotFree) { for(uint64_t i = 0; i < table_.size_ - 1; ++i) table_.ReserveEntry(i, 1); MinEpochTable::Entry* entry = nullptr; EXPECT_TRUE(table_.GetEntryForThread(&entry).ok()); EXPECT_NE(nullptr, entry); EXPECT_EQ(entry, &table_.table_[table_.size_ - 1]); EXPECT_EQ(Environment::Get()->GetThreadId(), entry->thread_id.load()); EXPECT_EQ(0llu, entry->protected_epoch.load()); EXPECT_EQ(0llu, entry->last_unprotected_epoch); } TEST_F(MinEpochTableTest, reserveEntryForThread) { for(uint64_t i = 0; i < table_.size_; ++i) { EXPECT_EQ(0lu, table_.table_[i].thread_id.load()); EXPECT_EQ(0llu, table_.table_[i].protected_epoch.load()); EXPECT_EQ(0llu, table_.table_[i].last_unprotected_epoch); } MinEpochTable::Entry* entry = table_.ReserveEntryForThread(); EXPECT_NE(nullptr, entry); // Make sure the table is clear except the one new entry. for(uint64_t i = 0; i < table_.size_; ++i) { if(entry == &table_.table_[i]) continue; EXPECT_EQ(0lu, table_.table_[i].thread_id.load()); EXPECT_EQ(0llu, table_.table_[i].protected_epoch.load()); EXPECT_EQ(0llu, table_.table_[i].last_unprotected_epoch); } EXPECT_EQ(Environment::Get()->GetThreadId(), entry->thread_id.load()); EXPECT_EQ(0llu, entry->protected_epoch.load()); EXPECT_EQ(0llu, entry->last_unprotected_epoch); } TEST_F(MinEpochTableTest, reserveEntry) { EXPECT_EQ(0u, table_.table_[0].thread_id.load()); table_.ReserveEntry(0, 1); EXPECT_EQ(1u, table_.table_[0].thread_id.load()); table_.ReserveEntry(0, 2); EXPECT_EQ(1u, table_.table_[0].thread_id.load()); EXPECT_EQ(2u, table_.table_[1].thread_id.load()); table_.ReserveEntry(table_.size_ - 1, 3); EXPECT_EQ(3u, table_.table_[table_.size_ - 1].thread_id.load()); table_.ReserveEntry(table_.size_ - 1, 4); EXPECT_EQ(4u, table_.table_[2].thread_id.load()); } } // namespace pmwcas int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); #ifdef WIN32 pmwcas::InitLibrary(pmwcas::DefaultAllocator::Create, pmwcas::DefaultAllocator::Destroy, pmwcas::WindowsEnvironment::Create, pmwcas::WindowsEnvironment::Destroy); #else pmwcas::InitLibrary(pmwcas::TlsAllocator::Create, pmwcas::TlsAllocator::Destroy, pmwcas::LinuxEnvironment::Create, pmwcas::LinuxEnvironment::Destroy); #endif return RUN_ALL_TESTS(); } <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #define NOMINMAX #define GLOG_NO_ABBREVIATED_SEVERITIES #include <Windows.h> #undef ERROR // Avoid collision of ERROR definition in Windows.h with glog #include <Shlwapi.h> #include <tchar.h> #include <chrono> #include <vector> #include <string> #include <iomanip> #include <ios> #include <glog/logging.h> #include "common/allocator_internal.h" #include "environment/environment_windows.h" #include "util/auto_ptr.h" #include "util/macros.h" #include <glog/logging.h> namespace pmwcas { std::string FormatWin32AndHRESULT(DWORD win32_result) { std::stringstream ss; ss << "Win32(" << win32_result << ") HRESULT(" << std::showbase << std::uppercase << std::setfill('0') << std::hex << HRESULT_FROM_WIN32(win32_result) << ")"; return ss.str(); } WindowsEnvironment::WindowsEnvironment() : perf_counter_frequency_{} { LARGE_INTEGER qpf; BOOL ret = QueryPerformanceFrequency(&qpf); DCHECK(ret); perf_counter_frequency_ = qpf.QuadPart; ::GetSystemInfo(&sys_info_); } uint64_t WindowsEnvironment::NowMicros() { // all std::chrono clocks on windows proved to return // values that may repeat that is not good enough for some uses. const int64_t c_UnixEpochStartTicks = 116444736000000000i64; const int64_t c_FtToMicroSec = 10; // This interface needs to return system time and not // just any microseconds because it is often used as an argument // to TimedWait() on condition variable FILETIME ftSystemTime; GetSystemTimePreciseAsFileTime(&ftSystemTime); LARGE_INTEGER li; li.LowPart = ftSystemTime.dwLowDateTime; li.HighPart = ftSystemTime.dwHighDateTime; // Subtract unix epoch start li.QuadPart -= c_UnixEpochStartTicks; // Convert to microsecs li.QuadPart /= c_FtToMicroSec; return li.QuadPart; } uint64_t WindowsEnvironment::NowNanos() { // all std::chrono clocks on windows have the same resolution that is only // good enough for microseconds but not nanoseconds // On Windows 8 and Windows 2012 Server // GetSystemTimePreciseAsFileTime(&current_time) can be used LARGE_INTEGER li; QueryPerformanceCounter(&li); // Convert to nanoseconds first to avoid loss of precision // and divide by frequency li.QuadPart *= std::nano::den; li.QuadPart /= perf_counter_frequency_; return li.QuadPart; } typedef BOOL(WINAPI* LPFN_GLPI)( PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD); /// Counts the number of set bits in a mask. Helper function for GetCoreCount. static size_t CountSetBits(ULONG_PTR bitMask) { DWORD LSHIFT = sizeof(ULONG_PTR) * 8 - 1; size_t bitSetCount = 0; ULONG_PTR bitTest = (ULONG_PTR)1 << LSHIFT; DWORD i; for(i = 0; i <= LSHIFT; ++i) { bitSetCount += ((bitMask & bitTest) ? 1 : 0); bitTest /= 2; } return bitSetCount; } /// Returns the core count on the test machine uint32_t WindowsEnvironment::GetCoreCount() { LPFN_GLPI glpi; BOOL done = FALSE; PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer = NULL; PSYSTEM_LOGICAL_PROCESSOR_INFORMATION ptr = NULL; DWORD returnLength = 0; DWORD byteOffset = 0; glpi = (LPFN_GLPI)::GetProcAddress(GetModuleHandle(TEXT("kernel32")), "GetLogicalProcessorInformation"); if(!glpi) { return 0; } while(!done) { DWORD rc = glpi(buffer, &returnLength); if(FALSE == rc) { if(GetLastError() == ERROR_INSUFFICIENT_BUFFER) { if(buffer) { free(buffer); } buffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)malloc( returnLength); if(NULL == buffer) { return 0; } } else { return 0; } } else { done = TRUE; } } uint32_t count = 0; ptr = buffer; while(byteOffset + sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION) <= returnLength) { switch(ptr->Relationship) { case RelationProcessorCore: // A hyperthreaded core supplies more than one logical processor. count += CountSetBits(ptr->ProcessorMask); break; default: break; } byteOffset += sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); ptr++; } free(buffer); return count; } void WindowsEnvironment::Sleep(uint32_t ms_to_sleep) { ::Sleep(ms_to_sleep); } Status WindowsEnvironment::NewRandomReadWriteAsyncFile( const std::string& filename, const FileOptions& options, ThreadPool* threadpool, RandomReadWriteAsyncFile** file, bool* exists) { if(exists) { *exists = PathFileExists(filename.c_str()); } *file = nullptr; unique_ptr_t<RandomReadWriteAsyncFile> alloc_guard; RETURN_NOT_OK(WindowsRandomReadRandomWriteFile::Create(alloc_guard)); RETURN_NOT_OK(alloc_guard->Open(filename, options, threadpool)); *file = alloc_guard.release(); return Status::OK(); } Status WindowsEnvironment::NewSharedMemorySegment(const std::string& segname, uint64_t size, bool open_existing, SharedMemorySegment** seg) { *seg = nullptr; unique_ptr_t<SharedMemorySegment> alloc_guard; RETURN_NOT_OK(WindowsSharedMemorySegment::Create(alloc_guard)); RETURN_NOT_OK(alloc_guard->Initialize(segname, size, open_existing)); *seg = alloc_guard.release(); return Status::OK(); } Status WindowsEnvironment::NewThreadPool(uint32_t max_threads, ThreadPool** pool) { *pool = nullptr; unique_ptr_t<ThreadPool> pool_guard; RETURN_NOT_OK(WindowsPtpThreadPool::Create(max_threads, pool_guard)); *pool = pool_guard.release(); return Status::OK(); } Status WindowsEnvironment::GetWorkingDirectory(std::string& directory) { DWORD result = ::GetCurrentDirectory(0, _T("")); if(result == 0) { return Status::IOError("error in GetCurrentDirectory", std::to_string(HRESULT_FROM_WIN32(::GetLastError()))); } // Allocate temporary buffer. The retured length includes the // terminating _T('\0'). td::vector is guaranteed to be sequential, // thus can serve as a buffer that can be written to. std::vector<TCHAR> currentDirectory(result); // If the buffer is large enough, the return value does _not_ include // the terminating _T('\0') result = ::GetCurrentDirectory(static_cast<DWORD>(currentDirectory.size()), &currentDirectory[0]); if((result == 0) || (result > currentDirectory.size())) { return Status::IOError("error in GetCurrentDirectory", std::to_string(HRESULT_FROM_WIN32(::GetLastError()))); } std::wstring wdirectory(currentDirectory.begin(), currentDirectory.begin() + static_cast<std::size_t>(result)); directory = std::string(wdirectory.begin(), wdirectory.end()); return Status::OK(); } Status WindowsEnvironment::GetExecutableDirectory(std::string& directory) { std::vector<TCHAR> currentDirectory(MAX_PATH); DWORD result = ::GetModuleFileName(NULL, &currentDirectory[0], MAX_PATH); if((0 == result) || (result > currentDirectory.size())) { return Status::IOError("error in GetExecutableDirectory", FormatWin32AndHRESULT(result)); } PathRemoveFileSpec(&currentDirectory[0]); size_t str_length = _tcslen(&currentDirectory[0]) / sizeof(TCHAR); std::wstring wdirectory(currentDirectory.begin(), currentDirectory.begin() + static_cast<std::size_t>(str_length)); directory = std::string(wdirectory.begin(), wdirectory.end()); return Status::OK(); } Status WindowsEnvironment::SetThreadAffinity(uint64_t core, AffinityPattern affinity_pattern) { HANDLE thread_handle = ::GetCurrentThread(); return SetThreadAffinity(thread_handle, core, affinity_pattern); } Status WindowsEnvironment::SetThreadAffinity(HANDLE thread, uint64_t core, AffinityPattern affinity_pattern) { if(affinity_pattern == AffinityPattern::PhysicalCoresFirst) { // Recalculate "core" so that all physical cores are scheduled, 1 thread per // each, before we schedule any hyperthread cores. if(core >= sys_info_.dwNumberOfProcessors) { return Status::Aborted("Too few logical cores.", std::to_string(sys_info_.dwNumberOfProcessors)); } // Assume 2 logical cores per physical core. if(sys_info_.dwNumberOfProcessors % 2 != 0) { return Status::Aborted("Not an even number of logical cores.", std::to_string(sys_info_.dwNumberOfProcessors)); } uint32_t physical_core_count = sys_info_.dwNumberOfProcessors / 2; if(core < physical_core_count) { core = core * 2; } else { core = (core - physical_core_count) * 2 + 1; } } else if(affinity_pattern == AffinityPattern::BalanceNumaNodes) { // For now, assume that we're running on a 4-node NUMA system, where the // cores are numbered with the first n cores on node 0, the next n cores on // node 1, ... and the last n cores on node 3. const uint32_t numa_node_count = 4; CHECK_EQ(sys_info_.dwNumberOfProcessors % numa_node_count, 0) << "Unexpected system configuration!"; uint32_t logical_core_count = sys_info_.dwNumberOfProcessors / numa_node_count; // Assume 2 logical cores per physical core. CHECK_EQ(logical_core_count % 2, 0) << "Unexpected system configuration!"; uint32_t physical_core_count = logical_core_count / 2; uint32_t numa_node = core % numa_node_count; uint32_t numa_core = core / numa_node_count; if(numa_core < physical_core_count) { numa_core = numa_core * 2; } else { numa_core = (numa_core - physical_core_count) * 2 + 1; } core = (numa_node * logical_core_count) + numa_core; } DWORD_PTR result = ::SetThreadAffinityMask(thread, (uint64_t)0x1 << core); if(result == 0) { DWORD error = ::GetLastError(); return Status::Aborted("Failed to set thread affinity.", FormatWin32AndHRESULT(result)); } else { return Status::OK(); } } Status WindowsEnvironment::AllocateTlsIndex(uint32_t& index) { index = uint32_t{}; uint32_t new_index = ::TlsAlloc(); if(TLS_OUT_OF_INDEXES == new_index) { return Status::Aborted("No TLS indexes available", FormatWin32AndHRESULT(::GetLastError())); } index = new_index; return Status::OK(); } Status WindowsEnvironment::FreeTlsIndex(uint32_t index) { BOOL ok = ::TlsFree(index); if(0 == ok) { return Status::Aborted("TlsFree error.", FormatWin32AndHRESULT(::GetLastError())); } return Status::OK(); } Status WindowsEnvironment::GetTlsValue(uint32_t index, void** value) { *value = ::TlsGetValue(index); if(*value == 0) { DWORD error = ::GetLastError(); if(ERROR_SUCCESS != error) { return Status::Aborted("TlsGetValue error", FormatWin32AndHRESULT(error)); } } return Status::OK(); } Status WindowsEnvironment::SetTlsValue(uint32_t index, void* value) { BOOL ok = ::TlsSetValue(index, value); if(0 == ok) { return Status::Aborted("TlsSetValue error.", FormatWin32AndHRESULT(::GetLastError())); } return Status::OK(); } WindowsRandomReadRandomWriteFile::WindowsRandomReadRandomWriteFile() : RandomReadWriteAsyncFile() , direct_io_{ false } , file_handle_ { INVALID_HANDLE_VALUE } , map_handle_ { INVALID_HANDLE_VALUE } , map_address_ { nullptr } , device_alignment_{} , filename_{} , threadpool_{} { } WindowsRandomReadRandomWriteFile::~WindowsRandomReadRandomWriteFile() { Status s = Close(); ALWAYS_ASSERT(s.ok()); } RandomReadWriteAsyncFile::~RandomReadWriteAsyncFile() { } Status WindowsRandomReadRandomWriteFile::Create( unique_ptr_t<RandomReadWriteAsyncFile>& file) { file.reset(); file = alloc_unique<RandomReadWriteAsyncFile>( sizeof(WindowsRandomReadRandomWriteFile)); if(!file.get()) return Status::OutOfMemory(); new(file.get())WindowsRandomReadRandomWriteFile(); return Status::OK(); } uint64_t WindowsRandomReadRandomWriteFile::GetFileIdentifier() const { return reinterpret_cast<uint64_t>(file_handle_); } bool WindowsRandomReadRandomWriteFile::DirectIO() { return direct_io_; } size_t WindowsRandomReadRandomWriteFile::GetAlignment() { return device_alignment_; } Status WindowsRandomReadRandomWriteFile::Open(const std::string& filename, const FileOptions& options, ThreadPool* threadpool) { MARK_UNREFERENCED(options); DWORD desired_access = GENERIC_READ | GENERIC_WRITE; DWORD const flags = FILE_FLAG_RANDOM_ACCESS | FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING; DWORD create_disposition = options.truncate_if_exists ? CREATE_ALWAYS : OPEN_ALWAYS; DWORD shared_mode = 0; LPSECURITY_ATTRIBUTES const security = NULL; file_handle_ = ::CreateFileA(filename.c_str(), desired_access, shared_mode, security, create_disposition, flags, NULL); if(INVALID_HANDLE_VALUE == file_handle_) { auto error = ::GetLastError(); return Status::IOError("Failed to create random read random write " "file: " + filename, FormatWin32AndHRESULT(error)); } unique_ptr_t<HANDLE> handle_guard = unique_ptr_t<HANDLE> (&file_handle_, [=](HANDLE* h) { ::CloseHandle(*h); *h = INVALID_HANDLE_VALUE; }); RETURN_NOT_OK(GetDeviceAlignment(filename, device_alignment_)); RETURN_NOT_OK(threadpool->CreateAsyncIOHandler(ThreadPoolPriority::Low, *this, async_io_handler_)); filename_ = filename; threadpool_ = threadpool; handle_guard.release(); LOG(INFO) << "Opened file: " << filename; return Status::OK(); } Status WindowsRandomReadRandomWriteFile::Close() { if(INVALID_HANDLE_VALUE != file_handle_) { BOOL ret = ::CloseHandle(file_handle_); file_handle_ = INVALID_HANDLE_VALUE; if(!ret) { auto error = ::GetLastError(); return Status::IOError( "Error closing file: " + FormatWin32AndHRESULT(error)); } } return Status(); } Status pmwcas::WindowsRandomReadRandomWriteFile::Delete() { BOOL ret = ::DeleteFileA(filename_.c_str()); if(!ret) { auto error = ::GetLastError(); LOG(ERROR) << "Failed to delete file: " << filename_ << ": (" << FormatWin32AndHRESULT(error); return Status::IOError("Failed to delete file( " + filename_ + "): " + FormatWin32AndHRESULT(error)); } return Status::OK(); } void WindowsRandomReadRandomWriteFile::BlockingCallback(IAsyncContext* context, Status status, size_t transfer_size) { MARK_UNREFERENCED(transfer_size); BlockingIOContext* blocking_context = reinterpret_cast<BlockingIOContext*>( context); unique_ptr_t<BlockingIOContext> context_guard(blocking_context, [=](BlockingIOContext* c) { Allocator::Get()->Free(c); }); if(!status.ok()) { LOG(ERROR) << "Blocking IO error: %s\n", status.ToString().c_str(); } ::SetEvent(context_guard->continuation_handle); } void WindowsRandomReadRandomWriteFile::AsyncReadCallback(IAsyncContext* context, Status status, size_t transfer_size) { unique_ptr_t<AsyncIOContext> io_context( reinterpret_cast<AsyncIOContext*>(context), [](AsyncIOContext* c) { Allocator::Get()->Free(c); }); if(transfer_size != io_context->bytes_to_transfer) { LOG(ERROR) << "Async read error size transfer and request mismatch (transfer: " << transfer_size << " request: " << io_context->bytes_to_transfer << ")"; } io_context->callback(io_context->context, status, transfer_size); } Status WindowsRandomReadRandomWriteFile::Read(size_t offset, uint32_t length, uint8_t* buffer, const IAsyncContext& context, RandomReadWriteAsyncFile::AsyncCallback callback) { if((uintptr_t(buffer) & (device_alignment_ - 1)) > 0) { return Status::IOError("IO Buffer not aligned to device alignment :" + std::to_string(device_alignment_)); } else if((offset & (device_alignment_ - 1)) > 0) { return Status::IOError("IO offset not aligned to device alignment :" + std::to_string(device_alignment_)); } else if((length & (device_alignment_ - 1)) > 0) { return Status::IOError("Length not aligned to device alignment :" + std::to_string(device_alignment_)); } AsyncIOContext async_context{ const_cast<IAsyncContext*>(&context), callback, buffer, length, this }; RETURN_NOT_OK(async_io_handler_->ScheduleRead(buffer, offset, length, AsyncReadCallback, reinterpret_cast<IAsyncContext*>(&async_context))); return Status::OK(); } void WindowsRandomReadRandomWriteFile::AsyncWriteCallback( IAsyncContext* context, Status status, size_t transfer_size) { AsyncIOContext* raw_context = reinterpret_cast<AsyncIOContext*>(context); unique_ptr_t<AsyncIOContext> io_context(raw_context, [=](AsyncIOContext* c) { Allocator::Get()->Free(c); }); if(transfer_size != io_context->bytes_to_transfer) { LOG(ERROR) << "Async read error size transfer and request mismatch (transfer: " << transfer_size << " request: " << io_context->bytes_to_transfer << ")"; } io_context->callback(io_context->context, status, transfer_size); } Status WindowsRandomReadRandomWriteFile::Write(size_t offset, uint32_t length, uint8_t* buffer, const IAsyncContext& context, RandomReadWriteAsyncFile::AsyncCallback callback) { if((uintptr_t(buffer) & (device_alignment_ - 1)) > 0) { return Status::IOError("IO Buffer not aligned to device alignment :" + std::to_string(device_alignment_)); } else if((offset & (device_alignment_ - 1)) > 0) { return Status::IOError("IO offset not aligned to device alignment :" + std::to_string(device_alignment_)); } else if((length & (device_alignment_ - 1)) > 0) { return Status::IOError("Length not aligned to device alignment :" + std::to_string(device_alignment_)); } AsyncIOContext async_context{ const_cast<IAsyncContext*>(&context), callback, buffer, length, this }; RETURN_NOT_OK(async_io_handler_->ScheduleWrite(buffer, offset, length, AsyncWriteCallback, reinterpret_cast<IAsyncContext*>(&async_context))); return Status::OK(); } Status WindowsRandomReadRandomWriteFile::GetDeviceAlignment( const std::string& filename, size_t& alignment) { // Prepend device prefix to the "X:" portion of the file name. char fullname[MAX_PATH]; GetFullPathName(filename.c_str(), MAX_PATH, fullname, NULL); std::string prefixed = std::string(fullname); prefixed = "\\\\.\\" + prefixed.substr(0, 2); HANDLE device = ::CreateFileA(prefixed.c_str(), 0, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if(INVALID_HANDLE_VALUE == device) { auto error = ::GetLastError(); return Status::IOError("Failed to create random read random write " "file for alignment query: " + filename, std::to_string(HRESULT_FROM_WIN32(error))); } unique_ptr_t<HANDLE> handle_guard = unique_ptr_t<HANDLE> (&device, [=](HANDLE* h) { ::CloseHandle(*h); }); STORAGE_PROPERTY_QUERY spq; spq.PropertyId = StorageAccessAlignmentProperty; spq.QueryType = PropertyStandardQuery; STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR alignmentDescriptor; BOOL ret = DeviceIoControl(device, IOCTL_STORAGE_QUERY_PROPERTY, &spq, sizeof(spq), (BYTE*)&alignmentDescriptor, sizeof(alignmentDescriptor), nullptr, nullptr); if(ret) { alignment = alignmentDescriptor.BytesPerLogicalSector; } else { // Many devices do not support StorageProcessAlignmentProperty. // Any failure here and we fall back to logical alignment DISK_GEOMETRY geometry; ret = DeviceIoControl(device, IOCTL_DISK_GET_DRIVE_GEOMETRY, nullptr, 0, &geometry, sizeof(geometry), nullptr, nullptr); if(!ret) { auto error = ::GetLastError(); return Status::IOError("Could not determine block alignment for " "device: " + filename, std::to_string(HRESULT_FROM_WIN32(error))); } alignment = geometry.BytesPerSector; } return Status::OK(); } WindowsSharedMemorySegment::WindowsSharedMemorySegment() : SharedMemorySegment() , segment_name_ { "" } , size_ { 0 } , map_handle_ { INVALID_HANDLE_VALUE } , map_address_ { nullptr } { } WindowsSharedMemorySegment::~WindowsSharedMemorySegment() {} SharedMemorySegment::~SharedMemorySegment() {} Status WindowsSharedMemorySegment::Create( unique_ptr_t<SharedMemorySegment>& segment) { segment.reset(); segment = alloc_unique<SharedMemorySegment>(sizeof(WindowsSharedMemorySegment)); if(!segment.get()) return Status::OutOfMemory(); new(segment.get())WindowsSharedMemorySegment(); return Status::OK(); } Status WindowsSharedMemorySegment::Initialize(const std::string& segname, uint64_t size, bool open_existing) { segment_name_ = segname; size_ = size; if(open_existing) { // Open an existing mapping to Attach() later map_handle_ = OpenFileMapping(FILE_MAP_ALL_ACCESS, false, segment_name_.c_str()); } else { // Create a new mapping for others and me to Attach() later map_handle_ = CreateFileMapping(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, size_, segment_name_.c_str()); } if(INVALID_HANDLE_VALUE == map_handle_) { auto error = ::GetLastError(); return Status::IOError("Failed to create file mapping", std::to_string(HRESULT_FROM_WIN32(error))); } return Status::OK(); } Status WindowsSharedMemorySegment::Attach(void* base_address) { map_address_ = MapViewOfFileEx(map_handle_, FILE_MAP_ALL_ACCESS, 0, 0, size_, base_address); if(nullptr == map_address_) { auto error = ::GetLastError(); return Status::IOError("Failed to attach to shared memory segment " + segment_name_ + " of " + std::to_string(size_) + " bytes with base address " + std::to_string((uint64_t)base_address), std::to_string(HRESULT_FROM_WIN32(error))); } return Status::OK(); } Status WindowsSharedMemorySegment::Detach() { UnmapViewOfFile(map_address_); map_address_ = nullptr; return Status::OK(); } void* WindowsSharedMemorySegment::GetMapAddress() { return map_address_; } WindowsPtpThreadPool::WindowsPtpThreadPool() : pool_{} , callback_environments_{} , cleanup_group_{} , max_threads_{} { } WindowsPtpThreadPool::~WindowsPtpThreadPool() { // Wait until all callbacks have finished. ::CloseThreadpoolCleanupGroupMembers(cleanup_group_, FALSE, nullptr); for(uint8_t priority = uint8_t(ThreadPoolPriority::Low); priority < uint8_t(ThreadPoolPriority::Last); ++priority) { PTP_CALLBACK_ENVIRON env = &callback_environments_[priority]; ::DestroyThreadpoolEnvironment(env); } ::CloseThreadpoolCleanupGroup(cleanup_group_); ::CloseThreadpool(pool_); cleanup_group_ = nullptr; pool_ = nullptr; } Status WindowsPtpThreadPool::Create(uint32_t max_threads, unique_ptr_t<ThreadPool>& threadpool) { threadpool.reset(); threadpool = alloc_unique<ThreadPool>(sizeof(WindowsPtpThreadPool)); if(!threadpool.get()) return Status::OutOfMemory(); new(threadpool.get())WindowsPtpThreadPool(); return static_cast<WindowsPtpThreadPool*>( threadpool.get())->Initialize(max_threads); } Status WindowsPtpThreadPool::Initialize(uint32_t max_threads) { PTP_POOL pool = ::CreateThreadpool(nullptr); ::SetThreadpoolThreadMaximum(pool, max_threads); BOOL ret = ::SetThreadpoolThreadMinimum(pool, 1); if(!ret) return Status::Corruption("Unable to set threadpool minimum count"); cleanup_group_ = ::CreateThreadpoolCleanupGroup(); if(!cleanup_group_) { return Status::Corruption("Unable to create threadpool cleanup group " "error: " + std::to_string(HRESULT_FROM_WIN32(::GetLastError()))); } for(uint8_t priority = size_t(ThreadPoolPriority::Low); priority < size_t(ThreadPoolPriority::Last); ++priority) { PTP_CALLBACK_ENVIRON env = &callback_environments_[priority]; ::InitializeThreadpoolEnvironment(env); ::SetThreadpoolCallbackPool(env, pool); ::SetThreadpoolCallbackPriority(env, TranslatePriority( static_cast<ThreadPoolPriority>(priority))); ::SetThreadpoolCallbackCleanupGroup(env, cleanup_group_, nullptr); } max_threads = max_threads; pool_ = pool; return Status::OK(); } void CALLBACK WindowsPtpThreadPool::TaskStartSpringboard( PTP_CALLBACK_INSTANCE instance, PVOID parameter, PTP_WORK work) { MARK_UNREFERENCED(instance); unique_ptr_t<TaskInfo> info = make_unique_ptr_t<TaskInfo>( reinterpret_cast<TaskInfo*>(parameter)); Status s = info->task(info->task_parameters); if(!s.ok()) { LOG(ERROR) << "Task callback did not return successfully: " << s.ToString(); } CloseThreadpoolWork(work); } Status WindowsPtpThreadPool::Schedule(ThreadPoolPriority priority, Task task, void* task_parameters) { unique_ptr_t<TaskInfo> info = alloc_unique<TaskInfo>(sizeof(TaskInfo)); if(!info.get()) return Status::OutOfMemory(); new(info.get()) TaskInfo(); info->task = task; info->task_parameters = task_parameters; PTP_CALLBACK_ENVIRON environment = &callback_environments_[size_t(priority)]; PTP_WORK_CALLBACK ptp_callback = TaskStartSpringboard; PTP_WORK work = CreateThreadpoolWork(ptp_callback, info.get(), environment); if(!work) { std::stringstream ss; ss << "Failed to schedule work: " << FormatWin32AndHRESULT(::GetLastError()); LOG(ERROR) << ss.str(); return Status::Aborted(ss.str()); } SubmitThreadpoolWork(work); info.release(); return Status::OK(); } Status WindowsPtpThreadPool::ScheduleTimer(ThreadPoolPriority priority, Task task, void* task_argument, uint32_t ms_period, void** timer_handle) { MARK_UNREFERENCED(priority); MARK_UNREFERENCED(task); MARK_UNREFERENCED(task_argument); MARK_UNREFERENCED(ms_period); MARK_UNREFERENCED(timer_handle); return Status::NotSupported("Not implemented"); } Status WindowsPtpThreadPool::CreateAsyncIOHandler(ThreadPoolPriority priority, const File& file, unique_ptr_t<AsyncIOHandler>& async_io) { async_io.reset(); HANDLE file_handle = reinterpret_cast<HANDLE>(file.GetFileIdentifier()); if(INVALID_HANDLE_VALUE == file_handle) { return Status::IOError("Invalid file handle"); } async_io = alloc_unique<AsyncIOHandler>(sizeof(WindowsAsyncIOHandler)); if(!async_io.get()) return Status::OutOfMemory(); new(async_io.get()) WindowsAsyncIOHandler(); return static_cast<WindowsAsyncIOHandler*>(async_io.get())->Initialize(this, file_handle, &callback_environments_[uint8_t(priority)], priority); } TP_CALLBACK_PRIORITY WindowsPtpThreadPool::TranslatePriority( ThreadPoolPriority priority) { switch(priority) { case ThreadPoolPriority::Low: return TP_CALLBACK_PRIORITY_LOW; break; case ThreadPoolPriority::Medium: return TP_CALLBACK_PRIORITY_NORMAL; break; case ThreadPoolPriority::High: return TP_CALLBACK_PRIORITY_HIGH; break; default: return TP_CALLBACK_PRIORITY_INVALID; } } WindowsAsyncIOHandler::WindowsAsyncIOHandler() : file_handle_(NULL) , io_object_(nullptr) , threadpool_{ nullptr } , io_priority_{ ThreadPoolPriority::Low } { } WindowsAsyncIOHandler::~WindowsAsyncIOHandler() { if(!io_object_) return; ::WaitForThreadpoolIoCallbacks(io_object_, TRUE); ::CloseThreadpoolIo(io_object_); io_object_ = nullptr; file_handle_ = nullptr; } void CALLBACK WindowsAsyncIOHandler::IOCompletionCallback( PTP_CALLBACK_INSTANCE instance, PVOID context, PVOID overlapped, ULONG ioResult, ULONG_PTR bytesTransferred, PTP_IO io) { MARK_UNREFERENCED(instance); MARK_UNREFERENCED(context); MARK_UNREFERENCED(io); // context is always nullptr; state is threaded via the OVERLAPPED unique_ptr_t<WindowsAsyncIOHandler::IOCallbackContext> callback_context( reinterpret_cast<IOCallbackContext*>(overlapped), [](IOCallbackContext* c) { Allocator::Get()->Free(c); }); HRESULT hr = HRESULT_FROM_WIN32(ioResult); Status return_status; if(FAILED(hr)) { return_status = Status::IOError("Error in async IO: " + std::to_string(hr)); } else { return_status = Status::OK(); } callback_context->callback(callback_context->caller_context, return_status, size_t(bytesTransferred)); } Status WindowsAsyncIOHandler::Initialize(ThreadPool* threadpool, HANDLE file_handle, PTP_CALLBACK_ENVIRON environment, ThreadPoolPriority priority) { if(io_object_) return Status::OK(); io_object_= ::CreateThreadpoolIo(file_handle, IOCompletionCallback, nullptr, environment); if(!io_object_) { return Status::IOError("Unable to create ThreadpoolIo"); } file_handle_ = file_handle; threadpool_ = threadpool; io_priority_ = priority; return Status::OK(); } Status WindowsAsyncIOHandler::ScheduleRead(uint8_t* buffer, size_t offset, uint32_t length, AsyncIOHandler::AsyncCallback callback, IAsyncContext* context) { return ScheduleOperation(OperationType::Read, buffer, offset, length, callback, context); } Status WindowsAsyncIOHandler::ScheduleWrite(uint8_t* buffer, size_t offset, uint32_t length, AsyncIOHandler::AsyncCallback callback, IAsyncContext* context) { return ScheduleOperation(OperationType::Write, buffer, offset, length, callback, context); } Status WindowsAsyncIOHandler::FinishSyncIOAsyncTask(void* context) { unique_ptr_t<WindowsAsyncIOHandler::IOCallbackContext> io_context( reinterpret_cast<IOCallbackContext*>(context), [](IOCallbackContext* c) { Allocator::Get()->Free(c); }); // No need to log errors or check for IO failure. This function assumes that // it is completing a successful synchronous IO. io_context->callback(io_context->caller_context, Status::OK(), io_context->bytes_transferred); return Status::OK(); } Status WindowsAsyncIOHandler::ScheduleOperation(OperationType operationType, void* buffer, size_t offset, uint32_t length, AsyncIOHandler::AsyncCallback callback, IAsyncContext* context) { unique_ptr_t<IOCallbackContext> io_context( reinterpret_cast<IOCallbackContext*>(Allocator::Get()->Allocate( sizeof(IOCallbackContext))), [](IOCallbackContext* c) { Status s = c->caller_context->DeepDelete(); ALWAYS_ASSERT(s.ok()); Allocator::Get()->Free(c); }); if(!io_context.get()) return Status::OutOfMemory(); new(io_context.get()) IOCallbackContext(); IAsyncContext* caller_context_copy = nullptr; RETURN_NOT_OK(context->DeepCopy(&caller_context_copy)); io_context->handler = this; io_context->callback = callback; io_context->caller_context = caller_context_copy; ::memset(&(io_context->overlapped), 0, sizeof(OVERLAPPED)); io_context->overlapped.Offset = offset & 0xffffffffllu; io_context->overlapped.OffsetHigh = offset >> 32; ::StartThreadpoolIo(io_object_); BOOL success = FALSE; DWORD bytes_transferred = 0; if(OperationType::Read == operationType) { success = ::ReadFile(file_handle_, buffer, length, &bytes_transferred, &io_context->overlapped); } else { success = ::WriteFile(file_handle_, buffer, length, &bytes_transferred, &io_context->overlapped); } if(!success) { DWORD win32_result = ::GetLastError(); // Any error other than ERROR_IO_PENDING means the IO failed. Otherwise it // will finish asynchronously on the threadpool if(ERROR_IO_PENDING != win32_result) { ::CancelThreadpoolIo(io_object_); std::stringstream ss; ss << "Failed to schedule async IO: " << FormatWin32AndHRESULT(win32_result); LOG(ERROR) << ss.str(); return Status::IOError(ss.str()); } } else { // The IO finished syncrhonously. Even though the IO was threadpooled, NTFS // may finish the IO synchronously (especially on VMs). To honor the fully // async call contract, schedule the completion on a separate thread using // the threadpool. io_context->bytes_transferred = length; RETURN_NOT_OK(threadpool_->Schedule(io_priority_, FinishSyncIOAsyncTask, reinterpret_cast<void*>(io_context.get()))); } io_context.release(); return Status::OK(); } } // namespace pmwcas <file_sep>set(UTIL_HEADERS atomics.h auto_ptr.h hash.h macros.h performance_test.h random_number_generator.h ) set(UTIL_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/nvram.cc ${CMAKE_CURRENT_SOURCE_DIR}/status.cc ) set_property(GLOBAL APPEND PROPERTY PMWCAS_SRC ${UTIL_SOURCES}) <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once #include <cstdint> #include <atomic> #include <vector> #include <deque> #include <memory> #include "include/environment.h" #include "common/environment_internal.h" #include "util/macros.h" namespace pmwcas { /// Run-time check to ensure a narrowing conversion is safe. template <class Narrow, class Wide> Narrow narrow(const Wide& wide) { Narrow narrow = static_cast<Narrow>(wide); return narrow; } /// An aid to reduce the boilerplate of writing multi-threaded performance or /// smoke tests. To use this class, subclass it directly in your unit test. /// Declare any shared data that all thread will operate on as class members. /// Provide an Entry() implementation and call run() to have several threads /// run the code (one variant of run() runs with a varying number of threads /// as well). After the test executes GetLastRunSeconds() and /// GetAllRunSeconds() can be used to find out how long the test took. /// The Setup() and Teardown() methods can also be overridden to reset things /// before/after each set of threads enters Entry(). /// /// One note on implementing Entry(): the body of Entry() must call /// WaitForStart(). This notifies the main thread that the thread is ready /// to run the experiment; it blocks until all participating threads have /// called the method. This makes the timing of the tests more reliable /// (it guarantees that we aren't measuring thread creation/destruction), and /// it gives threads a chance to initialize useful and potentially heavyweight /// stuff on their stack without messing up the measurements. class PerformanceTest { protected: /// Structure to record thread-local statistics. Cache line sized in order /// to prevent false cache line sharing across threads. struct alignas(64) WorkerStatistics { WorkerStatistics() : operation_count{} { } uint64_t operation_count; uint64_t ____filler[7]; }; static_assert(64 == sizeof(WorkerStatistics), "WorkerStatistics not cacheline size"); public: PerformanceTest() : threads_ready_{ 0 }, threads_finished_{ 0 }, start_running_{ false }, run_seconds_{}, is_shutdown_{ false }, use_worker_statistics_ { false }, runtime_before_shutdown_{} { } /// Provided by derived classes; contains that each thread should run during /// the test. Somewhere in this method WaitForStart() must be called, /// which acts as a barrier to synchronize the start of all the threads /// in the test and the start of timing in the main thread. virtual void Entry(size_t thread_index) { MARK_UNREFERENCED(thread_index); } /// Provided by the derived classes; Same as single-argument Entry function /// defined above with the addition of a reference to a thread-exclusive /// statistics struct use to record worker-specific statistics (e.g., /// operations completed). Statistics are aggregated by the master thread /// after the workload completes. virtual void Entry(size_t thread_index, WorkerStatistics* statistics) { MARK_UNREFERENCED(thread_index); MARK_UNREFERENCED(statistics); } /// Can be overridden by derived classes to reset member variables into /// the appropriate state before a set of threads enters Entry(). virtual void Setup() {} /// Can be overridden by derived classes to reset member variables into /// the appropriate state after a set of threads finishes running /// Entry(). This may be a good place to dump out statistics that are /// being tracked in member variables as well. virtual void Teardown() {} /// Sets the amount of time the test should run.The shutdown flag for the /// test will be set after \a nTime seconds.Worker threads can check for the /// flag using the IsShutdown() function. void SetRunTime(uint64_t time) { runtime_before_shutdown_ = time; } /// Sets a flag for whether to pass the Entry function a pointer to /// thread-local structure to record workload statistics. void UseWorkerStatistics() { use_worker_statistics_ = true; } /// Run \a threadCount threads running Entry() and measure how long the /// run takes.Afterward, GetLastRunSeconds() can be used to retrieve how /// long the execution took.This method will call Setup() and Teardown() /// respectively before and after the executions of Entry(). void Run(size_t threadCount) { threads_finished_ = 0; threads_ready_ = 0; start_running_ = false; Setup(); if(use_worker_statistics_) { worker_statistics_.reserve(threadCount); } // Start threads std::deque<Thread> threads; for(size_t i = 0; i < threadCount; ++i) { if(use_worker_statistics_) { worker_statistics_.emplace_back(); } threads.emplace_back(&PerformanceTest::entry, this, i, threadCount); } // Wait for threads to be ready while(threads_ready_.load() < threadCount); // Start the experiment uint64_t start = Environment::Get()->NowMicros(); start_running_.store(true, std::memory_order_release); if(runtime_before_shutdown_ > 0) { // Sleep the required amount of time before setting the shutdown flag. Environment::Get()->Sleep(runtime_before_shutdown_ * 1000); is_shutdown_.store(true, std::memory_order_release); } // Wait for all threads to finish their workload while(threads_finished_.load() < threadCount) { Environment::Get()->Sleep(10); } for(auto& thread : threads) { thread.join(); } // Record the run time in seconds run_seconds_.push_back((double)(end_ - start) / 1000); Teardown(); } /// Repeatedly run Entry() first starting with \a startingThreadCount /// and increasing by one until Entry() has been run with \a endThreadCount /// threads.Afterward, GetAllRunSeconds() can be used to retrieve how /// long each of the executions took.This method will call Setup() /// just before running each new round with a different number of threads /// through Entry().Similarly, Teardown() will be called after each /// set of threads finishes Entry(), before the next number of threads /// is run through Entry(). void Run(size_t startThreadCount, size_t endThreadCount) { for(size_t threadCount = startThreadCount; threadCount <= endThreadCount; ++threadCount) { Run(threadCount); } } /// Must be called in Entry() after initial setup and before the real /// work of the experiment starts.This acts as a barrier; the main thread /// waits for all threads running as part of the measurement to reach this /// point and then releases them to start to body of the experiment as /// closely synchronized as possible.Forgetting to call this in Entry() /// will result in an infinite loop. void WaitForStart() { threads_ready_.fetch_add(1, std::memory_order_acq_rel); while(!start_running_.load(std::memory_order_acquire)); } /// Must be called in Entry() after initial setup.Used by the worker threads /// to test for the shutdown flag after #m_nRuntTimeBeforeShutdown seconds /// have passed. bool IsShutdown() { return is_shutdown_.load(std::memory_order_acquire); } /// Return the number of seconds Entry() ran on any of the threads starting /// just after WaitForStart() up through the end of Entry(). double GetLastRunSeconds() { return run_seconds_.back(); } /// Return the number of seconds Entry() ran on any of the threads starting /// just after WaitForStart() up through the end of Entry() for all of the /// run of varying sets of threads. std::vector<double> GetAllRunSeconds() { return run_seconds_; } /// Returns the total operation count for the benchmark aggregated from all /// worker threads. This function is not threadsafe and should be called only /// after the workload completes. uint64_t GetTotalOperationCount() { if(!use_worker_statistics_) return 0; uint64_t total{}; for(auto iter = worker_statistics_.begin(); iter < worker_statistics_.end(); ++iter) { total += iter->operation_count; } return total; } private: /// Internal springboard used to automatically notify the main thread of /// Entry() completion.The last thread to finish the calls stuffs a snapshot /// of the ending time so the main thread can accurately determine how long /// the run took without polling aggressively and wasting a core. void entry(size_t threadIndex, size_t threadCount) { if(use_worker_statistics_) { Entry(threadIndex, &worker_statistics_[threadIndex]); } else { Entry(threadIndex); } size_t previous = threads_finished_.fetch_add(1, std::memory_order_acq_rel); if(previous + 1 == threadCount) { end_ = Environment::Get()->NowMicros(); } } private: /// Number of threads that have reached WaitForStart(). Used by the main /// thread to synchronize the start of the experiment. std::atomic<size_t> threads_ready_; /// Number of threads that have exited Entry(). Used by the main thread /// to determine when the experiment has completed. std::atomic<size_t> threads_finished_; /// The main thread sets this to true once #m_threadReady equals the /// number of threads that are part of the experiment. This releases all /// the threads to run the remainder of Entry() that follows the call /// to WaitForStart(). std::atomic<bool> start_running_; /// Tracks how long in seconds each collective run of Entry() took for /// a set of threads. Used in GetAllRunSeconds() and GetLastRunSeconds(). std::vector<double> run_seconds_; /// Time in QueryPerformanceCounter ticks that the last thread finished /// its work. uint64_t end_; /// Shutdown flag for timed tests. std::atomic<bool> is_shutdown_; /// Number of seconds a test will run before the #is_shutdown_ flag is set. uint64_t runtime_before_shutdown_; /// Whether the workload will have workers record statistics. bool use_worker_statistics_; /// Vector of workload statistics to hand out to each worker. Only allocated /// if use_worker_statistics_ is true. std::vector<WorkerStatistics> worker_statistics_; }; } // namespace pmwcas <file_sep># Persistent Multi-Word Compare-and-Swap (PMwCAS) for NVRAM ![Windows Build Status](https://justinlevandoski.visualstudio.com/_apis/public/build/definitions/c59a8e03-b063-4da5-8b4b-b0092d61c7cb/3/badge "Windows Build Status") PMwCAS is a library that allows atomically changing multiple 8-byte words on non-volatile memory in a lock-free manner. It allows developers to easily build lock-free data structures for non-volatile memory and requires no custom recovery logic from the application. More details are described in the following [slide deck](http://www.cs.sfu.ca/~tzwang/pmwcas-slides.pdf), [full paper](http://justinlevandoski.org/papers/ICDE18_mwcas.pdf) and [extended abstract](http://www.cs.sfu.ca/~tzwang/pmwcas-nvmw.pdf): ``` Easy Lock-Free Indexing in Non-Volatile Memory. <NAME>, <NAME> and <NAME>. ICDE 2018. ``` ``` Easy Lock-Free Programming in Non-Volatile Memory. <NAME>, <NAME> and <NAME>. NVMW 2019. Finalist for Memorable Paper Award. ``` ## Environment and Variants The current code supports both Windows (CMake + Visual Studio) and Linux (CMake + gcc/clang) and four variants with different persistence modes: 1. Persistence using Intel [PMDK](https://pmem.io) 2. Persistence by emulation with DRAM 3. Volatile (no persistence support) 4. Volatile with Intel TSX (using hardware transaction memory to install descriptors, for `Volatile` only) A persistence mode must be specified at build time through the `PMEM_BACKEND` option in CMake (default PMDK). See below for how to pass this option to CMake. ## Build (for Linux) Suppose we build in a separate directory "build" under the source directory. We need to clone the repository with `--recursive` to enable google test build. To build PMwCAS without TSX: ``` $ mkdir build $ cd build $ cmake -DPMEM_BACKEND=[PMDK/Volatile/Emu] -DCMAKE_BUILD_TYPE=[Debug/Release/RelWithDebInfo] .. $ make -jN ``` To build a **volatile** PMwCAS variant that uses TSX to install descriptor pointers: ``` $ mkdir build $ cd build $ cmake -DPMEM_BACKEND=Volatile -DWITH_RTM=1 -DCMAKE_BUILD_TYPE=[Debug/Release/RelWithDebInfo] .. $ make -jN ``` #### Descriptor size By default each descriptor can hold up to four words. This can be adjusted at compile-time by specifying the `DESC_CAP` parameter to CMake, for example the following will allow up to 8 words per descriptor: ``` $ cmake -DDESC_CAP=8 -DPMEM_BACKEND=Volatile -DWITH_RTM=1 -DCMAKE_BUILD_TYPE=[Debug/Release/RelWithDebInfo] .. ``` #### Huge pages and memlock limits (for Linux) Under Linux the `volatile` and `emu` variants use a simple thread-local allocator that uses huge pages. Make sure the system has enough huge pages: ``` sudo sh -c 'echo [x pages] > /proc/sys/vm/nr_hugepages' ``` By default the allocator needs ~10GB per socket, defined by `kNumaMemorySize` in [src/environment/environment_linux.h](./src/environment/environment_linux.h). On Linux `mwcas_shm_server` (see below) requires a proper value for memlock limits. Add the following to `/etc/security/limits.conf` (replace "[user]" with your login) to make it unlimited (need **re-login** to apply): ``` [user] soft memlock unlimited [user] hard memlock unlimited ``` #### To build on Windows (to be tested for PMDK): ``` $ md build $ cd build $ cmake -G [generator] .. ``` `[generator]` should match the version of Visual Studio installed and specify `Win64`, e.g., `Visual Studio 14 2015 Win64`. Use `cmake -G` to get a full list. Then either opening and building pmwcas.sln in Visual Studio, or use: ``` $ msbuild pmwcas.sln /p:Configuration=[Release/Debug] ``` ## NVRAM Emulation For runs without real NVRAM device (e.g., NVDIMM or Intel 3D-XPoint), we provide a shared-memory interface for emulation. The basic idea is to start a dedicated process which creates a shared memory segment for the application (another process) to attach to, so that data will remain intact when the application crashes (the dedicated shared memory process is alive). The shared memory process is implemented in [src/benchmarks/mwcas_shm_server.cc](./src/benchmarks/mwcas_shm_server.cc). It needs to start before the application. ## APIs The central concept of PMwCAS is desrciptors. The typical steps to change multiple 8-byte words are: 1. Allocate a descriptor; 2. Fill in the descriptor with the expected and new values of each target word; 3. Issue the PMwCAS command to actually conduct the operation. The target words often are pointers to dynamically allocated memory blocks. PMwCAS allows transparent handling of dynamically allocated memory depending on user-specified policy. For example, one can specify to allocate a memory block and use it as the 'new value' of a target word, and specify that this memory block be deallocated if the PMwCAS failed. See [APIs.md](./APIs.md) for a list of useful APIs and memory related polices and examples. ## Thread Model It is important to note that PMwCAS uses C++11 thread_local variables which must be reset if the descriptor pool is destructed and/or a thread is (in rare cases) re-purposed to use a different descriptor pool later. The library provides a `Thread` abstraction that extends `std::thread` for this purpose. The user application is expected to use the `Thread` class whenever `std::thread` is needed. `Thread` has the exactly same APIs as `std::thread` with an overloaded join() interface that clears its own thread-local variables upon exit. The `Thread` class also provides a static `ClearRegistry()` function that allows the user application to clear all thread local variables. All the user application needs is to invoke this function upon changing/destroying a descriptor pool. For example, the below pattern is often used in our test cases: ``` DescriptorPool pool_1 = new DescriptorPool(...); // Create a descriptor pool ... use pool_1 ... delete pool_1; Thread::ClearRegistry(); // Reset the TLS variables, after this it is safe to use another pool DescriptorPool *pool_2 = new DescriptorPool(...); ... use pool_2 ... Thread::ClearRegistry(); ``` ## Benchmarks To use PMwCAS, simply link the built library with your application. See the [ICDE paper](http://justinlevandoski.org/papers/ICDE18_mwcas.pdf) for a complete list of APIs. The project provides two examples: ### Array benchmark This benchmark atomically changes a random number of entries in a fixed-sized array (code in [src/benchmarks/mwcas_benchmark.cc](./src/benchmarks/mwcas_benchmark.cc)). A sample 10-second, 2-thread, 100-entry array run that changes four words: ``` $ mwcas_shm_server -shm_segment "mwcas" # start the shared memory process $ mwcas_benchmark -shm_segment "mwcas" -threads 2 -seconds 10 -array_size 100 -word_count 4 ``` See the source file for a complete list of parameters. ### Doubly-linked list Inside [src/double-linked-list](./src/double-linked-list) are implementations of lock-free doubly-linked lists using single-word CAS and PMwCAS. A benchmark is implemented in [src/benchmarks/doubly_linked_list_benchmark.cc](./src/benchmarks/doubly_linked_list_benchmark.cc). # Contributing This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com. When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [<EMAIL>](mailto:<EMAIL>) with any additional questions or comments. ## License Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #define GLOG_NO_ABBREVIATED_SEVERITIES #include <sys/mman.h> #include <fcntl.h> #include <unistd.h> #include <chrono> #include <vector> #include <string> #include <iomanip> #include <ios> #include "common/allocator_internal.h" #include "environment/environment_linux.h" #include "util/auto_ptr.h" #include "util/macros.h" namespace pmwcas { LinuxEnvironment::LinuxEnvironment() {} uint64_t LinuxEnvironment::NowMicros() { struct timespec ts; memset(&ts, 0, sizeof(ts)); clock_gettime(CLOCK_REALTIME, &ts); uint64_t ns = ts.tv_sec * 1000000000LL + ts.tv_nsec; return ns / 1000 + (ns % 1000 >= 500); } uint64_t LinuxEnvironment::NowNanos() { struct timespec ts; memset(&ts, 0, sizeof(ts)); clock_gettime(CLOCK_REALTIME, &ts); uint64_t ns = ts.tv_sec * 1000000000LL + ts.tv_nsec; return ns / 1000 + (ns % 1000 >= 500); } /// Returns the core count on the test machine uint32_t LinuxEnvironment::GetCoreCount() { return std::thread::hardware_concurrency(); } void LinuxEnvironment::Sleep(uint32_t ms_to_sleep) { std::this_thread::sleep_for(std::chrono::milliseconds(ms_to_sleep)); } Status LinuxEnvironment::NewRandomReadWriteAsyncFile(const std::string& filename, const FileOptions& options, ThreadPool* threadpool, RandomReadWriteAsyncFile** file, bool* exists) { return Status::NotSupported("Not implemented"); } Status LinuxEnvironment::NewSharedMemorySegment(const std::string& segname, uint64_t size, bool open_existing, SharedMemorySegment** seg) { *seg = nullptr; unique_ptr_t<SharedMemorySegment> alloc_guard; RETURN_NOT_OK(LinuxSharedMemorySegment::Create(alloc_guard)); RETURN_NOT_OK(alloc_guard->Initialize(segname, size, open_existing)); *seg = alloc_guard.release(); return Status::OK(); } Status LinuxEnvironment::NewThreadPool(uint32_t max_threads, ThreadPool** pool) { return Status::NotSupported("Not implemented"); } Status LinuxEnvironment::GetWorkingDirectory(std::string& directory) { char cwd[4096]; memset(cwd, 0, 4096); char *c = getcwd(cwd, sizeof(cwd)); directory = std::string(cwd); return Status::OK(); } Status LinuxEnvironment::GetExecutableDirectory(std::string& directory) { // FIXME(tzwang): assuming same as working dir GetWorkingDirectory(directory); return Status::OK(); } Status LinuxEnvironment::SetThreadAffinity(uint64_t core, AffinityPattern affinity_pattern) { pthread_t thread_handle = pthread_self(); return SetThreadAffinity(thread_handle, core, affinity_pattern); } Status LinuxEnvironment::SetThreadAffinity(pthread_t thread, uint64_t core, AffinityPattern affinity_pattern) { if(affinity_pattern == AffinityPattern::BalanceNumaNodes) { // For now, assume that we're running on a 4-node NUMA system, where the // cores are numbered with the first n cores on node 0, the next n cores on // node 1, ... and the last n cores on node 3. const uint32_t numa_node_count = 4; CHECK_EQ(GetCoreCount() % numa_node_count, 0) << "Unexpected system configuration!"; uint32_t logical_core_count = GetCoreCount() / numa_node_count; // Assume 2 logical cores per physical core. CHECK_EQ(logical_core_count % 2, 0) << "Unexpected system configuration!"; uint32_t physical_core_count = logical_core_count / 2; uint32_t numa_node = core % numa_node_count; uint32_t numa_core = core / numa_node_count; if(numa_core < physical_core_count) { numa_core = numa_core * 2; } else { numa_core = (numa_core - physical_core_count) * 2 + 1; } core = (numa_node * logical_core_count) + numa_core; } else if(affinity_pattern == 4) { // crossfire switch(core) { case 0: core = 0; break; case 1: core = 4; break; case 2: core = 8; break; case 3: core = 12; break; case 4: core = 16; break; case 5: core = 20; break; case 6: core = 1; break; case 7: core = 5; break; case 8: core = 9; break; case 9: core = 13; break; case 10: core = 17; break; case 11: core = 21; break; case 12: core = 2; break; case 13: core = 6; break; case 14: core = 10; break; case 15: core = 14; break; case 16: core = 18; break; case 17: core = 22; break; case 18: core = 3; break; case 19: core = 7; break; case 20: core = 11; break; case 21: core = 15; break; case 22: core = 19; break; case 23: core = 23; break; default: RAW_CHECK(false, "wrong core"); break; } } else if(affinity_pattern == 5) { // spread on c153 uint64_t orig_core = core; if(core >= 32) { core -= 32; } uint32_t nodes = 4; uint32_t total_cores = 32; uint32_t cores_per_node = 8; uint32_t pcore = (core % nodes) * cores_per_node + core / nodes; if(orig_core >= 32) { pcore += 32; } LOG(INFO) << "Core " << orig_core << " -> " << pcore; core = pcore; } else { // Assuming 0-n are all the physical cores } cpu_set_t cpuset; CPU_ZERO(&cpuset); CPU_SET(core, &cpuset); int result = pthread_setaffinity_np(thread, sizeof(cpuset), &cpuset); if(result != 0) { return Status::Aborted("Failed to set thread affinity.", strerror(errno)); } else { return Status::OK(); } return Status::OK(); } LinuxSharedMemorySegment::LinuxSharedMemorySegment() : SharedMemorySegment() , segment_name_ { "" } , size_ { 0 } , map_fd_ { 0 } , map_address_ { nullptr } { } LinuxSharedMemorySegment::~LinuxSharedMemorySegment() {} SharedMemorySegment::~SharedMemorySegment() {} Status LinuxSharedMemorySegment::Create( unique_ptr_t<SharedMemorySegment>& segment) { segment.reset(); segment = alloc_unique<SharedMemorySegment>(sizeof(LinuxSharedMemorySegment)); if(!segment.get()) return Status::OutOfMemory(); new(segment.get())LinuxSharedMemorySegment(); return Status::OK(); } Status LinuxSharedMemorySegment::Initialize(const std::string& segname, uint64_t size, bool open_existing) { segment_name_ = segname; size_ = size; if(open_existing) { // Open an existing mapping to Attach() later map_fd_ = shm_open(segment_name_.c_str(), O_RDWR, S_IRWXU|S_IRUSR|S_IWUSR); } else { // Create a new mapping for others and me to Attach() later map_fd_ = shm_open(segment_name_.c_str(), O_CREAT|O_RDWR, S_IRWXU|S_IRUSR|S_IWUSR); auto ret = ftruncate(map_fd_, size_); (void)ret; } if(-1 == map_fd_) { return Status::IOError("Failed to create file mapping", std::string(strerror(errno))); } return Status::OK(); } Status LinuxSharedMemorySegment::Attach(void* base_address) { map_address_ = mmap(base_address, size_, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_LOCKED, map_fd_, (off_t)0); if(MAP_FAILED == map_address_) { return Status::IOError( "Failed to attach to shared memory segment " + segment_name_ + " of " + std::to_string(size_) + " bytes with base address " + std::to_string((uint64_t)base_address), std::string(strerror(errno))); } return Status::OK(); } Status LinuxSharedMemorySegment::Detach() { munmap(map_address_, size_); map_address_ = nullptr; return Status::OK(); } void* LinuxSharedMemorySegment::GetMapAddress() { return map_address_; } } // namespace pmwcas <file_sep>set(MWCAS_HEADERS metrics.h mwcas.h ) set(MWCAS_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/mwcas.cc ) set_property(GLOBAL APPEND PROPERTY PMWCAS_SRC ${MWCAS_SOURCES}) ADD_PMWCAS_TEST(mwcas_tests) <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #include "nvram.h" namespace pmwcas { #ifdef PMEM uint64_t NVRAM::write_delay_cycles = 0; double NVRAM::write_byte_per_cycle = 0; bool NVRAM::use_clflush = false; #endif } // namespace pmwcas <file_sep>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #include <vector> #include <glog/logging.h> #include <gtest/gtest.h> #include "common/allocator_internal.h" #include "doubly_linked_list.h" #include "include/pmwcas.h" #include "include/environment.h" #include "include/allocator.h" #include "include/status.h" #include "util/random_number_generator.h" #include "util/performance_test.h" #ifdef WIN32 #include "environment/environment_windows.h" #else #include "environment/environment_linux.h" #endif uint32_t descriptor_pool_size = 100000; namespace pmwcas { namespace test { struct SingleThreadTest { IDList* dll; std::vector<DListNode*> nodes; const uint32_t kInitialNodes = 1000; SingleThreadTest(IDList* list) : dll(list) { Initialize(); } void Initialize() { if(dll->GetSyncMethod() == IDList::kSyncMwCAS) { MwCASMetrics::ThreadInitialize(); } ASSERT_TRUE(nodes.size() == 0); ASSERT_TRUE(dll->GetHead()->prev == nullptr); ASSERT_TRUE(dll->GetHead()->next == dll->GetTail()); ASSERT_TRUE(dll->GetTail()->prev == dll->GetHead()); ASSERT_TRUE(dll->GetTail()->next == nullptr); for(int i = 0; i < kInitialNodes; ++i) { auto* n = new DListNode; nodes.push_back(n); auto s = dll->InsertAfter(dll->GetTail(), n, false); ASSERT_TRUE(s.ok()); } ASSERT_TRUE(nodes.size() == kInitialNodes); for(uint32_t i = 0; i < nodes.size(); i++) { if(dll->GetSyncMethod() == IDList::kSyncCAS) { ASSERT_FALSE(CASDList::MarkedNext(nodes[i])); ASSERT_FALSE(CASDList::MarkedPrev(nodes[i])); } } SanityCheck(); } ~SingleThreadTest() { Teardown(); } void Teardown() { SanityCheck(); for(uint32_t i = 0; i < nodes.size(); i++) { delete nodes[i]; } Thread::ClearRegistry(); } void SanityCheck() { if(nodes.size() == 0) { // TestDelete empties node the vector return; } bool found_head = false, found_tail = false; for(auto& n : nodes) { ASSERT_TRUE(n->prev && n->next); auto* next = dll->GetNext(n); if(next) { ASSERT_TRUE(dll->GetPrev(next) == n); if(n->prev == dll->GetHead()) { ASSERT_FALSE(found_head); found_head = true; } } auto* prev = dll->GetPrev(n); if(prev) { ASSERT_TRUE(prev->next == n); if(n->next == dll->GetTail()) { ASSERT_FALSE(found_tail); found_tail = true; } } } ASSERT_TRUE(found_head); ASSERT_TRUE(found_tail); uint32_t n = 0; DListCursor iter((IDList*)dll); while(iter.Next() != dll->GetTail()) { n++; } EXPECT_EQ(n, nodes.size()); dll->SingleThreadSanityCheck(); } void TestInsert() { RandomNumberGenerator rng(1234567); // Insert some new nodes at random locations const int kInserts = 1000; for(int i = 0; i < kInserts; i++) { int idx = rng.Generate(nodes.size()); ASSERT_TRUE(idx >= 0 && idx < nodes.size()); DListNode* n = new DListNode; if(rng.Generate(2) == 0) { auto s = dll->InsertBefore(nodes[idx], n, false); ASSERT_TRUE(s.ok()); } else { auto s = dll->InsertAfter(nodes[idx], n, false); ASSERT_TRUE(s.ok()); } nodes.push_back(n); } ASSERT_TRUE(nodes.size() == kInitialNodes + kInserts); } void TestDelete() { RandomNumberGenerator rng(1234567); // Delete some nodes at random locations while(nodes.size()) { int idx = rng.Generate(nodes.size()); ASSERT_TRUE(idx >= 0 && idx < nodes.size()); dll->Delete(nodes[idx], false); delete nodes[idx]; nodes.erase(nodes.begin() + idx); } ASSERT_TRUE(nodes.size() == 0); } void TestInsertDelete() { RandomNumberGenerator rng(1234567); const int kInsertPct = 50; const int kDeletePct = 100 - kInsertPct; const int kOps = 1000; for(int i = 0; i < kOps; i++) { if(nodes.size() && rng.Generate(100) >= kDeletePct) { int idx = rng.Generate(nodes.size()); ASSERT_TRUE(nodes[idx]->prev); ASSERT_TRUE(nodes[idx]->next); ASSERT_TRUE(dll->GetNext(dll->GetPrev(nodes[idx])) == dll->GetPrev( dll->GetNext(nodes[idx]))); ASSERT_TRUE(dll->GetNext(dll->GetPrev(nodes[idx])) == nodes[idx]); auto s = dll->Delete(nodes[idx], false); ASSERT_TRUE(s.ok()); DListNode* prev = nodes[idx]->prev; DListNode* next = nodes[idx]->next; if(dll->GetSyncMethod() == IDList::kSyncCAS) { ASSERT_TRUE(nodes[idx]->prev); ASSERT_TRUE(nodes[idx]->next); prev = ((CASDList*)dll)->DereferenceNodePointer(&(nodes[idx]->prev)); next = ((CASDList*)dll)->DereferenceNodePointer(&(nodes[idx]->next)); ASSERT_TRUE(dll->GetNext(prev) == next); ASSERT_TRUE(dll->GetPrev(next) == prev); } delete nodes[idx]; nodes.erase(nodes.begin() + idx); } else { int idx = rng.Generate(nodes.size()); ASSERT_TRUE(idx >= 0 && idx < nodes.size()); DListNode* n = new DListNode(nullptr, nullptr, 0); if(rng.Generate(2) == 0) { auto s = dll->InsertBefore(nodes[idx], n, false); ASSERT_TRUE(s.ok()); ASSERT_TRUE(dll->GetPrev(nodes[idx]) == n); ASSERT_TRUE(n->next == nodes[idx]); } else { auto s = dll->InsertAfter(nodes[idx], n, false); ASSERT_TRUE(s.ok()); ASSERT_TRUE(nodes[idx]->next == n); ASSERT_TRUE(n->prev == nodes[idx]); } nodes.push_back(n); } } } }; struct MultiThreadInsertDeleteTest : public PerformanceTest { static const int kInitialNodes = 1000; std::vector<DListNode*> nodes; std::atomic<int32_t> node_count; IDList* dll; Barrier barrier; MultiThreadInsertDeleteTest(IDList* list, uint32_t thread_count) : PerformanceTest(), node_count(0), dll(list), barrier{ thread_count } {} void Entry(size_t thread_index) { if(dll->GetSyncMethod() == IDList::kSyncMwCAS) { MwCASMetrics::ThreadInitialize(); } if(thread_index == 0) { RandomNumberGenerator rng(1234567); for(int i = 0; i < kInitialNodes; ++i) { nodes.push_back(new DListNode()); dll->InsertAfter(dll->GetHead(), nodes[i], false); node_count++; } dll->SingleThreadSanityCheck(); } const int kOps = 1000; RandomNumberGenerator rng(1234567); int next_insert_idx = 0; int done_ops = 0; std::vector<DListNode*> my_nodes; for(int i = 0; i < kOps; ++i) { // Lazy, this is more than enough my_nodes.push_back(new DListNode()); } WaitForStart(); while(done_ops++ != kOps) { int32_t nc = node_count.load(std::memory_order_seq_cst); uint8_t ops = 3; // insert-before/after/delete if(nc <= 0) { ops--; // exclude delete } ASSERT_TRUE(ops == 2 || ops == 3); DListNode* target = dll->GetHead(); int idx = rng.Generate(nc); DListCursor iter((IDList*)dll); while(--idx > 0 && target) { target = iter.Next(); } if(!target) { continue; } int op = rng.Generate(ops); if(op == 0) { auto s = dll->InsertBefore(target, my_nodes[next_insert_idx++], false); ASSERT_TRUE(s.ok()); node_count++; } else if(op == 1) { auto s = dll->InsertAfter(target, my_nodes[next_insert_idx++], false); ASSERT_TRUE(s.ok()); node_count++; } else { auto s = dll->Delete(target, false); ASSERT_TRUE(s.ok()); if(target != dll->GetHead() && target != dll->GetTail()) { node_count--; } } } barrier.CountAndWait(); if(thread_index == 0) { dll->SingleThreadSanityCheck(); } } }; struct MultiThreadDeleteTest : public PerformanceTest { static const int kInitialNodes = 1000; std::vector<DListNode*> nodes; IDList* dll; Barrier barrier; MultiThreadDeleteTest(IDList* list, uint32_t thread_count) : PerformanceTest(), dll(list), barrier { thread_count } {} void Entry(size_t thread_index) { if(dll->GetSyncMethod() == IDList::kSyncMwCAS) { MwCASMetrics::ThreadInitialize(); } if(thread_index == 0) { RandomNumberGenerator rng(1234567); for(int i = 0; i < kInitialNodes; ++i) { nodes.push_back(new DListNode()); dll->InsertAfter(dll->GetHead(), nodes[i], false); } } RandomNumberGenerator rng(1234567); int deletes = 200; WaitForStart(); while(deletes-- > 0 && dll->GetHead()->next != dll->GetTail()) { int idx = rng.Generate(kInitialNodes); DListNode* node = nodes[idx]; ASSERT_TRUE(node); ASSERT_TRUE(node != dll->GetHead()); ASSERT_TRUE(node != dll->GetTail()); dll->Delete(node, false); } barrier.CountAndWait(); if(thread_index == 0) { dll->SingleThreadSanityCheck(); for(int i = 0; i < kInitialNodes; ++i) { delete nodes[i]; } } } }; struct MultiThreadInsertTest : public PerformanceTest { std::atomic<uint32_t> insert_count; IDList* dll; Barrier barrier; MultiThreadInsertTest(IDList* list, uint32_t thread_count) : PerformanceTest(), insert_count(0), dll(list), barrier { thread_count } {} void Entry(size_t thread_index) { if(dll->GetSyncMethod() == IDList::kSyncMwCAS) { MwCASMetrics::ThreadInitialize(); } RandomNumberGenerator rng(1234567); const int kInserts = 1000; std::vector<DListNode*> thread_nodes; // Populate my vector of nodes to be inserted for(int i = 0; i < kInserts; ++i) { thread_nodes.push_back(new DListNode()); } for(int i = 0; i < kInserts; ++i) { ASSERT_TRUE(((int64_t)thread_nodes[i] & 0x3) == 0); } WaitForStart(); for(int i = 0; i < kInserts; ++i) { // Pick a neighbor: the dummy head if dll is empty, otherwise // try a random guy in the middle of the list. DListNode* neighbor = dll->GetHead(); if(insert_count > 0) { int idx = rng.Generate(insert_count); DListCursor iter((IDList*)dll); do { neighbor = iter.Next(); } while(--idx > 0); ASSERT_TRUE(neighbor); } if(rng.Generate(2) == 0) { auto s = dll->InsertBefore(neighbor, thread_nodes[i], false); ASSERT_TRUE(s.ok()); } else { auto s = dll->InsertAfter(neighbor, thread_nodes[i], false); ASSERT_TRUE(s.ok()); } ++insert_count; } barrier.CountAndWait(); if(thread_index == 0) { dll->SingleThreadSanityCheck(); uint32_t n = 0; auto* prev = dll->GetHead(); DListCursor iter((IDList*)dll); // Check the insert count too while(true) { auto* node = iter.Next(); ASSERT_TRUE(dll->GetPrev(node) == prev); ASSERT_TRUE(prev->next == node); if(node == dll->GetTail()) { break; } n++; prev = node; } EXPECT_EQ(n, insert_count); } } }; GTEST_TEST(DListTest, CASDSingleThreadInsert) { CASDList dll; SingleThreadTest t(&dll); t.TestInsert(); } GTEST_TEST(DListTest, CASDSingleThreadDelete) { CASDList dll; SingleThreadTest t(&dll); t.TestDelete(); } GTEST_TEST(DListTest, CASDSingleThreadInsertDelete) { CASDList dll; SingleThreadTest t(&dll); t.TestInsertDelete(); } GTEST_TEST(DListTest, CASDMultiThreadInsert) { CASDList dll; auto thread_count = Environment::Get()->GetCoreCount(); MultiThreadInsertTest test(&dll, thread_count); test.Run(thread_count); } GTEST_TEST(DListTest, CASDMultiThreadDelete) { CASDList dll; auto thread_count = Environment::Get()->GetCoreCount(); MultiThreadDeleteTest test(&dll, thread_count); test.Run(thread_count); } GTEST_TEST(DListTest, CASDMultiThreadInsertDelete) { CASDList dll; auto thread_count = Environment::Get()->GetCoreCount(); MultiThreadInsertDeleteTest test(&dll, thread_count); test.Run(thread_count); } GTEST_TEST(DListTest, MwCASSingleThreadInsert) { auto thread_count = Environment::Get()->GetCoreCount(); std::unique_ptr<pmwcas::DescriptorPool> pool( new pmwcas::DescriptorPool(descriptor_pool_size, thread_count)); std::unique_ptr<MwCASDList> dll(new MwCASDList(pool.get())); std::unique_ptr<SingleThreadTest> t (new SingleThreadTest(dll.get())); t->TestInsert(); } GTEST_TEST(DListTest, MwCASSingleThreadDelete) { auto thread_count = Environment::Get()->GetCoreCount(); std::unique_ptr<pmwcas::DescriptorPool> pool( new pmwcas::DescriptorPool(descriptor_pool_size, thread_count)); std::unique_ptr<MwCASDList> dll(new MwCASDList(pool.get())); std::unique_ptr<SingleThreadTest> t (new SingleThreadTest(dll.get())); t->TestDelete(); } GTEST_TEST(DListTest, MwCASSingleThreadInsertDelete) { auto thread_count = Environment::Get()->GetCoreCount(); std::unique_ptr<pmwcas::DescriptorPool> pool( new pmwcas::DescriptorPool(descriptor_pool_size, thread_count)); std::unique_ptr<MwCASDList> dll(new MwCASDList(pool.get())); std::unique_ptr<SingleThreadTest> t (new SingleThreadTest(dll.get())); t->TestInsertDelete(); } GTEST_TEST(DListTest, MwCASMultiThreadDelete) { auto thread_count = Environment::Get()->GetCoreCount(); std::unique_ptr<pmwcas::DescriptorPool> pool( new pmwcas::DescriptorPool(descriptor_pool_size, thread_count)); std::unique_ptr<MwCASDList> dll(new MwCASDList(pool.get())); MultiThreadDeleteTest* t = new MultiThreadDeleteTest(dll.get(), thread_count); t->Run(thread_count); } GTEST_TEST(DListTest, MwCASMultiThreadInsert) { auto thread_count = Environment::Get()->GetCoreCount(); std::unique_ptr<pmwcas::DescriptorPool> pool( new pmwcas::DescriptorPool(descriptor_pool_size, thread_count)); std::unique_ptr<MwCASDList> dll(new MwCASDList(pool.get())); MultiThreadInsertTest* t = new MultiThreadInsertTest(dll.get(), thread_count); t->Run(thread_count); } GTEST_TEST(DListTest, MwCASMultiThreadInsertDelete) { auto thread_count = Environment::Get()->GetCoreCount(); std::unique_ptr<pmwcas::DescriptorPool> pool( new pmwcas::DescriptorPool(descriptor_pool_size, thread_count)); std::unique_ptr<MwCASDList> dll(new MwCASDList(pool.get())); MultiThreadInsertDeleteTest* t = new MultiThreadInsertDeleteTest( dll.get(), thread_count); t->Run(thread_count); } } // namespace test } // namespace pmwcas int main(int argc, char** argv) { google::InitGoogleLogging(argv[0]); ::testing::InitGoogleTest(&argc, argv); FLAGS_minloglevel = 2; #ifdef WIN32 pmwcas::InitLibrary(pmwcas::DefaultAllocator::Create, pmwcas::DefaultAllocator::Destroy, pmwcas::WindowsEnvironment::Create, pmwcas::WindowsEnvironment::Destroy); #else #ifdef PMDK pmwcas::InitLibrary(pmwcas::PMDKAllocator::Create("doubly_linked_test_pool", "doubly_linked_layout", static_cast<uint64_t >(1024) * 1024 * 1204 * 5), pmwcas::PMDKAllocator::Destroy, pmwcas::LinuxEnvironment::Create, pmwcas::LinuxEnvironment::Destroy); #else pmwcas::InitLibrary(pmwcas::TlsAllocator::Create, pmwcas::TlsAllocator::Destroy, pmwcas::LinuxEnvironment::Create, pmwcas::LinuxEnvironment::Destroy); #endif // PMDK #endif // WIN32 return RUN_ALL_TESTS(); } <file_sep># Change Log ## Nov 2019 In this update, we fixed several bugs and improved performance. A big thank you to the following folks that helped to make PMwCAS even better. - <NAME> and his students from the University of Waterloo found a linearizability bug, which may cause spurious abort in some cases. - <NAME> from Carnegie Mellon University found an optimization that can improve the PMwCAS by reducing persistent memory flushes. - <NAME> from Tsinghua University located a bug in PMDK integration that a crash during allocation may cause a memory leak. - <NAME> from the University of Toronto fixed an incorrect `inline` which caused the code failed to build with gcc. ## June 2019 Added PMDK backend, bug fixes, and general improvements on code base. Note that the PMDK integration assumes a Linux environment and might not work well on Windows machines.
d579c4d11d84e330ec48fc5eb05985e98af3bb3f
[ "Markdown", "C", "CMake", "C++" ]
59
C++
microsoft/pmwcas
3c50dec9cfbe31e3c4b02ef7e0ffd9f0a210adc3
6b24e6ae11156be3f9daaf8284cb8d8834e72321
refs/heads/master
<repo_name>ARAGroupGIA/arapractice0-ARAJAMOMO5<file_sep>/Exercise2/exercise2.c /******************* Problem definition **********************************/ /* Implement a program that it shows the message "Hello World" on screen. */ /*************************************************************************/ /* Here, you must include the required libraries */ #include <stdio.h> void main(){ int A,B,C; printf("show value of B"); scanf("d",&B); printf("show value of C"); scanf("%d",&C); A=B+C; printf("the result of the sum is %d",A); }
b944cf748670f6c9c356e3d43ec9623aaff0801a
[ "C" ]
1
C
ARAGroupGIA/arapractice0-ARAJAMOMO5
ac60f74ef71aa8dcd564a075dc102b956bd490a6
7d3fc46f4e48589184598e417acac6b443ecace0
refs/heads/master
<repo_name>leewaggoner/DEPRECATED-RecyclerViewExpandingAdapter<file_sep>/recyclerviewexpandingadapter/src/main/java/com/wreckingball/recyclerviewexpandingadapter/ExpandingData.kt package com.wreckingball.recyclerviewexpandingadapter abstract class ExpandingData(var isParent: Boolean = false, var children: MutableList<out ExpandingData>? = null) { var isExpanded: Boolean = false var index: Int = 0 }<file_sep>/app/src/main/java/com/wreckingball/recyclerviewexpandingadapterlib/models/TestParent.kt package com.wreckingball.recyclerviewexpandingadapterlib.models import com.wreckingball.recyclerviewexpandingadapter.ExpandingData class TestParent( var parentText: String, childList: MutableList<TestChild>? ) : ExpandingData(true, childList)<file_sep>/app/src/androidTest/java/com/wreckingball/recyclerviewexpandingadapterlib/RecyclerViewExpandingAdapterTest.kt package com.wreckingball.recyclerviewexpandingadapterlib import androidx.recyclerview.widget.RecyclerView import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.contrib.RecyclerViewActions import androidx.test.espresso.matcher.ViewMatchers.* import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.rule.ActivityTestRule import com.wreckingball.recyclerviewexpandingadapter.RecyclerViewExpandingAdapter import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* import org.junit.Before import org.junit.Rule /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class RecyclerViewExpandingAdapterTest { @get:Rule val activityRule = ActivityTestRule(MainActivity::class.java) private lateinit var adapter: RecyclerViewExpandingAdapter private var originalItemCount: Int = 0 @Before fun setup() { val recyclerView = activityRule.activity.findViewById<RecyclerView>(R.id.recyclerViewExpanding) adapter = recyclerView.adapter as RecyclerViewExpandingAdapter originalItemCount = recyclerView.adapter!!.itemCount } @Test fun testOpenCloseOneItem() { assertTrue(20 == originalItemCount) //expand parent 0 onView(withId(R.id.recyclerViewExpanding)) .perform(RecyclerViewActions.actionOnItemAtPosition<RecyclerView.ViewHolder>(0, click())) var newCount = adapter.itemCount assertTrue(25 == newCount) //close parent 0 onView(withId(R.id.recyclerViewExpanding)) .perform(RecyclerViewActions.actionOnItemAtPosition<RecyclerView.ViewHolder>(0, click())) newCount = adapter.itemCount assertTrue(20 == newCount) } @Test fun testOpenOneItemCloseDifferent() { assertTrue(20 == originalItemCount) //expand parent 0 onView(withId(R.id.recyclerViewExpanding)) .perform(RecyclerViewActions.actionOnItemAtPosition<RecyclerView.ViewHolder>(0, click())) var newCount = adapter.itemCount assertTrue(25 == newCount) onView(withId(R.id.recyclerViewExpanding)) .perform(RecyclerViewActions.scrollToPosition<RecyclerView.ViewHolder>(14)) //expand parent 14 onView(withId(R.id.recyclerViewExpanding)) .perform(RecyclerViewActions.actionOnItemAtPosition<RecyclerView.ViewHolder>(19, click())) newCount = adapter.itemCount assertTrue(25 == newCount) onView(RecyclerViewMatcher(R.id.recyclerViewExpanding) .atPositionOnView(14, R.id.parent_title)) .check(matches(isDisplayed())) onView(RecyclerViewMatcher(R.id.recyclerViewExpanding) .atPositionOnView(14, R.id.parent_title)) .check(matches(withText("Hello there, parent 14!"))) } @Test fun testLastItemOpen() { assertTrue(20 == originalItemCount) //expand parent 19 onView(withId(R.id.recyclerViewExpanding)) .perform(RecyclerViewActions.actionOnItemAtPosition<RecyclerView.ViewHolder>(19, click())) var newCount = adapter.itemCount assertTrue(25 == newCount) onView(RecyclerViewMatcher(R.id.recyclerViewExpanding) .atPositionOnView(20, R.id.child_title)) .check(matches(isDisplayed())) } @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.wreckingball.recyclerviewexpandingadapterlib", appContext.packageName) } } <file_sep>/settings.gradle rootProject.name='RecyclerViewExpandingAdapterLib' include ':app' include ':recyclerviewexpandingadapter' <file_sep>/app/src/main/java/com/wreckingball/recyclerviewexpandingadapterlib/MainActivity.kt package com.wreckingball.recyclerviewexpandingadapterlib import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.wreckingball.recyclerviewexpandingadapter.RecyclerViewExpandingAdapter import com.wreckingball.recyclerviewexpandingadapterlib.adapters.TestExpandingCallback import com.wreckingball.recyclerviewexpandingadapterlib.models.TestChild import com.wreckingball.recyclerviewexpandingadapterlib.models.TestParent import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val expandingData = getData() recyclerViewExpanding.adapter = RecyclerViewExpandingAdapter(this, expandingData, R.layout.item_parent, R.layout.item_child, TestExpandingCallback()) } private fun getData() : List<TestParent> { val list = mutableListOf<TestParent>() for (i in 0 until 20) { val childList = mutableListOf<TestChild>() for (j in 0 until 5) { val childData = TestChild("Hi there child $i:$j!") childList.add(childData) } list.add(TestParent("Hello there, parent $i!", childList)) } return list } } <file_sep>/README.md # RecyclerViewExpandingAdapter A simple expanding recycler view adapter <file_sep>/recyclerviewexpandingadapter/src/main/java/com/wreckingball/recyclerviewexpandingadapter/RecyclerViewexpandingAdapter.kt package com.wreckingball.recyclerviewexpandingadapter import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView class RecyclerViewExpandingAdapter( private val context: Context, list: List<ExpandingData>, private val parentLayout: Int, private val childLayout: Int, private val expandingAdapterCallback: ExpandingAdapterCallback ) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private var itemList: MutableList<ExpandingData> private var expandingAdapter: RecyclerViewExpandingAdapter = this companion object { private const val TYPE_PARENT = 1 private const val TYPE_CHILD = 2 private const val UNEXPANDED = -1 private var itemExpanded = UNEXPANDED } init { itemExpanded = UNEXPANDED itemList = mutableListOf() for ((index, item) in list.withIndex()) { item.index = index itemList.add(item) } } class ParentViewHolder(private val parentView: View, private val list: MutableList<ExpandingData>, private val expandingAdapter: RecyclerViewExpandingAdapter, private val adapterCallback: ExpandingAdapterCallback) : RecyclerView.ViewHolder(parentView) { private var maxItems = 0 init { maxItems = list[list.size - 1].index } fun bindView(item: ExpandingData) { parentView.tag = item.index adapterCallback.onBindParentView(parentView, item) parentView.setOnClickListener {view -> expandCollapse(view) } } private fun expandCollapse(view: View) { val index = list[layoutPosition].index when (itemExpanded) { UNEXPANDED -> expandAlbum(list, index, view) layoutPosition -> collapseAlbum(list, itemExpanded, view) else -> { //user clicked a parent while a different parent is expanded collapseAlbum(list, itemExpanded, view) expandAlbum(list, index, view) } } } private fun expandAlbum(list: MutableList<ExpandingData>, index: Int, view: View) { val listSize = list.size - 1 val children = list[index].children if (!children.isNullOrEmpty()) { adapterCallback.onParentExpand(view) itemExpanded = index for ((childIndex, i) in (index + 1 until index + 1 + children.size).withIndex()) { val child = children[childIndex] list.add(i, child) } list[index].isExpanded = true expandingAdapter.notifyItemRangeInserted(layoutPosition + 1, children.size) if (index == maxItems) { val recyclerView = view.parent as RecyclerView recyclerView.scrollToPosition(listSize + 1) } } } private fun collapseAlbum(list: MutableList<ExpandingData>, expandedItem: Int, view: View) { val parentView = view.parent as View val collapseView = parentView.findViewWithTag<View>(expandedItem) if (collapseView != null) { adapterCallback.onParentCollapse(collapseView) } val children = list[expandedItem].children if (!children.isNullOrEmpty()) { itemExpanded = UNEXPANDED for (i in (expandedItem + 1 until expandedItem + 1 + children.size)) { list.removeAt(expandedItem + 1) } list[expandedItem].isExpanded = false expandingAdapter.notifyItemRangeRemoved(expandedItem + 1, children.size) } } } class ChildViewHolder(private val childView: View, private val adapterCallback: ExpandingAdapterCallback) : RecyclerView.ViewHolder(childView) { fun bindView(item: ExpandingData) { adapterCallback.onBindChildView(childView, item) childView.setOnClickListener { adapterCallback.onChildClick(childView, item) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return if (viewType == TYPE_PARENT) { val view = LayoutInflater.from(context).inflate(parentLayout, parent, false) ParentViewHolder(view, itemList, expandingAdapter, expandingAdapterCallback) } else { val view = LayoutInflater.from(context).inflate(childLayout, parent, false) ChildViewHolder(view, expandingAdapterCallback) } } override fun getItemCount(): Int { return itemList.size } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val item = itemList[position] if (item.isParent) { (holder as ParentViewHolder).bindView(item) } else { (holder as ChildViewHolder).bindView(item) } } override fun getItemViewType(position: Int): Int { return if (itemList[position].isParent) { TYPE_PARENT } else { TYPE_CHILD } } }<file_sep>/app/src/main/java/com/wreckingball/recyclerviewexpandingadapterlib/adapters/TestExpandingCallback.kt package com.wreckingball.recyclerviewexpandingadapterlib.adapters import android.view.View import com.google.android.material.snackbar.Snackbar import com.wreckingball.recyclerviewexpandingadapter.ExpandingAdapterCallback import com.wreckingball.recyclerviewexpandingadapter.ExpandingData import com.wreckingball.recyclerviewexpandingadapterlib.R import com.wreckingball.recyclerviewexpandingadapterlib.models.TestChild import com.wreckingball.recyclerviewexpandingadapterlib.models.TestParent import kotlinx.android.synthetic.main.item_child.view.* import kotlinx.android.synthetic.main.item_parent.view.* class TestExpandingCallback : ExpandingAdapterCallback { override fun onBindParentView(itemView: View, item: ExpandingData) { val tag = itemView.tag val parent = item as TestParent itemView.parent_title.text = parent.parentText //needs to be done because of the way RecyclerView updates views -- if the expanded view //is off the screen, and you expand an onscreen view, the onParentCollapse view is null //(because it's been recycled), so when you scroll back to the initial expanded view, it's //got a new view if (item.isExpanded) { itemView.arrow.setImageResource(R.drawable.up) } else { itemView.arrow.setImageResource(R.drawable.down) } } override fun onParentExpand(itemView: View) { val tag = itemView.tag itemView.arrow.setImageResource(R.drawable.up) } override fun onParentCollapse(itemView: View) { //if the expanded view is off the screen, and you expand an onscreen view, onParentCollapse //will not be called val tag = itemView.tag itemView.arrow.setImageResource(R.drawable.down) } override fun onBindChildView(itemView: View, item: ExpandingData) { val child = item as TestChild itemView.child_title.text = child.childText } override fun onChildClick(itemView: View, item: ExpandingData) { val child = item as TestChild Snackbar.make(itemView, "Clicked {${child.childText}!", Snackbar.LENGTH_LONG).show() } }<file_sep>/recyclerviewexpandingadapter/src/main/java/com/wreckingball/recyclerviewexpandingadapter/ExpandingAdapterCallback.kt package com.wreckingball.recyclerviewexpandingadapter import android.view.View interface ExpandingAdapterCallback { fun onBindParentView(itemView: View, item: ExpandingData) fun onParentExpand(itemView: View) fun onParentCollapse(itemView: View) fun onBindChildView(itemView: View, item: ExpandingData) fun onChildClick(itemView: View, item: ExpandingData) }<file_sep>/app/src/main/java/com/wreckingball/recyclerviewexpandingadapterlib/models/TestChild.kt package com.wreckingball.recyclerviewexpandingadapterlib.models import com.wreckingball.recyclerviewexpandingadapter.ExpandingData class TestChild( var childText: String ) : ExpandingData()
11112ec2f8fcacf585e311bcb9cbf44bad25a868
[ "Markdown", "Kotlin", "Gradle" ]
10
Kotlin
leewaggoner/DEPRECATED-RecyclerViewExpandingAdapter
7b33f4f4f2c18e30b5f15b57ae0ab5d778cd8405
34199185c190472584b0956cb33381f36d977da8
refs/heads/master
<file_sep># target.py # Simulates an archery target. Click anywhere to exit. from graphics import * def main(): win = GraphWin('Target', 320, 320) win.setBackground('gray') center = Point(160,160) yellowCirc = Circle(center, 30) yellowCirc.setFill('yellow') redCirc = Circle(center, 60) redCirc.setFill('red') blueCirc = Circle(center, 90) blueCirc.setFill('blue') blackCirc = Circle(center, 120) blackCirc.setFill('black') whiteCirc = Circle(center, 150) whiteCirc.setFill('white') whiteCirc.draw(win) blackCirc.draw(win) blueCirc.draw(win) redCirc.draw(win) yellowCirc.draw(win) win.getMouse() main() <file_sep># binarySearch.py import random import time def binarySearch(x, nums): low = 0 high = len(nums) - 1 while low <= high: # there is still a range to search mid = (low + high)//2 # position of middle item item = nums[mid] if x == item: # found it, return the index return mid elif x < item: # x is in lower half of range high = mid - 1 # move top marker down else: # x is in higher half of range low = mid + 1 # move bottom marker up return -1 # x is not there def main(): listLength = 10 # start the list off at 10 numbers doSearch = True while doSearch: print('Creating list of size {}...'.format(listLength)) numList = [i*3 for i in range(listLength)] # this time dont shuffle the list, needs to be in order numToSearch = random.choice(numList) print('Searching for {} in a list of size {}...'.format(numToSearch, listLength)) startTime = time.time() index = binarySearch(numToSearch, numList) totalTime = time.time() - startTime print('Found {} at position {}. This search took {:.3f} seconds.'.format(numToSearch, index, totalTime)) listLength *= 10 # multiplay by a factor of 10 each time doSearch = (input('Search again using a list of size {}? (y/n): '.format(listLength)).lower()[0] == 'y') print() # blank line to visually seperate searches if __name__ == '__main__': main() input("Press any key to continue . . . ") <file_sep># house.py ''' <NAME> CS-1400-001 Professor <NAME> Project Due: Feb 10, 2018 Programming Project 2 Draw a house according to the users mouse input (5 clicks). 1. Bottom left of the house 2. Top right of the house. The house should be red, and it is a rectangle 3. The top center of the door. The door's width is 1/5 of the house, and should stop at the bottom of the house. The door is black. 4. The center of a square window, half as wide as the door. The window is gray. 5. The peak of the roof, which is a triangle that extends down to the top-left and top-right of the house. The roof is brown. The major steps I took to complete the program include making variables for the colors, creating the window, creating the house with extra variables for use later (like houseWidth), creating the door, again making useful variables like doorWidth, creating the window after calculating the width of the window, and finally making a polygon for the roof using previously made house variables. What I learned: - Setting up extra variables helps makes your code more readable and easier to change later - It's good to store points in variables because you might not know when you need to use them again - The order of drawing is very important; generally, the lower down the code is in the program the closer it will be drawn to the screen. - I learned how to set up the width and height of the main window by adding width and height parameters when you create it - I figured out how to draw the door so it's width is 1/5 of the house - subtract 1/10 from each side of the center X position. ''' from graphics import * def main(): # Set up colors as variables houseCol = 'red' doorCol = 'black' windowCol = 'gray' roofCol = 'brown' # Create the window winWidth, winHeight = 600, 600 win = GraphWin('House', winWidth, winHeight) winCenter = winWidth/2 # Tell the user what click is needed next instructions = Text(Point(winCenter,20), 'Click where the bottom-left of the house should be.') instructions.draw(win) # Store the two points needed for the house in variables, then draw houseBL = win.getMouse() instructions.setText('Click where the top-right of the house should be.') houseTR = win.getMouse() houseWidth = abs(houseTR.getX() - houseBL.getX()) houseRect = Rectangle(houseBL, houseTR) houseRect.setFill(houseCol) houseRect.draw(win) # Get the point for the top center of the door and calculate the rectangle positions, then draw instructions.setText('Click where the top-center of the door should be.') doorTC = win.getMouse() doorWidth = houseWidth/5 doorBL = Point(doorTC.getX() - (doorWidth/2), houseBL.getY()) doorTR = Point(doorTC.getX() + (doorWidth/2), doorTC.getY()) doorRect = Rectangle(doorBL, doorTR) doorRect.setFill(doorCol) doorRect.draw(win) # Get the point for the center of the window and calculate the rectangle positions, then draw instructions.setText('Click where the center of the window should be.') windowC = win.getMouse() windowWidth = doorWidth/2 windowBL = Point(windowC.getX() - (windowWidth/2), windowC.getY()+(windowWidth/2)) windowTR = Point(windowC.getX() + (windowWidth/2), windowC.getY()-(windowWidth/2)) windowRect = Rectangle(windowBL, windowTR) windowRect.setFill(windowCol) windowRect.draw(win) # Get the peak of the roof and calculate the position of the polygon points, then draw instructions.setText('Click where the top of the roof should be.') roofTC = win.getMouse() roofPoint1 = Point(houseBL.getX(), houseTR.getY()) # top left of the house roofPoint2 = houseTR.clone() # top right of the house roofPoly = Polygon(roofPoint1, roofPoint2, roofTC) roofPoly.setFill(roofCol) roofPoly.draw(win) instructions.setText('This is a very lovely house.') win.getMouse() main() <file_sep># grayscale.py # Test image used: https://i.imgur.com/UnJS0H5.gif # This program converts an image to black and white. # If you're viewing this file on GitHub, I have included an image (wario.gif). from graphics import * def createImage(): while True: try: imgFile = input('Enter image file to convert: ') img = Image(Point(0, 0), imgFile) break except: print('Not a valid file. Valid formats: PPM or GIF') img.move(img.getWidth()/2, img.getHeight()/2) return img def convertToGray(img): for row in range(img.getHeight()): for col in range(img.getWidth()): r, g, b = img.getPixel(col, row) l = round(r*0.299 + g*0.587 + b*0.114) img.setPixel(col, row, color_rgb(l, l, l)) update() def saveFile(img): saveName = input('Enter file name to save (leave blank to skip): ') if saveName == '': return False else: img.save(saveName) return 'File saved.' def main(): img = createImage() win = GraphWin('Grayscale Conversion', img.getWidth(), img.getHeight()) img.draw(win) print('Click to convert to grayscale.') win.getMouse() print('Converting...', end=' ') convertToGray(img) print('Done.') while True: try: if saveFile(img): print('File saved.') break except: print('Not a valid file. Valid formats: PPM or GIF') win.close() if __name__ == '__main__': main() input("Press any key to continue . . . ") <file_sep># pizzaCost.py # A program that calculates the cost per square inch of # a circular pizza given it's total price and diameter. import math def main(): price = float(input('Cost of pizza: $')) diameter = float(input('Diameter of pizza in inches: ')) radius = diameter / 2 area = math.pi * radius**2 costPerSqIn = price / area print('Pizza cost: ${:.2f}'.format(price)) print('Pizza diameter:', diameter, 'inches.') print('Pizza area:', area, 'inches squared.') print('Your pizza costs ${:.2f} per square inch.'.format(costPerSqIn)) main() input("Press any key to continue . . . ") <file_sep># linearSearch.py import random import time def linearSearch(x, nums): for i in range(len(nums)): if nums[i] == x: # item found, return the index value return i return -1 # loop finished, item was not in list def main(): listLength = 10 # start the list off at 10 numbers doSearch = True while doSearch: # on my machine, creating and shuffling the list took longer than searching for it on bigger lists print('Creating and shuffling list of size {}...'.format(listLength)) numList = [i for i in range(listLength)] random.shuffle(numList) numToSearch = random.choice(numList) print('Searching for {} in a list of size {}...'.format(numToSearch, listLength)) startTime = time.time() index = linearSearch(numToSearch, numList) # totalTime is just the time it took to search, but creating and shuffling # the list will also take a long time. totalTime = time.time() - startTime print('Found {} at position {}. This search took {:.3f} seconds.'.format(numToSearch, index, totalTime)) listLength *= 10 # multiplay by a factor of 10 each time doSearch = (input('Search again using a list of size {}? (y/n): '.format(listLength)).lower()[0] == 'y') print() # blank line to visually seperate searches if __name__ == '__main__': main() <file_sep># twoCircles2.py # Takes user input for the center position and radius for two circles # and draws them on a 400x400 GraphWin. Tells the user if the circles # are overlapping. import math from graphics import * def main(): c1x = float(input('Circle 1 center x-position: ')) c1y = float(input('Circle 1 center y-position: ')) c1Rad = int(input('Circle 1 radius: ')) c2x = float(input('Circle 2 center x-position: ')) c2y = float(input('Circle 2 center y-position: ')) c2Rad = int(input('Circle 2 radius: ')) win = GraphWin('Two Circles', 400, 400) Circle(Point(c1x, c1y), c1Rad).draw(win) Circle(Point(c2x, c2y), c2Rad).draw(win) if math.sqrt((c2x-c2y)**2 + (c2y-c1y)**2) <= c1Rad + c2Rad: txt = 'The circles are overlapping.' else: txt = 'The circles are not overlapping.' Text(Point(200, 375), txt).draw(win) win.getMouse() if __name__ == '__main__': main() <file_sep># bowling.py ''' File Prologue Identifying information: Name: <NAME> Course: CS-1400-001 Professor: <NAME> Project Title: Bowling Team Due Date: April 26, 2018 Restatement of original problem: Your Saturday bowling league wants a program that neatly displays player data and team data, and saves them to a file. At the end of each game, the players type in their first name and their score. When all the players are done entering their data, entering an empty line indicates that the data is finished being entered. The program then prints: 1. The names and scores of each bowler in the order entered 2. The names and scores in descending order with high scorer at the top 3. The names and scores in alphabetical order If any of the players had a perfect game, put an asterisk in front of their name. The program then displays: 1. A congratulatory message showing the high score and who got it 2. A sympathetic message showing the lowest score and who got it 3. The team average score, rounded down to the nearest pin Finally, the program should write all of the same information in the same format to a file named game_results.txt Description of major steps of my solution: First, I created a Bowler class to keep the name and score of each player. I made getter methods for both of the instance variables, as well as an extre getNameLower() method used for sorting alphabetically. Then, I started making functions having to do with the bowlers. I created a list of bowlers, and some primitive text functions. I soon realized that all of the functions relate to the same thing, a bowling team, so I created a class which turned out to be helpful. I created methods to print to the screen the tables and summary, but had some trouble when it came to saving to disk. So instead of just printing string literals, I decided to save an entire "text" instance variable to the BowlingTeam class in order to use the text to print, save to file, or anything else for that matter. I finished by making a summary, an introduction, and making the formatting pretty just for some extra eye candy. Bullet list of what I learned: - I learned to saving the text, and printing should be two different methods. I also added a writeToFile method, just to make it clear. - I learned that not only does the sort method have a key=func parameter, but max() and min() have them too. - I learned you can use variables for the format method, called "Paramtrized formats". ''' class Bowler: """A bowler has a name and a score.""" def __init__(self, name, score): self.name = name self.score = score def getName(self): """Returns the name.""" return self.name def getNameLower(self): """Returns the name, but lower to make sure the sorting is correct.""" return self.name.lower() def getScore(self): """Returns their score.""" return self.score class BowlingTeam: """A BowlingTeam represents a list of bowlers, and some data and methods to print the scores and names.""" def __init__(self): self.bowlers = [] self.text = '' def getInput(self): """Gets and validates the input for the names and scores for players and adds them to the list bowlers.""" print('Enter first name and score of a player seperated by a space, or a blank line to stop.') while True: data = input('Player name and score: ').split() if len(data) == 0: # if they enter a blank line, they're done break try: name = data[0] score = int(data[1]) except: print('Bad input, please enter again.') continue if score < 0 or score > 300: print('Score needs to be between 0 and 300 points.') continue # If they entered everything correctly, add the bowler to the team self.bowlers.append(Bowler(name, score)) def getTableTextList(self, listType): """Returns a list of strings ready to either print or write to file.""" # Max name length is 16 nameLen = 16 scoreLen = 5 border = '+-{}-+-{}-+'.format('-' * nameLen,'-' * scoreLen) separator = '|-{}-+-{}-|'.format('-' * nameLen,'-' * scoreLen) width = len(border) # bowlingText represents the whole table in text bowlingText = [] bowlingText.append(listType.center(width)) bowlingText.append(border) bowlingText.append('| {:^{nameW}} | {:^{scoreW}} |'.format('Name', 'Score', nameW=nameLen, scoreW=scoreLen)) bowlingText.append(border) for bowler in self.bowlers: if bowler.getScore() == 300: name = '*' + bowler.getName() else: name = bowler.getName() score = str(bowler.getScore()).rjust(3) bowlingText.append('| {:<{nameW}} | {:^{scoreW}} |'.format(name, score, nameW=nameLen, scoreW=scoreLen)) # Don't print the separator if it's the last bowler if self.bowlers.index(bowler) != len(self.bowlers) - 1: bowlingText.append(separator) bowlingText.append(border) return bowlingText def getTeamAverage(self): """Computes the team average rounded DOWN to the nearest pin.""" total = 0 for b in self.bowlers: total += b.getScore() return int(total / len(self.bowlers)) def sortByScore(self): """Sorts the bowlers instance variable in place by score, in descending order.""" self.bowlers.sort(key=Bowler.getScore, reverse=True) def sortByName(self): """Sorts the bowlers instance variable in place by name.""" self.bowlers.sort(key=Bowler.getNameLower) def addTables(self): """Adds all three tables into one big text string.""" text = '' original = self.getTableTextList('Bowling Team') self.sortByScore() scores = self.getTableTextList('Bowling Team by Score') self.sortByName() names = self.getTableTextList('Bowling Team by Name') for i in range(len(original)): text += '{} {} {}\n'.format(original[i], scores[i], names[i]) self.text = text def concatSummary(self): highScorer = max(self.bowlers, key=Bowler.getScore) lowScorer = min(self.bowlers, key=Bowler.getScore) teamAverage = self.getTeamAverage() self.text += 'Congratulations {}, you got the highest score of {}!\n'.format( highScorer.getName(), highScorer.getScore()) # Condescending sorry message self.text += 'Sorry {}, you got the lowest score of {}. :(\n'.format( lowScorer.getName(), lowScorer.getScore()) self.text += 'The team average (rounded down to the nearest pin) is {}.\n'.format(teamAverage) def createText(self): self.addTables() self.concatSummary() def printText(self): """Prints the text to the window.""" self.createText() print(self.text) def writeToFile(self): """Writes the text to the file 'game_restuls.txt'.""" outFile = open('game_results.txt', 'w', encoding='utf-8') outFile.write(self.text) outFile.close() print('Tables and summary saved to file.') def printIntro(): print('Saturday Bowling League Scoring Program') print('This program gets the names and scores of players on a bowling team and prints') print('three tables: 1. The order entered. 2. Descending order in terms of score.') print('and 3. Ascending alphabetical order. It also writes the three tables to disk') print('with the filename \'game_results.txt\'.') print() def main(): printIntro() team = BowlingTeam() team.getInput() team.printText() team.writeToFile() if __name__ == '__main__': main() input("Press any key to continue . . . ") <file_sep># windchill.py # This program computes windchill. def computeWindchill(temp, windSpeed): if windSpeed > 3: return 35.74 + 0.6215*temp - 35.75*(windSpeed**0.16) + 0.4275*temp*(windSpeed**0.16) else: return temp def main(): # Initial setup for displaying tableTitle = 'Wind Chill Table (°F)' rowTitle = 'Wind Speed (mph)' rowTitleWidth = len(rowTitle) colTitle = 'Temperature (°F)' entryWidth = 6 rowHeader = ' ' * rowTitleWidth + '|' for temp in range(-20, 61, 10): rowHeader += '{:2}'.format(temp).center(entryWidth) # makes sure the 0 is in the ones-place tableWidth = len(rowHeader) # Printing and calculating the data print(tableTitle.center(tableWidth)) print() print(' ' * rowTitleWidth + colTitle.center(tableWidth - rowTitleWidth)) print(rowHeader) print(rowTitle + '|' + '-' * (tableWidth - rowTitleWidth - 1)) for spd in range(0, 51, 5): colHeader = str(spd).rjust(len(rowTitle)) + '|' print(colHeader, end='') for temp in range(-20, 61, 10): wc = computeWindchill(temp, spd) wcStr = '{:.1f}'.format(wc) print(wcStr.rjust(entryWidth), end='') print() if __name__ == '__main__': main() print() input("Press any key to continue . . . ") <file_sep># farmer_john.py ''' File Prologue Identifying information: Name: <NAME> Course: CS-1400-001 Professor: <NAME> Project Title: Farm John's Field Due Date: February 24, 2018 Restatement of original problem: Farmer john is interested in the area inside of the square that isn't part of the circles. The points ABCD are formed by four vertices located at the center of four identical circles, which are the new circular irrigation system. Draw an image that looks like the given image. - 4 circles, labeled A, B, C, D - the shaded area inbetween them - the lines that make up the square Compute the area of the shaded region after being given one of the sides of the square. -The length of the side must be larger than zero, and the user input must catch any errors and quit gracefully. 4. Description of major steps of my solution: - Create a 400x400 window, name "Farmer John's Field" - Make a drawFarm function, doing the following: - Draw the square and fill it with gray - Draw the four circles, fill them with white, and label them - Draw the square outline - Get the user input for a side length of the square - Make a function to compute the area of the shaded region - Handle how the user exits 5. Bullet list of what I learned: - Since the square region has 4 parts of a circle, you can just take the square minus the circle areas to get the shaded area. - Learned how to make a docstring ''' import math from graphics import * def drawFarm(window): """Draws the farm as 4 circles with a shaded area. Args: window: The GraphWin to draw the farm on. """ # 10 pixel buffer on all sides rad = 95 pTL = Point(105, 105) pTR = Point(295, 105) pBL = Point(105, 295) pBR = Point(295, 295) # Draw the square and fill it with gray square = Rectangle(pTL, pBR) square.setFill('gray') square.draw(window) # Draw the four circles, fill them with white, label them c1 = Circle(pTL, rad) c1.setFill('white') c1.draw(window) c2 = Circle(pTR, rad) c2.setFill('white') c2.draw(window) c3 = Circle(pBL, rad) c3.setFill('white') c3.draw(window) c4 = Circle(pBR, rad) c4.setFill('white') c4.draw(window) Text(Point(pTL.getX()-15,pTL.getY()-15), 'A').draw(window) Text(Point(pTR.getX()+15,pTR.getY()-15), 'B').draw(window) Text(Point(pBL.getX()-15,pBL.getY()+15), 'C').draw(window) Text(Point(pBR.getX()+15,pBR.getY()+15), 'D').draw(window) # Draw the square outline sOutline = Rectangle(pTL, pBR) sOutline.setOutline('light gray') sOutline.draw(window) def calculateArea(length): """Gets a side length from user and calculates shaded area. Args: length: The length of the side of a square to calculate from. Returns: The area of a square of said length, minus a circle with a radius of half that length. """ rad = length/2 squareArea = length * length circleArea = math.pi * rad**2 return squareArea - circleArea def getLength(): """Gets a user-inputted length. Validate, and quit if bad input. Returns: Length if correct input, or None if something went wrong """ try: length = float(input('Enter side length of square: ')) if length > 0: return length else: print('Length must be larger than 0.') return None except: print('Length must be a number.') return None def main(): win = GraphWin('<NAME>', 400, 400) win.setBackground('mint cream') drawFarm(win) length = getLength() # Quit early if length is None if length == None: win.close() return area = calculateArea(length) print('Area of shaded region:', str(round(area, 2)) + '.') # Tell the user to click on window to quit. If they push the X instead, handle that. print('Click anywhere on window to terminate.') try: win.getMouse() win.close() except: return if __name__ == '__main__': main() <file_sep># innerProd.py def innerProd(x, y): total = 0 # found out online that the "zip" function does exactly # what I was trying to do: for xi, yi in x, y (this resulted in an error) for xi, yi in zip(x, y): total += xi * yi return total list1 = [10, 10, 10] list2 = [3, 2, 1] print(innerProd(list1, list2)) # prints 60 input("Press any key to continue . . . ") <file_sep># sphereInfo.py # This program has 2 functions for returning the surface area and # volume of a sphere having the given radius. import math def sphereArea(radius): return 4 * math.pi * radius**2 def sphereVolume(radius): return 4/3 * math.pi * radius**3 def main(): rad = float(input('Enter radius of sphere: ')) area = sphereArea(rad) volume = sphereVolume(rad) print('The surface area of a sphere with a ' 'radius of {} units is: {:.2f} units squared.'.format(rad, area)) print('The volume of a sphere with a radius ' 'of {} units is: {:.2f} units cubed.'.format(rad, volume)) main() input("Press any key to continue . . . ") <file_sep># futval.py # A program to compute the value of an investment # carried user-inputted years into the future. def main(): print("This program calculates the future value") print("of a variable-year investment.") principal = eval(input("Enter the initial principal: ")) apr = eval(input("Enter the annual interest rate: ")) years = int(input("Enter the number of years: ")) for i in range(years): principal *= (1 + apr) print("The value in", years, "years is:", principal) main() input("Press any key to continue . . . ") <file_sep># rabbits.py ''' File Prologue Identifying information: Name: <NAME> Course: CS-1400-001 Professor: <NAME> Project Title: Rabbits, Rabbits, Rabbits Due Date: March 10, 2018 Restatement of original problem: A scientist is researching rabbits for her experiments. She starts out with one pair of adult rabbits. At the end of each month, each pair of rabbits produce one pair of offspring. Offspring can't reproduce until they are at least one month old, and won't have babies until the following month. The scientist has 500 cages to hold the rabbits, each cage olds one pair of rabbits. Assuming the rabbits are immortal, when will she run out of cages? -Print a nicely formatted table that shows: -Number of months that have passed -Number of adult rabbit pairs (those over 1 month old) -Number of baby rabbit pairs produced THIS month -Total number of rabbit pairs in the lab -Calculate how many months it will take until there are no more cages -Stop printing when you run out of cages -Print a message about how many months it takes to run out of cages Description of major steps of my solution: -Print a description of what the program does -Loop thru nicely printing information -Create accumulator variables initializing them with the starting months numbers -Calculate and update accumulator variables -Stop when we run out of cages (500) -Print how many months it took for the scientist to run out of cages Bullet list of what I learned: -I learned that this is a fibonacci pattern -I learned different ways to implement a fibonacci pattern (from google) ''' def printIntro(cages): # Print a description of what the table is and when it stops print('This program shows a table of rabbit pairs in') print('a certain scientist\'s lab.') print('It stops when the total number of rabbits') print('has surpassed the number of cages ({}).'.format(cages)) print() def createTable(cages): # Create some initial helper variables for printing seperator = '+-------+--------+--------+-------+' header = '| Month | Adults | Babies | Total |' firstMonth = '| {:>5} | {:>6} | {:>6} | {:>5} |'.format(1, 1, 0, 1) width = len(seperator) # Print the table, calculating the adults, babies, total on each loop print('{:^{w}}'.format('Rabbit Pairs', w=width)) print(seperator) print(header) print(seperator) print(firstMonth) month = 1 adults = [1, 1] babies = [0, 1] total = 1 while total < cages: # Using month-1 for indexes because lists start at index 0 # Makes use of pythons negative indices to get the last 2 numbers month += 1 adults.append(adults[-2] + adults[-1]) babies.append(babies[-2] + babies[-1]) total = adults[month-1] + babies[month-1] print('| {:>5} | {:>6} | {:>6} | {:>5} |'.format( month, adults[month-1], babies[month-1], total)) print(seperator) return month def printResults(month): # Print the month when the cages will run out # The whole program is actually dynamic according to how many cages there are (in main) print() print('Cages will run out in month {}.'.format(month)) def main(): cages = 3000 printIntro(cages) month = createTable(cages) printResults(month) if __name__ == '__main__': main() print() input("Press any key to continue . . . ") <file_sep># speeding.py # This program determines if you are speeding, and what you owe. def main(): base = 50 mphOver = 5 over90 = 200 limit = float(input('Enter speed limit (mph): ')) speed = float(input('Enter clocked speed (mph): ')) if speed <= limit: print('That speed was legal.') else: speedOver = speed - limit fine = base + (mphOver * speedOver) if speed > 90: fine += 200 print('That speed was illegal. Total fine: ${:.2f}'.format(fine)) if __name__ == '__main__': main() input("Press any key to continue . . . ") <file_sep># volleyball.py # Modified version of raquetball.py with changes for volleyball's rally scoring from random import random def printIntro(): # Changed intro to volleyball, and use teams instead of players print('This program simulates a game of volleyball between two') print('teams called "A" and "B" using rally scoring. The ability') print('of each team is indicated by a probability (a number between') print('0 and 1) that a team wins a point. Team A always starts serving.') def getInputs(): # Changed from "player" to "team" a = float(input('What is the probability team A wins a point? ')) b = float(input('What is the probability team B wins a point? ')) n = int(input('How many games to simulate? ')) return a, b, n def simNGames(n, probA, probB): # Simplified it without the probabilities winsA = winsB = 0 for i in range(n): scoreA, scoreB = simOneGame(probA, probB) if scoreA > scoreB: winsA += 1 else: winsB += 1 return winsA, winsB def simOneGame(probA, probB): # Changed it so that either team can get a point, not just the serving serving = 'A' scoreA = 0 scoreB = 0 while not gameOver(scoreA, scoreB): if serving == 'A': if random() < probA: scoreA += 1 else: scoreB += 1 serving = 'B' else: if random() < probB: scoreB += 1 else: scoreA += 1 serving = 'A' return scoreA, scoreB def gameOver(a, b): # Main change - one team has to have 25 points, and the difference must be # greater than or equal to 2 return (a >= 25 or b >= 25) and abs(a - b) >= 2 def printSummary(winsA, winsB): # Prints a summary of wins for each player. n = winsA + winsB print('\nGames simulated:', n) print('Wins for A {0} ({1:0.1%})'.format(winsA, winsA/n)) print('Wins for B {0} ({1:0.1%})'.format(winsB, winsB/n)) def main(): printIntro() probA, probB, n = getInputs() winsA, winsB = simNGames(n, probA, probB) printSummary(winsA, winsB) if __name__ == '__main__': main() input("Press any key to continue . . . ") <file_sep># twoCircles.py # Takes user input for the center position and radius for two circles # and draws them on a 400x400 GraphWin. from graphics import * def main(): print('This program takes input for the center position and radius') print('for two circles and draws them on a 400x400 GraphWin.') c1x = float(input('Circle 1 center x-position: ')) c1y = float(input('Circle 1 center y-position: ')) c1Rad = int(input('Circle 1 radius: ')) c2x = float(input('Circle 2 center x-position: ')) c2y = float(input('Circle 2 center y-position: ')) c2Rad = int(input('Circle 2 radius: ')) win = GraphWin('Two Circles', 400, 400) Circle(Point(c1x, c1y), c1Rad).draw(win) Circle(Point(c2x, c2y), c2Rad).draw(win) win.getMouse() main() # if math.sqrt((c2x-c2y)** + (c2y-c1y)**) <= c1Rad + c2Rad: # areOverlapped = True <file_sep># convert.py # A program to convert Celsius temps to Fahrenheit def main(): print("This program converts Celsius to Fahrenheit every 10 degrees from 0-100.") print("C | F") for celsius in range(0, 101, 10): fahrenheit = 9/5 * celsius + 32 print(celsius, "|", fahrenheit) main() input("Press any key to continue . . . ") <file_sep># politician.py # This program checks if you can be a senator and/ or a representative according to your age. def main(): senatorAge = 30 senatorCit = 9 representativeAge = 25 representativeCit = 7 age = int(input('Enter age: ')) citizenship = int(input('Enter years of citizenship: ')) if (age >= senatorAge) and (citizenship >= senatorCit): print('You are eligible to be a US senator.') if (age >= representativeAge) and (citizenship >= representativeCit): print('You are eligible to be a US representative.') else: print('Sorry, you are not eligible to be a US senator or representative.') if __name__ == '__main__': main() input("Press any key to continue . . . ") <file_sep># random_walk.pyw ''' File Prologue Identifying information: Name: <NAME> Course: CS-1400-001 Professor: <NAME> Project Title: Random Walk Due Date: March 31, 2018 Restatement of original problem: Create a Monte Carlo simulation using pseudorandom number generator (python's random module). Ask the user how many steps they want to take. To make a step, we first make a random angle using angle = random() * math.pi * 2, then to get the x and y components we use the equations x += cos(angle) and y += sin(angle). In a unit grid of size 100x100, start at 0,0 and draw a line between each step (for however many steps the user inputted). At the end, the program should print out the displacement, and the total distance traveled, rounded to the nearest whole unit. Description of major steps of my solution: I first created a main function, and other functions I thought might work (top-down), but eventually decided to try to make a class since that's what we've been learning in chapter 10. I then made the constructor function, and several instance variables I knew I would need such as a tracker, the GraphWin itself, and an Entry object. Then I created some methods for the class, like getInput, and walkStep. getInput validates the user input to make sure it's a number, and then does one more check to make sure it is greater than 0. walkStep is where the main functionality of the project happens. Then I made a function to show the results of the simulation. Finally, I added some extra "quality of life" adjustments to the program, such as showing the starting and ending position, and making a quit button. Bullet list of what I learned: - Not exactly related to the project, but I learned that if you have a long string that you want to make spanding over several lines, you can just use parenthesis and the string will still be valid, e.g.: txt = ('This is a test ' 'string.') will print: This is a test string. - I learned how to use the GraphWin.setCoords() method better. - I learned/figured out that you can still use a single unit for this project, but the unit can be longer than just 1 pixel. (using graphwin's setCoords). - I learned further how to use classes (this is my first attempt since reading ch. 10). ''' from math import pi, cos, sin, sqrt from random import random from graphics import * from button import Button class WalkWin: """ WalkWin is a modified GraphWin that has a unit graph of 100x100, an Entry object that accepts an int, a display text, and a quit button. """ def __init__(self, updateSpeed): self.win = GraphWin('Random Walk', 600, 750, autoflush=False) # set coordinates so 0,0 will be the center of the graph self.win.setCoords(-50,-75, 50,50) # draw a line to seperate graph from input/text Line(Point(-50,-50), Point(50,-50)).draw(self.win) # draw center point center = Circle(Point(0, 0), 0.5) center.setOutline('blue') center.setFill('blue') center.draw(self.win) Text(Point(-4, -54), 'Steps:').draw(self.win) self.input = Entry(Point(4,-54), 4) self.input.setFill('light gray') self.input.setText('100') self.input.setFace('courier') self.input.draw(self.win) txt = 'Enter number of steps to simulate. Press <Enter> to start.' self.displayText = Text(Point(0, -61), txt) self.displayText.draw(self.win) self.tracker = Point(0, 0) self.updateSpeed = updateSpeed self.totalDistance = 0 self.quitButton = Button(self.win, Point(0, -71), 10, 6, 'Quit') def getInput(self): """ Gets the input if it is a positive integer. """ # input validation loop while True: while True: # input modal key = self.win.getKey() if key == 'Return': break try: num = int(self.input.getText()) if num <= 0: self.displayText.setText('Number of steps must be a positive integer.') continue Text(self.input.getAnchor(), str(num)).draw(self.win) self.input.undraw() return num except: self.displayText.setText('Number of steps must be a positive integer.') def walkStep(self, angle): """ Draws a line between the current position and the new position. Updates the totalDistance instance variable. """ # store old x and y so we can draw a line x = self.tracker.getX() y = self.tracker.getY() # calculate the new step, move the tracker, and add the distance in our instance variable dx = cos(angle) dy = sin(angle) self.totalDistance += sqrt(dx * dx + dy * dy) self.tracker.move(dx, dy) # finally, draw the line with the created values Line(Point(x,y), self.tracker).draw(self.win) update(self.updateSpeed) def displayResults(self): """ Displays the total distance and displacement, also shows the final location of the tracker. """ # display total distance, and displacement distanceStr = str(round(self.totalDistance)) displacement = sqrt(self.tracker.getX()**2 + self.tracker.getY()**2) displacementStr = str(round(displacement)) txt = ('Total distance traveled: {} units.\n' 'Displacement (straight-line distance): {} units.' ).format(distanceStr, displacementStr) self.displayText.setText(txt) finalPos = Circle(self.tracker, 0.5) finalPos.setOutline('red') finalPos.setFill('red') finalPos.draw(self.win) finalLine = Line(Point(0,0), self.tracker) finalLine.setOutline('red') finalLine.draw(self.win) def quit(self): """ Waits for the user to click the quit button (or X button on window). """ self.quitButton.activate() while True: try: # added this try so that if they click X it doesnt crash with error. pt = self.win.getMouse() if self.quitButton.clicked(pt): self.win.close() return except: return def main(): FPS = 60 randWalk = WalkWin(FPS) num = randWalk.getInput() for i in range(num): angle = random() * pi * 2 randWalk.walkStep(angle) randWalk.displayResults() randWalk.quit() if __name__ == '__main__': main() <file_sep># target.py from graphics import * from random import randrange class Target: """ Creates a randomly sized rectangle somewhere downrange in the animation. When a target is hit, a new target is generated. """ def __init__(self, win): """ win is the GraphWin to draw in. This assumes "downrange" on the x-axis is somewhere between 10 and 210. """ self.xmin = 10 self.xmax = 255 self.ymin = 0 self.ymax = 155 self.sizeMin = 3 self.sizeMax = 40 self.createRect() def createRect(self): """ Creates a rectangle with appropriate sizes/positions. """ width = randrange(self.sizeMin, self.sizeMax) height = randrange(self.sizeMin, self.sizeMax) # bottom-left self.blX = randrange(self.xmin, self.xmax - width) self.blY = randrange(self.ymin, self.ymax - height) # top-right self.trX = self.blX + width self.trY = self.blY + height self.rect = Rectangle(Point(self.blX,self.blY), Point(self.trX,self.trY)) self.rect.setFill('gray') self.rect.draw(win) def update(self, pt): """ Deletes the target if it was hit, and creates a new target. """ if (self.blX <= pt.getX() <= self.trX and self.blY <= pt.getY() <= self.trY): self.rect.undraw() self.createRect() <file_sep># simpleTip.py ''' <NAME> CS-1400-001 Professor <NAME> January 20, 2018 Project 1 - Simple Tip Calculator This program takes a user-inputted cost of a meal, and calculates several tip amount possibilities. Gets the input of the total cost of the meal, and prints 4 lines of information. Excellent service is 20% Average service is 15% Poor service is 10% ''' def main(): cost = float(input('Enter the cost of the meal: $')) excellentTip = cost * .20 averageTip = cost * .15 poorTip = cost * .10 excellentTotal = cost + excellentTip averageTotal = cost + averageTip poorTotal = cost + poorTip print('Cost of meal: ${:.2f}'.format(cost)) print('Excellent Service tip: ${:.2f} total: ${:.2f}'.format(excellentTip, excellentTotal)) print('Average Service tip: ${:.2f} total: ${:.2f}'.format(averageTip, averageTotal)) print('Poor Service tip: ${:.2f} total: ${:.2f}'.format(poorTip, poorTotal)) main() input("Press any key to continue . . . ") <file_sep># shuffle.py from random import random, randrange def shuffle(ls): newList = [] while len(ls) > 0: j = randrange(0, len(ls)) # this gets rid of the item from the original list newItem = ls.pop(j) newList.append(newItem) return newList myList = ['shoes', 'socks', 'pants', 'gloves', 'shirt'] print(shuffle(myList)) input("Press any key to continue . . . ") <file_sep># chaos.py # A simple program illustrating chaotic behavior. def main(): print("This program illustrates a chaotic function") x = float(input("Enter a number between 0 and 1: ")) y = float(input("Enter a second number: ")) print(str(x), "|", str(y)) for i in range(10): x = 3.9 * x * (1 - x) y = 3.9 * y * (1 - x) print(str(x) + " | " + str(y)) main() input("Press any key to continue . . . ") <file_sep># dice.py from random import * def main(): yahtzees = 0 for i in range(100000): dice = [randrange(1, 7) for die in range(5)] # quick trick I found on google for seeing if all the items in a list are the same if len(set(dice)) == 1: yahtzees += 1 print(yahtzees, 'yahtzees out of 100,000 tries.') if __name__ == '__main__': main() input("Press any key to continue . . . ") <file_sep># fluffshuffle.py ''' File Prologue Identifying information: Name: <NAME> Course: CS-1400-001 Professor: <NAME> Project Title: Payroll Shuffle Due Date: April 14, 2018 Restatement of original problem: An internet company by the name of "FluffShuffle Electronics" wants a payroll program that shows a summary of each employee. The owner of FluffShuffle has specified that there are currently 6 emplyees, and they don't expect significant growth, but may employ more people in the future. The employee list will be kept as a text file. The program will read the data and calculate the employees salary (net pay) by deducting 20% for Federal income tax, and 7.5% for State income tax. The program needs to read the data, and show the following attributes about each employee: 1. Employee number 2. Name 3. Street address 4. Hourly wage 5. Hours worked this week 6. Net pay for that week (calculated from the information given) The GUI should clearly show each attribute and it's value. The program should be able to let the user open a text file with a tkinter dialog. There should be a "next" and "previous" button. Description of major steps of my solution: I first drew and listed everything out on a scratch piece of paper, such as how the GraphWin would look, what classes I would need, what instance variables and methods those classes needed, etc. Then I made the Employee class, given the specification. To calculate the salary of employees with overtime, I used the modulos operator. Then I moved on and started the Payroll class which does the majority of the logic. The Payroll class creates a list of Employee objects from a text string which is created from a file object that the user chooses. The Payroll's constructor also creates a dictionary to store the text labels for the Employee attributes. It also creates the labels for the text labels (like the string literal "Employee Number"), as well as the 3 buttons. I made several helper methods to keep the code clean and more readable. For the labels I created some formatted strings to make displaying the text neater. The run() method is the main event loop. It gets clicks from the user, deactivates/activates buttons, and updates the current employee shown to the screen. Bullet list of what I learned: - I learned that askopenfilename returns a string instead of a file object. - I learned further how objects can interact with eachother and use methods from other classes in a list. - I learned you're never supposed to pass "self" when calling a method inside of the __init__ method (d'oh). - I learned/figured out how to calculate overtime for employees with over 40 hours. ''' from button import Button from tkinter.filedialog import askopenfilename from graphics import * class Employee: """An employee is an object that knows it's ID, name, address, wage, and hoursWorked, as well as it's salary.""" def __init__(self, ID, name, address, wage, hoursWorked): """Creates an Employee. Args: ID: The employee's number. name: The employee's name. address: The employee's address. wage: The wage they are given. hoursWorked: The hours they worked this week. Note that it can be over 40. Returns: An Employee object. """ self.ID = ID self.name = name self.address = address self.wage = wage self.hoursWorked = hoursWorked self.salary = self.calcSalary() def calcSalary(self): """Calculates an employee's salary based on hours worked and wage. Any overtime is counted as "a time and a half". Returns: Their salary for this week. """ hours = self.hoursWorked overtime = 0 # change if they worked overtime if self.hoursWorked > 40: overtime = self.hoursWorked % 40 hours = 40 gross = (hours * self.wage) + overtime * (self.wage * 1.5) # account for taxes using percentages federalTax = 0.20 * gross stateTax = 0.075 * gross return gross - federalTax - stateTax def getID(self): """Returns employee's ID.""" return self.ID def getName(self): """Returns employee's name.""" return self.name def getAddress(self): """Returns employee's address.""" return self.address def getWage(self): """Returns employee's wage.""" return self.wage def getHoursWorked(self): """Returns how many hours the employee has worked this week.""" return self.hoursWorked def getSalary(self): """Returns employee's salary.""" return self.salary class Payroll: """The main program class. The event loop is in the run() method.""" def __init__(self): """Creates the appropriate GraphWin, Buttons, Text labels. It creates a list where employees will be placed.""" self.win = GraphWin('Fluff Shuffle Electronics', 540, 420) self.drawStaticText() self.previousButton = Button(self.win, Point(270-100,380), 80, 30, 'Previous') self.nextButton = Button(self.win, Point(270+100,380), 80, 30, 'Next') self.quitButton = Button(self.win, Point(504,400), 60, 30, 'Quit') dataFile = askopenfilename() dataText = self.readFile(dataFile) # if the file didn't read properly, don't continue if (not dataText): return self.employees = self.createEmployees(dataText) self.currentEmployeeIndex = 0 self.attributeTexts = self.createAttributeTexts() self.displayEmployeeInfo() self.nextButton.activate() self.quitButton.activate() def createAttributeTexts(self): """This method creates the attribute texts that will be displayed and updated when a new employee is selected. Returns: A dictionary of Text objects. """ textX = 380 textSize = 12 attributeTexts = { 'ID': None, 'name': None, 'address': None, 'wage': None, 'hours': None, 'salary': None } i = 0 for attribute in attributeTexts.keys(): txt = Text(Point(textX,90 + i*42 ), '') txt.setSize(textSize) txt.setFace('courier') txt.draw(self.win) i += 1 attributeTexts[attribute] = txt return attributeTexts def displayEmployeeInfo(self): """Updates the appropriate Text objects for the current employee.""" i = self.currentEmployeeIndex # set up the strings ID = '{:<25}'.format(self.employees[i].getID()) name = '{:<25}'.format(self.employees[i].getName()) address = '{:<25}'.format(self.employees[i].getAddress()) wage = '${:<24.2f}'.format(self.employees[i].getWage()) hours = '{:<25}'.format(self.employees[i].getHoursWorked()) salary = '${:<24.2f}'.format(self.employees[i].getSalary()) # this is where the the strings actually change self.attributeTexts['ID'].setText(ID) self.attributeTexts['name'].setText(name) self.attributeTexts['address'].setText(address) self.attributeTexts['wage'].setText(wage) self.attributeTexts['hours'].setText(hours) self.attributeTexts['salary'].setText(salary) def drawStaticText(self): """Draws the static text that will never change.""" # title self.drawText(270, 28, 32, 'Fluff Shuffle Payroll', bold=True) # labels used to indicate attributes of Employees labelX = 120 labelSize = 20 base = '{:>16}' self.drawText(labelX, 90, labelSize, base.format('Employee Number:')) self.drawText(labelX + 32, 132, labelSize, base.format('Name:')) self.drawText(labelX + 30, 174, labelSize, base.format('Address:')) self.drawText(labelX + 16, 216, labelSize, base.format('Hourly Wage:')) self.drawText(labelX + 12, 258, labelSize, base.format('Hours Worked:')) self.drawText(labelX + 32, 300, labelSize, base.format('Net Pay:')) def drawText(self, x, y, size, string, bold=False): """Helper method to draw text to the window.""" label = Text(Point(x,y), string) label.setSize(size) if bold: label.setStyle('bold') label.draw(self.win) def readFile(self, fileName): """This method opens the file, and returns a string of the text, then closes the file.""" try: file = open(fileName, 'r', encoding='utf-8') text = file.read() file.close() except: return False return text def createEmployees(self, text): """Parses the text for appropriate attributes, and adds employees to the employee list. Returns: A list of employees.""" emps = [] textList = text.split(sep='\n') while len(textList) >= 4: ID = int(textList.pop(0)) name = textList.pop(0) address = textList.pop(0) wageStr, hoursStr = textList.pop(0).split() wage = float(wageStr) hours = int(hoursStr) # this is where we add an employee emp = Employee(ID, name, address, wage, hours) emps.append(emp) return emps def run(self): """Main event loop.""" while True: try: pt = self.win.getMouse() except: self.win.close() return if self.previousButton.clicked(pt) and self.currentEmployeeIndex > 0: self.currentEmployeeIndex -= 1 self.displayEmployeeInfo() elif self.nextButton.clicked(pt) and self.currentEmployeeIndex < len(self.employees) - 1: self.currentEmployeeIndex += 1 self.displayEmployeeInfo() elif self.quitButton.clicked(pt): self.win.close() return # now update the button states if self.currentEmployeeIndex == 0: self.previousButton.deactivate() else: self.previousButton.activate() if self.currentEmployeeIndex == len(self.employees) - 1: self.nextButton.deactivate() else: self.nextButton.activate() def main(): Payroll().run() if __name__ == '__main__': main() <file_sep># triangle.pyw import math from graphics import * def square(x): return x**2 def distance(p1, p2): dist = math.sqrt(square(p2.getX() - p1.getX()) + square(p2.getY() - p1.getY())) return dist def calculateArea(a, b, c): s = (a+b+c)/2 return math.sqrt(s * (s-a) * (s-b) * (s-c)) def main(): win = GraphWin('Draw a Triangle') win.setCoords(0.0, 0.0, 10.0, 10.0) message = Text(Point(5, 1), 'Click on three points') message.draw(win) # Get and draw three vertices of triangle p1 = win.getMouse() p1.draw(win) p2 = win.getMouse() p2.draw(win) p3 = win.getMouse() p3.draw(win) # Use polygon object to draw the triangle triangle = Polygon(p1,p2,p3) triangle.setFill('peachpuff') triangle.setOutline('cyan') triangle.draw(win) # Calculate the perimeter and area of the triangle side1 = distance(p1,p2) side2 = distance(p2,p3) side3 = distance(p3,p1) perim = side1 + side2 + side3 area = calculateArea(side1, side2, side3) message.setText('The perimeter is: {:.2f}\nThe area is: {:.2f}'.format(perim, area)) # Wait for another click to exit win.getMouse() win.close() main() <file_sep># circleIntersection.py import math from graphics import * def main(): radius = float(input('Enter circle radius (1-10): ')) intercept = float(input('Enter y-intercept (1-10): ')) radicand = radius**2 - intercept**2 win = GraphWin('Circle Intersection', 500, 500) win.setCoords(-10, -10, 10, 10) Circle(Point(0, 0), radius).draw(win) Line(Point(-10, intercept), Point(10, intercept)).draw(win) if radicand > 0: intersect1x = -(math.sqrt(radicand)) intersect2x = math.sqrt(radicand) p1 = Point(intersect1x, intercept) p1.setOutline('red') p1.draw(win) p2 = Point(intersect2x, intercept) p2.setOutline('red') p2.draw(win) print('Intersections: {} {}'.format(intersect1x, intersect2x)) else: print('The line does not intersect the circle.') win.getMouse() if __name__ == '__main__': main() <file_sep># factorial.py # Program to compute the factorial of a number # Illustrates for loop with an accumulator def main(): n = int(input('Please enter a whole number: ')) fact = n print(n, end='') for factor in range(n-1,1,-1): fact *= factor print('*{}'.format(factor), end='') print(' =', fact) print('The factorial of', n, 'is', fact) main() input("Press any key to continue . . . ") <file_sep># avg.py # A simple program to average two exam scores. # Illustrates use of multiple input (simultaneous assignment). def main(): print("This program computes the average of three exame scores.") score1, score2, score3 = eval(input("Enter three scores each seperated by a comma: ")) average = (score1+score2+score3) / 3 print("The average of the scores is:", average) main() input("Press any key to continue . . . ") <file_sep># numerology.py # Determines the numeric value of a name based on summing the characters. def main(): alphabet = 'abcdefghijklmnopqrstuvwxyz' print('This program determins the numeric value of a name based on') print('summing the characters, with a = 1 and z = 26.') names = input('Enter name(s) seperated by spaces: ').lower().split() total = 0 for name in names: for ch in name: total += (alphabet.find(ch) + 1) print('Total numeric value:', total) main() input("Press any key to continue . . . ") <file_sep># GCD.py def computeGCD(m, n): while m != 0: n, m = m, n%m return n def main(): print('This program computes the Greatest Common Divisor of two numbers.') while True: try: num1 = int(input('Enter number 1: ')) num2 = int(input('Enter number 2: ')) break except: print('Invalid input.') GCD = computeGCD(num1, num2) print('The greates common divisor of {} and {} is: {}.'.format(num1, num2, GCD)) if __name__ == '__main__': main() input("Press any key to continue . . . ") <file_sep># CS-1400 Assignments and projects from CS-1400 I took at Utah Valley University. In order for most of these files to work on your machine, you need: - [Python 3.4 or above](https://www.python.org/downloads/) - The graphics.py module. The easiest way is to install this using pip from your command line: `pip install graphics.py`
7c36ca9f69badf9a80257cfa048bede7379bf75b
[ "Markdown", "Python" ]
33
Python
MatthewJulian/CS-1400
993add3b016f889642fdeab6bb085df3a3c87369
89daa3ff8defec16540ae40d25b142985b82eca5
refs/heads/master
<repo_name>elderz6/crypto<file_sep>/Crypto2.py def cript(texto1): texcript = "" i = 0 while i < len(texto1): cript = ord(texto1[i]) texcript = texcript + chr(cript + 5) print(texcript) i+=1 print("Decrypt?") check = input(str()) if (check == "y"): decript(texcript) elif (check == "n"): print("Closing") else: print("Invalid command") print("closing") def decript(texto2): i = 0 decript = "" while i < len(texto2): cript = ord(texto2[i]) decript = decript + chr(cript - 5) print(decript) i+=1 texto1 = input() cript(texto1)
74935e727b7397f89b736ecf30fdb81669e34897
[ "Python" ]
1
Python
elderz6/crypto
7edb3fdf27929cf40bb44558144658217de32613
48f3f8001cdd8bb06357f3be868e86917a520452
refs/heads/main
<file_sep>import { Component, OnInit } from '@angular/core'; import { Cours } from '../models/Cours'; import { CoursService } from '../services/cours.service'; @Component({ selector: 'app-cours-details', templateUrl: './cours-details.component.html', styleUrls: ['./cours-details.component.scss'], }) export class CoursDetailsComponent implements OnInit { private coursactuel: any; constructor(private courseService: CoursService) {} ngOnInit(): void { this.coursactuel; } getCourse(id: string) { this.courseService.getCourse('2').subscribe((cours) => { this.coursactuel = cours; }); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { CoursService } from './../services/cours.service'; import { ClassesService } from './../services/classes.service'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'], }) export class HomeComponent implements OnInit { courses: any; classes: any; currentClasse: ''; constructor( private courseService: CoursService, private classesService: ClassesService ) {} ngOnInit(): void { this.AllCourses(); this.AllClasses(); } AllCourses() { this.courseService.getAllCourses().subscribe((courses) => { this.courses = courses; console.log(this.courses); }); } AllClasses() { this.classesService.getAllClasses().subscribe((classes) => { this.classes = classes; console.log(this.classes); }); } setGlobalsCurrentClass() {} } <file_sep>// var currentClass = ''; // var currentSubject = ''; // var currentCourse = ''; // var currentCoursePath1 = currentClass + currentSubject + currentCourse; // export var globals = { // currentClass: '', // currentSubject: '', // currentCourse: '', // currentCoursePath: currentCoursePath1, // }; <file_sep>import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root', }) export class ClassesService { apiUrl: string = 'http://franklinduval.pythonanywhere.com/'; constructor(private http: HttpClient) {} getAllClasses() { return this.http.get(this.apiUrl + `api/classe`); } } <file_sep>import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root', }) export class CoursService { apiUrl: string = 'http://franklinduval.pythonanywhere.com/'; constructor(private http: HttpClient) {} getAllCourses() { return this.http.get(this.apiUrl + `api/course`); } getCourse(id: string) { return this.http.get(this.apiUrl + `api/course/` + id); } } <file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { PageNotFoundComponent } from './page-not-found/page-not-found.component'; import { CoursComponent } from './cours/cours.component'; import { ExamensComponent } from './examens/examens.component'; import { ExercicesComponent } from './exercices/exercices.component'; import { ContactsComponent } from './contacts/contacts.component'; import { AideComponent } from './aide/aide.component'; import { HomeComponent } from './home/home.component'; import { ClasseComponent } from './classe/classe.component'; import { CoursDetailsComponent } from './cours-details/cours-details.component'; const routes: Routes = [ { path: '', redirectTo: '/', pathMatch: 'full' }, { path: '', component: HomeComponent }, { path: 'home', component: HomeComponent }, { path: 'cours', component: CoursComponent }, { path: 'exercices', component: ExercicesComponent }, { path: 'examens', component: ExamensComponent }, { path: 'contacts', component: ContactsComponent }, { path: 'aide', component: AideComponent }, { path: 'classe/:id', component: ClasseComponent }, { path: 'classe/2/cours-detail', component: CoursDetailsComponent }, { path: '**', component: PageNotFoundComponent }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], }) export class AppRoutingModule {} export const routingComponents = [PageNotFoundComponent];
3d31d7b7242106be4da48c60c1f0fbff03b1a56a
[ "TypeScript" ]
6
TypeScript
tsopgniduhamel/skoole
62c9993881c1386c869c515b2098a92ef6bd2839
718b316b2ec193b4c5911e66a689e5d7d3ebb71e
refs/heads/main
<file_sep><?php declare(strict_types=1); namespace BrenoRoosevelt\Psr11; use Exception; use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; class CompositeContainer implements ContainerInterface { /** @var ContainerInterface[] */ private array $containers; public function __construct(ContainerInterface ...$containers) { $this->containers = $containers; } /** @inheritDoc */ public function get(string $id) { foreach ($this->containers as $container) { if ($container->has($id)) { return $container->get($id); } } $message = sprintf('Composite Container Exception: no entry was found for %s', $id); throw new class($message) extends Exception implements NotFoundExceptionInterface { }; } /** @inheritDoc */ public function has(string $id): bool { foreach ($this->containers as $container) { if ($container->has($id)) { return true; } } return false; } } <file_sep><?php declare(strict_types=1); namespace BrenoRoosevelt\Psr11\Tests; use BrenoRoosevelt\Psr11\CompositeContainer; use BrenoRoosevelt\Psr11\StaticContainer; use PHPUnit\Framework\TestCase; use Psr\Container\NotFoundExceptionInterface; class CompositeContainerTest extends TestCase { public function testGet(): void { $container = new CompositeContainer( new StaticContainer(['id1' => 'value1']), new StaticContainer(['id2' => 'value2']), ); $this->assertEquals('value1', $container->get('id1')); $this->assertEquals('value2', $container->get('id2')); } public function testGetException(): void { $container = new CompositeContainer( new StaticContainer(['id1' => 'value1']), new StaticContainer(['id2' => 'value2']), ); $this->expectException(NotFoundExceptionInterface::class); $container->get('invalid'); } public function testHas(): void { $container = new CompositeContainer( new StaticContainer(['id1' => 'value1']), new StaticContainer(['id2' => 'value2']), ); $this->assertTrue($container->has('id1')); $this->assertTrue($container->has('id2')); $this->assertFalse($container->has('id3')); } } <file_sep><?php declare(strict_types=1); namespace BrenoRoosevelt\Psr11; use Exception; use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; class StaticContainer implements ContainerInterface { private array $services; /** * @param array<string, mixed> $services */ public function __construct(array $services = []) { $this->services = $services; } /** @inheritDoc */ public function get(string $id) { if (! array_key_exists($id, $this->services)) { $message = sprintf('Static Container Exception: no entry was found for %s', $id); throw new class($message) extends Exception implements NotFoundExceptionInterface { }; } return $this->services[$id]; } /** @inheritDoc */ public function has(string $id): bool { return array_key_exists($id, $this->services); } } <file_sep># Null Container [![CI Build](https://github.com/brenoroosevelt/psr-nullcontainer/actions/workflows/ci.yml/badge.svg)](https://github.com/brenoroosevelt/psr-nullcontainer/actions/workflows/ci.yml) [![codecov](https://codecov.io/gh/brenoroosevelt/psr-nullcontainer/branch/main/graph/badge.svg?token=S1QBA18IBX)](https://codecov.io/gh/brenoroosevelt/psr-nullcontainer) [![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat)](LICENSE.md) Null Object Pattern for PSR-11 Container ## Requirements The following versions of PHP are supported: `7.4`, `8.0`, `8.1`. ## Install ```bash $ composer require brenoroosevelt/psr-nullcontainer ``` ## Usage ```php $container = new \BrenoRoosevelt\Psr11\NullContainer(); ``` ## License This project is licensed under the terms of the MIT license. See the [LICENSE](LICENSE.md) file for license rights and limitations. <file_sep><?php declare(strict_types=1); namespace BrenoRoosevelt\Psr11; use Exception; use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; class NullContainer implements ContainerInterface { public function get(string $id) { $message = sprintf('Null Container Exception: no entry was found for %s', $id); throw new class($message) extends Exception implements NotFoundExceptionInterface { }; } public function has(string $id): bool { return false; } } <file_sep><?php declare(strict_types=1); namespace BrenoRoosevelt\Psr11\Tests; use BrenoRoosevelt\Psr11\StaticContainer; use PHPUnit\Framework\TestCase; use Psr\Container\NotFoundExceptionInterface; class StaticContainerTest extends TestCase { public function testGet(): void { $container = new StaticContainer(['id' => 'value']); $this->assertEquals('value', $container->get('id')); } public function testGetException(): void { $this->expectException(NotFoundExceptionInterface::class); (new StaticContainer)->get('invalid'); } public function testHas(): void { $container = new StaticContainer(['id' => 'value']); $this->assertTrue($container->has('id')); $this->assertFalse($container->has('invalid')); } } <file_sep><?php declare(strict_types=1); namespace BrenoRoosevelt\Psr11\Tests; use BrenoRoosevelt\Psr11\NullContainer; use PHPUnit\Framework\TestCase; use Psr\Container\NotFoundExceptionInterface; class NullContainerTest extends TestCase { public function testGet(): void { $this->expectException(NotFoundExceptionInterface::class); (new NullContainer)->get('any'); } public function testHas(): void { $result = (new NullContainer)->has('any'); $this->assertFalse($result); } }
d69bf5eb9c2eeeb1a763a1135af2ac9704c942c1
[ "Markdown", "PHP" ]
7
PHP
brenoroosevelt/psr-nullcontainer
90043924c6495588c7ecdda40685b649a44399ba
a457c1116f25e474ad2db324247c6212d5bfca3e
refs/heads/master
<file_sep>package com.rabobank.controller; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import com.robobank.controller.RobobankController; import com.robobank.service.ExtractService; @RunWith(SpringRunner.class) @WebMvcTest class RobobankControllerTest { @Autowired private MockMvc mockMvc; @MockBean private ExtractService extractService; @InjectMocks private RobobankController robobankController; private InputStream is; @BeforeEach void setUp() throws Exception { MockitoAnnotations.initMocks(this); mockMvc = MockMvcBuilders.standaloneSetup(robobankController).build(); } @Test void testProcess() throws IOException, Exception { Map<Integer,String> records= new HashMap<Integer, String>(); records.put(112806,"duplicate record found in the statement"); is = robobankController.getClass().getClassLoader().getResourceAsStream("records.csv"); MockMultipartFile mockMultipartFile = new MockMultipartFile("file", "records.csv", "multipart/form-data", is); when(extractService.processStatement(mockMultipartFile)).thenReturn(records); mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/process") .contentType(MediaType.MULTIPART_FORM_DATA).content(mockMultipartFile.getBytes())) .andExpect(MockMvcResultMatchers.status().isBadRequest()) .andDo(MockMvcResultHandlers.print()); } @Test void testObjectToString() { Map<Integer,String> records= new HashMap<Integer, String>(); records.put(112806,"duplicate record found in the statement"); String str = robobankController.ObjectToString(records); assertEquals("","{\"112806\":\"duplicate record found in the statement\"}",str); } } <file_sep>package com.rabobank.exception; import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import com.robobank.exception.ServiceException; class ServiceExceptionTest { @InjectMocks private ServiceException serviceException; @BeforeEach void setUp() throws Exception { } } <file_sep>package com.robobank.controller; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.robobank.exception.ServiceException; import com.robobank.service.ExtractService; @RestController public class RobobankController { private static final Logger log = LoggerFactory.getLogger(RobobankController.class); @Autowired public ExtractService extractService; @PostMapping(value="/api/v1/process",consumes = { "multipart/form-data" }) public ResponseEntity<?> process(@RequestParam("file") MultipartFile multipart) { log.debug("inside rest Api process method "); Map<Integer,String> records=null; if (multipart.isEmpty()) { log.error("Empty file in the request "); return new ResponseEntity<String>(ObjectToString("Empty file input is provided"),HttpStatus.BAD_REQUEST); } else { try { records = extractService.processStatement(multipart); } catch (ServiceException e) { return new ResponseEntity<String>(e.getMessage(),HttpStatus.INTERNAL_SERVER_ERROR); } } return new ResponseEntity<String>(ObjectToString(records),HttpStatus.OK); } public String ObjectToString(Object obj) { String result = null; try { result = new ObjectMapper().writeValueAsString(obj); } catch (JsonProcessingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } } <file_sep>package com.robobank; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @ComponentScan(basePackages="com.*") @SpringBootApplication public class RobobankAssignmentDemo1Application { public static void main(String[] args) { SpringApplication.run(RobobankAssignmentDemo1Application.class, args); } } <file_sep><h1>Rabobank Customer Statement Processor</h1> Rabobank receives monthly deliveries of customer statement records. This information is delivered in two formats, CSV and XML. These records need to be validated. <div class="paragraph"> <p>The format of the file is a simplified version of the MT940 format. The format is as follows:</p> </div> <table class="tableblock frame-all grid-all spread"> <caption class="title">Table 1. Record description</caption> <colgroup> <col style="width: 50%;"> <col style="width: 50%;"> </colgroup> <thead> <tr> <th class="tableblock halign-left valign-top">Field</th> <th class="tableblock halign-left valign-top">Description</th> </tr> </thead> <tbody> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">Transaction reference</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">A numeric value</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">Account number</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">An IBAN</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">Start Balance</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">The starting balance in Euros</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">Mutation</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Either an addition (+) or a deduction (-)</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">Description</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Free text</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">End Balance</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">The end balance in Euros</p></td> </tr> </tbody> </table> <div class="sect1"> <h2 id="_output">Output</h2> <div class="sectionbody"> <div class="paragraph"> <p>There are two validations:</p> </div> <div class="ulist"> <ul> <li> <p>all transaction references should be unique</p> </li> <li> <p>the end balance needs to be validated</p> </li> </ul> </div> <div class="paragraph"> <p>At the end of the processing, a report needs to be created which will display both the transaction reference and description of each of the failed records.</p> </div> </div> </div> </div> <div id="footer"> </div> <h3>Steps to run the application:</h3> 1. Clone the project Rabobank (Spring boot project). git command : git clone https://github.com/rajshekar4/robobank-assignment 2. Run batch (run.bat) from your terminal/command prompt 3. it will do mvn clean install and runs all junit unit test cases and started the application. 4. Open any REST api testing tool (Postman app tool client/ postman chrome plugin(it will not work because csv/xml format) : http://localhost:8080/api/v1/process 5. Upload input csv/xml file in the service using postman client and select post 6. The input file will be validated based on two conduction mentioned in the problem statment.(validation condition mentioned in expected output section) Duplicate Transaction key check, End balance calculation check. (endbalance = startbalance – mutation) 7.Finally invalid/failure records will be sent as response of rest api. <H3>code coverage report : </h3> <img src="https://github.com/rajshekar4/robobank-assignment/blob/master/documentation/codecoverage.JPG"/> <H3>Screen shots</h3> <h2> End balance calculation check.</h2> <br> <img src="https://github.com/rajshekar4/robobank-assignment/blob/master/documentation/end_balance.JPG"/> <br> <h2> all transaction references should be unique. displaying failure records </h2> <br> <img src="https://github.com/rajshekar4/robobank-assignment/blob/master/documentation/duplicate_records.JPG"/> <br> <file_sep>package com.rabobank; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.robobank.RobobankAssignmentDemo1Application; class RobobankAssignmentDemo1ApplicationTest { @BeforeEach void setUp() throws Exception { } @Test void testMain() { RobobankAssignmentDemo1Application.main(new String[] {}); } }
7b2239ffc3d554beb32d103190302b4d49984c10
[ "Markdown", "Java" ]
6
Java
rajshekar4/robobank-assignment
fc9463808bfab4e23de0a9cb53f18929275daf06
b62827d0364ab0367bea75a210988a005e153a69
refs/heads/master
<repo_name>BenJacobsen/DeltaHacks<file_sep>/flask_implementation/global.py from flask import Flask, request, Response, g from frame import game, player def prompt_assign(num_players, prompts): return [[prompts[0], prompts[1]] for i in range(num_players)] app = Flask(__name__) @app.route('/api/login', methods=['POST']) def login(): # mutexify if g.gamer.players_in < g.gamer.max_players: g.gamer.players_in += 1 this_id = g.gamer.players_in g.gamer.players.append(player(g.gamer.players_in, request.data.name)) #await for others/ prompts to be assigned return Response(response=jsonpickle.encode({"data":{"id":g.gamer.players[this_id].id, "prompt":g.gamer.players[this_id][round_num]}, "errMsg": ""}), status=200, mimetype="application/json") else: return Response(response=jsonpickle.encode({"errMsg": "Too many in game"}), status=400, mimetype="application/json") @app.route('/', methods=['GET']) def base(): return g.max_players if __name__ == '__main__': g.gamer = game('localhost', ['Favorite Sport?', 'Favorite Food?'], prompt_assign) app.run(debug=True)<file_sep>/client-mc.py import socket import select import errno import sys import tkinter as tk class client_mc(tk.Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.pack() self.create_widgets() def submit(self, btn): if self.username == "": self.username = self.entry_text.get() print("yeee") self.subOption = btn self.submit_done = True def setStateLoading(self, stateText): self.text["text"] = stateText self.submitA["text"] = "A" self.entry.pack_forget() self.hide_interaction() def setStatePrompt(self, prompt): self.entry_text.set("") self.text["text"] = prompt self.show_interaction() self.submit_done = False def create_widgets(self): self.username = "" self.subOption = "" self.text = tk.Label(self, text = "Please input your username") self.text.pack() self.entry_text = tk.StringVar(self) self.entry = tk.Entry(self, bd = 5, textvariable = self.entry_text) self.entry.pack() self.submitA = tk.Button(self, text="Submit", fg="black", command = lambda :self.submit("A")) self.submitA.pack() self.submitB = tk.Button(self, text="B", fg="black", command = lambda :self.submit("B")) self.submit_done = False def update_text(self, text): self.text["text"] = text self.text.pack() def hide_interaction(self): self.submitA.pack_forget() self.submitB.pack_forget() def show_interaction(self): self.submitA.pack(side = 'left') self.submitB.pack(side = 'right') root = tk.Tk() ui = client_mc(master=root) while True: ui.update() ui.update_idletasks() if ui.submit_done: ui.setStateLoading("Waiting for other players...") ui.update() ui.update_idletasks() break HEADER_LENGTH = 10 IP = "127.0.0.1" PORT = 1234 my_username = ui.username print("done") #my_username = "ben" # Create a socket # socket.AF_INET - address family, IPv4, some otehr possible are AF_INET6, AF_BLUETOOTH, AF_UNIX # socket.SOCK_STREAM - TCP, conection-based, socket.SOCK_DGRAM - UDP, connectionless, datagrams, socket.SOCK_RAW - raw IP packets client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect to a given ip and port client_socket.connect((IP, PORT)) # Set connection to non-blocking state, so .recv() call won;t block, just return some exception we'll handle client_socket.setblocking(False) # Prepare username and header and send them # We need to encode username to bytes, then count number of bytes and prepare header of fixed size, that we encode to bytes as well username = my_username.encode('utf-8') username_header = f"{len(username):<{HEADER_LENGTH}}".encode('utf-8') client_socket.send(username_header + username) #send username #if user_message: # Encode message to bytes, prepare header and convert to bytes, like for username above, then send #user_message = message.encode('utf-8') #user_message_header = f"{len(user_message):<{HEADER_LENGTH}}".encode('utf-8') #client_socket.send(user_message_header + user_message) while True: try: # Now we want to loop over received messages (there might be more than one) and print them while True: # Receive our "header" containing username length, it's size is defined and constant prompt_header = client_socket.recv(HEADER_LENGTH) # If we received no data, server gracefully closed a connection, for example using socket.close() or socket.shutdown(socket.SHUT_RDWR) if not len(prompt_header): print('Connection closed by the server') sys.exit() prompt_length = int(prompt_header.decode('utf-8').strip()) prompt = client_socket.recv(prompt_length).decode('utf-8') # Print message TURN INTO GENERAL FUNCTION ui.setStatePrompt(f'{prompt}') while True: ui.update() ui.update_idletasks() if ui.submit_done: ui.setStateLoading("Waiting for other players to respond...") ui.update() ui.update_idletasks() break # Wait for user to input a message message = ui.subOption #message = input(f'{res_pretext} > ') # If message is not empty - send it if message: # Encode message to bytes, prepare header and convert to bytes, like for username above, then send message = message.encode('utf-8') message_header = f"{len(message):<{HEADER_LENGTH}}".encode('utf-8') client_socket.send(message_header + message) except IOError as e: # This is normal on non blocking connections - when there are no incoming data error is going to be raised # Some operating systems will indicate that using AGAIN, and some using WOULDBLOCK error code # We are going to check for both - if one of them - that's expected, means no incoming data, continue as normal # If we got different error code - something happened if e.errno != errno.EAGAIN and e.errno != errno.EWOULDBLOCK: print('Reading error: {}'.format(str(e))) sys.exit() # We just did not receive anything continue except Exception as e: # Any other exception - something happened, exit print('Reading error: '.format(str(e))) sys.exit()<file_sep>/test_vote.py from frame import game, player IP = "127.0.0.1" prompts = ['Pick'] def prompt_assign(game): return [game.prompts for i in range(game.num_players)] def round_start_func(game): print("Which drink do you prefer?") print('A : Coke') print('B : Pepsi') def round_end_func(game): print('Round' + str(game.round_num)+ ':') for key in game.player_keys: #answer = game.players[key].responses[game.round_num - 1] == '0' ? 'A' : 'B' print(game.players[key].name + ' answered: ' + game.players[key].responses[game.round_num - 1]) def end_func(game): print('Round ' + str(game.max_rounds)+ ':') for key in game.player_keys: print(game.players[key].name + ' answered: ' + game.players[key].responses[game.max_rounds - 1]) print("GAME OVER") max_players = 2 max_rounds = 1 if __name__ == '__main__': new_game = game(IP, prompts, prompt_assign, round_start_func, round_end_func, end_func, max_players, max_rounds) new_game.start()<file_sep>/README.md Library for making jackbox-like games on web server. Research things needed for bare-bones implementation (Host connect to individual user, are sockets needed? Basic auth to identify answers by each player. Library creates server but need config file for port and url. Stick to text but make player response data general. Difficulty comes from making this scalable, only provide functions for web app communication or have html templates like angular make in node.js or flask, learn how to make a library, how much has to be accounted for? frontend and backend assuming we provide login/ response components. <file_sep>/test.py from frame import game, player IP = "127.0.0.1" prompts = ['Favorite Sport?', 'Favorite Food?'] def prompt_assign(game): return [[game.prompts[0], game.prompts[1]] for i in range(game.num_players)] def round_start_func(game): return def round_end_func(game): print('Round' + str(game.round_num)+ ':') for key in game.player_keys: print(game.players[key].name + ' said: ' + game.players[key].responses[game.round_num - 1]) def end_func(game): print("GAME OVER") print("ROUND RECAPS:") for i in range(1, game.round_num + 1): print('Round ' + str(i) + ':') for key in game.player_keys: print(game.players[key].name + ' said: ' + game.players[key].responses[i - 1]) max_players = 2 max_rounds = 2 if __name__ == '__main__': new_game = game(IP, prompts, prompt_assign, round_start_func, round_end_func, end_func, max_players, max_rounds) new_game.start()<file_sep>/frame.py import socket import select HEADER_LENGTH = 10 PORT = 1234 class player: def __init__(self, name): self.name = name self.prompts = [] self.responses = [] class game: def __init__(self, url, prompts, prompt_assign_func, round_start_func, round_end_func, end_func, max_players, max_rounds): #front_end self.players = {} self.player_keys = [] self.num_players = 0 self.round_num = 0 self.num_answers = 0 self.IP = url self.prompts = prompts self.prompt_assign_func = prompt_assign_func self.round_start_func = round_start_func self.round_end_func = round_end_func self.end_func = end_func self.max_players = max_players self.max_rounds = max_rounds def setup_after_login(self): sorted_prompts = self.prompt_assign_func(self) for i in range(0, len(self.player_keys)): self.players[self.player_keys[i]].prompts = sorted_prompts[i] if self.max_rounds == 0: for prompt in sorted_prompts: if len(prompt) > self.max_rounds: self.max_rounds = len(prompt) def start(self): # Create a socket # socket.AF_INET - address family, IPv4, some otehr possible are AF_INET6, AF_BLUETOOTH, AF_UNIX # socket.SOCK_STREAM - TCP, conection-based, socket.SOCK_DGRAM - UDP, connectionless, datagrams, socket.SOCK_RAW - raw IP packets server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # SO_ - socket option # SOL_ - socket option level # Sets REUSEADDR (as a socket option) to 1 on socket server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Bind, so server informs operating system that it's going to use given IP and port # For a server using 0.0.0.0 means to listen on all available interfaces, useful to connect locally to 127.0.0.1 and remotely to LAN interface IP server_socket.bind((self.IP, PORT)) # This makes server listen to new connections server_socket.listen() # List of sockets for select.select() #sockets_list = [server_socket] sockets_list = [] server_list = [server_socket] # List of connected clients - socket as a key, user header and name as data print(f'Listening for connections on {self.IP}:{PORT}...') def receive_login(client_socket): try: # Receive our "header" containing message length, it's size is defined and constant message_header = client_socket.recv(HEADER_LENGTH) # If we received no data, client gracefully closed a connection, for example using socket.close() or socket.shutdown(socket.SHUT_RDWR) if not len(message_header): return False # Convert header to int value message_length = int(message_header.decode('utf-8').strip()) name = str(client_socket.recv(message_length)) # Return an object of message header and message data return player(name[2:-1]) #return {'header': message_header, 'data': client_socket.recv(message_length)} except: # If we are here, client closed connection violently, for example by pressing ctrl+c on his script # or just lost his connection # socket.close() also invokes socket.shutdown(socket.SHUT_RDWR) what sends information about closing the socket (shutdown read/write) # and that's also a cause when we receive an empty message return False # Handles message receiving def receive_response(client_socket): try: # Receive our "header" containing message length, it's size is defined and constant message_header = client_socket.recv(HEADER_LENGTH) # If we received no data, client gracefully closed a connection, for example using socket.close() or socket.shutdown(socket.SHUT_RDWR) if not len(message_header): return False # Convert header to int value message_length = int(message_header.decode('utf-8').strip()) # Return an object of message header and message data return str(client_socket.recv(message_length))[2:-1] except: # If we are here, client closed connection violently, for example by pressing ctrl+c on his script # or just lost his connection # socket.close() also invokes socket.shutdown(socket.SHUT_RDWR) what sends information about closing the socket (shutdown read/write) # and that's also a cause when we receive an empty message return False def perform_round(): for player_socket in self.player_keys: prompt = self.players[player_socket].prompts[self.round_num] prompt_header = f"{len(prompt):<{HEADER_LENGTH}}".encode('utf-8') player_socket.send(prompt_header + prompt.encode('utf-8')) self.round_num += 1 #Loop for accepting users while self.num_players < self.max_players or (self.round_num <= self.max_rounds and self.num_answers < self.num_players): # Calls Unix select() system call or Windows select() WinSock call with three parameters: # - rlist - sockets to be monitored for incoming data # - wlist - sockets for data to be send to (checks if for example buffers are not full and socket is ready to send some data) # - xlist - sockets to be monitored for exceptions (we want to monitor all sockets for errors, so we can use rlist) # Returns lists: # - reading - sockets we received some data on (that way we don't have to check sockets manually) # - writing - sockets ready for data to be send thru them # - errors - sockets with some exceptions # This is a blocking call, code execution will "wait" here and "get" notified in case any action should be taken read_sockets, _, exception_sockets = select.select(server_list + sockets_list, [], server_list + sockets_list) # Iterate over notified sockets for notified_socket in read_sockets: # If notified socket is a server socket - new connection, accept it if notified_socket == server_socket and self.num_players < self.max_players: # Accept new connection # That gives us new socket - client socket, connected to this given client only, it's unique for that client # The other returned object is ip/port set client_socket, client_address = server_socket.accept() if self.num_players >= self.max_players: #print() print("bad_login") continue # Client should send his name right away, receive it #print(player.name) #print(player.id) # If False - client disconnected before he sent his name #print(self.num_players) #print(self.max_players) self.num_players += 1 # Add accepted socket to select.select() list sockets_list.append(client_socket) # Also save username and username header self.players[client_socket] = receive_login(client_socket) print('Accepted new connection from {}:{}, username: {}.'.format(*client_address, self.players[client_socket].name)) if (self.num_players == self.max_players): self.player_keys = sockets_list self.setup_after_login() perform_round() self.round_start_func(self) # Else existing socket is sending a message else: #check if already answered if len(self.players[notified_socket].responses) == self.round_num - 1: self.num_answers += 1 self.players[notified_socket].responses.append(receive_response(notified_socket)) #everyone answered if self.num_answers == self.num_players and self.round_num < self.max_rounds: self.round_end_func(self) perform_round() self.round_start_func(self) self.num_answers = 0 # It's not really necessary to have this, but will handle some socket exceptions just in case for notified_socket in exception_sockets: # Remove from list for socket.socket() sockets_list.remove(notified_socket) #for key,value in self.players.items(): # print(key) #print(sockets_list[0]) #print(self.players[self.player_keys].responses[0]) self.end_func(self) # Remove from our list of users <file_sep>/sockets.py import socket import select from frame import game, player HEADER_LENGTH = 10 IP = "127.0.0.1" PORT = 1234 def prompt_assign(num_players, prompts): return [[prompts[0], prompts[1]] for i in range(num_players)] gamer = game('localhost', ['Favorite Sport?', 'Favorite Food?'], prompt_assign, 2) # Create a socket # socket.AF_INET - address family, IPv4, some otehr possible are AF_INET6, AF_BLUETOOTH, AF_UNIX # socket.SOCK_STREAM - TCP, conection-based, socket.SOCK_DGRAM - UDP, connectionless, datagrams, socket.SOCK_RAW - raw IP packets server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # SO_ - socket option # SOL_ - socket option level # Sets REUSEADDR (as a socket option) to 1 on socket server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Bind, so server informs operating system that it's going to use given IP and port # For a server using 0.0.0.0 means to listen on all available interfaces, useful to connect locally to 127.0.0.1 and remotely to LAN interface IP server_socket.bind((IP, PORT)) # This makes server listen to new connections server_socket.listen() # List of sockets for select.select() #sockets_list = [server_socket] sockets_list = [] server_list = [server_socket] # List of connected clients - socket as a key, user header and name as data print(f'Listening for connections on {IP}:{PORT}...') def receive_login(client_socket): try: # Receive our "header" containing message length, it's size is defined and constant message_header = client_socket.recv(HEADER_LENGTH) # If we received no data, client gracefully closed a connection, for example using socket.close() or socket.shutdown(socket.SHUT_RDWR) if not len(message_header): return False # Convert header to int value message_length = int(message_header.decode('utf-8').strip()) name = str(client_socket.recv(message_length)) # Return an object of message header and message data return player(name) #return {'header': message_header, 'data': client_socket.recv(message_length)} except: # If we are here, client closed connection violently, for example by pressing ctrl+c on his script # or just lost his connection # socket.close() also invokes socket.shutdown(socket.SHUT_RDWR) what sends information about closing the socket (shutdown read/write) # and that's also a cause when we receive an empty message return False # Handles message receiving def receive_response(client_socket): try: # Receive our "header" containing message length, it's size is defined and constant message_header = client_socket.recv(HEADER_LENGTH) # If we received no data, client gracefully closed a connection, for example using socket.close() or socket.shutdown(socket.SHUT_RDWR) if not len(message_header): return False # Convert header to int value message_length = int(message_header.decode('utf-8').strip()) # Return an object of message header and message data return str(client_socket.recv(message_length)) except: # If we are here, client closed connection violently, for example by pressing ctrl+c on his script # or just lost his connection # socket.close() also invokes socket.shutdown(socket.SHUT_RDWR) what sends information about closing the socket (shutdown read/write) # and that's also a cause when we receive an empty message return False def perform_round(): print("round") print(gamer.round_num) for player_socket in gamer.player_keys: prompt = gamer.players[player_socket].prompts[gamer.round_num] prompt_header = f"{len(prompt):<{HEADER_LENGTH}}".encode('utf-8') player_socket.send(prompt_header + prompt.encode('utf-8')) gamer.round_num += 1 #Loop for accepting users while gamer.num_players < gamer.max_players or (gamer.round_num <= gamer.max_rounds and gamer.num_answers < gamer.num_players): # Calls Unix select() system call or Windows select() WinSock call with three parameters: # - rlist - sockets to be monitored for incoming data # - wlist - sockets for data to be send to (checks if for example buffers are not full and socket is ready to send some data) # - xlist - sockets to be monitored for exceptions (we want to monitor all sockets for errors, so we can use rlist) # Returns lists: # - reading - sockets we received some data on (that way we don't have to check sockets manually) # - writing - sockets ready for data to be send thru them # - errors - sockets with some exceptions # This is a blocking call, code execution will "wait" here and "get" notified in case any action should be taken read_sockets, _, exception_sockets = select.select(server_list + sockets_list, [], server_list + sockets_list) # Iterate over notified sockets for notified_socket in read_sockets: # If notified socket is a server socket - new connection, accept it if notified_socket == server_socket and gamer.num_players < gamer.max_players: # Accept new connection # That gives us new socket - client socket, connected to this given client only, it's unique for that client # The other returned object is ip/port set client_socket, client_address = server_socket.accept() if gamer.num_players >= gamer.max_players: #print() print("bad_login") continue # Client should send his name right away, receive it #print(player.name) #print(player.id) # If False - client disconnected before he sent his name #print(gamer.num_players) #print(gamer.max_players) gamer.num_players += 1 # Add accepted socket to select.select() list sockets_list.append(client_socket) # Also save username and username header gamer.players[client_socket] = receive_login(client_socket) print('Accepted new connection from {}:{}, username: {}.'.format(*client_address, gamer.players[client_socket].name)) if (gamer.num_players == gamer.max_players): gamer.player_keys = sockets_list gamer.setup_after_login() perform_round() # Else existing socket is sending a message else: #client_socket, client_address = server_socket.accept() #print(gamer.players[notified_socket].name) #print(len(gamer.players[notified_socket].responses)) #print(gamer.round_num) if len(gamer.players[notified_socket].responses) == gamer.round_num - 1: gamer.num_answers += 1 print("here") gamer.players[notified_socket].responses.append(receive_response(notified_socket)) print(gamer.players[notified_socket].responses[0]) if gamer.num_answers == gamer.num_players and gamer.round_num < gamer.max_rounds: perform_round() gamer.num_answers = 0 # It's not really necessary to have this, but will handle some socket exceptions just in case for notified_socket in exception_sockets: # Remove from list for socket.socket() sockets_list.remove(notified_socket) #for key,value in gamer.players.items(): # print(key) #print(sockets_list[0]) #print(gamer.players[gamer.player_keys].responses[0]) print("GAME OVER") # Remove from our list of users
da36cb4209914a95aeb73c4f3747ae6d2c67a7fe
[ "Markdown", "Python" ]
7
Python
BenJacobsen/DeltaHacks
c7f9e6c0c1c38554a0254a3aa6b6cb2514a77cf0
adbc5d277ba5b680df998a58988878afd751abb3
refs/heads/master
<repo_name>longhuang318/adp_rl<file_sep>/scripts/maze_solver.py """ Approximate Dynamic Programming & Reinforcement Learning - WS 2018 Programming Assignment <NAME> 30.01.2019 Command necessary to test the code. python main.py maze.txt """ #from __future__ import division from maze_environment import Maze_env import numpy as np import matplotlib.pyplot as plt from matplotlib import cm # Determine whether goal state skipped or not. # This is implemented just for some tests. SKIP_GOAL_STATE = 0 GRUND_TRUTH = 0.99 class Maze_solver(object): def __init__(self): self.maze_env = Maze_env() self.policy = [] self.values = [] # initialize as zero. # holds the grund truth for both g1 and g2 respectively. self.gt_PI= [] self.gt_VI = [] self.algorithm_name = "" def read_file(self, path): """ Read the maze. :param path: :return: """ maze = [] with open(path) as f: for line in f.read().splitlines(): line = line.replace(" ", "") if not line.startswith("#"): maze.append(list(line)) self.maze_env.maze = maze self.maze_env.maze = np.asarray(self.maze_env.maze) self.maze_env.set_environment() def policy_evaluation(self, discount_factor, max_iteration, theta=1e-25): """ Runs the policy evaluation algorithm. :param discount_factor: :param max_iteration: :param theta: :return: returns the converged value function and total number of iterations. """ V = np.zeros(self.maze_env.nS) it_eval = 0 for i in range(max_iteration): delta = 0 it_eval += 1 # For each state, perform a "full backup" for s in range(self.maze_env.nS): v = 0 if s in self.maze_env.walls: continue # Look at the possible next actions for a, action_prob in enumerate(self.policy[s]): # For each action, look at the possible next states... for prob, next_state, reward, done in self.maze_env.P[s][a]: # Calculate the expected value. v += action_prob * prob * (reward + discount_factor * V[next_state]) # How much our value function changed (across any states) delta = max(delta, np.abs(v - V[s])) V[s] = v # Stop evaluating once our value function change is below a threshold if delta < theta: break return np.array(V), it_eval def policy_iteration(self, discount_factor, max_iteration): """ Runs the policy iteration algorithm. We first create random policy and then runs policy evaluation and policy improvement algorithms, respectively. :param discount_factor: :param max_iteration: :return: Returns the optimal policy and cost function with the total number of iterations. """ self.policy = self.create_random_policy() self.values = [] it = 0 while True: # Evaluation of current policy V, iter = self.policy_evaluation(discount_factor, max_iteration) # this will be set to false if we make any changes. self.values.append(V[self.maze_env.start]) optimal_policy = True it += 1 for s in range(self.maze_env.nS): # the walls also part of the state but we skip it since there can be no actions inside the wall. if s in self.maze_env.walls: continue chosen_a = np.argmax(self.policy[s]) A = self.values_of_actions(s, V, discount_factor) # Choose the best action which minimize the value function best_a = np.argmin(A) # Greedily update the policy if chosen_a != best_a: optimal_policy = False self.policy[s] = np.eye(self.maze_env.nA)[best_a] if optimal_policy or it == max_iteration: if discount_factor == GRUND_TRUTH: self.gt_PI.append(V[self.maze_env.start]) return self.policy, V, it def values_of_actions(self, state, V, discount_factor): """ For the given value function and the state and discount factor, returns the values of each available action on that state. :param state: :param V: values of state, array. :param discount_factor: :return: values of each available action on that state """ # Find the values of each action by looking successor states. A = np.zeros(self.maze_env.nA) av_ac = self.maze_env.available_actions(state) for a in range(self.maze_env.nA): if a in av_ac: for prob, next_state, reward, done in self.maze_env.P[state][a]: A[a] += prob * (reward + discount_factor * V[next_state]) else: A[a] = np.inf return A def value_iteration(self, discount_factor, max_iteration, theta=1e-25): """ Runs the value iteration algorithm. :param discount_factor: :param max_iteration: :param theta: :return: Returns the optimal policy, value function and total number of iteration for algorithm. """ V = np.zeros(self.maze_env.nS) it = 0 while it != max_iteration: # Condition for stop delta = 0 # increase the iteration it += 1 # Update each state for s in range(self.maze_env.nS): # the walls also part of the state but we skip it since there can be no actions inside the wall. if s in self.maze_env.walls: continue # Find the values of each action by looking successor states. A = self.values_of_actions(s, V, discount_factor) best_action_value = np.min(A) # Calculate delta across all states seen so far delta = max(delta, np.abs(best_action_value - V[s])) # Update the value function. Ref: Sutton book eq. 4.10. V[s] = best_action_value self.values.append(V[self.maze_env.t]) # Check if we can stop if delta < theta: break # Create "the" policy based on the optimal value function. policy = np.zeros([self.maze_env.nS, self.maze_env.nA]) for s in range(self.maze_env.nS): # the walls also part of the state but we skip it since there can be no actions inside the wall. if s in self.maze_env.walls: continue # Find the best action for this state using the corresponding values of each action. A = self.values_of_actions(s, V, discount_factor) best_action = np.argmin(A) # Always take the best action policy[s, best_action] = 1.0 if discount_factor == GRUND_TRUTH: self.gt_VI.append(V[self.maze_env.start]) return policy, V, it def create_random_policy(self): """ This function creates uniform random policy. :return: """ #self.policy = np.zeros([self.maze_env.nS, self.maze_env.nA]) policy = np.zeros([self.maze_env.nS, self.maze_env.nA]) it = np.nditer(self.maze_env.grid, flags=['multi_index']) while not it.finished: s = it.iterindex y, x = it.multi_index # Skip the transition probabilities for the wall. if self.maze_env.maze[y][x] == '1': it.iternext() continue # determine the available actions for the given state. actions = self.maze_env.available_actions(s) for a in actions: policy[s][a] = 1.0/len(actions) it.iternext() return policy def show_maze(self): """ This function call shows the maze, if it is needed. :return: """ plt.grid('on') nrows, ncols = self.maze_env.maze.shape ax = plt.gca() ax.set_xticks(np.arange(0.5, nrows+1, 1)) ax.set_yticks(np.arange(0.5, ncols+1, 1)) ax.set_xticklabels([]) ax.set_yticklabels([]) canvas = np.ones((nrows, ncols)) for var in range(len(self.maze_env.goal_loc[0])): row = self.maze_env.goal_loc[0][var] col = self.maze_env.goal_loc[1][var] canvas[row,col] = 0.5 for var in range(len(self.maze_env.start_loc[0])): row = self.maze_env.start_loc[0][var] col = self.maze_env.start_loc[1][var] canvas[row,col] = 0.3 for var in range(len(self.maze_env.traps_loc[0])): row = self.maze_env.traps_loc[0][var] col = self.maze_env.traps_loc[1][var] canvas[row,col] = 0.7 for var in range(len(self.maze_env.walls_loc[0])): row = self.maze_env.walls_loc[0][var] col = self.maze_env.walls_loc[1][var] canvas[row,col] = 0.0 canvas = np.array(canvas, dtype=float) img = plt.imshow(canvas, interpolation='none', cmap='gray') return img def plot_value_function(self, text): """ Plots the value function at start position with the number of iterations. :param text: :return: """ plt.clf() plt.plot(self.values) plt.ylabel('Values') plt.xlabel('Iterations') plt.title(text) plt.show() def plot_error(self, gt, values, title): """ Plots the squared distance error. :param gt: Ground truth :param values: Values of start position w.r.t the number of iterations. :param title: :return: """ #plt.clf() fig = plt.figure() errors = [] #gt = gt * np.ones(len(values)) #dist = np.linalg.norm(gt - values) for i in range(len(values)): errors.append(np.sqrt((gt-values[i])**2)) iter = range(1, len(values)+1) # plt.plot(iter, errors) plt.ylabel('Squared Distance') plt.xlabel('Iterations') plt.title(title) plt.tight_layout() title = title + "_error" directory = "plots/" #plt.savefig(title+"."+"png", format="png", dpi = 1200) #plt.savefig(directory+title+"."+"pdf", format="pdf", dpi = 1200) #plt.show() def visulaze_results(self, V, p, title, save = False, format = "png",): """ This function creates heatmap and quiver plot for the given value function and policy. :param V: "The" (optimal) value function. :param p: "The" (optimal) policy. :param title: Title of the plot. :param save: :param format: :return: """ #plt.clf() fig, ax = plt.subplots() nrows = self.maze_env.max_y ncols = self.maze_env.max_x V = np.reshape(V, (nrows, ncols)) p_shaped = np.reshape(np.argmax(p, axis=1), self.maze_env.shape) for var in range(len(self.maze_env.walls_loc[0])): row = self.maze_env.walls_loc[0][var] col = self.maze_env.walls_loc[1][var] V[row][col] = np.nan p_shaped[row][col] = -1 # masked array to hold walls masked_array = np.ma.array (V, mask=np.isnan(V)) current_cmap = cm.get_cmap() current_cmap.set_bad('black') im = ax.imshow(masked_array, cmap=current_cmap) plt.colorbar(im, fraction=0.046, pad=0.04) plt.title(title) y_pos = self.maze_env.ava_states[0] x_pos = self.maze_env.ava_states[1] x_direct, y_direct = self.helper_quiver_plot(p_shaped) ax.quiver(x_pos,y_pos,x_direct,y_direct, scale=20) plt.tight_layout() #directory = "plots/" #plt.savefig(title+"."+"png", format="png", dpi = 1200) #plt.savefig(directory+title+"."+"pdf", format="pdf", dpi = 1200) def helper_quiver_plot(self, p_shaped): """ This function helps to plot quiver. :param p_shaped: policy array with the shape of the maze. :return: """ x_direct = [] y_direct = [] for j in range(self.maze_env.max_y): for i in range(self.maze_env.max_x): # skip if it is a wall if p_shaped[j][i] == -1: continue # add the up. if p_shaped[j][i] == 0: x_direct.append(0) y_direct.append(1) # Right. elif p_shaped[j][i] == 1: x_direct.append(1) y_direct.append(0) # Down. elif p_shaped[j][i] == 2: x_direct.append(0) y_direct.append(-1) # Right. elif p_shaped[j][i] == 3: x_direct.append(-1) y_direct.append(0) # Idle elif p_shaped[j][i] == 4: x_direct.append(0) y_direct.append(0) return x_direct, y_direct <file_sep>/scripts/maze_environment.py """ Approximate Dynamic Programming & Reinforcement Learning - WS 2018 Programming Assignment <NAME> 30.01.2019 Command necessary to test the code. python main.py maze.txt """ import numpy as np UP = 0 RIGHT = 1 DOWN = 2 LEFT = 3 IDLE = 4 # Simulation parameters. # define the cost as minus and maximize the value function. COST_TRAP = 50 COST_ENERGY = 1 GOAL_REACHED = -1 # This is the probability of reaching adjacent states when the action is executed. PRO = 0.1 SKIP_GOAL_STATE = 0 class Maze_env(object): def __init__(self): # Matrix of lists to store the maze. self.maze = [] # Stores the maze with iteration numbers e.g. [1 2 3 ..\n 11 12 ... 79]. self.grid = [] # Stores the maze as a vector form. self.maze_vec = [] # Stores the dimensions of maze self.shape = [] # number of states self.nS = 0 # number of actions = {UP, RIGHT, DOWN, LEFT, IDLE}. self.nA = 5 # Maximum x direction of maze. self.max_y = 0 # Maximum y direction of maze. self.max_x = 0 # transition probability matrix. self.P = {} # location of start. self.start = 0 # location of goal in the maze. self.goal = 0 # Stores all the wall locations in the tuple. self.walls = () # Stores all the trap locations in the tuple. self.traps = () # Stores the goal location using coordinates e.g. (x, y) = (0, 1) self.goal_loc = () # Stores the start location using coordinates e.g. (x, y) = (0, 1) self.start_loc = () # Stores all the wall locations using coordinates e.g. (x, y) = (0, 1) self.walls_loc = () # Stores all the trap locations using coordinates e.g. (x, y) = (0, 1) self.traps_loc = () # Stores the available states self.ava_states = () def set_environment(self): """ Set the variables of environment. :return: """ self.shape = self.maze.shape self.nS = np.prod(self.shape) self.max_y = self.shape[0] self.max_x = self.shape[1] self.grid = np.arange(self.nS).reshape(self.shape) self.ava_states = np.where(self.maze != '1') itemindex_g = np.where(self.maze=='G') self.goal_loc = itemindex_g self.goal = self.grid[itemindex_g[0][0]][itemindex_g[1][0]] itemindex_s = np.where(self.maze=='S') self.start_loc = itemindex_s self.start = self.grid[itemindex_s[0][0]][itemindex_s[1][0]] itemindex_1 = np.where(self.maze=='1') self.walls_loc = itemindex_1 wall_list = [] for var in range(len(self.walls_loc[0])): wall_list.append(self.grid[itemindex_1[0][var]][itemindex_1[1][var]]) self.walls = tuple(wall_list) itemindex_t = np.where(self.maze=='T') self.traps_loc = itemindex_t trap_list = [] for var in range(len(self.traps_loc[0])): trap_list.append(self.grid[itemindex_t[0][var]][itemindex_t[1][var]]) self.traps = tuple(trap_list) self.maze_vec = self.maze.flatten() def build_transition_probability_matrix(self, cost_function): """ Set the transition probabilities for the given maze and const function :param cost_function: set the transition probability matrix using the given cost function. :return: """ it = np.nditer(self.grid, flags=['multi_index']) while not it.finished: s = it.iterindex y, x = it.multi_index # Skip the transition probabilities for the wall if self.maze[y][x] == '1': it.iternext() continue # P[s][a] = (prob, next_state, reward, is_done) self.P[s] = {a : [] for a in range(self.nA)} is_goal_reached = lambda s: s == self.goal # We're stuck in a terminal state if is_goal_reached(s): self.P[s][IDLE] = [(1.0, s, 0, True)] # Not a terminal state else: for a in self.available_actions(s): self.P[s][a] = self.determine_probabilities(s, a, cost_function) it.iternext() # if the next state is wall, then probability of that action is zero. # only available actions are input def determine_probabilities(self, state, a, cost_function): """ Determine the probabilities for the given state action set. Remind that the floor is slippery. :param state: Current state number. :param a: Action on the state. :return: List of possible actions for the given state and action. """ action_pro = [] is_goal_reached = lambda s: s == self.goal adjacents = 0 if a == UP: ns = state - self.max_x # left adjacent of next state because of the slippery floor. ns_l = ns-1 # right adjacent of next state because of the slippery floor. ns_r = ns+1 # then left adjacent of up is not wall. if self.maze.flat[ns_l] != '1': action_pro.append(tuple((PRO, ns_l, self.one_step_cost(state, ns_l, cost_function), is_goal_reached(ns_l)))) adjacents += 1 if self.maze.flat[ns_r] != '1': action_pro.append(tuple((PRO, ns_r, self.one_step_cost(state, ns_r, cost_function), is_goal_reached(ns_r)))) adjacents += 1 action_pro.append(tuple((1- adjacents*PRO, ns, self.one_step_cost(state, ns, cost_function), is_goal_reached(ns)))) elif a == RIGHT: ns = state+1 # left adjacent of next state because of the slippery floor. ns_l = ns-self.max_x # right adjacent of next state because of the slippery floor. ns_r = ns+self.max_x # then left adjacent of right is not wall. if self.maze.flat[ns_l] != '1': action_pro.append(tuple((PRO, ns_l, self.one_step_cost(state, ns_l, cost_function), is_goal_reached(ns_l)))) adjacents += 1 if self.maze.flat[ns_r] != '1': action_pro.append(tuple((PRO, ns_r, self.one_step_cost(state, ns_r, cost_function), is_goal_reached(ns_r)))) adjacents += 1 action_pro.append(tuple((1 - adjacents*PRO, ns, self.one_step_cost(state, ns, cost_function), is_goal_reached(ns)))) elif a == DOWN: ns = state + self.max_x # left adjacent of next state because of the slippery floor. ns_l = ns+1 # right adjacent of next state because of the slippery floor. ns_r = ns-1 # then left adjacent of right is not wall. if self.maze.flat[ns_l] != '1': action_pro.append(tuple((PRO, ns_l, self.one_step_cost(state, ns_l, cost_function), is_goal_reached(ns_l)))) adjacents += 1 if self.maze.flat[ns_r] != '1': action_pro.append(tuple((PRO, ns_r, self.one_step_cost(state, ns_r, cost_function), is_goal_reached(ns_r)))) adjacents += 1 action_pro.append(tuple((1- adjacents*PRO, ns, self.one_step_cost(state, ns, cost_function), is_goal_reached(ns)))) elif a == LEFT: ns = state - 1 # left adjacent of next state because of the slippery floor. ns_l = ns + self.max_x # right adjacent of next state because of the slippery floor. ns_r = ns - self.max_x # then left adjacent of right is not wall. if self.maze.flat[ns_l] != '1': action_pro.append(tuple((PRO, ns_l, self.one_step_cost(state, ns_l, cost_function), is_goal_reached(ns_l)))) adjacents += 1 if self.maze.flat[ns_r] != '1': action_pro.append(tuple((PRO, ns_r, self.one_step_cost(state, ns_r, cost_function), is_goal_reached(ns_r)))) adjacents += 1 action_pro.append(tuple((1- adjacents*PRO, ns, self.one_step_cost(state, ns, cost_function), is_goal_reached(ns)))) # If it is a IDLE action at the state. else: action_pro.append(tuple((1.0, state, self.one_step_cost(state, state, cost_function), is_goal_reached(state)))) return action_pro def available_actions(self, state): """ This function is necessary to determine the available actions for the given states. :param state: Current state in the maze. :return: List of actions that is available for that state. """ actions = [] ns_up = state - self.max_x ns_right = state + 1 ns_down = state + self.max_x ns_left = state - 1 # If goal state is reached actions.append(IDLE) if self.maze.flat[state] == 'G': return actions if self.maze.flat[ns_up] != '1': actions.append(UP) if self.maze.flat[ns_right] != '1': actions.append(RIGHT) if self.maze.flat[ns_down] != '1': actions.append(DOWN) if self.maze.flat[ns_left] != '1': actions.append(LEFT) return actions def one_step_cost(self, state, next_state, cost_function): """ This function exploits two cost functions where there is no cost for transitioning into the terminal goal state. Also implements cost for each action. :param state: Current state :param next_state: Next state :return: total cost for the action """ # define the initial cost as zero cost = 0 # Trap affects both costs. if self.maze.flat[next_state] == 'T': cost = cost + COST_TRAP if cost_function == 1: if self.maze.flat[next_state] == 'G': cost = cost + GOAL_REACHED # For other actions, there is no cost. elif cost_function == 2: #if self.maze.flat[next_state] != 'G': cost = cost + COST_ENERGY else: print("Undefined cost function is selected.") return cost <file_sep>/scripts/main.py """ Approximate Dynamic Programming & Reinforcement Learning - WS 2018 Programming Assignment <NAME> 30.01.2019 Command necessary to test the code. python main.py maze.txt """ from __future__ import division import sys import os from maze_environment import Maze_env from maze_solver import Maze_solver import matplotlib.pyplot as plt from matplotlib.pyplot import figure MAX_ITER = 1000 if __name__ == '__main__': if len(sys.argv) < 2: print('Arguments: <input file> <output file>', len(sys.argv)) sys.exit(1) script = sys.argv[0] input_file = sys.argv[1] maze_sol = Maze_solver() maze_sol.read_file(input_file) cost_functions = [1, 2] alpha = [0.99, 0.01, 0.3, 0.5, 0.7, 0.9] for g in cost_functions: maze_sol.maze_env.build_transition_probability_matrix(cost_function = g) for a in alpha: policy, v, it = maze_sol.policy_iteration(discount_factor = a, max_iteration=MAX_ITER) print("Policy Iteration: " + str(it) + " Cost function: " + str(g) + " Discount factor: " + str(a) ) text = "PI"+ ",g" + str(g) + ",a=" + str(a) maze_sol.plot_error(maze_sol.gt_PI[g-1], maze_sol.values, text) maze_sol.visulaze_results(v, policy, text) policy, v, it = maze_sol.value_iteration(discount_factor = a, max_iteration=MAX_ITER) print("Value Iteration: " + str(it) + " Cost function: " + str(g) + " Discount factor: " + str(a)) text_v = "VI"+ ",g" + str(g) + ",a=" + str(a) maze_sol.plot_error(maze_sol.gt_VI[g-1], maze_sol.values, text_v) maze_sol.visulaze_results(v, policy, text_v) plt.show() <file_sep>/README.md # adp_rl Approximate Dynamic Programming and Reinforcement Learning - Programming Assignment The purpose of this assignment is to implement a simple environment and learn to make optimal decisions inside a maze by solving the problem with Dynamic Programming. Value Iteration(VI) and Policy Iteration(PI) i.e. Policy Evaluation, Policy Improvement methods are implemented and analyzed. Run the `python main.py /absolute/path/to/maze.txt` command to launch the application.
d6219e91be402f94d73297a26f8e540b738521b6
[ "Markdown", "Python" ]
4
Python
longhuang318/adp_rl
644a50a9b13ca23bcc1b1399c5b4aa178d5d3e40
60117ecf7461f0d5ee2dc30af4e604c328c63434
refs/heads/master
<file_sep>const { generate } = require('../src/lib') describe('testing generate() function', () => { it('generate() without any parameter should generate data with predefined values', () => { const data = generate() const firstWeek = data[0] || {} const lastWeek = data[51] || {} expect(data.length).toBe(52) expect(firstWeek.week).toBe(1) expect(firstWeek.value).toBe(2) expect(lastWeek.week).toBe(52) expect(lastWeek.value).toBe(104) }) it('generate({ weeks: 4 }) should generate data with 4 weeks', () => { const data = generate({ weeks: 4 }) expect(data.length).toBe(4) }) it('generate({ weeks: 5, initialValue: 5 }) should generate data with 5 weeks and values multiples of 5', () => { const data = generate({ weeks: 5, initialValue: 5 }) const firstWeek = data[0] || {} const lastWeek = data[4] || {} expect(data.length).toBe(5) expect(firstWeek.week).toBe(1) expect(firstWeek.value).toBe(5) expect(lastWeek.week).toBe(5) expect(lastWeek.value).toBe(25) }) }) <file_sep>/** * @method factoryWeek * @param {Number} week * @param {Number} value * @return {Object} { week: Number, value: Number } */ const factoryWeek = (week, value) => { return { week, value } } /** * @method generate * @param {Object} options { initialValue: String, weeks: Number } * @return {Array<Week>} [ { week: Number, value: Number } ] */ const generate = (options = {}) => { const { initialValue = 2, weeks = 52 } = options return Array.from({ length: weeks }, (_, week) => { const weekNumber = week + 1 return factoryWeek(weekNumber, initialValue * weekNumber) }) } module.exports = { generate } <file_sep># fifty-two-challenge ## Install ```sh yarn add fifty-two-challenge # npm install fifty-two-challenge ``` ## Usage ```js const { generate } = require('fifty-two-challenge') generate({ initialValue: 5, weeks: 4 }) // return a array of weeks ``` ## API ### generate(options = {}) Generate an array of weeks with corresponding values from each week #### Arguments `options`: An object with two fields: * **initialValue**: initial value to generate data. Default is 2 * **weeks**: number of weeks. Default is 52 #### Returns * Array of weeks: the week object is a object with value and week fields ## Author <NAME> * Twitter [@emanuelgsouza](https://twitter.com/emanuelgsouza) * Github [@emanuelgsouza](https://github.com/emanuelgsouza)
11fdf7e9af070c2dd1c1794846e56f6c89680af6
[ "JavaScript", "Markdown" ]
3
JavaScript
emanuelgsouza/fifty-two-challenge
aab4fb8c1eeaebb4d892628272f28668e0fedbcc
92b00bb0f86ea7afa702a6ce9b46a39e70b951f3
refs/heads/master
<file_sep>#include <linux/module.h> #include <linux/vermagic.h> #include <linux/compiler.h> MODULE_INFO(vermagic, VERMAGIC_STRING); struct module __this_module __attribute__((section(".gnu.linkonce.this_module"))) = { .name = KBUILD_MODNAME, .init = init_module, #ifdef CONFIG_MODULE_UNLOAD .exit = cleanup_module, #endif .arch = MODULE_ARCH_INIT, }; static const struct modversion_info ____versions[] __used __attribute__((section("__versions"))) = { { 0x465ae224, "module_layout" }, { 0x35525017, "rtdm_timer_start" }, { 0x47229b5c, "gpio_request" }, { 0xcb4a1f12, "rtdm_timer_destroy" }, { 0x65d6d0f0, "gpio_direction_input" }, { 0x27e1a049, "printk" }, { 0x328a05f1, "strncpy" }, { 0xa8f59416, "gpio_direction_output" }, { 0x2196324, "__aeabi_idiv" }, { 0xc2165d85, "__arm_iounmap" }, { 0xa2577d47, "rtdm_tbase" }, { 0xfe990052, "gpio_free" }, { 0x40a6f522, "__arm_ioremap" }, { 0xefd6cf06, "__aeabi_unwind_cpp_pr0" }, { 0xa21a3d82, "__xntimer_init" }, }; static const char __module_depends[] __used __attribute__((section(".modinfo"))) = "depends="; MODULE_INFO(srcversion, "EECD7D9238BAB7AD40B131C"); <file_sep>#include <linux/sched.h> #include <linux/interrupt.h> /* mark_bh */ #include <linux/in.h> #include <linux/netdevice.h> /* struct device, and other headers */ #include <linux/skbuff.h> #include <linux/in6.h> #include <linux/delay.h> #include <linux/miscdevice.h> #include <linux/gpio.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/mm.h> #include <linux/fs.h> #include <linux/types.h> #include <linux/moduleparam.h> #include <linux/slab.h> #include <linux/errno.h> #include <linux/ioctl.h> #include <linux/cdev.h> #include <linux/string.h> #include <linux/list.h> #include <linux/pci.h> #include <asm/uaccess.h> #include <asm/atomic.h> #include <asm/unistd.h> #include <asm/io.h> #include <asm/system.h> #include <linux/iio/consumer.h> #include <linux/iio/iio.h> #include <asm/checksum.h> #include <linux/kthread.h> #include <linux/err.h> #include <linux/wait.h> #include <linux/timex.h> #include <linux/clk.h> #include <linux/pinctrl/consumer.h> #include <linux/hrtimer.h> #include <linux/ktime.h> #include <linux/module.h> #include <rtdm/rtdm_driver.h> #include <asm/io.h> // ioremap #include <linux/proc_fs.h> #include <linux/skbuff.h> #include <linux/ip.h> /* struct iphdr */ #include <linux/tcp.h> /* struct tcphdr */ #include <linux/if_arp.h> #include <linux/rslib.h> #include <fftw3.h> #include "ofdm.h" #define DEVICE_NAME "vlc" MODULE_AUTHOR("<NAME>"); MODULE_LICENSE("Dual BSD/GPL"); // Timer: used to trigger sending/receiving symbols static rtdm_timer_t phy_timer; static _Bool f_adjust_slot = 0; uint32_t slot_ns; volatile void* gpio1; volatile void* gpio2; static int frq = 50; // Unit: K static int decoding_sleep_slot = 1; enum {SENSING, RX, TX} phy_state; // Short sensing is implemented in tx state long OFDM_readFile(char* fileName, uint8_t** buffer) { *buffer = NULL; long length; int fd = open(fileName, O_RDONLY); if (fd) { length = (long)lseek (fd, 0, SEEK_END); lseek (fd, 0, SEEK_SET); *buffer = (uint8_t*) malloc (length); if (*buffer) { read (fd, *buffer, length); //printf("reading\n"); } else { close (fd); return OFDM_AllocationError; } close (fd); } else { return OFDM_FileError; } //printf("buffer is %02x %02x %d",(*buffer)[0],(*buffer)[length-1],length); return length; } void modulate(uint8_t* data,long Length, long offset, fftw_complex* out) { uint8_t* in = NULL; int i = 0; int j = 0; int k = 0; uint8_t mask= 0x80; //printf("modulating\n"); in = (uint8_t*)malloc (Length*8*sizeof(uint8_t)); if(in == NULL) { printf("it's null don't go further"); } for(k = 0; k < 64; k++) { out[k][0] = 0; out[k][1] = 0; } for(i = 0; i<Length; i++) { //printf("the byte is %02x\n",data[offset+i]); for(j = 0; j < 8; j++) { //printf("mask is %02x\n",mask); //printf("i is %d, j is %d\n",i,j); in[i*8+j] =(uint8_t) ((data[offset+i] & mask) >> (7-j)); out[i*8+j+1][0] = bpsk_i[in[i*8+j]]; out[i*8+j+1][1] = 0; out[SIZE_IFFT-(i*8+j)-1][0] = bpsk_i[in[i*8+j]]; out[SIZE_IFFT-(i*8+j)-1][1] = 0; //printf("%x",in[i*8+j]); //printf("shifting\n"); mask = mask >> 0x1 ; } mask= 0x80; //printf("\n"); //printf("next Byte please\n"); } //printf("done\n"); free(in); } void performIfft(fftw_complex* mod, fftw_complex* time_out) { fftw_plan ifft; fftw_complex *in = fftw_alloc_complex(64); fftw_complex *out = fftw_alloc_complex(64); int i; for (i = 0; i < 64; i++) { in[i][0] = mod[i][0]; in[i][1] = mod[i][1]; } ifft = fftw_plan_dft_1d(64, in, out, FFTW_BACKWARD, FFTW_ESTIMATE); fftw_execute(ifft); for (i = 0; i < 64; i++) { time_out[i][0] = out[i][0]; time_out[i][1] = out[i][1]; } fftw_destroy_plan(ifft); fftw_free(in); fftw_free(out); } void sum_samples(fftw_complex *in_a, fftw_complex *in_b, int size_b, int base_index) { int i; for (i = 0; i < size_b; i++) { in_a[i + base_index][0] += in_b[i][0]; in_a[i + base_index][1] += in_b[i][1]; } } void convert_signal_to_levels(fftw_complex* signal, fftw_complex* levels, int max, int size) { int i=0; for(i=0;i<size;i++) levels[i][0]=(signal[i][0]*4095/max); } int init_gpios() { fdm = -1; /* gpio1_addr = NULL; gpio1_oe_addr = NULL; gpio1_setdataout_addr = NULL; gpio1_cleardataout_addr = NULL; gpio2_addr = NULL; gpio2_oe_addr = NULL; gpio2_setdataout_addr = NULL; gpio2_cleardataout_addr = NULL; gpio3_addr = NULL; gpio3_oe_addr = NULL; gpio3_setdataout_addr = NULL; gpio3_cleardataout_addr = NULL; */ pin_map[0].gpio = 3; pin_map[0].number = 1 << 20; // printf("gpio pin of 0 is %d", pin_map[0].gpio); pin_map[1].gpio = 2; pin_map[1].number = 1 << 2; pin_map[2].gpio = 2; pin_map[2].number = 1 << 3; pin_map[3].gpio = 2; pin_map[3].number = 1 << 5; pin_map[4].gpio = 2; pin_map[4].number = 1 << 4; pin_map[5].gpio = 3; pin_map[5].number = 1 << 16; pin_map[6].gpio = 3; pin_map[6].number = 1 << 19; pin_map[7].gpio = 3; pin_map[7].number = 1 << 21; pin_map[8].gpio = 1; pin_map[8].number = 1 << 17; pin_map[9].gpio = 1; pin_map[9].number = 1 << 16; pin_map[10].gpio = 1; pin_map[10].number = 1 << 28; clc.gpio=1; clc.number=1 << 13; miso.gpio=0; miso.number=1 << 23; mosi.gpio=1; mosi.number=1 << 15; cs.gpio=1; cs.number=1 << 12; printf("gpio pin of 10 is %d", pin_map[10].gpio); fdm = open("/dev/mem", O_RDWR); if(fdm < 0) { return OFDM_GeneralError; } /*printf("Mapping %X - %X (size: %X)\n", GPIO1_START_ADDR, GPIO1_END_ADDR, GPIO1_SIZE);*/ // printf("gpio1 init\n"); // GPIO1 initialisation gpio1_addr = mmap(0, GPIO1_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fdm, GPIO1_START_ADDR); if(gpio1_addr == MAP_FAILED) { printf("Unable to map GPIO\n"); return OFDM_GeneralError; } printf("gpio 1 address %04x \n", gpio1_addr); gpio1_oe_addr = gpio1_addr + GPIO_OE; gpio1_setdataout_addr = gpio1_addr + GPIO_SETDATAOUT; gpio1_cleardataout_addr = gpio1_addr + GPIO_CLEARDATAOUT; // GPIO2 initialisation gpio2_addr = mmap(0, GPIO1_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fdm, GPIO2_START_ADDR); if(gpio2_addr == MAP_FAILED) { printf("Unable to map GPIO\n"); return OFDM_GeneralError; } printf("gpio 2 address %04x \n", gpio2_addr); gpio2_oe_addr = gpio2_addr + GPIO_OE; gpio2_setdataout_addr = gpio2_addr + GPIO_SETDATAOUT; gpio2_cleardataout_addr = gpio2_addr + GPIO_CLEARDATAOUT; // GPIO3 initialisation gpio3_addr = mmap(0, GPIO1_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fdm, GPIO3_START_ADDR); if(gpio3_addr == MAP_FAILED) { printf("Unable to map GPIO\n"); return OFDM_GeneralError; } printf("gpio 3 address %04x", gpio3_addr); gpio3_oe_addr = gpio3_addr + GPIO_OE; gpio3_setdataout_addr = gpio3_addr + GPIO_SETDATAOUT; gpio3_cleardataout_addr = gpio3_addr + GPIO_CLEARDATAOUT; printf("init done \n"); return 0; } void set_gpio(struct pin p) { // printf("setting gpio %d,%04x\n",p.gpio,p.number); switch(p.gpio) { case 1: { reg1 = *gpio1_oe_addr; reg1 = reg1 & (0xFFFFFFFF - p.number); *gpio1_oe_addr = reg1; *gpio1_setdataout_addr = p.number; break; } case 2: { //printf("please print this"); reg2 = *gpio2_oe_addr; reg2 = reg2 & (0xFFFFFFFF - p.number); *gpio2_oe_addr = reg2; *gpio2_setdataout_addr = p.number; break; } case 3: { reg3 = *gpio3_oe_addr; reg3 = reg3 & (0xFFFFFFFF - p.number); *gpio3_oe_addr = reg3; *gpio3_setdataout_addr = p.number; break; } default: break; } } void clear_gpio(struct pin p) { switch(p.gpio) { case 1: { reg1 = *gpio1_oe_addr; reg1 = reg1 & (0xFFFFFFFF - p.number); *gpio1_oe_addr = reg1; *gpio1_cleardataout_addr = p.number; break; } case 2: { //printf("clearing please"); reg2 = *gpio2_oe_addr; reg2 = reg2 & (0xFFFFFFFF - p.number); *gpio2_oe_addr = reg2; *gpio2_cleardataout_addr = p.number; break; } case 3: { reg3 = *gpio3_oe_addr; reg3 = reg3 & (0xFFFFFFFF - p.number); *gpio3_oe_addr = reg3; *gpio3_cleardataout_addr = p.number; break; } default: break; } } void nano_sleep() { struct timespec tim, tim2; tim.tv_sec = 1; tim.tv_nsec = 1000; if(nanosleep(&tim , &tim2) < 0 ) { printf("Nano sleep system call failed \n"); return -1; } } void SPI_write(uint16_t data) { uint16_t shift = 0x8000; while (shift > 0) { //writel(bit_clc, gpio2+CLEAR_OFFSET); clear_gpio(clc); // nano_sleep(); delay_n_NOP(); if ((data & shift) != 0) { //writel(1<<BIT_MOSI, gpio2+SET_OFFSET); // printf("1\n"); set_gpio(mosi); delay_n_NOP(); } else { //writel(1<<BIT_MOSI, gpio2+CLEAR_OFFSET); clear_gpio(mosi); // printf("0\n"); delay_n_NOP(); } shift >>= 1; //writel(bit_clc, gpio2+SET_OFFSET); set_gpio(clc); // nano_sleep(); // delay_n_NOP(); } } void delay_n_NOP(void) { int i; for(i=SPI_DELAY_CNT; i>0; i--) ; } void phy_timer_handler(rtdm_timer_t *timer) { int ret = 0; uint8_t* data = NULL; long bLength; int nSymbols; fftw_complex *mod; fftw_complex *ifft; fftw_complex *signal; fftw_complex *levels; mod = fftw_alloc_complex(SIZE_IFFT); ifft = fftw_alloc_complex(SIZE_IFFT); // read from file bLength = OFDM_readFile(argv[1], &data); if(bLength) { //printf("file size is %ld \n",bLength); } else if(bLength == OFDM_FileError) { printf("file error \n"); return 0; } else if(bLength == OFDM_AllocationError) { printf("allocation error \n"); return 0; } nSymbols = (((bLength*8)%N_REAL_SUBCARRIERS) == 0 ?((bLength*8)/N_REAL_SUBCARRIERS): ((bLength*8)/N_REAL_SUBCARRIERS) +1 ); signal = fftw_alloc_complex(SIZE_IFFT*nSymbols); levels = fftw_alloc_complex(SIZE_IFFT*nSymbols); //printf("number of sybols is %d\n",nSymbols); //printf("the first byte is %02x\n",data[100]); int i = 0; int size; //start timer for (i=0; i<nSymbols; i++) { size = 0; size = ((i+1)*3 <= bLength ? 3 : bLength-i*3); //printf("%d:the size is %d\n",i,size); modulate(data,size,i*3, mod); /*int k = 0; for(k = 0 ; k < 64 ; k++) { printf("%d: mod %lf\n",k, mod[k][0]); }*/ //ifft performIfft(mod,ifft); int k = 0; for(k = 0 ; k < 64 ; k++) { printf("%d: real %lf im %lf\n",k, ifft[k][0],ifft[k][1]); } sum_samples(signal, ifft, 64, i*64); } //stop timer printf("The time took for a buffer of length %d this operation is %ld \n ", bLength, (stop_time.tv_sec - start_time.tv_sec)*1000000000+stop_time.tv_nsec - start_time.tv_nsec); int j = 0; double minimum = signal[0][0]; double max = signal[0][0]; for(j = 1 ; j < SIZE_IFFT* nSymbols; j++) { if(minimum > signal[j][0]) minimum = signal[j][0]; if(max < signal[j][0]) max= signal[j][0]; } printf("minimum is %lf\n",minimum); if(minimum < 0) { for(j = 0; j < SIZE_IFFT* nSymbols; j++) { signal[j][0] -= minimum; printf("%lf\n",signal[j][0]); } max-=minimum; printf("the max is %lf",max); } printf("initializing gpios \n"); ret = init_gpios(); if(ret < 0) { printf("init error"); return 0; } //uint32_t pin = 1 << 7; convert_signal_to_levels(signal, levels, max,SIZE_IFFT*nSymbols); while(1) { int s_cpt=0; for(s_cpt=0;s_cpt<SIZE_IFFT*nSymbols;s_cpt++) { // set cs to low clear_gpio(cs); // send high byte uint16_t buffer = levels[s_cpt][0] ; buffer = 0x0FFF & buffer; buffer = 0x3000 | buffer; SPI_write(buffer); // set cs to low set_gpio(cs); delay_n_NOP(); } } } void vlc_init(struct net_device *dev) { // struct vlc_priv *priv; /*dev->addr_len = MAC_ADDR_LEN; dev->type = ARPHRD_LOOPBACK ; // ARPHRD_IEEE802154 vlc_setup(dev); /* assign some of the fields */ /* dev->netdev_ops = &vlc_netdev_ops; dev->header_ops = &vlc_header_ops; /* keep the default flags, just add NOARP */ /* dev->flags |= IFF_NOARP; dev->features |= NETIF_F_HW_CSUM; priv = netdev_priv(dev); memset(priv, 0, sizeof(struct vlc_priv)); //printk(".....4.....\n"); //spin_lock_init(&priv->lock); //printk(".....5.....\n"); if (mac_or_app == APP) { vlc_rx_ints(dev, 1); /* enable receive interrupts */ /* tx_pkt = kmalloc (sizeof (struct vlc_packet), GFP_KERNEL); rx_pkt = kmalloc (sizeof (struct vlc_packet), GFP_KERNEL); rx_pkt_check_dup = kmalloc (sizeof (struct vlc_packet), GFP_KERNEL); if (tx_pkt==NULL || rx_pkt_check_dup==NULL || rx_pkt==NULL) { printk (KERN_NOTICE "Ran out of memory allocating packet pool\n"); return ; } rx_pkt_check_dup->datalen = 0; vlc_setup_pool(dev); priv->tx_queue = NULL; flag_exit = 0; //printk(".....8.....\n"); //netif_start_queue(dev); //printk(".....9.....\n"); }*/ } void vlc_cleanup(void) { // struct vlc_packet *pkt; // struct vlc_priv *priv = netdev_priv(vlc_devs); ////unsigned long flags; //if (flag_lock) //spin_lock_bh(&priv->lock); // flag_exit = 1; // netif_stop_queue(vlc_devs); //if (flag_lock) //spin_unlock_bh(&priv->lock); // Clean the threads /* printk("stop phy decoding\n"); if (task_phy_decoding) { kthread_stop(task_phy_decoding); task_phy_decoding = NULL; }*/ printk("stop mac tx\n"); /* if (task_mac_tx) { kthread_stop(task_mac_tx); task_mac_tx = NULL; }*/ rtdm_timer_destroy(&phy_timer); iounmap(gpio1); iounmap(gpio2); // Clean the GPIOs gpio_free(GPIO_LED_ANODE); gpio_free(GPIO_LED_CATHODE); gpio_free(GPIO_BUFFER_CONTROL); gpio_free(GPIO_H_POWER_LED); gpio_free(GPIO_LED_OR_PD); gpio_free(SPI_CLC); gpio_free(SPI_MISO); gpio_free(SPI_MOSI); gpio_free(SPI_CS); // // Clean the devices /*if (vlc_devs) { if (mac_or_app == APP) { printk("clean the pool\n"); //if (flag_lock) //spin_lock_bh(&priv->lock); while(priv->tx_queue) { pkt = vlc_dequeue_pkt(vlc_devs); vlc_release_buffer(pkt); } //if (flag_lock) //spin_unlock_bh(&priv->lock); vlc_teardown_pool(vlc_devs); kfree(rx_pkt); kfree(rx_pkt_check_dup); kfree(tx_pkt); } printk("unregister the devs\n"); unregister_netdev(vlc_devs); //if (mac_or_app == APP) { //vlc_teardown_pool(vlc_devs); //} printk("free the devs\n"); free_netdev(vlc_devs); } remove_proc_entry("rx", vlc_dir); remove_proc_entry("tx", vlc_dir); remove_proc_entry("vlc", NULL); // Free the reed solomon resources if (rs_decoder) { free_rs(rs_decoder); } */ //printk("free packets\n"); //if (tx_pkt) //kfree(tx_pkt); //if (rx_pkt) //kfree(rx_pkt); //if (rx_pkt_check_dup) //kfree(rx_pkt_check_dup); //if (data_buffer_symbol) //kfree(data_buffer_symbol); printk(KERN_NOTICE "The VLC module has been removed.\n"); return; } static void vlc_regular_interrupt(int irq, void *dev_id, struct pt_regs *regs) { } int vlc_init_module(void) { int ret = -ENOMEM; printk("Initializing the VLC module...\n"); // vlc_interrupt = vlc_regular_interrupt; frq *= 1000; // Convert the frequency from KHz to Hz // May optimize this part /// Wait to be optimized decoding_sleep_slot = (1000*1/frq); decoding_sleep_slot = (decoding_sleep_slot>=1) ? decoding_sleep_slot : 1; printk("Sleep slot (while decoding) is %d ms\n", decoding_sleep_slot); /// Create the device and register it /*vlc_devs = alloc_netdev(sizeof(struct vlc_priv), "vlc%d", vlc_init); if (vlc_devs == NULL) goto out; ret = register_netdev(vlc_devs); if (ret) printk("VLC: error registering device \"%s\"\n", vlc_devs->name);*/ /// GPIOs for the LED if ( gpio_request(GPIO_LED_ANODE, "LED_ANODE") || gpio_request(GPIO_LED_CATHODE, "LED_CATHODE") || gpio_request(GPIO_BUFFER_CONTROL, "BUFFER_CONTROL") || gpio_request(GPIO_H_POWER_LED, "H_POWER_LED") || gpio_request(GPIO_LED_OR_PD, "LED_OR_PD") ) { printk("Request GPIO failed!\n"); ret = -ENOMEM; goto out; } gpio_direction_output(GPIO_LED_ANODE, GPIOF_INIT_LOW); gpio_direction_output(GPIO_LED_CATHODE, GPIOF_INIT_LOW); gpio_direction_output(GPIO_BUFFER_CONTROL, GPIOF_INIT_HIGH); gpio_direction_output(GPIO_H_POWER_LED, GPIOF_INIT_LOW); gpio_direction_output(GPIO_LED_OR_PD, GPIOF_INIT_LOW); /// GPIOs for SPI if ( gpio_request(SPI_CLC, "SPI_CLC") || gpio_request(SPI_MISO, "SPI_MISO") || gpio_request(SPI_MOSI, "SPI_MOSI") || gpio_request(SPI_CS, "SPI_CS") ) { printk("Request GPIO failed!\n"); ret = -ENOMEM; goto out; } gpio_direction_output(SPI_CLC, GPIOF_INIT_LOW); gpio_direction_input(SPI_MISO); gpio_direction_output(SPI_MOSI, GPIOF_INIT_LOW); gpio_direction_output(SPI_CS, GPIOF_INIT_LOW); // Qing - May 2, 2015 //if (pd_as_rx == 1) { // PD //gpio_direction_output(GPIO_LED_OR_PD, GPIOF_INIT_HIGH); //} else { // LED //gpio_direction_output(GPIO_LED_OR_PD, GPIOF_INIT_LOW); //} //if (hpl == 1) { //bit_led_anode = BIT_H_POWER_LED; // High-power LED as TX //gpio_direction_output(GPIO_LED_OR_PD, GPIOF_INIT_LOW); // PD as RX //} else { // LED //bit_led_anode = BIT_LED_ANODE; // LED as TX //gpio_direction_output(GPIO_LED_OR_PD, GPIOF_INIT_HIGH); // LED as RX //} //switch_tx(); gpio1 = ioremap(ADDR_BASE_0, 4); gpio2 = ioremap(ADDR_BASE_1, 4); phy_state = RX; //switch_led_to_rx(); printk("my_gpio: Access address to device is:0x%x 0x%x\n", (unsigned int) gpio1, (unsigned int) gpio2); if (!(gpio1 && gpio2)) goto out; /* vlc_dir = proc_mkdir("vlc", NULL); rx_device = create_proc_entry("rx", 0666, vlc_dir); tx_device = create_proc_entry("tx", 0666, vlc_dir); if (rx_device && tx_device) { rx_device->data = &rx_device_value; rx_device->read_proc = proc_read; rx_device->write_proc = proc_write; tx_device->data = &tx_device_value; tx_device->read_proc = proc_read; tx_device->write_proc = proc_write; }*/ /// Timer slot_ns = 1000000000 / frq; printk("Slot in nanosecond: %d\n", slot_ns); ret = rtdm_timer_init(&phy_timer, phy_timer_handler, "phy timer"); if(ret) { rtdm_printk("PWM: error initializing up-timer: %i\n", ret); return ret; } ret = rtdm_timer_start(&phy_timer, slot_ns, slot_ns, RTDM_TIMERMODE_RELATIVE); if(ret) { rtdm_printk("PWM: error starting up-timer: %i\n", ret); return ret; } rtdm_printk("PWM: timers created\n"); ///// Threads /* if (!rx) { task_mac_tx = kthread_run(mac_tx,"TX thread","VLC_TX"); if (IS_ERR(task_mac_tx)){ printk("Unable to start kernel threads. \n"); ret= PTR_ERR(task_phy_decoding); task_mac_tx = NULL; task_phy_decoding = NULL; goto out; } } task_phy_decoding = kthread_run(phy_decoding,"RX thread","VLC_DECODING"); if (IS_ERR(task_phy_decoding)){ printk("Unable to start kernel threads. \n"); ret= PTR_ERR(task_phy_decoding); task_mac_tx = NULL; task_phy_decoding = NULL; goto out; } */ printk("The VLC module has been initialized.\n\n"); out: printk("------EXIT vlc_init_module------\n"); if (ret) vlc_cleanup(); return ret; } module_init(vlc_init_module); module_exit(vlc_cleanup);
8aefda2495c38685cfce9321d919cd6d2f13d68b
[ "C" ]
2
C
nourSmaoui/OfdmVLCKernel
bf660ef31b5eaaa339d1d1821e348b2f3ccf77a3
50e262c20dd276963c9a9bb0f3c2fc56e42cc7d6
refs/heads/master
<repo_name>justin-john/web-server-log-parser<file_sep>/calculate.js module.exports = function (filePath, isTestRun) { var fs = require('fs'); /* Set file path */ var fPath = filePath || 'sample.log'; /* EndPoint Object Declare */ var cntPenMsg = { pattern: /\/api\/users\/(\d)+\/count_pending_messages/, count: 0, dyno: {}, responseTime: [] }, getMsg = { pattern: /\/api\/users\/(\d)+\/get_messages/, count: 0, dyno: {}, responseTime: [] }, getFrndProgress = { pattern: /\/api\/users\/(\d)+\/get_friends_progress/, count: 0, dyno: {}, responseTime: [] }, getFrndScore = { pattern: /\/api\/users\/(\d)+\/get_friends_score/, count: 0, dyno: {}, responseTime: [] }, postUser = { pattern: /\/api\/users\/(\d)+/, count: 0, dyno: {}, responseTime: [] }, getUser = { pattern: /\/api\/users\/(\d)+/, count: 0, dyno: {}, responseTime: [] }; /* File Read */ var rd = fs.readFileSync(fPath); /* Split file string with new line char to array */ var rdArray = rd.toString().split("\n"); /** * Set count in each endpoints object. * Set each lines service + connect time as response time from each line object. * Increment corresponding dyno's count in each endpoints object(cntPenMsg.dyno) * * @param {Object} buildObj // cntPenMsg, getMsg .. objects etc * @param {Object} lineObj * */ var buildObjOnEndPoints = function (buildObj, lineObj) { buildObj.count++; buildObj.responseTime.push(parseInt(lineObj.connect) + parseInt(lineObj.service)); if (typeof buildObj.dyno[lineObj.dyno] !== 'undefined') { buildObj.dyno[lineObj.dyno] = buildObj.dyno[lineObj.dyno] + 1; } else { buildObj.dyno[lineObj.dyno] = 1; } } /* Iterate file read array to create each line object and manipulate the data in it */ rdArray.map(function(line) { var lineSplitColon = line.split(": ")[1].trim(); var lineSplitSpace = lineSplitColon.split(' '); /** * Create line Obj for each line. * * Example * { at: 'info', method: 'get', path: '/api/users/100001971407609', ... dyno: 'web.10', connect: '2ms', service: '22ms' } */ var lineObj = {}; lineSplitSpace.map(function(n) { lineObj[n.split('=')[0]] = n.split('=')[1]; }); /* Check each endpoints path with regex */ if (cntPenMsg.pattern.test(lineObj.path)) { buildObjOnEndPoints(cntPenMsg, lineObj); } else if (getMsg.pattern.test(lineObj.path)) { buildObjOnEndPoints(getMsg, lineObj); } else if (getFrndProgress.pattern.test(lineObj.path)) { buildObjOnEndPoints(getFrndProgress, lineObj); } else if (getFrndScore.pattern.test(lineObj.path)) { buildObjOnEndPoints(getFrndScore, lineObj); } else if (getUser.pattern.test(lineObj.path)) { if (lineObj.method == 'GET') { buildObjOnEndPoints(getUser, lineObj); } else if (lineObj.method == 'POST') { buildObjOnEndPoints(postUser, lineObj); } } }); var mean = function (arr) { return arr.reduce(function(a, b){return a+b;}) / arr.length; } var median = function (arr) { arr.sort( function(a,b) {return a - b;} ); var half = Math.floor(arr.length/2); if(arr.length % 2) return arr[half]; else return (arr[half-1] + arr[half]) / 2.0; } var mode = function (arr) { return arr.reduce(function(current, item) { var val = current.numMapping[item] = (current.numMapping[item] || 0) + 1; if (val > current.greatestFreq) { current.greatestFreq = val; current.mode = item; } return current; }, {mode: null, greatestFreq: -Infinity, numMapping: {}}, arr).mode; }; /** * Set Mean, Median, Mode object property for each endpoints */ var setMeasures = function (buildEndPointArr) { buildEndPointArr.map(function(buildObj) { if (buildObj.responseTime.length) { buildObj.mean = mean(buildObj.responseTime); buildObj.median = median(buildObj.responseTime); buildObj.mode = mode(buildObj.responseTime); } else { buildObj.mean = buildObj.median = buildObj.mode = null; } }); } setMeasures([cntPenMsg, getMsg, getFrndProgress, getFrndScore, postUser, getUser]); /** * Set max dyno to each endpoints objects */ var setMaxHitDyno = function(buildEndPointArr) { buildEndPointArr.map(function(buildObj) { var getDyno = {}; for (var prop in buildObj.dyno) { if (!getDyno.max || (buildObj.dyno[prop] > getDyno.max)) { getDyno.name = prop; getDyno.max = buildObj.dyno[prop]; } } buildObj.dynoName = getDyno.name; }); } setMaxHitDyno([cntPenMsg, getMsg, getFrndProgress, getFrndScore, postUser, getUser]); var writeParsedStream = function (writeObj) { return { count: writeObj.count, mean: writeObj.mean, median: writeObj.median, mode: writeObj.mode, dyno: writeObj.dynoName } } /* Final file parsed data */ var finalParsedData = { countPendingMsg: writeParsedStream(cntPenMsg), getMsg: writeParsedStream(getMsg), getFriendProgress: writeParsedStream(getFrndProgress), getFriendScore: writeParsedStream(getFrndScore), postUser: writeParsedStream(postUser), getUser: writeParsedStream(getUser) }; /* Test Supress print */ if (isTestRun) { console.log = function () {}; } var printStream = function (writeObj) { console.log('Count:', writeObj.count); console.log('Mean:', writeObj.mean); console.log('Median:', writeObj.median); console.log('Mode:', writeObj.mode); console.log('Dyno:', writeObj.dyno); console.log('\n'); } console.log('\n'); console.log('Endpoint: /api/users/{user_id}/count_pending_messages/ '); printStream(finalParsedData.countPendingMsg); console.log('Endpoint: /api/users/{user_id}/get_messages '); printStream(finalParsedData.getMsg); console.log('Endpoint: /api/users/{user_id}/get_friends_progress '); printStream(finalParsedData.getFriendProgress); console.log('Endpoint: /api/users/{user_id}/get_friends_score '); printStream(finalParsedData.getFriendScore); console.log('Endpoint - POST: /api/users/{user_id} '); printStream(finalParsedData.postUser); console.log('Endpoint - GET: /api/users/{user_id} '); printStream(finalParsedData.getUser); return finalParsedData; };<file_sep>/start.js console.log('\nStarting server log file data parsing.... '); /** * Require Calculate Module with arguments "server log file path" and "variable to check test is * running or not and suppress the console prints" * * @param {String} FilePath * @param {Boolean} Variable * return {Object} * **/ require('./calculate')('sample.log'); console.log('Finished server log file data parsing. \n');<file_sep>/README.md Web server log file parser example in node.js ============================================= A sample code for parsing server log file. This parser will parse each line in log file to extract following criteria - The number of times the URL was called. - The mean (average), median and mode of the response time (connect time + service time). - The "dyno" that responded the most. Sample parsed data of single URL ``` Endpoint: /api/users/{user_id}/count_pending_messages/ Count: 2430 Mean: 25 Median: 15 Mode: 11 Dyno: web.2 ``` A sample web server log file and test log file with small set of entries is available in `test` directory for unit testing is available in repository. ## To run the parser ```bash $ node start.js ``` ## To run unit testing ```bash $ node test/test.js ``` ### To Viewer Please review and contact me with your suggestions or make your changes in repo with pull request.
f6780283004b1d3b45ed83d6ccaa0d01d980d6c4
[ "JavaScript", "Markdown" ]
3
JavaScript
justin-john/web-server-log-parser
682c642016292d93b7213c66175fe8d253e8b6a5
52151f9afd3c5daa70e5dc31a5b9ff00169f9935
refs/heads/master
<file_sep># Event Reminder Ever forgot important event or someones birthday? Do you spend a lot of time on your computer? Well look no further than my ghetto event reminder! ## Requirements This was written in python 3.7 so it is required to run it. Additionally you need to install [Dateutil](https://dateutil.readthedocs.io/en/stable/) ``` pip install python-dateutil ``` ## How it works Fill in json however you please by given example then simply run the program using provided batchfile with command ``` run ``` Or if you wish to provide different path and wait(before disappearing) or deadline(when said event is supposed to be reminded) use ``` python --filepath=YOUR_PATH --wait_time=YOUR_WAIT_TIME --deadline=YOUR_DEADLINE ``` ## Okay but whats the point? Well, as I've said its heavily personalized. I've got into trouble of not remembering someones birthday and I happen to turn on my computer daily. This was made specifically to run at system startup and either disappear before I notice it or remind me of something that I had to know. You can achieve it by simple batch file or adding it to task scheduler - its up to you to decide. <file_sep>import sys import json import time import argparse from events import Event from datetime import date from dateutil.parser import parse def load_file(path): with open(path) as data_file: if data_file.name.endswith('.json'): return parse_json(data_file) else: print("Unsupported file format") quit() def parse_json(data_file): data = json.load(data_file) events = [] for entry in data: date_obj = parse(entry['date']).date() event = Event().date(date_obj).event_type(entry['event_type']).person_name(entry['person_name']).description( entry['description']) events.append(event) return events def check_dates(events, wait_time, deadline_threshold): today = date.today() event_found = False for event in events: remaining_days = event.days_to_deadline(today) if remaining_days <= deadline_threshold and remaining_days >= 0: input(event) event_found = True if not event_found: print("No upcoming events") time.sleep(wait_time) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--filepath", help="specify path to data file", required=True) parser.add_argument("--wait_time", help="time to wait before window disappears", type=int, default=4) parser.add_argument("--deadline", help="how many days before event to set reminder for", type=int, default=7) args = parser.parse_args() events_list = load_file(path=args.filepath) check_dates(events=events_list, wait_time=args.wait_time, deadline_threshold=args.deadline) quit() <file_sep>class Event: def __init__(self): self._date = None self._event_type = None self._person_name = None self._description = None def __str__(self): return ("Event Type: %s\n" "Date: %s\n" "Person Name: %s\n" "Description: %s\n" % (self._event_type, self._date, self._person_name, self._description) ) def date(self,date): self._date = date return self def person_name(self, person_name): self._person_name = person_name return self def event_type(self, event_type): self._event_type = event_type return self def description(self, description): self._description = description return self def days_to_deadline(self, today): date_diff = self._date - today return date_diff.days
d87c5cc0f79050cf6c36f23ba11f5b6b91990605
[ "Markdown", "Python" ]
3
Markdown
RevinderDev/event-reminder
6fed61338989ba0bb586a23ffe12f6e6cfcd79b3
9fb20b559e4c57c0b320005dcf6195552cd8f77d
refs/heads/master
<repo_name>Insoumis/analysons-lepen<file_sep>/scripts/genenrate.js const path = require('path') const fs = require('fs') const Hjson = require('hjson') const marked = require('marked') const THEMES = path.join(__dirname, '..', 'themes') const OUTPUT = path.join(__dirname, '..', 'src', 'themes.json') const TOMD = ['intro', 'fn', 'fi', 'aec'] const result = {} const themes = fs .readdirSync(THEMES) .filter(fName => fName.slice(-6) === '.hjson') .map((fName) => { const slug = fName.slice(0, -6) const file = fs.readFileSync(path.join(THEMES, fName)).toString() const theme = Hjson.parse(file) // add slug theme.slug = slug // convert markdown to html TOMD.forEach((key) => { if (theme.hasOwnProperty(key)) { theme[key] = marked(theme[key], { breaks: true }) .trim() .slice(3, -4) // remove <p></p> } }) return theme }) .map((theme, _, arr) => { if (theme.parent) { const parent = arr.find(t => t.slug === theme.parent) theme.relatives = parent.subs } return theme }) .forEach((theme) => { result[theme.slug] = theme }) fs.writeFileSync(OUTPUT, JSON.stringify(result, null, 2)) <file_sep>/src/router.js import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter) import Home from './Home.vue' import Theme from './Theme.vue' const routes = [ { path: '/', component: Home }, { path: '/themes/:theme', component: Theme }, ] export default new VueRouter({ mode: 'history', scrollBehavior: (to, from, savedPosition) => { if (from.params.theme && to.params.theme) { return { x: 0, y: window.scrollTop } } return (savedPosition) ? savedPosition : { x: 0, y: 0 } }, routes }) <file_sep>/README.md # analysons-lepen > analysons-lepen ## Build Setup ``` bash # install dependencies yarn # serve with hot reload at localhost:8080 yarn dev # build for production with minification yarn build ``` ## Install and build locally (nodejs required with npm) npm run gen ## Test locally npm run dev
3d63ee0603aa5871266ab6f4521f47bcd7d6b6c1
[ "JavaScript", "Markdown" ]
3
JavaScript
Insoumis/analysons-lepen
38ad6d04fc018afb7ed60e73c8daf38a54ff8d59
2b20f5eefe44ddc6e8c3871aed027acc3100249b