Module: VikingIO::CLI::Commands

Defined in:
lib/vikingio/cli/commands.rb

Constant Summary collapse

BASE_PATH =
"http://build1.vikingio.com/"
UNITY_COMPILER_PATH_OSX =
"/Applications/Unity/Unity.app/Contents/Frameworks/MonoBleedingEdge/bin/gmcs"
UNITY_MONO_PATH_OSX =
"/Applications/Unity/Unity.app/Contents/Frameworks/MonoBleedingEdge/bin/mono"
UNITY_MONO_DLL_PATH_OSX =
"/Applications/Unity/Unity.app/Contents/Frameworks/MonoBleedingEdge/lib/"
TEMPLATES_DIR =

File.expand_path(File.join(File.dirname(__FILE__), “..”, “..”, “..”, “templates”))

File.expand_path(File.join(File.dirname(__FILE__), "..", "..", "..", "templates"))
CSC_V35_64_PATH =
File.expand_path("c:/Windows/Microsoft.Net/Framework64/v3.5/csc.exe")
COMMANDS =
[ 
    ["help", {:short => "", :full => ""}],
    ["login", {:short => "Authenticate with VikingIO", :full => ""}],
    ["logout", {:short => "Clear your authentication credentials", :full => ""}],
    ["create", {:short => "Create a new VikingIO application", :full => "Ex: vikingio create [app-name]"}], 
    ["generate", {:short => "Generate a VikingIO node", :full => "Ex: vikingio generate node GameServer"}],
    #["link", {:short => "Link the current directory with an existing VikingIO application", :full => "Ex: vikingio link [app-name]"}],
    ["unlink", {:short => "Unlink the current directory with it's VikingIO application", :full => "Ex: vikingio unlink"}],
    #["compile", {:short => "Compile your application on the server.", :full => "Once compiled, your application is ready to deploy."}],
    ["deploy", {:short => "Deploy your application", :full => "The latest build will be deployed to our cloud infrastructure. [NOTE: Billing will begin immediately after your application is deployed.]"}],
    #["destroy", {:short => "Destroy all production nodes in the VikingIO cloud", :full => "This will completely shut down and remove all of your production nodes for this application."}],
    ["run", {:short => "Compile and run your application locally", :full => ""}],
    #["status", {:short => "Get status of nodes", :full => ""}],
    #[""]
]

Class Method Summary collapse

Class Method Details

.compile_and_run(*args) ⇒ Object



306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# File 'lib/vikingio/cli/commands.rb', line 306

def self.compile_and_run(*args)
                                             
  tmp_dir = File.join(Dir.tmpdir, "vikingio")
  node_data = VikingIO::CLI.get_node_data
  default_port = 14242
  
  if self.compile_nodes(tmp_dir, node_data)
    pids = []      
      
    node_data.each do |node|     
      exe_file = "#{tmp_dir}/VikingIO/#{node["node_class"]}.exe" 
      if IS_WINDOWS
        pids << spawn("#{exe_file} #{default_port}")       
      else       
        pids << spawn("DYLD_LIBRARY_PATH=#{UNITY_MONO_DLL_PATH_OSX} #{UNITY_MONO_PATH_OSX} #{exe_file} #{default_port}")
      end
      default_port += 1
    end 
   
    begin
      puts "Press ctrl-C to stop"
      while true do
        sleep 0.1
      end
    rescue Interrupt => e  
      pids.each {|pid| Process.kill("INT", pid) }
      puts "Stopped processes: #{pids.join(",")}."
    end
  else
    
  end 
end

.compile_nodes(tmp_dir, node_data) ⇒ Object



201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/vikingio/cli/commands.rb', line 201

def self.compile_nodes(tmp_dir, node_data)   
  begin                                       
    FileUtils::rm_rf(tmp_dir)
    FileUtils::mkdir_p(tmp_dir)  

    if IS_WINDOWS  
      working_directory =  `echo %cd%`.chomp 
    else
      working_directory = Dir.pwd
    end  

    puts "Copying project"
    FileUtils::cp_r(File.join(File.expand_path(working_directory), "Assets", "VikingIO"), tmp_dir)

    puts "Removing Client directory"
    FileUtils::rm_rf(File.join(tmp_dir, "VikingIO", "Client"))
    
    puts "Removing meta files"
    meta_files = Dir["#{tmp_dir}/VikingIO/**/*.meta"] 
    meta_files.each {|x| FileUtils.rm_rf(x) }
    
    puts "Generating Main"
    templates_dir = File.join(File.dirname(__FILE__), "..", "..", "..", "templates")
    program_template = File.read(File.join(templates_dir, "Program.cs"))

    app_data = VikingIO::CLI.get_app_data
      
    #puts "Loading App Data: #{app_data}"              
    #dlls_dir = File.join(File.dirname(__FILE__), "../../../dlls")
    #viking_dll_path = File.join(dlls_dir, "VikingIO.Network.dll") 
    #FileUtils::cp(viking_dll_path, File.join(tmp_dir, "VikingIO"))
   
    cs_files = Dir["#{tmp_dir}/VikingIO/**/*.cs"]     
  
    references = Dir["#{tmp_dir}/VikingIO/Server/External/**/*.dll"]  
    reference_str = references.map{|x| "-reference:#{x}" }.join(" ")      
                                  
    log_file = File.join(tmp_dir, "VikingIO", "log")    
  
    node_data.each do |node|               
      @exit_status = nil
      @exit_msg = ""
      puts "Compiling '" + node["node_class"] + "' node"     
      node_class = node["node_class"]
    
      program_path = File.join(tmp_dir, "VikingIO", node_class + ".Main.cs")                
                                                                   
      puts app_data["name"]
      File.open(program_path, "w") do |f|
        f << program_template.gsub("[MODULE_NAME]", node_class).gsub("[APP_NAME]", app_data["name"])
      end              
    
      all_files = cs_files + [program_path] 
      out_file = "#{tmp_dir}/VikingIO/#{node_class}.exe"  


      library_path = File.join(tmp_dir, "VikingIO", "Server", "External") 
      csc_path = "c:\\Windows\\Microsoft.Net\\Framework64\\v3.5\\csc.exe"

      if IS_WINDOWS
        references = Dir["#{tmp_dir}/VikingIO/Server/External/**/*.dll"]
        reference_str = references.map {|x| "/r:#{File.expand_path(x)}" }.join(" ")
        cs_files = Dir["#{tmp_dir}/VikingIO/**/*.cs"]
        cs_files_str = cs_files.map {|x| File.expand_path(x) }.join(" ")

        Open3.popen3("cd #{tmp_dir}/VikingIO && #{CSC_V35_64_PATH} #{reference_str} /out:#{node_class}.exe /recurse:Server\\*.cs /recurse:Shared\\.cs #{node_class}.Main.cs")  {|stdin, stdout, stderr, wait_thr|
          pid = wait_thr.pid # pid of the started process.

          @exit_status = wait_thr.value # Process::Status object returned.
      
          stderr.each do |x|
            @exit_msg << x    
          end
        }   
      else
        Open3.popen3("#{UNITY_COMPILER_PATH_OSX} #{reference_str} -lib:#{library_path} -optimize #{all_files.join(" ")} -out:#{out_file}") {|stdin, stdout, stderr, wait_thr|
          pid = wait_thr.pid # pid of the started process.

          @exit_status = wait_thr.value # Process::Status object returned.
      
          stderr.each do |x|
            @exit_msg << x    
          end
        }   
      end
                   
      references.each {|x| FileUtils.cp x, File.join(tmp_dir, "VikingIO") }         
    
      if @exit_status.success? == false
        puts "ERROR COMPILING: #{@exit_msg}"
        return false;
      end                                                                               
    end 
    
    node_data.each {|x| FileUtils.rm_rf File.join(tmp_dir, "VikingIO", "#{x}.cs") } 
    
    src_files = Dir.glob("#{tmp_dir}/VikingIO/**").reject {|x| x.end_with?("exe") || x.end_with?("Data") || x.end_with?("dll") }
    src_files.each {|x| FileUtils.rm_rf x }
         
  rescue Exception => e  
    puts "Error compiling: #{e}"
    return false
  end           
end

.create(*args) ⇒ Object



347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
# File 'lib/vikingio/cli/commands.rb', line 347

def self.create(*args)     
  args.flatten!
  
  if !VikingIO::CLI.authenticated?
    puts "Please login first."
    return       
  end    
  
  if VikingIO::CLI.linked?
    puts "A VikingIO application is already linked to this directory. Use 'vikingio unlink' to clear the application data for this directory."
    return
  end
  
  app_name = args.join(" ") rescue nil
  
  app = VikingIO::CLI::Client.create_app(app_name) 

  if app["status"] == "error"
    puts app["message"]
    return;
  end

  VikingIO::CLI.link_app(app)             
  
  puts "Created application '#{app['name']}'."     
  
  self.generate("--force")
end

.deploy(*args) ⇒ Object

def self.compile_on_server(*args)

args.flatten!

app_data = VikingIO::CLI.get_app_data
user_key = VikingIO::CLI.get_netrc_key

puts "Synchronizing '#{app_data["name"]}' files..." 

VikingIO::CLI::Client.request_build_job(user_key, app_data["key"])

Dir.chdir(File.join(Dir.pwd, "Assets", "VikingIO")) do
  files = Dir.glob("**/**/**").reject {|x| x.start_with?("Client") }.reject {|x| Dir.exist?(x) }.reject {|x| x.end_with?(".meta") }
  files.each do |file|         
    puts file + "..."
    VikingIO::CLI::Client.synchronize_file(user_key, app_data["key"], file)
  end
end           

puts "Compiling..."

VikingIO::CLI::Client.compile_server(user_key, app_data["key"], app_data["name"])

puts "done."

end



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/vikingio/cli/commands.rb', line 110

def self.deploy(*args)
  args.flatten!
  
  app_data = VikingIO::CLI.get_app_data
  user_key = VikingIO::CLI.get_netrc_key  
  node_data = VikingIO::CLI.get_node_data
  
  tmp_dir = File.join(Dir.tmpdir, "vikingio")    
  
  compile = !args.include?("--skip-compilation")
  compilation_success = true 
  
  if args.include?("--check")
    new_node_ct = VikingIO::CLI::Client.deploy_check(user_key, app_data["key"]).to_i
    
    if new_node_ct == 0
      puts "No new nodes will be created."
    else
      puts "#{new_node_ct} new node(s) will be created."
    end
    return
  end    
  
  if compile
    if !self.compile_nodes(tmp_dir, node_data)
      compilation_success = false 
    else

      if IS_WINDOWS
        directory = "#{File.join(tmp_dir, "VikingIO", "Data")}"
        zipfile_name = "#{File.join(tmp_dir, "Data.zip")}"

        Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
            Dir[File.join(directory, '**', '**')].each do |file|
              zipfile.add(file.sub(directory, ''), file)
            end
        end

        VikingIO::CLI::Client.deploy_data(user_key, app_data["key"], zipfile_name)

        FileUtils.rm_rf(directory)

        directory = "#{File.join(tmp_dir, "VikingIO", File::SEPARATOR)}"
        zipfile_name = "#{File.join(tmp_dir, "VikingIO.zip")}"

        Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
          Dir[File.join(directory, '**', '**')].each do |file|
            zipfile.add(file.sub(directory, ''), file)
          end
        end

        VikingIO::CLI::Client.deploy_servers(user_key, app_data["key"], zipfile_name)
      else
        `cd #{File.join(tmp_dir, "VikingIO")} && tar -zcvf Data.tar.gz Data`                            
        puts "Deploying data..."
        VikingIO::CLI::Client.deploy_data(user_key, app_data["key"], File.join(tmp_dir, "VikingIO", "Data.tar.gz"))      
        `rm -rf #{File.join(tmp_dir, "VikingIO", "Data")}*`   
        `cd #{File.join(tmp_dir, "VikingIO")} && tar -zcvf #{File.join(tmp_dir, "VikingIO.tar.gz")} .`          
        puts "Deploying nodes..."
        VikingIO::CLI::Client.deploy_servers(user_key, app_data["key"], File.join(tmp_dir, "VikingIO.tar.gz"))
      end
    end
  end
  
  if compilation_success                           
        
    new_node_ct = VikingIO::CLI::Client.deploy_check(user_key, app_data["key"]).to_i
    deploy = true
    
    if new_node_ct != 0
      puts "#{new_node_ct} new node(s) will be created. Continue? (y/n)"
      y_or_n = STDIN.gets.chomp.downcase

      if !["y", "yes"].include?(y_or_n)
        deploy = false
        puts "Aborting."
      end 
      
    end   
    
    if deploy
      puts "Deploying"
      puts VikingIO::CLI::Client.deploy(user_key, app_data["key"])
    end
    
#          VikingIO::CLI::Client.deploy(user_key, app_data["key"], node_data.to_json)   
  else
    puts "Compilation failed. Aborting deploy."
  end
end

.destroy(*args) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/vikingio/cli/commands.rb', line 67

def self.destroy(*args)
  
  puts ""
  puts "****** WARNING *******"
  puts "This will shut down all of the server node instances for this application. You will have to re-deploy from scratch."
  puts ""
  
  puts "Proceed? (y/n)" 
  y_or_n = STDIN.gets.chomp.downcase
  
  if ["y", "yes"].include?(y_or_n)
      
  else
    puts "Aborting."
  end
  
end

.generate(*args) ⇒ Object



376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
# File 'lib/vikingio/cli/commands.rb', line 376

def self.generate(*args)
  args.flatten!
  
  assets_path = File.join(Dir.pwd, "Assets")
  viking_assets_path = File.join(assets_path, "VikingIO")           
  app_data = VikingIO::CLI.get_app_data          
  
  if args[0] == "node"                                       
    if args[1] == "" || args[1] == nil
      puts "Please enter a camel cased name for your node. i.e. GameServer"
      return
    end
    
    node_data = VikingIO::CLI::Client.create_node(args[1], app_data["key"]) 
    VikingIO::CLI.save_node_data(node_data["nodes"])
    
    puts ""  
    
    
    if node_data["status"] == "error"       
      puts node_data["msg"]
      puts "\nIf you want to create a new node, delete your existing node with 'vikingio destroy node #{node_data["nodes"][0]["node_class"]}'. \nThis will shut down any deployed and running node instances.\n\n"
    end 
    
    node_output_path = File.join(viking_assets_path, "Server", "#{args[1]}.cs")
    if File.exist?(node_output_path)
      puts "#{node_output_path} already exists. Ignoring template generation. Delete the file first if you want to override it."
    else
      server_node_template = File.read(File.join(TEMPLATES_DIR, "ServerNodeTemplate.cs")).gsub("[SERVER_NAME]", args[1])
      File.open(node_output_path, 'w') { |file| file.write(server_node_template) }
    end
    
    return                                                                     
    
    node_output_path = File.join(viking_assets_path, "Server", "#{args[1]}.cs")
    
    if !File.exist?(node_output_path)
      server_node_template = File.read(File.join(TEMPLATES_DIR, "ServerNodeTemplate.cs")).gsub("[SERVER_NAME]", args[1])
      File.open(node_output_path, 'w') { |file| file.write(server_node_template) } 
      node_data = VikingIO::CLI.get_node_data
      node_data << args[1]
      VikingIO::CLI.save_node_data(node_data) 
    end                      
    
    puts "Node '#{args[1]}' created."
    return
  end      
  
  if args[0] == "message"
    puts "Message '#{args[1]}' created."
    server_node_template = File.read(File.join(TEMPLATES_DIR, "MessageTemplate.cs")).gsub("[MESSAGE_NAME]", args[1])
    File.open(File.join(viking_assets_path, "Shared", "Messages", "#{args[1]}.cs"), 'w') { |file| file.write(server_node_template) }
    return
  end
  
  if File.exist?(viking_assets_path) && !args.include?("--force")
    puts "VikingIO already exists in your Assets folder. Run this command again with the --force command to overwrite."
    return
  end                   
  
  puts "Generating skeleton application"                  
  
#        puts "Generating folder structure..."
  FileUtils::mkdir_p(File.join(viking_assets_path, "Client", "External"))
  FileUtils::mkdir_p(File.join(viking_assets_path, "Server", "External"))
  FileUtils::mkdir_p(File.join(viking_assets_path, "Shared", "Messages"))
  FileUtils::mkdir_p(File.join(viking_assets_path, "Data"))     
       
  dlls_dir = File.join(File.dirname(__FILE__), "..", "..", "..", "dlls")   
  
  config_dest = File.join(viking_assets_path, "Client", "VikingIO.Config.cs")
  
#        puts "Copying template files..."                                                                                     
  FileUtils.cp(File.join(TEMPLATES_DIR, "NetworkManager.cs"), File.join(viking_assets_path, "Client", "NetworkManager.cs")) 
  FileUtils.cp(File.join(TEMPLATES_DIR, "VikingIO.Config.cs"), config_dest)                                                 
                                               
  contents = File.read(config_dest).gsub("[APP_NAME]", app_data["name"]).gsub("[APP_ID]", app_data["id"].to_s)
       
  File.open(config_dest, 'w') { |file| file.write(contents) }
  
  File.open(File.join(viking_assets_path, "Nodefile"), "w") do |f|
    f << [].to_json
  end           
  
#        puts "Copying dlls..."
  FileUtils.cp(File.join(dlls_dir, "VikingIO.Network.dll"), File.join(viking_assets_path, "Server", "External", "VikingIO.Network.dll")) 
  FileUtils.cp(File.join(dlls_dir, "VikingIO.Network.Client.dll"), File.join(viking_assets_path, "Client", "External", "VikingIO.Network.Client.dll"))
 puts "Done."
end

.help(*args) ⇒ Object



466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
# File 'lib/vikingio/cli/commands.rb', line 466

def self.help(*args) 
  args.flatten!
  if args.size == 0
    puts "\nCommands: \n\n"     
    
    COMMANDS.each do |cmd|   
      if cmd[1][:short].nil?   
        puts cmd[0]
      else
        puts "#{cmd[0]} - #{cmd[1][:short]}"
      end
    end

    puts ""     
  else
    cmd = COMMANDS.find {|x| x[0] == args[0] }

    puts "\n===========  " + cmd[0] + "  ===========\n\n"
    puts cmd[1][:short] + "\n\n"                      
    puts cmd[1][:full]
  end   
  puts ""              
end


339
340
# File 'lib/vikingio/cli/commands.rb', line 339

def self.link(*args)
end

.login(*args) ⇒ Object



490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
# File 'lib/vikingio/cli/commands.rb', line 490

def self.(*args)   
  email = ""
  password = ""
  
  puts "Enter your email:"
  email = STDIN.gets.chomp
  
  puts ""
  puts "Enter your password:"
  password = STDIN.noecho(&:gets).chomp
                                            
  if email.nil? || email == "" || password.nil? || password == ""
    puts "Email or Password empty" 
    return 
  end           
  
  app_key = VikingIO::CLI::Client.authenticate(email, password)    
  
  if app_key.nil?
    puts "Invalid authentication." 
    return         
  end
  
  if VikingIO::CLI.netrc_exist?
    if VikingIO::CLI.in_netrc?
      VikingIO::CLI.update_netrc_key(app_key)
    else
      VikingIO::CLI.add_netrc_key(email, app_key)
    end                       
    puts "Authenticated #{email}."
  else
    VikingIO::CLI.create_netrc(email, app_key)
    puts "Authenticated #{email}."
  end                       
  
end

.logout(*args) ⇒ Object



527
528
529
530
531
# File 'lib/vikingio/cli/commands.rb', line 527

def self.logout(*args)           
  VikingIO::CLI.remove_netrc_key 
  
  puts "Authentication cleared."
end

.run(command, args) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/vikingio/cli/commands.rb', line 28

def self.run(command, args) 
  puts "VikingIO Version: #{VikingIO::CLI::VERSION}"

  case command
    when "help"
      help(args)
    when "login"
      (args) 
    when "logout"
      logout(args)
    when "create"
      create(args)
    when "generate"
      generate(args)
    when "link"
      link(args)
    when "unlink"
      unlink(args)  
    when "run"
      compile_and_run(args)  
    when "deploy"
      deploy(args)   
    #when "compile"
    #  compile_on_server(args)  
    when "destroy"
      destroy(args) 
    when "status"
      status(args)
    else
      help(args)
  end
end

.status(*args) ⇒ Object



61
62
63
64
65
# File 'lib/vikingio/cli/commands.rb', line 61

def self.status(*args) 
  app_data = VikingIO::CLI.get_app_data
  user_key = VikingIO::CLI.get_netrc_key
  puts VikingIO::CLI::Client.get_status(user_key, app_data["key"])
end


342
343
344
345
# File 'lib/vikingio/cli/commands.rb', line 342

def self.unlink(*args)
  VikingIO::CLI.unlink_app
  puts "Application data cleared."
end